1.4.24 • Published 10 months ago

@therocketcodemx/trc_authentication v1.4.24

Weekly downloads
-
License
ISC
Repository
-
Last release
10 months ago

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: 'test@test.com'
  }, // (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', 'test@test.com');

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);
1.4.24

10 months ago

1.4.20

10 months ago

1.4.22

10 months ago

1.4.21

10 months ago

1.4.15

10 months ago

1.4.14

11 months ago

1.4.17

10 months ago

1.4.16

10 months ago

1.4.19

10 months ago

1.4.18

10 months ago

1.4.11

11 months ago

1.4.10

11 months ago

1.4.13

11 months ago

1.4.12

11 months ago

1.4.6

11 months ago

1.4.5

11 months ago

1.4.4

11 months ago

1.4.3

11 months ago

1.4.9

11 months ago

1.4.8

11 months ago

1.4.7

11 months ago

1.2.81

12 months ago

1.2.82

12 months ago

1.2.80

12 months ago

1.2.71

12 months ago

1.2.74

12 months ago

1.2.75

12 months ago

1.2.72

12 months ago

1.2.73

12 months ago

1.2.78

12 months ago

1.2.79

12 months ago

1.2.76

12 months ago

1.2.77

12 months ago

1.4.1

11 months ago

1.4.0

12 months ago

1.3.0

12 months ago

1.2.60

1 year ago

1.2.63

1 year ago

1.2.64

1 year ago

1.2.61

1 year ago

1.2.62

1 year ago

1.2.67

1 year ago

1.2.68

1 year ago

1.2.65

1 year ago

1.2.66

1 year ago

1.2.69

1 year ago

1.2.70

1 year ago

1.6.4

1 year ago

1.0.9

1 year ago

1.6.3

1 year ago

1.0.8

1 year ago

1.6.2

1 year ago

1.0.7

1 year ago

1.0.6

1 year ago

1.4.2

1 year ago

1.0.5

1 year ago

1.2.2

1 year ago

1.0.4

1 year ago

1.2.41

1 year ago

1.2.42

1 year ago

1.2.40

1 year ago

1.2.45

1 year ago

1.2.46

1 year ago

1.2.43

1 year ago

1.2.44

1 year ago

1.2.49

1 year ago

1.2.47

1 year ago

1.2.48

1 year ago

1.7.9

1 year ago

1.7.8

1 year ago

1.2.52

1 year ago

1.7.7

1 year ago

1.2.53

1 year ago

1.7.6

1 year ago

1.2.50

1 year ago

1.7.5

1 year ago

1.2.51

1 year ago

1.7.4

1 year ago

1.2.56

1 year ago

1.2.57

1 year ago

1.2.54

1 year ago

1.2.55

1 year ago

1.2.58

1 year ago

1.2.59

1 year ago

1.2.19

1 year ago

1.7.3

1 year ago

1.7.2

1 year ago

1.7.1

1 year ago

1.7.0

1 year ago

1.5.2

1 year ago

1.3.2

1 year ago

1.1.2

1 year ago

1.2.20

1 year ago

1.2.23

1 year ago

1.2.24

1 year ago

1.2.21

1 year ago

1.2.22

1 year ago

1.2.27

1 year ago

1.1.16

1 year ago

1.2.28

1 year ago

1.1.15

1 year ago

1.2.25

1 year ago

1.2.26

1 year ago

1.1.19

1 year ago

1.2.29

1 year ago

1.1.18

1 year ago

1.1.17

1 year ago

1.2.30

1 year ago

1.6.8

1 year ago

1.2.31

1 year ago

1.6.7

1 year ago

1.6.6

1 year ago

1.6.5

1 year ago

1.2.34

1 year ago

1.0.11

1 year ago

1.2.35

1 year ago

1.0.10

1 year ago

1.2.32

1 year ago

1.2.33

1 year ago

1.2.38

1 year ago

1.0.15

1 year ago

1.2.39

1 year ago

1.0.14

1 year ago

1.2.36

1 year ago

1.0.13

1 year ago

1.2.37

1 year ago

1.0.12

1 year ago

1.0.3

1 year ago

1.0.2

1 year ago