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

@therocketcodemx/trc_authentication

v1.4.24

Published

Library with common function about authentication

Downloads

173

Readme

node-therocketcodemx

:rocket: Table of Contents :rocket:

Install

This is a Node.js module available through the npm registry.

Before installing, download and install Node.js. Node.js 0.6 or higher is required.

Installation is done using the npm install command:

$ npm install @therocketcodemx/trc_authentication

Introduction

This is an authentication module developed using Node.js. It provides robust and secure user authentication functionalities to Node.js applications. This library integrates with PostgreSQL for user data storage and implements multiple features to enhance security and improve user management.

The key features of this module include:

Email Validation: It sends a One Time Password (OTP) via email to the user for email verification. User Registration: Allows user registration with necessary validation. Login and Logout: Facilitates secure user login and logout operations. Password Recovery: Provides functionality to recover forgotten passwords through email. Password Update: Allows users to change their passwords securely. The library provides a set of interfaces for easy interaction and implementation. It also allows customization of email templates for OTP and password recovery operations. This library is built with a focus on security, scalability, and ease of use.

Here is an example of how to initialize the module:

import { Authentication } from '@therocketcodemx/trc_authentication';
// configuration object to connect to DB postgres
const connectionDB = {
    host: '',
    database: '',
    user: '',
    password: ''
}
const authentication = new Authentication(connectionDB);

...

For the connection to the database, the postgres engine is used. For more information

To use this library you need to have the following tables created:

Click here to see the DB model

Interfaces used

All interfaces can be imported from the library.

interface RegisterUser {
    username?: string | null; // (optional) user nickname
    name: string; // usernames
    surname: string; // father's last name
    second_surname: string; //mother's last name
    password: string; // user's personal password
    role?: string; // (optional) user rol
}
interface LoginOptions {
  /**
   * The unique `identifier` for a user, which can be a `user_name`, `id_user`, `email`, or `mobile`.
   * By default, it uses the email as the identifier if none is provided.
   */
  identifier?: string;
}
interface CredentialsProps {
  /**The username of the user attempting to log in. */
  user: string;
  /**The password of the user attempting to log in. */
  password: string;
}
interface LoginAttemptProps {
  ip: string;
  login_attempt?: string;
  time_login?: Date;
}
interface TokenProps {
  /**The secret key used to encrypt token. */
  secretKey?: string;
  /** Time the token expires expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms.js).  Eg: 60, "2 days", "10h", "7d" */
  expiresIn?: string;
}
interface LoginResult {
  /**This property indicates whether the login was successful. If the value is `true`, the login was successful; if it is `false`, the login failed. */
  success: boolean;
  /**This property contains a message related to the login result. It can be a message informing the user about the success or failure of the login, or an error message in case an issue occurs during the process. */
  message: string;
  /**This optional property contains the authentication token generated for the user in case of a successful login. The token is used to authenticate the user's subsequent requests. If the login fails, this property will not be present in the `LoginResult` object. */
  token?: string;
  /**This optional property contains the secret key used to generate the authentication token. It is useful for debugging purposes or for storing the key in a secure log. If the login fails, this property will not be present in the `LoginResult` object. */
  secretKey?: string;
  /**This optional property contains the expiration time of the authentication token. It can be a string representing a time interval (e.g., "1h" for one hour) or a numeric value in seconds. If the login fails, this property will not be present in the `LoginResult` object. */
  tokenExpiresIn?: string;
}
// Credentials for using Mailjet
interface ClientParams {
    apiKey: string; // the api key is obtained by creating an account at mailjet (https://www.mailjet.com/)
    apiSecret: string; // the api secret is obtained by creating an account at mailjet (https://www.mailjet.com/)
    apiToken?: string; // (optional) the api token is obtained by creating an account at mailjet (https://www.mailjet.com/)
    options?: null | RequestOptions; // (optional) additional options object
    config?: null | Partial<RequestConfig>; // (optional) configuration object
}

interface Email {
    Email: string; // user email
}
interface Variables {
    [key: string]: any;
}

export interface ConfigSendInBlue {
    apiKey: string;
    sendSmtpEmail: SibApiV3Sdk.SendSmtpEmail;
    urlRecovery: string;
}

