diff --git a/.env.sample b/.env.sample index 7c6a231..6d767bf 100644 --- a/.env.sample +++ b/.env.sample @@ -1,8 +1,10 @@ +APP_URL="http://localhost:3000" +APP_FRONT="http://localhost:3100" PORT=3000 MONGO_URI="mongodb://archetype:archetype@localhost:27501/" DBNAME="NEMBBMS" VERIFICATION_CODE_LIFE_TIME=10 -RESEND_VC_LIFE_TIME=2 JWT_SECRET="c44a89a1a70313e49ee9a9155364cdb8" +JWT_REFRESH="69b6a16a472a429ba0b11cf6504f2794" SENDGRID_API_KEY="SG.your_api_key" RECAPTCHA_KEY="google_recpatcha_key" \ No newline at end of file diff --git a/.github/workflows/telegram-notifier.yml b/.github/workflows/telegram-notifier.yml index b6d6dc8..1db873f 100644 --- a/.github/workflows/telegram-notifier.yml +++ b/.github/workflows/telegram-notifier.yml @@ -24,5 +24,5 @@ jobs: token: ${{ secrets.token }} # savethe bot token at settings/secrets with name: token to: ${{ secrets.to }} # save your chat id at settings/secrets with name: chat thread_id: ${{secrets.threadid}} # set this for sending message in thread or group topic - disable_web_page_preview: false # set this to true to disable link previw in telegram + disable_web_page_preview: true # set this to true to disable link previw in telegram disable_notification: false # set tjis true to send message in silet mode diff --git a/README.md b/README.md index dbfc33f..bd62cb3 100644 --- a/README.md +++ b/README.md @@ -113,8 +113,6 @@ first make sure have the `docker` engine installed and runing on your machine { return next(); } const extractedErrors = []; - errors.array().map(err => extractedErrors.push({ [err.param]: err.msg })); + errors.array().map(err => extractedErrors.push({ [err.path]: err.msg })); return res.status(422).json({ errors: extractedErrors, }); @@ -35,7 +35,8 @@ export const mobileValidator = body('mobile').matches(mobilePattern, 'g').withMe export const emailValidator = body('email').isEmail().withMessage('please enter valid email address'); -export const codeValidator = body('code').exists({ checkFalsy: true, checkNull: true }).withMessage('code is not valid'); +export const paramCodeValidator = param('code').exists({ checkFalsy: true, checkNull: true }).withMessage('code is not valid'); +export const bodyCodeValidator = body('code').exists({ checkFalsy: true, checkNull: true }).withMessage('code is not valid'); export const captchaValidator = body('captcha').exists({ checkFalsy: true, checkNull: true }).withMessage('Captcha is not valid'); diff --git a/config.js b/config.js index ee2323e..6708540 100644 --- a/config.js +++ b/config.js @@ -6,11 +6,12 @@ const env = process.env; const logTypes = process.env.NODE_ENV !== 'test' ? ['error', 'info', 'warn', 'log', 'success', 'validation'] : []; export default { LOG_TYPES: logTypes, + APP_URL: env.APP_URL, + APP_FRONT: env.APP_FRONT, PORT: env.PORT, MONGO_URI: env.MONGO_URI, DBNAME: env.DBNAME, VERIFICATION_CODE_LIFE_TIME: env.VERIFICATION_CODE_LIFE_TIME, - RESEND_VC_LIFE_TIME: env.RESEND_VC_LIFE_TIME, // AUTH_TABLE_NAME: env.AUTH_TABLE_NAME, JWT_SECRET: env.JWT_SECRET, SENDGRID_API_KEY: env.SENDGRID_API_KEY, diff --git a/modules/user/controller.js b/modules/user/controller.js index 90b612d..3594b13 100644 --- a/modules/user/controller.js +++ b/modules/user/controller.js @@ -27,6 +27,7 @@ class userController { const userEmail = email.toLowerCase(); const userName = name.toLowerCase(); const userLastname = lastName.toLowerCase(); + const userPassword = this.sha256(password); try { @@ -40,7 +41,7 @@ class userController { name: userName, lastName: userLastname, verificationCode, - password + password: userPassword }); if (process.env.NODE_ENV !== 'test') { @@ -81,30 +82,37 @@ class userController { const userEmail = req.body.email.toLowerCase(); const userInfo = await this.model.findEntityByParams({ email: userEmail }); if (_.get(userInfo, 'verified') || !userInfo) { - res.send({ status: 'failed' }); + return res.send({ status: 'failed' }); } else { const vcDate = new Date(userInfo.verificationCodeDate); vcDate.setMinutes(vcDate.getMinutes() + config.VERIFICATION_CODE_LIFE_TIME); let verificationCodeDate = userInfo.verificationCodeDate; - if (vcDate.getTime() < Date.now()) { + if ( + (process.env.NODE_ENV !== 'test' && vcDate.getTime() < Date.now()) || + process.env.NODE_ENV === 'test') { const verificationCode = this.generateVerificationCode(); verificationCodeDate = new Date(); await this.model.updateEntityByModel(userInfo, { verificationCode, verificationCodeDate }); - const templateTags = [ - { name: "__USERNAME", value: userInfo.email }, - { name: "__CONFIRMATION_URL", value: verificationCode }, // Todo: #44 is here - ]; - SendGrid.sendMailByTemplate( - 'Confirm your email address', - 'signup-confirmation', - templateTags, - [newUser.email], - 'no-reply@site.com' - ); + if (process.env.NODE_ENV !== 'test') { + const key = this.sha256(verificationCode); + const verificationURL = `${config.APP_URL}/user/verify/${key}`; + const templateTags = [ + { name: "__USERNAME", value: userInfo.email }, + { name: "__CONFIRMATION_URL", value: verificationURL }, + ]; + + SendGrid.sendMailByTemplate( + 'Confirm your email address', + 'signup-confirmation', + templateTags, + [newUser.email], + 'no-reply@site.com' + ); + } } res.send({ status: 'success', verificationCodeDate }); } @@ -120,21 +128,22 @@ class userController { */ verify = async (req, res) => { try { - const code = req.body.code; - const userInfo = await this.model.findEntityByParams({ - email: req.body.email.toLowerCase(), - verificationCode: code - }); + let frontURL = `${config.APP_FRONT}/confirmation/`; + const code = req.params.code; + const userInfo = await this.model.findEntityByParams({ verificationCode: code }); if (userInfo === null) { - return res.send({ verified: false }); + frontURL += `failed`; + return res.redirect(frontURL); } const vcDate = new Date(userInfo.verificationCodeDate); vcDate.setMinutes(vcDate.getMinutes() + config.VERIFICATION_CODE_LIFE_TIME); - if (userInfo.verificationCode === code && vcDate.getTime() > Date.now()) { - res.send({ verified: true, email: userInfo.email, code: userInfo.verificationCode }); + if (vcDate.getTime() > Date.now()) { + await this.model.updateEntityByModel(userInfo, { verified: true }); + frontURL += `success`; } else { - res.send({ verified: false }); + frontURL += `failed`; } + res.redirect(frontURL); } catch (error) { this.errorHandler(error, res); } @@ -146,23 +155,18 @@ class userController { * @param res * @param next */ - userAuth = async ({ body: { email, password } }, res, next) => { + userAuth = async (req, res, next) => { try { + const { body: { email, password } } = req; const userEmail = email.toLowerCase(); const pwd = this.sha256(password); let userInfo = await this.model.findEntityByParams({ email: userEmail, password: pwd }, { 'password': false }); if (userInfo === null) { - return res.status(400).send({ - errorCode: 'AUTHFAILED', - additionalInformation: { - message: 'username or password is wrong!' - } - }); + return res.send({ status: 'failed', message: 'username or password is wrong!' }); } - userInfo = userInfo.toObject(); - const token = await Auth.sign(userInfo); + const token = await Auth.sign(userInfo.toObject()); res.set('Authorization', token); - res._user = userInfo; + req._user = userInfo; next(); } catch (error) { this.errorHandler(error, res); @@ -174,7 +178,7 @@ class userController { * @param req * @param res */ - login = async ({ _user: { name = ``, lastName = ``, email = `` } }, res) => { + login = async ({ _user: { name = ``, lastName = ``, email = `` } = {} }, res) => { res.send({ name, lastName, email }); } @@ -183,21 +187,15 @@ class userController { * @param req * @param res */ - changeUserPassword = async ({ _user, body: { password, new: newPWD } }, res) => { + changeUserPassword = async (req, res) => { try { - const userInfo = await this.model.findEntityByParams({ _id: _user._id }); - const currentPassword = this.sha256(password); - const newPassword = this.sha256(newPWD); - if (currentPassword === userInfo.password) { - await this.model.updateEntityByModel(userInfo, { password: newPassword }); - res.send({ status: true }); + const { _user, body: { password, new: newPWD } = {} } = {} = req; + const userInfo = await this.model.findEntityByParams({ email: _user.email }); + if (!!userInfo && this.sha256(password) === userInfo.password) { + await this.model.updateEntityByModel(userInfo, { password: this.sha256(newPWD) }); + res.send({ status: 'success' }); } else { - res.status(400).send({ - errorCode: 'VALIDATIONFAILED', - additionalInformation: { - message: 'current password is wrong!' - } - }); + res.send({ status: 'failed', message: 'current password is wrong' }); } } catch (error) { this.errorHandler(error, res); @@ -229,17 +227,12 @@ class userController { const userEmail = email.toLowerCase(); const userInfo = await this.model.findEntityByParams({ email: userEmail }, { password: false }); if (userInfo === null) { - return res.status(400).send({ - errorCode: 'AUTHFAILED', - additionalInformation: { - message: 'username is wrong' - } - }); + return res.send({ status: 'failed', message: 'user does not exists' }); } const vcDate = new Date(userInfo.verificationCodeDate); vcDate.setMinutes(vcDate.getMinutes() + config.VERIFICATION_CODE_LIFE_TIME); if (Date.now() < vcDate.getTime()) { - res.send({ success: true, verificationCodeDate: userInfo.verificationCodeDate }); + res.send({ status: 'success', verificationCodeDate: userInfo.verificationCodeDate }); } else if (userInfo.verified === true) { const verificationCode = this.generateVerificationCode(); const verificationCodeDate = new Date(); @@ -247,28 +240,24 @@ class userController { verificationCode, verificationCodeDate }); + if (process.env.NODE_ENV !== 'test') { + const templateTags = [ + { name: "__USERNAME", value: userInfo.email }, + { name: "__RESET_URL", value: verificationCode }, // Todo: #44 is here + ]; - const templateTags = [ - { name: "__USERNAME", value: userInfo.email }, - { name: "__RESET_URL", value: verificationCode }, // Todo: #44 is here - ]; - - SendGrid.sendMailByTemplate( - 'Forgot your password?', - 'forget-password', - templateTags, - [newUser.email], - 'no-reply@site.com' - ); + SendGrid.sendMailByTemplate( + 'Forgot your password?', + 'forget-password', + templateTags, + [newUser.email], + 'no-reply@site.com' + ); + } - res.send({ success: true, verificationCodeDate }); + res.send({ success: 'success', verificationCodeDate }); } else { - res.status(400).send({ - errorCode: 'NOTVERIFIED', - additionalInformation: { - message: 'user not verified!' - } - }); + res.send({ status: 'failed' }); } } catch (error) { this.errorHandler(error, res); @@ -285,26 +274,16 @@ class userController { const userEmail = email.toLowerCase(); const userInfo = await this.model.findEntityByParams({ email: userEmail }); if (userInfo === null) { - return res.status(400).send({ - errorCode: 'AUTHFAILED', - additionalInformation: { - message: 'username is wrong!' - } - }); + return res.send({ status: 'failed', message: 'user does not exists' }); } const secureKeyDate = new Date(userInfo.verificationCodeDate); secureKeyDate.setMinutes(secureKeyDate.getMinutes() + config.VERIFICATION_CODE_LIFE_TIME); if (userInfo.verificationCode === code && userInfo.verified === true && secureKeyDate.getTime() > Date.now()) { - password = (password) ? this.sha256(password).toString() : ''; - await this.model.updateEntityByModel(userInfo, { password }); - res.send({ success: true }); + const newPassword = (password) ? this.sha256(password).toString() : ''; + await this.model.updateEntityByModel(userInfo, { password: newPassword }); + res.send({ status: 'success' }); } else { - res.status(400).send({ - errorCode: 'INVALIDCODE', - additionalInformation: { - message: 'verification code is not valid!' - } - }); + res.send({ status: 'failed', message: 'invalid or expired request' }); } } catch (error) { this.errorHandler(error, res); diff --git a/modules/user/route.js b/modules/user/route.js index bd21cf7..5f1de33 100644 --- a/modules/user/route.js +++ b/modules/user/route.js @@ -19,7 +19,7 @@ class usersRouter { userRouter.post('/', [...validator.signup()], userCtrl.signup); userRouter.post('/resendVerification', [...validator.resendVerification()], userCtrl.resendVerification); - userRouter.post('/verify', [...validator.verify()], userCtrl.verify); + userRouter.get('/verify/:code', [...validator.verify()], userCtrl.verify); userRouter.post('/login', [...validator.login()], userCtrl.userAuth, userCtrl.login); userRouter.post('/changePassword', [Auth.isLoggedIn, ...validator.changePassword()], userCtrl.changeUserPassword); userRouter.post('/updateProfile', [Auth.isLoggedIn, ...validator.updateProfile()], userCtrl.updateProfile); diff --git a/modules/user/user.test.js b/modules/user/user.test.js index 25c9ffe..1e443fe 100644 --- a/modules/user/user.test.js +++ b/modules/user/user.test.js @@ -1,8 +1,13 @@ import supertest from 'supertest'; import app from '../../app.js'; +import config from '../../config.js'; +import { describe } from 'jest-circus'; const request = supertest(app); +import { ModelFactory } from '../../common/index.js'; +import { UserModel } from './schema.js'; const _pawssword = 'A7_c1UzPO.rO'; +let JWTToken = null; const newUserData = { email: 'sample@example.com', name: 'Ethan', @@ -11,18 +16,22 @@ const newUserData = { captcha: 'xxx' }; +const userModel = new ModelFactory(UserModel); + describe('User Module', () => { + JWTToken = null; // we reset here + /** * positive scenario * will not check Recaptcha & will not send any email */ test('POST /user should create a new user', async () => { - const newUser = await request.post('/user').send(newUserData); + const req = await request.post('/user').send(newUserData); - expect(newUser.status).toBe(200); - expect(newUser.body).toHaveProperty('username'); - expect(newUser.body).toHaveProperty('verificationCodeDate'); + expect(req.status).toBe(200); + expect(req.body).toHaveProperty('username'); + expect(req.body).toHaveProperty('verificationCodeDate'); }); /** @@ -30,20 +39,219 @@ describe('User Module', () => { * will check for duplication */ test('POST /user raise duplication error', async () => { - const duplicateUser = await request.post('/user').send(newUserData); + const req = await request.post('/user').send(newUserData); + + expect(req.status).toBe(422); + expect(req.body).toHaveProperty('errorMessage'); + expect(req.body.errorMessage).toEqual('user Already Registered.'); + }); + + test('POST /user raise validation error', async () => { + const req = await request.post('/user').send(); + + expect(req.status).toBe(422); + expect(req.body).toHaveProperty('errors'); + }); + + /** + * positive scenario - depeneded on previous test actions + */ + test('POST /user/resendVerification update user verification code', async () => { + const req = await request.post('/user/resendVerification').send({ email: newUserData.email }); + + expect(req.status).toBe(200); + expect(req.body).toHaveProperty('status'); + expect(req.body).toHaveProperty('verificationCodeDate'); + expect(req.body.status).toEqual('success'); + }); + + /** + * negative scenario + */ + test('POST /user/resendVerification fail to update user verification code for not existing user', async () => { + const req = await request.post('/user/resendVerification').send({ email: 'noExists@user.com' }); + expect(req.status).toBe(200); + expect(req.body).toHaveProperty('status'); + expect(req.body.status).toEqual('failed'); + }); + + test('POST /user/resendVerification should fail due to input validation', async () => { + const req = await request.post('/user/resendVerification').send(); + expect(req.status).toBe(422); + expect(req.body).toHaveProperty('errors'); + }); + + test('POST /user/resendVerification should fail because user is already verified', async () => { + const userInfo = await userModel.findEntityByParams({ email: newUserData.email }); + await userModel.updateEntityByModel(userInfo, { verified: true }); + const req = await request.post('/user/resendVerification').send({ email: newUserData.email }); + expect(req.status).toBe(200); + expect(req.body).toHaveProperty('status'); + expect(req.body.status).toEqual('failed'); + await userModel.updateEntityByModel(userInfo, { verified: false }); + }); + + /** + * negative scenarios + */ + test('POST /user/verify/ should fail due to input validation', async () => { + const req = await request.get('/user/verify/uwjdyuwjk').send(); + expect(req.status).toBe(302); + expect(req.headers).toHaveProperty('location'); + expect(req.headers.location).toEqual(`${config.APP_FRONT}/confirmation/failed`); + }); - expect(duplicateUser.status).toBe(422); - expect(duplicateUser.body).toHaveProperty('errorMessage'); - expect(duplicateUser.body.errorMessage).toEqual('user Already Registered.'); + /** + * positive scenario + */ + test('POST /user/verify/ should verify the user', async () => { + const { verificationCode } = await userModel.findEntityByParams({ email: newUserData.email }); + const req = await request.get(`/user/verify/${verificationCode}`).send(); + expect(req.status).toBe(302); + expect(req.headers).toHaveProperty('location'); + expect(req.headers.location).toEqual(`${config.APP_FRONT}/confirmation/success`); + }); + + /** + * negative scenarios + */ + test('POST /user/forgetPassword should fail submit request', async () => { + const req = await request.post(`/user/forgetPassword`).send(); + expect(req.status).toBe(422); + expect(req.body).toHaveProperty('errors'); + }); + + test('POST /user/forgetPassword should fail submit request', async () => { + const req = await request.post(`/user/forgetPassword`).send({ email: 'noSuch@user.com' }); + expect(req.status).toBe(200); + expect(req.body).toHaveProperty('status'); + expect(req.body.status).toEqual('failed'); + }); + + test('POST /user/forgetPassword should successfully submit request', async () => { + const req = await request.post(`/user/forgetPassword`).send({ email: newUserData.email }); + expect(req.status).toBe(200); + expect(req.body).toHaveProperty('status'); + expect(req.body.status).toEqual('success'); + }); + + /** + * negative scenarios + */ + test('POST /user/setNewPassword should fail submit request', async () => { + const req = await request.post(`/user/setNewPassword`).send(); + expect(req.status).toBe(422); + expect(req.body).toHaveProperty('errors'); + }); + + test('POST /user/setNewPassword should fail submit request', async () => { + const req = await request.post(`/user/setNewPassword`).send({ email: 'wrong@email.com', code: 'wrong_Code', password: 'abcd1234' }); + expect(req.status).toBe(200); + expect(req.body).toHaveProperty('status'); + expect(req.body.status).toEqual('failed'); + expect(req.body).toHaveProperty('message'); + expect(req.body.message).toEqual('user does not exists'); + }); + + test('POST /user/setNewPassword should fail submit request', async () => { + const req = await request.post(`/user/setNewPassword`).send({ email: newUserData.email, code: 'WrongCode', password: 'abcd1234' }); + expect(req.status).toBe(200); + expect(req.body).toHaveProperty('status'); + expect(req.body.status).toEqual('failed'); + expect(req.body).toHaveProperty('message'); + expect(req.body.message).toEqual('invalid or expired request'); + }); + + /** + * positive scenario + */ + test('POST /user/setNewPassword should successfully submit request', async () => { + const { verificationCode } = await userModel.findEntityByParams({ email: newUserData.email }); + const req = await request.post(`/user/setNewPassword`).send({ email: newUserData.email, code: verificationCode, password: 'abcd1234' }); + expect(req.status).toBe(200); + expect(req.body).toHaveProperty('status'); + expect(req.body.status).toEqual('success'); + }); + + // note that we changed password in previous test and now it is "abcd1234" + /** + * negative scenarios + */ + test('POST /user/login should fail to log in', async () => { + + const req = await request.post(`/user/login`).send(); + expect(req.status).toBe(422); + expect(req.body).toHaveProperty('errors'); + }); + + test('POST /user/login should fail to log in - worng password', async () => { + const req = await request.post(`/user/login`).send({ email: newUserData.email, password: 'wrongOne' }); + expect(req.status).toBe(200); + expect(req.body).toHaveProperty('status'); + expect(req.body.status).toEqual('failed'); + expect(req.body).toHaveProperty('message'); + expect(req.body.message).toEqual('username or password is wrong!'); + }); + + test('POST /user/login should fail to log in - wrong email', async () => { + const req = await request.post(`/user/login`).send({ email: 'noExists@user.com', password: 'abcd1234' }); + expect(req.status).toBe(200); + expect(req.body).toHaveProperty('status'); + expect(req.body.status).toEqual('failed'); + expect(req.body).toHaveProperty('message'); + expect(req.body.message).toEqual('username or password is wrong!'); + }); + + /** + * positive scenario + */ + test('POST /user/login should sucessfully to log in', async () => { + const req = await request.post(`/user/login`).send({ email: newUserData.email, password: 'abcd1234' }); + expect(req.status).toBe(200); + expect(req.headers).toHaveProperty('authorization'); + expect(req.body).toHaveProperty('name'); + expect(req.body).toHaveProperty('email'); + expect(req.body).toHaveProperty('lastName'); + JWTToken = req.header['authorization']; + }); + + test('POST /user/changePassword should fail to action - unathorized', async () => { + const req = await request.post(`/user/changePassword`).send(); + expect(req.status).toBe(401); + }); + + test('POST /user/changePassword should fail to action - validation failure', async () => { + const req = await request.post(`/user/changePassword`).set('Authorization', `Basic ${JWTToken}`).send(); + expect(req.status).toBe(422); + expect(req.body).toHaveProperty('errors'); + }); + + test('POST /user/changePassword should fail to action - wrong pssword', async () => { + const req = await request.post(`/user/changePassword`).set('Authorization', `Basic ${JWTToken}`).send({ + password: 'wrongone', + new: newUserData.password + }); + expect(req.status).toBe(200); + expect(req.body).toHaveProperty('status'); + expect(req.body.status).toEqual('failed'); + }); + + /** + * positive scenario + */ + test('POST /user/changePassword should succed to action', async () => { + const req = await request.post(`/user/changePassword`).set('Authorization', `Basic ${JWTToken}`).send({ + password: 'abcd1234', + new: newUserData.password + }); + expect(req.status).toBe(200); + expect(req.body).toHaveProperty('status'); + expect(req.body.status).toEqual('success'); }); // below need to be implemented - // '/resendVerification' - // '/verify' - // '/login' - // '/changePassword' + // '/updateProfile' - // '/forgetPassword' - // '/setNewPassword' + // '/getProfile' }); diff --git a/modules/user/validator.js b/modules/user/validator.js index 6f81603..e42363c 100644 --- a/modules/user/validator.js +++ b/modules/user/validator.js @@ -1,5 +1,5 @@ import { body } from 'express-validator'; -import { V, emailValidator, mobileValidator, codeValidator, nameValidator, lastNameValidator, passwordValidaotr, captchaValidator } from '../../common/index.js'; +import { V, emailValidator, paramCodeValidator, bodyCodeValidator, nameValidator, lastNameValidator, passwordValidaotr, captchaValidator } from '../../common/index.js'; export default { signup: () => { @@ -15,7 +15,7 @@ export default { return V([emailValidator]); }, verify: () => { - return V([emailValidator, codeValidator]); + return V([paramCodeValidator]); }, login: () => { return V([emailValidator, passwordValidaotr]); @@ -34,6 +34,6 @@ export default { return V([emailValidator]); }, setNewPassword: () => { - return V([emailValidator, codeValidator, passwordValidaotr]); + return V([emailValidator, bodyCodeValidator, passwordValidaotr]); } }; diff --git a/package.json b/package.json index b6eca49..297a1aa 100644 --- a/package.json +++ b/package.json @@ -48,7 +48,7 @@ "dotenv": "^16.0.3", "express": "^4.18.2", "express-validator": "^7.0.1", - "jsonwebtoken": "^9.0.0", + "jsonwebtoken": "^9.0.1", "lodash": "^4.17.21", "mjml": "^4.14.1", "mongoose": "^7.0.4", @@ -68,4 +68,4 @@ "nodemon": "^2.0.22", "supertest": "^6.3.3" } -} \ No newline at end of file +} diff --git a/services/jwt.js b/services/jwt.js index be13570..bad4c46 100644 --- a/services/jwt.js +++ b/services/jwt.js @@ -1,5 +1,5 @@ import config from '../config.js'; -import * as jsonwebtoken from 'jsonwebtoken'; +import JsonWebToken from 'jsonwebtoken'; // JWT provider options @@ -40,7 +40,7 @@ export class JWT { */ sign = async (payload, options) => { const jti = payload.jti || generateId(10); - const token = jsonwebtoken.sign({ ...payload, jti }, config.JWT_SECRET, Object.assign({ expiresIn: '1d' }, options)); + const token = JsonWebToken.sign({ ...payload, jti }, config.JWT_SECRET, Object.assign({ expiresIn: '1d' }, options)); return token; } @@ -51,7 +51,7 @@ export class JWT { * @returns */ decode(token, options) { - return jsonwebtoken.decode(token, options); + return JsonWebToken.decode(token, options); } /** @@ -62,7 +62,7 @@ export class JWT { */ async verify(token, options) { const decoded_1 = await new Promise((resolve, reject) => { - return jsonwebtoken.verify(token, config.JWT_SECRET, options, (err, decoded) => { + return JsonWebToken.verify(token, config.JWT_SECRET, options, (err, decoded) => { if (err) { return reject(err); } @@ -85,15 +85,14 @@ export class JWT { isLoggedIn = async (req, res, next) => { let tokenKey = req.get('Authorization'); if (tokenKey === undefined) { - return res.status(401).send('unAuthorized'); + return res.status(401).send(); } else { try { let tokenString = tokenKey.split(' ')[1]; req._user = await this.verify(tokenString); next(); } catch (error) { - logger.error('Authentication Failed => ', error.toString()); - return res.status(401).send('unAuthorized'); + return res.status(401).send(); } } } diff --git a/yarn.lock b/yarn.lock index 54e14cd..79f09e5 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4218,10 +4218,10 @@ json5@^2.2.2: resolved "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz" integrity sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg== -jsonwebtoken@^9.0.0: - version "9.0.0" - resolved "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.0.tgz" - integrity sha512-tuGfYXxkQGDPnLJ7SibiQgVgeDgfbPq2k2ICcbgqW8WxWLBAxKQM/ZCu/IT8SOSwmaYl4dpTFCW5xZv7YbbWUw== +jsonwebtoken@^9.0.1: + version "9.0.1" + resolved "https://registry.yarnpkg.com/jsonwebtoken/-/jsonwebtoken-9.0.1.tgz#81d8c901c112c24e497a55daf6b2be1225b40145" + integrity sha512-K8wx7eJ5TPvEjuiVSkv167EVboBDv9PZdDoF7BgeQnBLVvZWW9clr2PsQHVJDTKaEIH5JBIwHujGcHp7GgI2eg== dependencies: jws "^3.2.2" lodash "^4.17.21"