Auth nodejs

From bighardperson/computer-science-skills-collection · View interactive version

Auth nodejs is an AI agent skill from the GitHub repository bighardperson/computer-science-skills-collection. Complete guide for CloudBase Auth using the CloudBase Node SDK – caller identity, user lookup, custom login tickets, and server-side best practices.

How to use this skill

Skill file

When to use this skill

Use this skill whenever the task involves server-side authentication or identity in a CloudBase project, and the code is running in Node.js, for example:

Do NOT use this skill for:

When the user request mixes frontend and backend concerns (e.g. "build a web login page and a Node API that knows the user"), treat them separately:


How to use this skill (for a coding agent)

When you load this skill to work on a task:

  1. Clarify the runtime and responsibility

Ask the user:

  1. Confirm CloudBase environment and SDK

```ts

import tcb from "@cloudbase/node-sdk";

const app = tcb.init({ env: "your-env-id" });

const auth = app.auth();

```

  1. Pick the relevant scenario from this file
  1. Follow Node SDK API shapes exactly
  1. If you are unsure about an API

Node auth architecture – how Node fits into CloudBase Auth

CloudBase Auth v2 separates where users log in from where backend code runs:

In practice, Node code usually does one or more of:

  1. Identify the current caller
  1. Look up other users
  1. Issue custom login tickets
  1. Log client IP for security

The scenarios later in this file turn these responsibilities into explicit, copy‑pasteable patterns.


Node Auth APIs covered by this skill

This skill covers the following auth methods on the CloudBase Node SDK. Treat these method signatures as the only supported entry points for Node auth flows when using this skill:

Returns { openId, appId, uid, customUserId } for the current caller.

Returns detailed CloudBase end‑user profile for a given uid or for the current caller (when uid is omitted).

Finds a user by login identifier (platform + platformId) or uid.

Returns the caller’s IP address when running in a supported environment (e.g. 云函数).

Creates a custom login ticket for the given customUserId that clients can exchange for a CloudBase login.

The exact field names and allowed values for EndUserInfo, IUserInfoQuery, and ICreateTicketOpts are defined by the official CloudBase Node SDK typings and documentation. When writing Node code, do not guess shapes; follow the SDK types and the examples in this file.


Scenarios – Node auth patterns

Scenario 1: Initialize Node SDK and auth in a CloudBase function

Use this when writing a CloudBase 云函数 that needs to interact with Auth:

import tcb from "@cloudbase/node-sdk";

const app = tcb.init({ env: "your-env-id" });
const auth = app.auth();

exports.main = async (event, context) => {
  // Your logic here
};

Key points:

Scenario 2: Get caller identity in a CloudBase function

Use this when you need to know who is calling your cloud function:

import tcb from "@cloudbase/node-sdk";

const app = tcb.init({ env: "your-env-id" });
const auth = app.auth();

exports.main = async (event, context) => {
  const { openId, appId, uid, customUserId } = auth.getUserInfo();

  console.log("Caller identity", { openId, appId, uid, customUserId });

  // Use uid / customUserId for authorization decisions
  // e.g. check roles, permissions, or data ownership
};

Best practices:

Scenario 3: Get full end‑user profile by UID

Use this when you know a user’s CloudBase uid (for example, from a database record) and you need detailed profile information:

import tcb from "@cloudbase/node-sdk";

const app = tcb.init({ env: "your-env-id" });
const auth = app.auth();

exports.main = async (event, context) => {
  const uid = "user-uid";

  try {
    const { userInfo } = await auth.getEndUserInfo(uid);
    console.log("User profile", userInfo);
  } catch (error) {
    console.error("Failed to get end user info", error.message);
  }
};

Best practices:

Scenario 4: Get full profile for the current caller

Use this when you want the current caller’s full profile without manually passing uid:

import tcb from "@cloudbase/node-sdk";

const app = tcb.init({ env: "your-env-id" });
const auth = app.auth();

exports.main = async (event, context) => {
  try {
    const { userInfo } = await auth.getEndUserInfo();
    console.log("Current caller profile", userInfo);
  } catch (error) {
    console.error("Failed to get current caller profile", error.message);
  }
};

This relies on the environment providing the caller’s identity (e.g. within a CloudBase 云函数). If called where no caller context exists, refer to the official docs and handle errors gracefully.

Scenario 5: Query user by login identifier

Use this when you only know a user’s login identifier (phone, email, username, or custom ID) and need their CloudBase profile:

import tcb from "@cloudbase/node-sdk";

const app = tcb.init({ env: "your-env-id" });
const auth = app.auth();

exports.main = async (event, context) => {
  try {
    // Find by phone number
    const { userInfo: byPhone } = await auth.queryUserInfo({
      platform: "PHONE",
      platformId: "+86 13800000000",
    });

    // Find by email
    const { userInfo: byEmail } = await auth.queryUserInfo({
      platform: "EMAIL",
      platformId: "test@example.com",
    });

    // Find by customUserId
    const { userInfo: byCustomId } = await auth.queryUserInfo({
      platform: "CUSTOM",
      platformId: "your-customUserId",
    });

    console.log({ byPhone, byEmail, byCustomId });
  } catch (error) {
    console.error("Failed to query user info", error.message);
  }
};

Best practices:

Scenario 6: Get client IP in a function

Use this for logging or basic IP‑based checks:

import tcb from "@cloudbase/node-sdk";

const app = tcb.init({ env: "your-env-id" });
const auth = app.auth();

exports.main = async (event, context) => {
  const ip = auth.getClientIP();
  console.log("Caller IP", ip);

  // e.g. block or flag suspicious IPs
};

Custom login tickets (Node side only)

Custom login lets you keep your existing user system while still mapping each user to a CloudBase account.

Scenario 7: Initialize Node SDK with custom login credentials

Before issuing tickets, install the custom login private key file from the CloudBase console and load it in Node:

import tcb from "@cloudbase/node-sdk";
import path from "node:path";

const app = tcb.init({
  env: "your-env-id",
  credentials: require(path.join(__dirname, "tcb_custom_login.json")),
});

const auth = app.auth();

Keep tcb_custom_login.json secret and never bundle it into frontend code.

Scenario 8: Issue a custom login ticket for a given customUserId

Use this in backend code that has already authenticated your own user and wants to let them log into CloudBase:

import tcb from "@cloudbase/node-sdk";

const app = tcb.init({
  env: "your-env-id",
  credentials: require("/secure/path/to/tcb_custom_login.json"),
});

const auth = app.auth();

exports.main = async (event, context) => {
  const customUserId = "your-customUserId";

  const ticket = auth.createTicket(customUserId, {
    refresh: 3600 * 1000,       // access_token refresh interval (ms)
    expire: 24 * 3600 * 1000,   // ticket expiration time (ms)
  });

  // Return the ticket to the trusted client (e.g. via HTTP response)
  return { ticket };
};

Constraints for customUserId (from official docs):

Best practices:

Scenario 9: How this pairs with Web custom login

This skill only covers Node-side ticket issuance. For the client-side flow:

Keep the responsibility clear:


Node auth best practices


Summary

Use this Node Auth skill whenever you need to:

For end‑to‑end experiences, pair this skill with:

Treat the official CloudBase Auth Node SDK documentation as the canonical reference for Node auth APIs, and treat the scenarios in this file as vetted best‑practice building blocks.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.