@alwatr/token
TypeScript icon, indicating that this package has built-in type declarations

0.30.0 • Public • Published

Alwatr Token - @alwatr/token

Secure authentication HOTP token generator (HMAC-based One-Time Password algorithm) written in tiny TypeScript module.

Example

import {createLogger} from '@alwatr/logger';
import {type TokenStatus, AlwatrTokenGenerator} from '@alwatr/token';

type User = {
  id: string;
  name: string;
  role: 'admin' | 'user';
  auth: string;
};

const logger = createLogger('token/demo');

const tokenGenerator = new AlwatrTokenGenerator({
  secret: 'my-very-secret-key',
  duration: '1h',
  algorithm: 'sha512',
  encoding: 'base64url',
});

const user: User = {
  id: 'alimd',
  name: 'Ali Mihandoost',
  role: 'admin',
  auth: '', // Generated in first login
};

// ------

// For example when user authenticated we send user data contain valid auth token.
function login(): User {
  user.auth = tokenGenerator.generate(`${user.id}-${user.role}`);
  logger.logMethodFull('login', {}, {user});
  return user;
}

// Now request received and we want to validate the token to ensure that the user is authenticated.
function userValidate(user: User): TokenStatus {
  const validateStatus = tokenGenerator.verify(`${user.id}-${user.role}`, user.auth);
  logger.logMethodFull('userValidate', {user}, {validateStatus});
  return validateStatus;
}

// demo
const userData = login();
userValidate(userData); // 'valid'

// one hour later
userValidate(user); // 'expired'

// one hours later
userValidate(user); // 'invalid'

References

Package Sidebar

Install

npm i @alwatr/token

Weekly Downloads

7

Version

0.30.0

License

MIT

Unpacked Size

15.8 kB

Total Files

12

Last publish

Collaborators

  • alimd