npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@screencloud/auth-sdk

v2.5.1

Published

ScreenCloud Authentication Microservice SDK

Downloads

840

Readme

ScreenCloud Auth SDK

semantic-release

Setup

install package using npm npm i -S @screencloud/auth-sdk

import and configure

import { Auth } from "@screencloud/auth-sdk";

// create it once and add it to your context
export const auth = new Auth({
  service: {
    urL: "https://auth-service.dev.next.sc:8022",
  },
  frontend: {
    urL: "https://auth.dev.next.sc:8020",
  },
});

Auth-class

Methods

get()

Retrieves the current session. Will internally call refresh() periodically and on the first call.

try {
  const session = await auth.get();
  if (!session) {
    console.log(`not logged in or error occurred`);
  } else {
    const { payload, token } = session;
    console.log(`logged in as ${payload.email}`);
    // use token to talk to APIs like studio graphql
  }
} catch (e) {
  console.log("something happened, handle it!");
}

shouldRefresh() and refresh()

These functions are used internally by get() but are exposed and can be called if desired.

Use refresh() to force a refresh of the current session. This triggers the initialized-event on the first run, triggers loggedOut or loggedIn if the current user has changed or refreshed if the current user is logged in and remained unchanged.

Note: refresh() will throw in several circumstances, use get() if you want this handled.

logout()

Calls the AuthService to log out the current user. Will always return { redirectUrl: string } and swallows up all errors for resilience. Will trigger loggedOut if user is currently logged in.

Either react to the event handler or to the functions result.

fetchJson()

A helper method used internally by refresh(), logout(), etc. which is exposed to serve other use-cases such as user creation or login.

Example:

// body can contain objects, which will be JSON stringified.
const body = {
  email: "[email protected]",
  password: "myUnsafePass123",
};

// catch the
const result = await auth.fetchJson("/ap/v1/user/create", { body });

fetchApiRequest()

A helper method used internally by most functions calling /api/v1/-prefixed routes.

Example:

// body can contain objects, which will be JSON stringified.
const body = {
  email: "[email protected]",
  password: "myUnsafePass123",
};

// always receive something
const { response } = await auth.fetchApiResponse("user/login", body);

Events

subscribe to events to react in real-time

auth.on("loggedIn", ({ token, claims }) => {
  console.log(`user logged in ${claims.email}`);
});

auth.on("loggedOut", ({ redirectUrl }) => {
  console.log(`user logged out, redirect to ${redirectUrl}`);
});

auth.on("refreshed", ({ token, claims }) => {
  console.log(`logged in user was refreshed ${claims.email}`);
});

auth.on("initialized", (session) => {
  if (!session) {
    console.log(`initial auth state: user is NOT logged in`);
  } else {
    console.log(`initial auth state: user is ${session.claims.email}`);
  }
});

if (!session) {
  console.log(`not logged in or error occurred`);
} else {
  const { payload, token } = session;
  console.log(`logged in as ${payload.email}`);
  // use token to talk to APIs like studio graphql
}

Automation

The SDK offers helper functionality to automatically update it's login state and sync it between tabs.

Be aware that these are based on event listeners and that it's best to just use one instance of Auth. To allow for garbage collection of an Auth-instance ensure to deactivate these again before clearing or losing references to the instance.

AutoSync

The Auth-class can automatically sync itself across tabs on the same origin using localStorage. Any invalid values received will be ignored for resilience.

Activate either during construction

const auth = new Auth({ autoSync: true });

or on the instance itself

// enable
auth.autoSync = true;

// disable
auth.autoSync = true;

AutoRefresh

The Auth-class can automatically refresh to keep it's session from expiring and to handle login and logout happening in the background. It will call shouldRefresh() internally every 15 seconds and run refresh() if required.

Activate either during construction

const auth = new Auth({ autoRefresh: true });

or on the instance itself

// enable
auth.autoRefresh = true;

// disable
auth.autoRefresh = true;

Debug

Debug mode can be activated by either setting debug: true during construction or by setting a DEBUG_AUTH_SDK=1-cookie.

Once activated the SDK will log detailed information to console. Once activated the SDK will log detailed information to console.

AuthManager-class

An extension of Auth, which adds methods for account management

Methods

createUserWithPassword()

Creates a user using the supplied password. Will return various validation errors if conditions aren't met.

createPendingUserWithPassword()

Creates a user using the supplied password and has not completed their email verifcation. Will return various validation errors if conditions aren't met.

activateUserWithCode()

Activates a previously with password created user. Requires the code which was sent via email.

verifyRegistrationCode()

Activates a pending password created user. Requires the shortened registration code which was sent via email.

loginWithPassword()

Logs a user in using email and password. The user must be active.

If an OTP was set up before, then you'll also need to send a valid otp.

changePassword()

Change a users password. Must supply both current valid and new password.

requestPasswordReset()

Request a password reset code in case a user wants to reset their password or has forgotten it.

resetPassword()

Reset a users password using a code received via email (see requestPasswordReset()).

userExistsByEmail()

Gets the public identities of a given email address in the shape of

const publicUserIdentities: {
  identity: string;
  verified: boolean;
  strategy: string;
  provider: string | null;
  connection: string | null;
}[] = await auth.userExistsByEmail("[email protected]");

Use this to check if an email exists and which login options to show.

setOTPKey()

Allows to activate, reset and deactivate 2FA for password-based users using timed OTPs.

This requires the email and password of the user similar to loginWithPassword() and is subject to the same verification.

When first setting up OTP-2FA, you'll need to supply both newOtpKey and a valid newOtp as proof.

When deactivating an account with OTP-2FA, you'll need to supply a currently valid otp.

When setting a new OTPKey for an account with OTP-2FA, you'll need to supply all three values: otp, newOtp and newOtpKey

Note: Use the generateOTPKey()-function to help with OTP key generation.

Functions

The package offers a few useful helper functions

isOTPToken(str: string): bool

Returns true if str is a valid OTPToken-string and false for everything else.

isOTPKey(str: string): bool

Returns true if str is a valid OTPKey-string and false for everything else.

generateOTPKey(opts?: { user?: string; issuer?: string; })

Returns a { otpKey: string; otpKeyUri: string; } of which otpKey is valid OTPKey to be used with Auth.setOTPKey().

You should expose optKey to the user and prompt to store it in a safe place. You can also use otpKeyUri to generate a QRCode for mobile apps such as Google Authenticator.