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

@ilittlebig/easy-auth

v0.0.9

Published

A simple, no-fuss authentication library using AWS SDK with SRP-based login. Designed to make AWS Cognito integration straightforward and secure.

Downloads

748

Readme

AWS Cognito Authentication Library

A simple, no-fuss authentication library using AWS SDK with SRP-based login. Designed to make AWS Cognito integration straightforward and secure.

Note: The implementation of this library is inspired by AWS Amplify.

Features

  • 🔒 Secure Authentication: Uses SRP (Secure Remote Password) for safe user logins.
  • ⚙️ AWS SDK Integration: Works seamlessly with AWS Cognito.
  • 👤 User Management: Easily handle user registration, login, and password resets.
  • ✅ Unit Tests: Fully tested to ensure everything works smoothly.

Table of Contents

Installation

  1. Run this command:
npm install @ilittlebig/easy-auth

Usage

Configuration

Before using the authentication functions, configure EasyAuth with your AWS Cognito credentials:

EasyAuth.configure({
  Auth: {
    Cognito: {
      userPoolId: "your-user-pool-id",
      userPoolClientId: "your-user-pool-client-id"
    },
  }
});

Sign In

To sign in a user, pass the username and password:

import { signIn } from "easy-auth";

const result = await signIn({
  username: "[email protected]",
  password: "LongPassword123!!"
});

The signIn function may return a nextStep if further action is needed (e.g., setting a new password or entering an MFA code). You can handle each step based on the nextStep.signInStep value:

import { confirmSignIn } from "easy-auth";

if (result.nextStep.signInStep === "CONFIRM_SIGN_IN_WITH_NEW_PASSWORD_REQUIRED") {
  // Handle new password requirement
  await confirmSignIn({ challengeResponse: "newPassword123" });
}

When all steps are completed, nextStep.signInStep will return DONE, indicating a successful sign-in.

Reset Password

To start the password reset flow, provide the username:

import { resetPassword } from "easy-auth";
await resetPassword({ username: "[email protected]" });

If a confirmation code is required, confirm the password reset:

import { confirmResetPassword } from "easy-auth";

await confirmResetPassword({
  username: "[email protected]",
  confirmationCode: "123456",
  newPassword: "LongPassword123!!",
});

Get Current Session

Retrieve the current session tokens, including the access and ID tokens, along with the user ID (sub). These tokens may contain user information, roles, and expiration details.

import { getCurrentSession } from "easy-auth";
const { tokens, sub } = await getCurrentSession();

Get Current User

Retrieve the current session tokens and user ID (sub) for ongoing authentication or session management needs.

import { getCurrentUser } from "easy-auth";
const { username, userId } = await getCurrentUser();

Sign Out

To sign out a user, use the signOut function. You can pass an optional parameter { isGlobal: true | false } to determine whether the sign-out should be global (across all devices) or just on the current client.

import { signOut } from "easy-auth";

// Sign out from all devices
await signOut({ isGlobal: true });

// Sign out only from the current device
await signOut({ isGlobal: false });

Update Password

Use the updatePassword function to update the password for an authenticated user. This function requires the current (previous) password and the new (proposed) password.

import { updatePassword } from "easy-auth";

await updatePassword({
  previousPassword: "oldPassword123",
  proposedPassword: "newPassword321"
});

Update MFA Preference

Use the updateMFAPreference function to configure the Multi-Factor Authentication (MFA) preferences for an authenticated user. You can set preferences for both totp (Time-based One-Time Password) and sms (SMS-based) MFA methods.

Both totp and sms preferences are optional and can be set to the following values:

  • "PREFERRED": Sets MFA as the preferred authentication method.
  • "ENABLED": Enables MFA but does not make it preferred.
  • "DISABLED": Disables MFA for this method.
  • "NOT_PREFERRED": Sets MFA as non-preferred.
import { updateMFAPreference } from "easy-auth";

await updateMFAPreference({
  totp: "PREFERRED",
  sms: "NOT_PREFERRED"
});

Get MFA Preference

Use the getMFAPreference function to retrieve the current Multi-Factor Authentication (MFA) preferences for an authenticated user. This function provides the user’s preferred MFA method and a list of all enabled MFA settings.

The response object includes:

  • preferredMFASetting: The preferred MFA method, such as "TOTP".
  • userMFASettingList: An array of enabled MFA methods, like ["TOTP","SMS"].
import { getMFAPreference } from "easy-auth";
const result = await getMFAPreference();

Get Devices

Use the getDevices function to retrieve a list of remembered devices associated with the authenticated user. This list includes devices that the user has previously chosen to remember during the login process.

import { getDevices } from "easy-auth";
const devices = await getDevices();

Get User Attributes

Retrieves key profile details for the authenticated user from AWS Cognito. This data often includes information such as the user's email, verification status, and unique user identifier (sub), among other attributes configured in your Cognito setup.

import { getUserAttributes } from "easy-auth";
const attributes = await getUserAttributes();

Verify TOTP

Verifies a Time-based One-Time Password (TOTP) code, typically used for Multi-Factor Authentication (MFA). Checks the code provided by the user and returns a result indicating whether the verification was successful or not.

The result object includes:

  • status: "SUCCESS" if the verification was successful, or "ERROR" if it failed.
  • session: An optional session token included if a session is available.
import { verifyTOTP } from "easy-auth";
const result = await verifyTOTP();

Sign Up

Registers a new user with AWS Cognito. To create a user, provide a username and password. You can also pass optional user attributes to customize the user's profile. AWS Cognito supports the following standard attributes:

  • name
  • family_name
  • given_name
  • middle_name
  • nickname
  • preferred_username
  • profile
  • picture
  • website
  • gender
  • birthdate
  • zoneinfo
  • locale
  • updated_at
  • address
  • email
  • phone_number
  • sub

Example:

import { signUp } from "easy-auth";

const result = await signUp({
  username: "[email protected]",
  password: "LongPassword123!!",
  options: {
    userAttributes: {
      gender: "Male",
      nickname: "Olof"
    }
  }
});

Confirm Sign Up

After signing up, the user must confirm their account, typically by entering a confirmation code sent to their email. Use the confirmSignUp function to verify the code and complete the registration process.

import { confirmSignUp } from "easy-auth";

let signUpCode = "123456";

const result = await confirmSignUp({
  username: "[email protected]",
  confirmationCode: signUpCode
});

Resend Sign Up Code

Allows you to resend the confirmation code to a user who is in the process of signing up but hasn’t yet confirmed their account. This is useful if the user didn’t receive the original code or needs a new one.

import { resendSignUpCode } from "easy-auth";

const codeDeliveryDetails = await resendSignUpCode({
  username: "[email protected]",
});

Delete User

Permanently deletes the authenticated user's account from AWS Cognito. This action is irreversible and removes all associated user data. It’s typically used when a user wants to close their account.

import { deleteUser } from "easy-auth";
await deleteUser();

Change Storage Provider

Select the default storage provider for managing token storage, such as localStorage or inMemoryStorage, which are stored locally, or opt for cookieStorage, where tokens are stored in cookies.

// Store tokens in cookies
import { EasyAuth, CookieStorage } from "easy-auth";
EasyAuth.setKeyValueStorage(new CookieStorage());

// Store tokens in memory
import { EasyAuth, InMemoryStorage } from "easy-auth";
EasyAuth.setKeyValueStorage(new InMemoryStorage());

Running Tests

To run the included unit tests:

npm test

References