interface BodyMailjet {
    urlRecovery: string; // url to which the user will be redirected to recover their password
    From: Email; // sender email
    To: Email[]; // email array for recipients
    TemplateID?: number; // (optional) Template ID, if you were create in mailjet
    Subject?: string // (optional) subject the email
    TemplateLanguage?: boolean; // (optional) if true, get the created template marked by the template ID
    HTMLPart?: string; // (optional) User created template
    TextPart?: string; // (optional) additional email text
    Variables?: Variables; // (optional) variables object to replace in template
}

export interface ConfigMailJet {
    body: BodyMailjet;
    config: ClientParams;
}

export interface ConfigSendInBlue {
    apiKey: string;
    sendSmtpEmail: SibApiV3Sdk.SendSmtpEmail; // import {SibApiV3Sdk} from '@therocketcodemx/trc_authentication';
    urlRecovery: string;
}

export type TimeDurations = 'hour' | 'day' | 'min';

interface ParamsValidateEmail {
    otpLength: number; // number of digits that the otp will have
    expiration: string; // otp expiration
    time: TimeDurations; // time used for the expiration of the otp (hours, minutes and days)
}

export type ConfigEmailServices = {
    'sendinblue'?: ConfigSendInBlue,
    'mailjet'?: ConfigMailJet,
}

Using methods

For use the methods the instance object is used of Authentication, for example:

validateEmail

this method is used to send an email to the user with an OTP to verify their email address. the method receives two parameters, the first is the OTP configuration and second is the email service configuration (mailjet or sendinblue).

// choose the service to send the email (mailjet or sendinblue)
const configEmailService: ConfigEmailServices = {
    'mailjet': {...},
    'sendinblue': {...},
}
const config: ParamsValidateEmail = {
    otpLength: 6,
    expiration: '1',
    time: 'hour',
}
const sendOTP = async (config: ConfigOTP, configEmailService: ConfigEmailServices) => {
    const authentication = new Authentication(/* connectionDB */);
  const response = await authentication.validateEmail(config, configEmailService);
};
sendOTP(config, configEmailService);

registerUser

Registers a new user in the database. The method receives four parameters. The first is the user data, the second is an boolean value that indicates if the user needs verification the user's email for send an OTP, the third is the OTP configuration and email service, and the fourth is an object containing the relationship between the user and other tables.

parameters optional:

  • verifiedEmail (default: false) - If true, the user will be sent an email with an OTP to verify their email address.
  • configVerifyEmail (default: null) - If verifiedEmail is true, the email service must be specified.
  • relationship (default: null) - If the user has a relationship with other tables, it must be specified.
import { Authentication } from '@therocketcodemx/trc_authentication';

const user = {
  user: 'myUsername', // user identifier for the login authentication
  password: 'myPassword',
  firebase_uid: '1234567890', // (optional) firebase uid
  roles: [1, 2], // (optional) user roles. the numbers are the id of the roles.
  userData: {
    firstName: 'Name',
    secondName: 'Second name',
    firstLastName: 'First last name',
    secondLastName: 'Second last name',
    email: '[email protected]'
  }, // (required) user data
  userAddress: {
    zipCode: '12345',
    extertalNumber: '123',
    internalNumber: '123',
    street: 'Street',
    settlement: 'Settlement',
    idState: 1,
  }, // (optional) user address
};


let response =  await Authentication.registerUser(user); // without verifiedEmail
let configVerifyEMail = {
    otpLength: 6,
    expiration: '1',
    time: 'hour',
}
// take the configuration of the email service of your preference (mailjet or sendinblue)
let configEmailService: ConfigEmailServices = {
    'mailjet': {...},
    'sendinblue': {...},
}
let response =  await Authentication.registerUser(user, true, configEmailService); // with verifiedEmail

activateAccount

if when registering the user, the verifiedEmail parameter is true, the user must activate their account with the OTP that was sent to their email.

For this, the activateAccount method is used, which receives two parameters, the first is the OTP and the second is the email of the user to be activated.

this function returns a message indicating if the account was activated successfully or message indicating that the OTP is incorrect or expired.


import { Authentication } from '@therocketcodemx/trc_authentication';

let response = await Authentication.activateAccount('123456', '[email protected]');

login

