@spica-devkit/auth

Sign users up and in, manage sessions, verify emails and phone numbers, reset passwords and log users in without passwords.

@spica-devkit/auth works with users, your product's end users.

Terminal
npm install @spica-devkit/auth
TypeScript
import * as Auth from "@spica-devkit/auth";

// In a client: no credentials needed to sign in
Auth.initialize({publicUrl: "https://api.example.com/api"});

// On a server or in a function: an API key for administrative calls
Auth.initialize({apikey: process.env.SPICA_API_KEY});

Sign up and sign in

TypeScript
const user = await Auth.signUp({username: "ada@example.com", password: "aStrongPassword1"});

const session = await Auth.signIn("ada@example.com", "aStrongPassword1");
session.token;     // the user JWT
session.userId;
session.username;

const me = await session.get();
await session.updatePassword("anEvenStrongerPassword2");
const freshToken = await session.refreshAccessToken();

signUp calls POST /passport/user, which needs an API key or an identity with passport:user:create. Run it on your server or in a function, not in the browser.

FunctionDescription
signUp({username, password}, headers?)Create a user.
signIn(username, password, tokenLifeSpan?, headers?)Log in. Returns a UserSession.
verifyToken(token, headers?)Verify a user token and return its payload.
refreshAccessToken(accessToken, headers?)Exchange an expired token for a new one (needs the refresh cookie).

Verification, reset and passwordless login

These flows need the matching settings in the user configuration, and a configured mailer or SMS sender.

FunctionDescription
addEmail(userId, email, "Otp" | "MagicLink")Send a verification code or link to an email address.
verifyEmail(userId, code, "Otp" | "MagicLink")Confirm it.
addPhoneNumber(userId, phone, strategy)Send a code or link by SMS.
verifyPhoneNumber(userId, code, strategy)Confirm it.
requestPasswordReset(username, "email" | "phone")Send a reset code.
completePasswordReset(username, code, newPassword, provider)Set the new password.
passwordlessLogin(username, provider)Send a login code.
completePasswordlessLogin(username, code, provider)Log in with the code. Returns a UserSession.
TypeScript
await Auth.passwordlessLogin("ada@example.com", "email");
const session = await Auth.completePasswordlessLogin("ada@example.com", "123456", "email");

Administration

With an API key or identity:

FunctionDescription
get(userId), getAll(queryParams?)Read users.
updatePassword(userId, {password})Change a password.
updateUsername(userId, username)Change a username.
ban(userId, bannedUntil)Block logins until a date.
deactivateUserTokens(userId, date)Invalidate tokens issued before a date.
remove(userId)Delete a user.
policy.attach(userId, policyIds), policy.detach(userId, policyIds)Manage policies.