Skip to content

Commit

Permalink
Merge pull request #33 from Shaurya0108/feat/jwt
Browse files Browse the repository at this point in the history
Added JWT. Added middleware to authorize API requests
  • Loading branch information
xavierlmendez authored Oct 20, 2023
2 parents 730b9e8 + 244e657 commit 52fba1d
Show file tree
Hide file tree
Showing 7 changed files with 137 additions and 18 deletions.
94 changes: 94 additions & 0 deletions Server/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"dotenv": "^16.3.1",
"express": "^4.18.2",
"http": "^0.0.1-security",
"jsonwebtoken": "^9.0.2",
"nodemon": "^3.0.1"
}
}
6 changes: 4 additions & 2 deletions Server/src/classes/Error.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
export class UnauthorizedError extends Error{
constructor(message) {
constructor(message, statusCode) {
super(message);
this.name = 'UnauthorizedError';
this.statusCode = statusCode;
}
}

export class ConflictError extends Error{
constructor(message) {
super(message);
this.name = 'ConflictError'
this.name = 'ConflictError';
this.statusCode = 409;
}
}
6 changes: 3 additions & 3 deletions Server/src/classes/User.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export class User{
};
const user = await DB.getByPrimaryKey(params);
if (user) {
throw new ConflictError("Username already exist");
throw new ConflictError("Username already exist", 409);
}
else {
const params = {
Expand Down Expand Up @@ -72,15 +72,15 @@ export class User{
};
const user = await DB.getByPrimaryKey(params);
if (!user) {
throw new UnauthorizedError("Not Allowed");
throw new UnauthorizedError("Not Allowed", 401);
}
const res = AWS.DynamoDB.Converter.unmarshall(user);
const password = res.password;
if (await bcrypt.compare(this.password, password)){
resolve(res.UserId);
}
else {
throw new UnauthorizedError("Not Allowed");
throw new UnauthorizedError("Not Allowed", 401);
}
} catch (err) {
console.log(err);
Expand Down
21 changes: 14 additions & 7 deletions Server/src/library/auth.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
import { UnauthorizedError } from '../classes/Error.js';
import dotenv from 'dotenv';
import jwt from 'jsonwebtoken';

dotenv.config();

export const auth = ({authorization}, resolve, reject) => {
if (authorization){
var authorized = true
resolve(authorized)
}
else {
throw new Error('no authorization');
const token = authorization && authorization.split(' ')[1];

if (!token){
throw new UnauthorizedError("Unauthorized", 401)
}
jwt.verify(token, process.env.secret_access_token, (err, user) => {
if (err) throw new UnauthorizedError("Forbidden", 403);
resolve(true);
})

}
}

17 changes: 13 additions & 4 deletions Server/src/routes/authroutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ import express from 'express';
import {DynamoDBConnector} from '../classes/DynamoDBConnector.js';
import {User} from '../classes/User.js';
import { UnauthorizedError, ConflictError } from '../classes/Error.js';
import jwt from 'jsonwebtoken';
import dotenv from 'dotenv';

dotenv.config();

var dbConnection = new DynamoDBConnector();

Expand All @@ -25,22 +29,27 @@ export const authroutes = () => {
return res.status(200).json(result);
} catch (error) {
if (error instanceof ConflictError) {
return res.status(409).json({"error": error.message});
return res.status(error.statusCode).json({"error": error.message});
}
else {
return res.status(500).json({"error": "Internal Server Error"});
}
}
});

router.get('/getUserId', async (req, res) => {
router.get('/login', async (req, res) => {
try {
var user = new User(req.body.username, req.body.password);
let result = await user.getUserId();
return res.status(200).json(result);

const accessToken = jwt.sign({
userId: result
}, process.env.secret_access_token, {expiresIn: '30m'})

return res.status(200).json({accessToken: accessToken});
} catch (error) {
if (error instanceof UnauthorizedError) {
return res.status(401).json({"error": error.message});
return res.status(error.statusCode).json({"error": error.message});
}
else {
return res.status(500).json({"error": "Internal Server Error"});
Expand Down
10 changes: 8 additions & 2 deletions Server/src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import * as routes from './routes/index.js';
import {auth} from './library/auth.js';
import AWS from 'aws-sdk'
import dotenv from 'dotenv'
import { UnauthorizedError } from './classes/Error.js';

dotenv.config();

Expand All @@ -31,10 +32,15 @@ virtualTAServer.use((req, res, next)=>{
new Promise((resolve, reject)=> {
auth(req.headers, resolve, reject)
}).then(authorized =>{

next()
}).catch(Error =>{
res.status(401).json(Error)
if (Error instanceof UnauthorizedError){
res.status(Error.statusCode).json({error: Error.message});
}
else {
console.log(Error);
res.status(500).json({error: "Internal Server Error"});
}
})
})

Expand Down

0 comments on commit 52fba1d

Please sign in to comment.