Skip to content

Commit

Permalink
Squashed commit of the following:
Browse files Browse the repository at this point in the history
commit 3e0da0c
Author: Muttaqin <[email protected]>
Date:   Fri Aug 11 00:13:20 2023 +0600

    Feat/token based authentication 2 (ISIL-ESTE#91)

    * Move .husky to the base dir.

    * Delete eslintrc.json.

    * Resolve ISIL-ESTE#71 & fix import paths for user_model .

    * token refresh & logout.

    * Add utility class auth_utils.

    * Configure cookie parser.

commit d5ff984
Author: Abdelouahab Bella <[email protected]>
Date:   Fri Jul 28 12:49:05 2023 +0100

    fix - add logo path to readme (ISIL-ESTE#86)

commit 00c882e
Author: Abdelouahab Bella <[email protected]>
Date:   Fri Jul 28 12:47:07 2023 +0100

    fix - eslint json roles -> js (ISIL-ESTE#85)

    * Update access to env

    * configure rate limiter to ignore the SSE requests

    * verify user authorities and restrictions

    * update access to env variables

    * fix - adapt testing to new functionalities

    * fix - env variables security

    * extra fix

    * fix eslint json -> js

commit f0674fb
Author: Abdelouahab Bella <[email protected]>
Date:   Fri Jul 28 11:29:11 2023 +0100

    Update app_config.js (ISIL-ESTE#84)

commit b659237
Author: Abdelouahab Bella <[email protected]>
Date:   Fri Jul 28 11:21:01 2023 +0100

    fix - Up date env variables : remove hard coded credentials  (ISIL-ESTE#83)

    * Update access to env

    * configure rate limiter to ignore the SSE requests

    * verify user authorities and restrictions

    * update access to env variables

    * fix - adapt testing to new functionalities

    * fix - env variables security

commit af609a1
Author: Abdelouahab Bella <[email protected]>
Date:   Fri Jul 28 10:41:55 2023 +0100

    Creating CONTRIBUTING.md (ISIL-ESTE#79)

commit 9254b1d
Author: Muttaqin <[email protected]>
Date:   Fri Jul 28 00:10:13 2023 +0600

    Feat/configure pre-commit hook (ISIL-ESTE#81)

    * configure pre-commit hooks.

    * Pre-commit hook test - lint & fix every .js & .json file.

commit fbb1537
Author: Abdelouahab Bella <[email protected]>
Date:   Wed Jul 26 17:47:48 2023 +0100

    fix - rate limiter & duplicated methods & env variables (ISIL-ESTE#74)

    * Update access to env

    * configure rate limiter to ignore the SSE requests

    * verify user authorities and restrictions

    * update access to env variables

commit c1894bc
Author: Abdelouahab Bella <[email protected]>
Date:   Tue Jul 25 19:59:30 2023 +0100

    add count of closed pr (ISIL-ESTE#76)

commit 8cf1209
Author: Muttaqin <[email protected]>
Date:   Wed Jul 26 00:38:42 2023 +0600

    Feat - token-based-authentication (ISIL-ESTE#75)

    * Configure linter and formatter.

    * Add configurations for access & refresh token.

    * Add token model.

    * Add functionality to generate Access & refresh token and send it to
    user.

    * save exact version of dev-dependencies.

commit 0140aa1
Author: boujrada yassine <[email protected]>
Date:   Fri Jul 21 10:44:15 2023 +0100

    Implement Sign Up Component with Next.js (ISIL-ESTE#67)

    * adding a login page but it need a auth

    * adding sign up componenet

commit e2227f9
Author: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Date:   Fri Jul 21 09:46:10 2023 +0100

     dependencies update ISIL-ESTE#69

    Bumps [word-wrap](https://github.com/jonschlinkert/word-wrap) from 1.2.3 to 1.2.4.
    - [Release notes](https://github.com/jonschlinkert/word-wrap/releases)
    - [Commits](jonschlinkert/word-wrap@1.2.3...1.2.4)

    ---
    updated-dependencies:
    - dependency-name: word-wrap
      dependency-type: indirect
    ...

    Signed-off-by: dependabot[bot] <[email protected]>
    Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

commit 19b5bf9
Author: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Date:   Fri Jul 21 09:45:40 2023 +0100

     dependencies update ISIL-ESTE#68

    Bumps [mongoose](https://github.com/Automattic/mongoose) from 6.10.4 to 6.11.3.
    - [Release notes](https://github.com/Automattic/mongoose/releases)
    - [Changelog](https://github.com/Automattic/mongoose/blob/master/CHANGELOG.md)
    - [Commits](Automattic/mongoose@6.10.4...6.11.3)

    ---
    updated-dependencies:
    - dependency-name: mongoose
      dependency-type: direct:production
    ...

    Signed-off-by: dependabot[bot] <[email protected]>
    Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

commit c6c6d61
Author: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Date:   Fri Jul 21 09:44:40 2023 +0100

     dependencies update ISIL-ESTE#65

    Bumps [semver](https://github.com/npm/node-semver) from 5.7.1 to 5.7.2.
    - [Release notes](https://github.com/npm/node-semver/releases)
    - [Changelog](https://github.com/npm/node-semver/blob/v5.7.2/CHANGELOG.md)
    - [Commits](npm/node-semver@v5.7.1...v5.7.2)

    ---
    updated-dependencies:
    - dependency-name: semver
      dependency-type: indirect
    ...

    Signed-off-by: dependabot[bot] <[email protected]>
    Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

commit dd8c55a
Merge: e2503a6 9b899d0
Author: Abdelouahab Bella <[email protected]>
Date:   Thu Jul 13 15:02:36 2023 +0100

    Bump semver from 6.3.0 to 6.3.1 in /frontend-app ISIL-ESTE#64

    Bump semver from 6.3.0 to 6.3.1 in /frontend-app ISIL-ESTE#64

commit e2503a6
Merge: 372d6ce 26702c0
Author: Abdelouahab Bella <[email protected]>
Date:   Thu Jul 13 15:01:06 2023 +0100

    Github Oauth integration ISIL-ESTE#58

    Github Oauth integration ISIL-ESTE#58

commit 9b899d0
Author: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Date:   Thu Jul 13 05:00:30 2023 +0000

    Bump semver from 6.3.0 to 6.3.1 in /frontend-app

    Bumps [semver](https://github.com/npm/node-semver) from 6.3.0 to 6.3.1.
    - [Release notes](https://github.com/npm/node-semver/releases)
    - [Changelog](https://github.com/npm/node-semver/blob/v6.3.1/CHANGELOG.md)
    - [Commits](npm/node-semver@v6.3.0...v6.3.1)

    ---
    updated-dependencies:
    - dependency-name: semver
      dependency-type: indirect
    ...

    Signed-off-by: dependabot[bot] <[email protected]>

commit 26702c0
Author: Muttaqin <[email protected]>
Date:   Fri Jul 7 10:12:04 2023 +0600

    Github integration.

commit 372d6ce
Merge: 55be937 92eddd6
Author: Abdelouahab Bella <[email protected]>
Date:   Sat Jul 1 16:29:57 2023 +0100

    Merge pull request ISIL-ESTE#61 from bellaabdelouahab/dev

    Enhance -  appError & code cleanup & login page in frontend [ISIL-ESTE#61]

commit 92eddd6
Merge: 2d3a5d3 d5b3b60
Author: Abdelouahab Bella <[email protected]>
Date:   Sat Jul 1 16:26:43 2023 +0100

    Merge commit 'd5b3b6057f88106099a3fd2a1095de400e767ff6' into dev

commit 2d3a5d3
Merge: fbbdda1 55be937
Author: Abdelouahab Bella <[email protected]>
Date:   Sat Jul 1 16:23:56 2023 +0100

    Merge branch 'ISIL-ESTE:dev' into dev

commit fbbdda1
Author: Abdelouahab Bella <[email protected]>
Date:   Sat Jul 1 16:22:42 2023 +0100

    enhe-app error clean up

commit 55be937
Merge: a6fe803 dab86a2
Author: Abdelouahab Bella <[email protected]>
Date:   Sat Jul 1 16:20:07 2023 +0100

    Merge pull request ISIL-ESTE#56 from bellaabdelouahab/dev

    Add user activation, metadata, routes, and soft delete logic; fix response path and server errors

commit d5b3b60
Author: yassineboujrada <[email protected]>
Date:   Wed Jun 28 23:29:42 2023 +0100

    adding page for login with tailwind the part need is fix auth

commit 1cdb4ae
Author: Abdelouahab Bella <[email protected]>
Date:   Tue Jun 27 18:57:46 2023 +0100

    fix errors and add testing for activation

commit dab86a2
Author: Abdelouahab Bella <[email protected]>
Date:   Mon Jun 26 19:49:14 2023 +0100

    requested changes

commit 41865dd
Author: Abdelouahab Bella <[email protected]>
Date:   Mon Jun 26 17:31:27 2023 +0100

    Add user activation, metadata, routes, and soft delete logic; fix response path and server errors

commit 8ebd680
Merge: 710ccbf a6fe803
Author: Abdelouahab Bella <[email protected]>
Date:   Sun Jun 25 21:56:09 2023 +0100

    trying to merge

commit a6fe803
Merge: 0115fee 2c4d94c
Author: Abdelouahab Bella <[email protected]>
Date:   Sun Jun 25 21:49:23 2023 +0100

    Merge pull request ISIL-ESTE#53 from muttaqin1/refactor/file-names

    Refactor - ISIL-ESTE#53  change file names

commit 2c4d94c
Author: muttaqin1 <[email protected]>
Date:   Mon Jun 26 02:18:51 2023 +0600

    Update import paths.

commit 7609c6b
Author: muttaqin1 <[email protected]>
Date:   Mon Jun 26 01:32:02 2023 +0600

    Refactor file names with underscore.

commit 392b611
Author: muttaqin1 <[email protected]>
Date:   Mon Jun 26 01:08:59 2023 +0600

    resolve ISIL-ESTE#52.

commit 710ccbf
Author: Abdelouahab Bella <[email protected]>
Date:   Sun Jun 25 19:17:42 2023 +0100

    requested changes

commit 0115fee
Merge: dca09e4 c7b8464
Author: Khalid BOUSSAROUAL <[email protected]>
Date:   Sun Jun 25 19:14:38 2023 +0100

    Merge pull request ISIL-ESTE#51 from bellaabdelouahab/dev

    fix - testing role managment

commit c7b8464
Author: Abdelouahab Bella <[email protected]>
Date:   Sun Jun 25 12:43:24 2023 +0100

    code cleaning

commit 5b65a0f
Merge: b2aa675 dca09e4
Author: Abdelouahab Bella <[email protected]>
Date:   Sun Jun 25 12:21:08 2023 +0100

    Merge remote-tracking

commit b2aa675
Author: Abdelouahab Bella <[email protected]>
Date:   Sun Jun 25 11:52:49 2023 +0100

    👌fix-swagger-autogen & endpoints & jwt,feat-tests

commit dca09e4
Merge: a97eeea 154d7ee
Author: Abdelouahab Bella <[email protected]>
Date:   Fri Jun 23 17:10:00 2023 +0100

    Merge pull request ISIL-ESTE#45 from muttaqin1/bugFix/ban-user

    [ISIL-ESTE#45 ] issue - Bug fix/ban user

commit 154d7ee
Merge: 8d857ee a97eeea
Author: Abdelouahab Bella <[email protected]>
Date:   Fri Jun 23 16:58:37 2023 +0100

    Merge branch 'dev' into bugFix/ban-user

commit 8d857ee
Author: muttaqin1 <[email protected]>
Date:   Fri Jun 23 21:34:32 2023 +0600

    Fix ban and unban user.

commit a97eeea
Merge: d9ae2c6 17e53a5
Author: Khalid BOUSSAROUAL <[email protected]>
Date:   Thu Jun 22 15:41:41 2023 +0100

    Merge pull request ISIL-ESTE#40 from bellaabdelouahab/dev

    test - start code testing for login and sign up

commit 17e53a5
Merge: be73f7d d9ae2c6
Author: Khalid BOUSSAROUAL <[email protected]>
Date:   Thu Jun 22 15:39:57 2023 +0100

    Merge branch 'dev' into dev

commit d9ae2c6
Merge: 9d0bdd6 d6ebb36
Author: Khalid BOUSSAROUAL <[email protected]>
Date:   Thu Jun 22 15:31:44 2023 +0100

    Merge pull request ISIL-ESTE#38 from ISIL-ESTE/limiter

    add rate limit

commit be73f7d
Author: Abdelouahab Bella <[email protected]>
Date:   Thu Jun 22 14:58:43 2023 +0100

    test - add basic example of testing & fix imports

commit d6ebb36
Author: Khalid BOUSSAROUAL <[email protected]>
Date:   Thu Jun 22 13:46:01 2023 +0100

    add rate limit

commit 70bbe22
Author: Abdelouahab Bella <[email protected]>
Date:   Thu Jun 22 11:33:17 2023 +0100

    👌 ensuring that main branch is protected

commit 7301c3b
Author: Abdelouahab Bella <[email protected]>
Date:   Thu Jun 22 11:27:28 2023 +0100

    👌ensuring that Conterbute is working
  • Loading branch information
bellaabdelouahab committed Aug 10, 2023
1 parent 6825ffb commit a3afdea
Show file tree
Hide file tree
Showing 16 changed files with 236 additions and 90 deletions.
5 changes: 5 additions & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#!/usr/bin/env sh
. "$(dirname "$0")/_/husky.sh"

cd backend-app
npx lint-staged
5 changes: 5 additions & 0 deletions .husky/pre-push
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#!/usr/bin/env sh
. "$(dirname "$0")/_/husky.sh"

cd backend-app
jest
2 changes: 1 addition & 1 deletion backend-app/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ REQUIRE_ACTIVATION = false
RATE_LIMIT_PER_HOUR = 500
GITHUB_OAUTH_CLIENT_ID = "Iv1.6f4b4b8b0b1b4b8b"
GITHUB_OAUTH_CLIENT_SECRET = "6f4b4b8b0b1b4b8b6f4b4b8b0b1b4b8b"
GITHUB_OAUTH_REDIRECT_URL = "http://localhost:3000/auth/github/callback"
GITHUB_OAUTH_REDIRECT_URL = "http://localhost:3000/auth/github/callback"
3 changes: 2 additions & 1 deletion backend-app/.eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ module.exports = {
'block-scoped-var': 'error',
'class-methods-use-this': 'error',
complexity: ['error', 10],
'consistent-return': 'error',
'consistent-return': 'off',
'default-case': 'error',
'dot-location': ['error', 'property'],
'dot-notation': 'error',
Expand Down Expand Up @@ -69,6 +69,7 @@ module.exports = {
yoda: 'error',
'no-console': 'warn',
'no-var': 'error',
'no-undef': 'off',
'no-unused-vars': 'warn',
'arrow-body-style': ['error', 'as-needed'],
},
Expand Down
9 changes: 8 additions & 1 deletion backend-app/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,12 @@ const cors = require('cors');
const morgan = require('./middlewares/morgan');
const setDefaultAPIVersion = require('./middlewares/api_version_controll');
const swaggerDocs = require('./utils/swagger');
const { CURRENT_ENV } = require('./config/app_config');
const {
COOKIE_SECRET,
CURRENT_ENV,
API_VERSION,
} = require('./config/app_config');
const cookieParser = require('cookie-parser');

const app = express();

Expand All @@ -20,6 +25,8 @@ swaggerDocs(app);

// use json as default format
app.use(express.json());
//configure cookie parser
app.use(cookieParser(COOKIE_SECRET));

// use morgan for logging
app.use(morgan);
Expand Down
21 changes: 13 additions & 8 deletions backend-app/config/app_config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,23 @@ const envFile = fs.existsSync('.env') ? '.env' : '.env.example';
dotenv.config({ path: join(__dirname, `../${envFile}`) });

exports.logFilePath = join(__dirname, '../server-logs');
exports.CURRENT_ENV = process.env.NODE_ENV ?.toLowerCase();
exports.API_VERSION = process.env.API_VERSION ;
exports.DATABASE = process.env.MONGO_URI ;
exports.PORT = process.env.PORT ;
exports.ADMIN_EMAIL = process.env.ADMIN_EMAIL ;
exports.ADMIN_PASSWORD = process.env.ADMIN_PASSWORD ;
exports.REQUIRE_ACTIVATION = process.env.REQUIRE_ACTIVATION ;
exports.RATE_LIMIT_PER_HOUR = process.env.RATE_LIMIT_PER_HOUR ;
exports.CURRENT_ENV = process.env.NODE_ENV?.toLowerCase();
exports.API_VERSION = process.env.API_VERSION;
exports.DATABASE = process.env.MONGO_URI;
exports.PORT = process.env.PORT;
exports.ADMIN_EMAIL = process.env.ADMIN_EMAIL;
exports.ADMIN_PASSWORD = process.env.ADMIN_PASSWORD;
exports.REQUIRE_ACTIVATION = process.env.REQUIRE_ACTIVATION;
exports.RATE_LIMIT_PER_HOUR = process.env.RATE_LIMIT_PER_HOUR;
exports.GITHUB_OAUTH_CLIENT_ID = process.env.GITHUB_OAUTH_CLIENT_ID;
exports.GITHUB_OAUTH_CLIENT_SECRET = process.env.GITHUB_OAUTH_CLIENT_SECRET;
exports.GITHUB_OAUTH_REDIRECT_URL = process.env.GITHUB_OAUTH_REDIRECT_URL;
exports.ACCESS_TOKEN_SECRET = process.env.ACCESS_TOKEN_SECRET;
exports.ACCESS_TOKEN_EXPIRY_TIME = process.env.ACCESS_TOKEN_EXPIRY_TIME;
exports.REFRESH_TOKEN_SECRET = process.env.REFRESH_TOKEN_SECRET;
exports.REFRESH_TOKEN_EXPIRY_TIME = process.env.REFRESH_TOKEN_EXPIRY_TIME;
exports.ACCESS_TOKEN_COOKIE_EXPIRY_TIME =
process.env.ACCESS_TOKEN_COOKIE_EXPIRY_TIME;
exports.REFRESH_TOKEN_COOKIE_EXPIRY_TIME =
process.env.REFRESH_TOKEN_COOKIE_EXPIRY_TIME;
exports.COOKIE_SECRET = process.env.COOKIE_SECRET;
137 changes: 82 additions & 55 deletions backend-app/controllers/auth_controller.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,17 @@
const { promisify } = require('util');
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');
const User = require('../models/user/user_model');
const AppError = require('../utils/app_error');
const Role = require('../utils/authorization/role/role');
const {
ACCESS_TOKEN_SECRET,
REQUIRE_ACTIVATION,
} = require('../config/app_config');
const { REQUIRE_ACTIVATION } = require('../config/app_config');
const {
getGithubOAuthUser,
getGithubOAuthToken,
getGithubOAuthUserPrimaryEmail,
} = require('../utils/authorization/github');
const TokenModel = require('../models/token_model');
const role = new Role();
const generateTokens = require('../utils/authorization/generateTokens');
const AuthUtils = require('../utils/authorization/auth_utils');
const searchCookies = require('../utils/searchCookie');

const generateActivationKey = async () => {
const randomBytesPromiseified = promisify(require('crypto').randomBytes);
Expand All @@ -26,17 +22,23 @@ const generateActivationKey = async () => {
exports.githubHandler = async (req, res, next) => {
try {
const Roles = await role.getRoles();
const { code } = req.query;
const { code, redirect_url } = req.query;
if (!redirect_url)
throw new AppError(400, 'fail', 'Please provide redirect_url');
if (!code) throw new AppError(400, 'fail', 'Please provide code');
const { access_token } = await getGithubOAuthToken(code);
if (!access_token) throw new AppError(400, 'fail', 'Invalid code');
const githubUser = await getGithubOAuthUser(access_token);
const primaryEmail = await getGithubOAuthUserPrimaryEmail(access_token);
const exists = await User.findOne({ email: primaryEmail });
if (exists)
return res.status(200).json({
token: await generateTokens(exists._id),
});
if (exists) {
const accessToken = AuthUtils.generateAccessToken(exists._id);
const refreshToken = AuthUtils.generateRefreshToken(exists._id);
AuthUtils.setAccessTokenCookie(
res,
accessToken
).setRefreshTokenCookie(res, refreshToken);
}
if (!githubUser)
throw new AppError(400, 'fail', 'Invalid access token');
const createdUser = await User.create({
Expand All @@ -50,11 +52,15 @@ exports.githubHandler = async (req, res, next) => {
githubOauthAccessToken: access_token,
active: true,
});
const tokens = await generateTokens(createdUser._id);
res.status(201).json({
user: createdUser,
tokens,
});

const accessToken = AuthUtils.generateAccessToken(createdUser._id);
const refreshToken = AuthUtils.generateRefreshToken(createdUser._id);
AuthUtils.setAccessTokenCookie(res, accessToken).setRefreshTokenCookie(
res,
refreshToken
);
//redirect user to redirect url
res.redirect(redirect_url);
} catch (err) {
next(err);
}
Expand Down Expand Up @@ -88,14 +94,18 @@ exports.login = async (req, res, next) => {
);
}

// 3) All correct, send jwt to client
const tokens = await generateTokens(user._id);
// 3) All correct, send accessToken & refreshToken to client via cookie
const accessToken = AuthUtils.generateAccessToken(user._id);
const refreshToken = AuthUtils.generateRefreshToken(user._id);
AuthUtils.setAccessTokenCookie(res, accessToken).setRefreshTokenCookie(
res,
refreshToken
);

// Remove the password from the output
user.password = undefined;

res.status(200).json({
tokens: tokens,
data: {
user,
},
Expand All @@ -105,14 +115,6 @@ exports.login = async (req, res, next) => {
}
};

/**
*
* @description Signup a new user
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @returns {Promise<void>}
*/
exports.signup = async (req, res, next) => {
try {
const activationKey = await generateActivationKey();
Expand All @@ -126,8 +128,13 @@ exports.signup = async (req, res, next) => {
restrictions: Roles.USER.restrictions,
...(REQUIRE_ACTIVATION && { activationKey }),
});
const tokens = await generateTokens(user._id);

const accessToken = AuthUtils.generateAccessToken(user._id);
const refreshToken = AuthUtils.generateRefreshToken(user._id);
AuthUtils.setAccessTokenCookie(res, accessToken).setRefreshTokenCookie(
res,
refreshToken
);
// Remove the password and activation key from the output
user.password = undefined;
user.activationKey = undefined;
Expand All @@ -143,7 +150,42 @@ exports.signup = async (req, res, next) => {
},
});
} catch (err) {
console.log(err);
next(err);
}
};

exports.tokenRefresh = async (req, res, next) => {
try {
const refreshToken = searchCookies(req, 'refresh_token');
if (!refreshToken)
throw new AppError(400, 'fail', 'You have to login to continue.');
const refreshTokenPayload = await AuthUtils.verifyRefreshToken(
refreshToken
);
if (!refreshTokenPayload || !refreshTokenPayload.id)
throw new AppError(400, 'fail', 'Invalid refresh token');
const user = await User.findById(refreshTokenPayload.id);
if (!user) throw new AppError(400, 'fail', 'Invalid refresh token');
const accessToken = AuthUtils.generateAccessToken(user._id);
//set or override accessToken cookie.
AuthUtils.setAccessTokenCookie(res, accessToken);
res.sendStatus(204);
} catch (err) {
next(err);
}
};
exports.logout = async (req, res, next) => {
try {
const accessToken = searchCookies(req, 'access_token');
if (!accessToken)
throw new AppError(400, 'fail', 'Please provide access token');
const accessTokenPayload = await AuthUtils.verifyAccessToken(
accessToken
);
if (!accessTokenPayload || !accessTokenPayload.id)
throw new AppError(400, 'fail', 'Invalid access token');
res.sendStatus(204);
} catch (err) {
next(err);
}
};
Expand Down Expand Up @@ -255,6 +297,7 @@ exports.forgotPassword = async (req, res, next) => {
);

// send email with reset key
// eslint-disable-next-line no-warning-comments
// TODO: send email with reset key

res.status(200).json({
Expand All @@ -267,39 +310,24 @@ exports.forgotPassword = async (req, res, next) => {

exports.protect = async (req, res, next) => {
try {
// 1) check if the token is there
let token;
if (
req.headers.authorization &&
req.headers.authorization.startsWith('Bearer')
) {
token = req.headers.authorization.split(' ')[1];
}
if (!token) {
return next(
new AppError(
401,
'fail',
'You are not logged in! Please login in to continue'
)
);
}

// 2) Verify token
const decode = await promisify(jwt.verify)(token, ACCESS_TOKEN_SECRET);
const accessToken = searchCookies(req, 'access_token');
if (!accessToken)
return next(new AppError(401, 'fail', 'Please login to continue'));

const accessTokenPayload = await AuthUtils.verifyAccessToken(
accessToken
);
if (!accessTokenPayload || !accessTokenPayload.id)
throw new AppError(401, 'fail', 'Invalid access token');
// 3) check if the user is exist (not deleted)
const user = await User.findById(decode.id).select(
const user = await User.findById(accessTokenPayload.id).select(
'+githubOauthAccessToken'
);
if (!user) {
return next(
new AppError(401, 'fail', 'This user is no longer exist')
);
}
const tokenRecord = await TokenModel.findOne({ userId: user._id });
if (!tokenRecord)
throw new AppError(401, 'fail', 'Invalid Access Token');

// Check if the account is banned
if (user?.accessRestricted)
Expand All @@ -311,7 +339,6 @@ exports.protect = async (req, res, next) => {
)
);
req.user = user;
req.token = tokenRecord;
// check if account is active
if (!user.active)
return next(
Expand Down
36 changes: 17 additions & 19 deletions backend-app/controllers/github_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,28 +14,26 @@ exports.getRecentRepo = async (req, res, next) => {
}
);
const mappedUserRepositories = userRepositories.data.map(
(repository) => {
return {
id: repository.id,
name: repository.name,
full_name: repository.full_name,
description: repository.description,
isFork: repository.fork,
language: repository.language,
license: repository.license?.name
? repository.license.name
: null,
openedIssuesCount: repository.open_issues_count,
repoCreatedAt: repository.created_at,
url: repository.url,
};
}
(repository) => ({
id: repository.id,
name: repository.name,
full_name: repository.full_name,
description: repository.description,
isFork: repository.fork,
language: repository.language,
license: repository.license?.name
? repository.license.name
: null,
openedIssuesCount: repository.open_issues_count,
repoCreatedAt: repository.created_at,
url: repository.url,
})
);
if (mappedUserRepositories.length <= 0)
throw new AppError(400, 'fail', 'No repositories found');
const sortedRepository = mappedUserRepositories.sort((a, b) => {
return new Date(b.repoCreatedAt) - new Date(a.repoCreatedAt);
});
const sortedRepository = mappedUserRepositories.sort(
(a, b) => new Date(b.repoCreatedAt) - new Date(a.repoCreatedAt)
);

const recentRepository = sortedRepository[0];
res.status(200).json({
Expand Down
1 change: 0 additions & 1 deletion backend-app/middlewares/global_error_handler.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
const httpStatus = require('http-status-codes');
const { CURRENT_ENV } = require('../config/app_config');
const AppError = require('../utils/app_error');
const { Logger } = require('winston');
require('../utils/logger');

/**
Expand Down
Loading

0 comments on commit a3afdea

Please sign in to comment.