Skip to content

Commit

Permalink
refactor signing in to return a token to pass with each request
Browse files Browse the repository at this point in the history
  • Loading branch information
Brad committed Sep 14, 2023
1 parent 72bf070 commit b36f3e1
Show file tree
Hide file tree
Showing 10 changed files with 57 additions and 8 deletions.
5 changes: 4 additions & 1 deletion backend/controllers/user.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ UserController.signin = function (req, res) {
return res.sendStatus(401);
}
const jsonToken = generateAccessToken(user, auth_origin);

EmailController.sendLoginLink(
req.body.email,
req.body.auth_origin,
Expand All @@ -159,7 +160,9 @@ UserController.signin = function (req, res) {
req.cookie,
origin,
);
return res.sendStatus(200);
res.status(200)
res.json({ token: jsonToken})
return
})
.catch((err) => {
console.log(err);
Expand Down
32 changes: 32 additions & 0 deletions backend/middleware/auth.middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,40 @@ function verifyCookie(req, res, next) {
});
}

function protect(req, res, next) {

const bearer = req.headers.authorization;

if(!bearer) {
res.status(401)
res.json({message: "You aren't authorized to do this."})
return
}

const [ , token] = bearer.split(' ');

if (!token) {
res.status(401)
res.json({message: "You don't have a valid token."})
return
}

try {
const user = jwt.verify(token, CONFIG_AUTH.SECRET)
req.user = user
next()
} catch(e) {
console.log(e)
res.status(401)
res.json({message: "You need a valid token, try again."})
return
}

}

const AuthUtil = {
verifyToken,
verifyCookie,
protect
};
module.exports = AuthUtil;
3 changes: 2 additions & 1 deletion backend/middleware/user.middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ function isAdminByEmail(req, res, next) {
return res.sendStatus(400);
} else {
const role = user.accessLevel;
if (req.get('origin').includes('3001') || role === 'admin' || user.managedProjects.length > 0) {
// removed the check for origin === 3001 it was hanging up in Postman
if (role === 'admin' || user.managedProjects.length > 0) {
next();
} else {
next(res.sendStatus(401));
Expand Down
2 changes: 1 addition & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"format": "prettier --check .",
"test": "jest",
"test:watch": "jest --watch",
"start": "node server.js",
"start": "nodemon server.js",
"dev": "nodemon server.js",
"client": "npm run start --prefix client",
"heroku-postbuild": "cd client && npm install && npm run build"
Expand Down
3 changes: 2 additions & 1 deletion backend/routers/projects.router.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
const express = require("express");
const router = express.Router();
const { AuthUtil } = require('../middleware')

const { ProjectController } = require('../controllers');

// The base is /api/projects
router.get('/', ProjectController.project_list);

router.post('/', ProjectController.create);
router.post('/', AuthUtil.protect, ProjectController.create);

router.get('/:ProjectId', ProjectController.project_by_id);

Expand Down
7 changes: 5 additions & 2 deletions client/src/api/ProjectApiService.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class ProjectApiService {
}

// Handles the POST request and returns the projects ID.
async create(projectData) {
async create(projectData, token) {
const {
name,
description,
Expand All @@ -36,7 +36,10 @@ class ProjectApiService {
} = projectData;
const requestOptions = {
method: 'POST',
headers: this.headers,
headers: {
...this.headers,
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({
name,
description,
Expand Down
6 changes: 5 additions & 1 deletion client/src/components/ProjectForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,13 @@ export default function ProjectForm({

// Handles POST request found in api/ProjectApiService.
const submitNewProject = async (data) => {
const token = localStorage.getItem('token')
if(!token) {
return null
}
const projectApi = new ProjectApiService();
try {
const id = await projectApi.create(data);
const id = await projectApi.create(data, token);
history.push(`/projects/${id}`);
} catch (errors) {
console.error(errors);
Expand Down
2 changes: 2 additions & 0 deletions client/src/components/auth/Auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ const Auth = () => {
}

const isAuth = await checkAuth(email, LOG_IN);
localStorage.setItem('token', isAuth.token);

if (isAuth) {
history.push('/emailsent');
} else {
Expand Down
1 change: 1 addition & 0 deletions client/src/context/authContext.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export const AuthProvider = ({ children }) => {
};

const logout = async () => {
localStorage.removeItem('token')
const res = await authApi.fetchLogout();

if (!res.ok) {
Expand Down
4 changes: 3 additions & 1 deletion client/src/services/user.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@ export async function checkAuth(email, auth_origin) {
headers: HEADERS,
body: JSON.stringify({ email: email, auth_origin: auth_origin }),
});
return response.status === 200;

const token = await response.json()
return token
} catch (error) {
console.log('User is not authorized in app');
console.log(error);
Expand Down

0 comments on commit b36f3e1

Please sign in to comment.