Authenticates a user and returns an object containing information about the login attempt, including whether it was successful, an optional token, and a message describing the result.

// Example usage
const loginOptions: LoginOptions = {
  identifier: 'user_name', // The unique `identifier` for a user, which can be a `user_name`, `id_user`, `email`, or `mobile`.
};

const credentials: CredentialsProps = {
  user: 'myUsername' | 'myEmail', // user identifier for the login authentication
  password: 'myPassword',
};

const loginAttemptData: LoginAttemptProps = {
  ip: '127.0.0.1', // internet protocol
  login_attempt: '1', // number of attempts to log in
  time_login: new Date(), // session time
};

const tokenProps: TokenProps = {
  secretKey: 'Ravipass',
  expiresIn: '1h',
};
const authentication = new Authentication(/* connectionDB */);
const result: LoginResult = await authentication.login(
  loginOptions,
  credentials,
  loginAttemptData,
  tokenProps
);
console.log(result);
// {
//  "success": true,
//  "message": "¡Usuario exitosamente autentificado!",
//  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImpvaG4uZG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",
//  "secretKey": "Ravipass",
//  "tokenExpiresIn": "1h"
// }

logout

Logout function that logs out a user by updating the logout time in the login_attempts table.

// Example usage
const token = 'YOURTOKEN';

const authentication = new Authentication(/* connectionDB */);
const result = await authentication.logout(token);
console.log(result);

recoverPassword

This method is used to send an email to the user with a link to recover their password. the method receives three parameters, the first is the configuration of the email service, the second is an boolean value that indicates if the user needs verification an OTP that was sent to the email (optional), and the third is the OTP is required if the second parameter is true.

Example of use with Mailjet;

const configEmailMailjet: ConfigEmailServices = {
  mailjet: {
    body: {
      urlRecovery: 'http://localhost:3000/recovery-password',
      From: {
        Email: '',
      },
      To: [
        {
          Email: '',
        },
      ],
      TemplateID: 0, // required if TemplateLanguage is used
      Subject: 'Password recovery',
      TemplateLanguage: true, // required if TemplateID is used
      HTMLPart:
        '<h3>Hi [[name]],</h3><p>To recover your password, click on the following link:</p><p><a href="[[URL_RECOVERY]]">Recover password</a></p><p>If you did not request to recover your password, ignore this email.</p>',
      TextPart: 'Password recovery',
      Variables: {
        name: 'Name',
        URL_RECOVERY: 'http://localhost:3000/recovery-password',
      },
    },
    config: {
      apiKey: '',
      apiSecret: '',
    },
  },
};

Example of use with Sendinblue;

const configEmailSendinblue: ConfigEmailServices = {
  sendinblue: {
    apiKey: '',
    sendSmtpEmail: {
      sender: {
        name: '',
        email: '',
      },
      to: [
        {
          email: '',
          name: '',
        },
      ],
      templateId: 0, // required if we used template of sendinblue
      subject: 'Password recovery',
      htmlContent:
        '<h3>Hi [[name]],</h3><p>To recover your password, click on the following link:</p><p><a href="[[URL_RECOVERY]]">Recover password</a></p><p>If you did not request to recover your password, ignore this email.</p>',
      params: {
        name: 'Name',
        URL_RECOVERY: 'http://localhost:3000/recovery-password',
      },
    },
    urlRecovery: 'http://localhost:3000/recovery-password',
  },
};
import { Authentication } from '@therocketcodemx/trc_authentication';

const authentication = new Authentication(/* connectionDB */);
let response = await authentication.recoverPassword(configEmailMailjet); // configEmailMailjet without OTP
let response = await authentication.recoverPassword(configEmailMailjet, true, '123456'); // or configEmailMailjet with OTP
let response = await authentication.recoverPassword(configEmailSendinblue); // or configEmailSendinblue without OTP
let response = await authentication.recoverPassword(configEmailSendinblue, true, '123456'); // or configEmailSendinblue with OTP

changePassword

Updates the user's password in the database.

// Example usage
const token = 'YOURTOKEN';
const password = 'PREVIOUSPASSWORD';
const newPassword = 'NEWPASSWORD';

const authentication = new Authentication(/* connectionDB */);
const result = await authentication.changePassword(
  token,
  password,
  newPassword
);
console.log(result);