Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

authenticate with JWT #8

Merged
merged 5 commits into from
Oct 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions backend/matching-service/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ Clients will send the following message to the server:
user_id: "<uid>",
question_complexity: "Easy" | "Hard" | "Medium",
question_category: "<category>",
token: "<json web token>",
}
```

Expand Down
106 changes: 106 additions & 0 deletions backend/matching-service/package-lock.json

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

2 changes: 2 additions & 0 deletions backend/matching-service/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.2",
"nodemon": "^3.0.1",
"ws": "^8.14.2"
}
Expand Down
16 changes: 15 additions & 1 deletion backend/matching-service/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ import { WebSocketServer } from "ws";
import { MatchService } from "./match-service.js";
import { generateCodeRoomId } from "./utils/generateRoomId.js";

import jwt from 'jsonwebtoken';
import dotenv from "dotenv"
dotenv.config({path: "../.env"})

const app = express();
app.use(cors({
origin: ["http://localhost:3000"],
Expand All @@ -24,7 +28,6 @@ const wss = new WebSocketServer({ server: httpServer });
const matchService = new MatchService();

wss.on("connection", (ws) => {
// TODO: Validate authentication?
console.info("Received new connection");

ws.on("error", console.error);
Expand All @@ -46,7 +49,18 @@ wss.on("connection", (ws) => {
const {
user_id: userId,
question_complexity: complexity,
token,
} = message;

// Authenticate users
try {
jwt.verify(token, process.env.JSON_WEB_TOKEN_SECRET);
} catch (error) {
console.error("Unauthenticated");
ws.close();
return;
}

if (complexity !== "Easy" && complexity !== "Medium" && complexity !== "Hard") {
console.error("Invalid complexity");
ws.close();
Expand Down
29 changes: 29 additions & 0 deletions backend/question-service/controllers/questionController.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,31 @@
const Questions = require("../models/questionModel");
require('dotenv').config({path: "../.env"});

const authenticate = async (req, res, next) => {
try {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
jwt.verify(token, process.env.JSON_WEB_TOKEN_SECRET);
} catch {
return res.sendStatus(401);
}
next();
};

const authenticateAdmin = async (req, res, next) => {
try {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
const { user } = jwt.verify(token, process.env.JWT_TOKEN_SECRET);
if (!user.isAdmin) {
return res.sendStatus(401);
}
} catch {
return res.sendStatus(401);
}
next();
};


const addQuestion = async(req, res, next) => {
try {
Expand Down Expand Up @@ -122,6 +149,8 @@ const deleteQuestion = async (req, res, next) => {
}

module.exports = {
authenticate,
authenticateAdmin,
addQuestion,
getAllQuestions,
getQuestionById,
Expand Down
10 changes: 5 additions & 5 deletions backend/question-service/routes/questionRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ const express = require('express');
const questionController = require("../controllers/questionController");
const questionRouter = express.Router();

questionRouter.post("/", questionController.addQuestion);
questionRouter.post("/", questionController.addQuestion, questionController.authenticateAdmin);

questionRouter.get("/", questionController.getAllQuestions);
questionRouter.get("/", questionController.getAllQuestions, questionController.authenticate);

questionRouter.get("/:questionId", questionController.getQuestionById);
questionRouter.get("/:questionId", questionController.getQuestionById, questionController.authenticate);

questionRouter.put("/:questionId", questionController.updateQuestion)
questionRouter.put("/:questionId", questionController.updateQuestion, questionController.authenticateAdmin)

questionRouter.delete("/:questionTitle", questionController.deleteQuestion);
questionRouter.delete("/:questionTitle", questionController.deleteQuestion, questionController.authenticateAdmin);

module.exports = questionRouter;
45 changes: 38 additions & 7 deletions backend/user-service/controllers/userController.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,33 @@
const { Users } = require('../models');
const bcrypt = require("bcrypt");
const { Op } = require('sequelize');
const jwt = require('jsonwebtoken');

require('dotenv').config({path: "../.env"});

const authenticate = async (req, res, next) => {
if (['/login', '/register'].includes(req.path)) {
next();
return;
}

try {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
console.log()
if (!jwt.verify(token, process.env.JSON_WEB_TOKEN_SECRET).isAdmin) {
return res.sendStatus(401);
}
} catch {
return res.sendStatus(401);
}
next();
};

const addUser = async (req, res, next) => {
try {
const { username, email, password } = req.body;

if (!username || !email || !password) {
res.status(400).json({error: "Missing field"});
return;
Expand All @@ -24,23 +46,22 @@ const addUser = async (req, res, next) => {
res.status(400).json({ error: "User already exists"});
return;
}

const hash = await bcrypt.hash(password, 10);

const user = await Users.create({
username: username,
email: email,
password: hash
});

res.status(201).json({ res: user});
} catch (err) {
next(err);
}
};


const loginUser = async (req, res) => {
const loginUser = async (req, res, next) => {
try {
const { username, password } = req.body;

Expand All @@ -63,7 +84,16 @@ const loginUser = async (req, res) => {
return;
}

res.status(200).json({ res: user})
const token = jwt.sign(
{
username: user.username,
isAdmin: user.isAdmin,
},
process.env.JSON_WEB_TOKEN_SECRET,
{ expiresIn: '7d' }
);
res.status(200).json({ res: token });

} catch (err) {
next(err);
}
Expand Down Expand Up @@ -173,6 +203,7 @@ const deleteUser = async (req, res, next) => {
};

module.exports = {
authenticate,
addUser,
loginUser,
getAllUsers,
Expand Down
4 changes: 4 additions & 0 deletions backend/user-service/models/userModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ module.exports = (sequelize, DataTypes) => {
type: DataTypes.STRING,
allowNULL: false,
},
isAdmin: {
type: DataTypes.BOOLEAN,
default: false,
},
firstName: {
type: DataTypes.STRING,
},
Expand Down
Loading