1.0.6 • Published 2 years ago

@brooks-blake/auth v1.0.6

Weekly downloads
-
License
ISC
Repository
-
Last release
2 years ago

BROOKS AND BLAKE V1 AUTH API '!'

This package help to simplify authentication system and error handling

Functions

/errors/bad-request-error /errors/custom-error /errors/database-connection-error /errors/not-authorized-error /errors/not-found-error /errors/request-validation-error /middlewares/role-base /middlewares/current-user /middlewares/error-handler /middlewares/require-auth /middlewares/validate-request

Error Functions

BadRequestError

  • To handle bad request CustomError
  • To handle a custom error message DatabaseConnectionError
  • To handle error on database NotAuthorizedError
  • To handle not authorize activity NotFoundError
  • To handle a not found error RequestValidationError

Error Middleware

errorHandler

  • To be implemented at the root file

Auth middlewares

currentUser

  • To get the current authenticated user data requireAuth
  • To secure a route to only be access by authenticated user roleBased
  • To secure a route to only be access by a user with asigned role ( will take array of roles to allow)

Request Validation Middleware

validateRequest

  • To handle request validation

Use case for role base for authentication

Import the roleBased function and pass it as a middleware.
import {  BadRequestError, roleBased, currentUser, requireAuth, validateRequest } from '@brooks-blake/auth';
import express, { Request, Response } from 'express';
import { body } from 'express-validator';
import jwt from 'jsonwebtoken';

import { Password } from '../../../services/password';
import {  BadRequestError, roleBased, currentUser, requireAuth, validateRequest } from '@brooks-blake/auth';
import { dynamo } from '../../../config/db';
import { UserManager } from '../../../services/user-manager';
import { EmailAttrs, TokenAttrs } from '../../../interface';
import { Role } from '../../../enums'

const router = express.Router();

router.post(
  '/api/users/set-password',
  [
    body('email').isEmail().withMessage('Email must be valid'),

    body('password')
      .trim()
      .isLength({ min: 4, max: 20 })
      .withMessage('Password must be between 4 and 20 character'),
  ],

  validateRequest,
  currentUser,
  requireAuth,
  roleBased([Role.CONTENT_MANAGER, Role.ACCREDITATION_MANAGER, Role.FRANCHISE_MANAGER, Role.GAMETIME_MANAGER, Role.MASTERCLASS_MANAGER, Role.MATCH_MANAGER,
    Role.STORE_MANAGER, Role.SUPER_ADMIN, Role.TEAM_MANAGER, Role.UNIFEST_MANAGER, Role.VOLUNTEER_MANAGER]),
  async (req: Request, res: Response) => {
    try {
      const TABLE_NAME = "User"
      const { email, password } = req.body;
      var params = {
        TableName : TABLE_NAME,
        KeyConditionExpression: "email = :email",
        ExpressionAttributeValues: {
            ":email": email
        }
      };
      
      const existingUser = await dynamo.query(params).promise()
    if (existingUser.Count! < 0) throw new BadRequestError('Error occured')

    /* authorization here */
    const hashed = await Password.toHash(password);
    dynamo.update({
      TableName: TABLE_NAME,
      Key: {email},
      UpdateExpression: "SET password = :pass",
      ExpressionAttributeValues: {
        ":pass": hashed,
      },
    })
    res
      .status(201)
      .send({ data: existingUser.Items![0], message: 'New Password has been set' });
    } catch (error) {
      
    }
    
  },
);

export { router as setPasswordRouter };

Use cases for validating

import { validateRequest, BadRequestError } from '@brooks-blake/auth'


import { body } from 'express-validator';
import jwt from 'jsonwebtoken';

import { validateRequest, BadRequestError } from '@brooks-blake/auth';
import { dynamo } from '../../../config/db';
import { Status } from '../../../enums';


const router = express.Router();

router.post(
  '/api/users/verify-email',
  [body('email').isEmail().withMessage('Email must be valid')],
  validateRequest,
  async (req: Request, res: Response) => {
    try {

      const TABLE_NAME = "User"
      const { email, code } = req.body;
      var params = {
        TableName : TABLE_NAME,
        KeyConditionExpression: "email = :email",
        ExpressionAttributeValues: {
            ":email": email
        }
      };
      
      const response = await dynamo.query(params).promise()
      if ( response.Count! < 1) throw new BadRequestError('Invalid credential');
    
      const user: any = response.Items![0]

    if (user.code === code) {
      dynamo.update({
        TableName: TABLE_NAME,
        Key: {email},
        UpdateExpression: "SET status = :status",
        ExpressionAttributeValues: {
          ":status": Status.ACTIVE,
          
        },
      })
     
      res
        .status(201)
        .send({ message: 'Email has been verified' });

    } else {
      throw new BadRequestError('Invalid OTP: Try Again');
    }
      
    } catch (error) {
      throw new BadRequestError('Unknown Error');
    }
    
  }

);

export { router as EmailVerify };