Skip to content

Commit

Permalink
Merge branch 'develop' into 187354251-ft-update-password
Browse files Browse the repository at this point in the history
  • Loading branch information
P-Rwirangira committed May 2, 2024
2 parents 8d4ac51 + 512caa3 commit eaba3b6
Show file tree
Hide file tree
Showing 9 changed files with 138 additions and 39 deletions.
6 changes: 5 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,8 @@ GOOGLE_CALLBACK_URL = ""
# CLOUDINARY CONFIGURATION
CLOUDINARY_NAME=""
CLOUDINARY_KEY=""
CLOUDINARY_SECRET=""
CLOUDINARY_SECRET=""

#USER ADMIN CREDENTIALS
ADMIN_PASSWORD=""
ADMIN_PHONE=""
12 changes: 5 additions & 7 deletions src/controllers/authController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@
import { Request, Response, NextFunction } from 'express';
import passport from 'passport';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcrypt';
import User, { UserAttributes } from '../database/models/user';
import { sendInternalErrorResponse, validateFields } from '../validations';
import logger from '../logs/config';
import { UUID } from 'crypto';
import { passwordCompare, passwordEncrypt } from '../helpers/encrypt';

const authenticateViaGoogle = (req: Request, res: Response, next: NextFunction) => {
passport.authenticate('google', (err: unknown, user: UserAttributes | null) => {
Expand Down Expand Up @@ -74,7 +73,7 @@ const login = async (req: Request, res: Response): Promise<void> => {
}

// Verify password
const passwordValid = await bcrypt.compare(password, user.password);
const passwordValid = await passwordCompare(password, user.password);
if (!passwordValid) {
logger.error('Invalid credentials');
res.status(404).json({ ok: false, message: 'Invalid credentials' });
Expand Down Expand Up @@ -102,12 +101,12 @@ const updatePassword = async (req: Request, res: Response): Promise<void> => {

// Access decoded user information from the request object
const user = req.user as {
id: UUID;
id: string;
password: string;
};

// Check if old password matches with the given one
const match = await bcrypt.compare(oldPassword, user.password);
const match = await passwordCompare(oldPassword, user.password);
if (!match) {
res.status(400).json({
ok: false,
Expand All @@ -117,8 +116,7 @@ const updatePassword = async (req: Request, res: Response): Promise<void> => {
}

// Generate salt and hash new password
const saltRound = await bcrypt.genSalt(10);
const hashedNewPassword = await bcrypt.hash(newPassword, saltRound);
const hashedNewPassword = await passwordEncrypt(newPassword);

// Update user's password
await User.update(
Expand Down
5 changes: 2 additions & 3 deletions src/controllers/userController.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Request, Response } from 'express';
import bcrypt from 'bcrypt';
import User from '../database/models/user';
import logger from '../logs/config';
import { userToken } from '../helpers/token.generator';
Expand All @@ -8,6 +7,7 @@ import * as jwt from 'jsonwebtoken';
import Role from '../database/models/role';
import { sendEmail } from '../helpers/send-email';
import { sendInternalErrorResponse, validateEmail, validateFields, validatePassword } from '../validations';
import { passwordEncrypt } from '../helpers/encrypt';

// Function for user signup
export const signupUser = async (req: Request, res: Response) => {
Expand Down Expand Up @@ -41,8 +41,7 @@ export const signupUser = async (req: Request, res: Response) => {
return res.status(400).json({ ok: false, error: 'Email is already used, Login to continuue' });
}

const saltRound = await bcrypt.genSalt(10);
const hashPassword = await bcrypt.hash(password, saltRound);
const hashPassword = await passwordEncrypt(password);

const newUser = await User.create({
firstName,
Expand Down
7 changes: 7 additions & 0 deletions src/database/seeders/20240427082911-create-default-role.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@ module.exports = {
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: '6ef1e121-304a-4f08-ad4e-cd07f9578b52',
name: 'admin',
displayName: 'Admin Role',
createdAt: new Date(),
updatedAt: new Date(),
},
]);
},

Expand Down
34 changes: 34 additions & 0 deletions src/database/seeders/20240501163745-User.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/* eslint-disable @typescript-eslint/no-var-requires */
'use strict';
const { v4: uuidv4 } = require('uuid');

/** @type {import('sequelize-cli').Seed} */
module.exports = {
async up(queryInterface, Sequelize) {
return queryInterface.bulkInsert(
'Users',
[
{
id: uuidv4(),
firstName: 'admin',
lastName: '',
email: process.env.EMAIL,
password:
'$2b$10$ZCgzouXesg4Zqgj22u7ale5aAOJzmjfOchCpMlSgBMV8o2f.zdYUq',
gender: 'not specified',
phoneNumber: process.env.ADMIN_PHONE,
verified: true,
createdAt: new Date(),
updatedAt: new Date(),
status: 'active',
RoleId: '6ef1e121-304a-4f08-ad4e-cd07f9578b52', // Replace with the actual RoleId
},
],
{}
);
},

async down(queryInterface, Sequelize) {
return queryInterface.bulkDelete('Users', null, {});
},
};
32 changes: 22 additions & 10 deletions src/docs/manageUserStatusDocs.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,16 @@ paths:
put:
summary: Deactivate a user account
description: Deactivates a user account and sends an email notification.
security:
- bearerAuth: []
parameters:
- in: path
name: userId
required: true
description: The ID of the user to deactivate
schema:
type: string
example: "123456789"
example: '123456789'
responses:
'200':
description: Success response
Expand All @@ -26,8 +28,8 @@ paths:
type: string
description: The status of the operation ('OK' for success)
example:
message: "User deactivated successfully"
status: "OK"
message: 'User deactivated successfully'
status: 'OK'
'400':
description: Bad request
content:
Expand All @@ -39,7 +41,7 @@ paths:
type: string
description: A message indicating the error
example:
message: "Invalid request parameters"
message: 'Invalid request parameters'
'500':
description: Internal server error
content:
Expand All @@ -51,11 +53,13 @@ paths:
type: string
description: A message indicating the error
example:
message: "Internal server error occurred"
message: 'Internal server error occurred'

/api/users/activate/{userId}:
put:
summary: Activate a user account
sercurity:
- bearerAuth: []
description: Activates a user account and sends an email notification.
parameters:
- in: path
Expand All @@ -64,7 +68,7 @@ paths:
description: The ID of the user to activate
schema:
type: string
example: "123456789"
example: '123456789'
responses:
'200':
description: Success response
Expand All @@ -80,8 +84,8 @@ paths:
type: string
description: The status of the operation ('OK' for success)
example:
message: "User activated successfully"
status: "OK"
message: 'User activated successfully'
status: 'OK'
'400':
description: Bad request
content:
Expand All @@ -93,7 +97,7 @@ paths:
type: string
description: A message indicating the error
example:
message: "Invalid request parameters"
message: 'Invalid request parameters'
'500':
description: Internal server error
content:
Expand All @@ -105,4 +109,12 @@ paths:
type: string
description: A message indicating the error
example:
message: "Internal server error occurred"
message: 'Internal server error occurred'
security:
- bearerAuth: []
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
32 changes: 25 additions & 7 deletions src/docs/roles.yaml
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
tags:
tags:
- name: Roles
description: The role API test
paths:
/api/roles:
get:
summary: Get a list of all roles
security:
- bearerAuth: []
tags:
- Roles
description: This tests the get request of roles
responses:
200:
description: Role successfully found
500:
description: Role can't be found
description: Role can't be found

post:
summary: Add the role
security:
- bearerAuth: []
tags:
- Roles
description: This add a new role to the role list
Expand All @@ -39,6 +43,8 @@ paths:
/api/roles/{id}:
get:
summary: Get a single role
security:
- bearerAuth: []
tags:
- Roles
parameters:
Expand All @@ -47,12 +53,14 @@ paths:
required: true
type: string
responses:
404:
404:
description: Role could not be found
200:
description: Role successfully found
delete:
summary: Find a role and delete it by id
security:
- bearerAuth: []
tags:
- Roles
parameters:
Expand All @@ -61,14 +69,16 @@ paths:
required: true
type: string
responses:
404:
404:
description: Role could not be found
200:
description: Role successfully deleted
500:
description: Role can't be deleted successfully
description: Role can't be deleted successfully
patch:
summary: Find a role by id and update it
security:
- bearerAuth: []
tags:
- Roles
parameters:
Expand All @@ -77,9 +87,17 @@ paths:
required: true
type: string
responses:
404:
404:
description: Role could not be found
200:
description: Role successfully updated
500:
description: Role can't be updated successfully
description: Role can't be updated successfully
security:
- bearerAuth: []
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
Loading

0 comments on commit eaba3b6

Please sign in to comment.