bsfe_server/src/middlewares/auth.js

63 lines
2.3 KiB
JavaScript
Raw Normal View History

2024-10-26 05:31:22 +03:00
import log from '../utils/log.js'
import jwt from 'jsonwebtoken';
import config from '../../config.json' with {type: "json"};
import GroupService from '../services/group.js';
const TAG = "/middlewares/auth.js"
const requireUsernameAndPassword = async (req, res, next) => {
if (req.method == "OPTIONS") next();
try {
const {username, password} = req.body;
if (!username) return res.status(400).send("Username is required");
if (!password) return res.status(400).send("Password is required");
next();
} catch (e) { return res.status(500).send(unknownError(`${TAG}/requireUsernameAndPassword: ${e}`)); }
}
const authenticate = async (req, res, next) => {
if (req.method == "OPTIONS") next();
try {
const token = req.headers.authorization.split(' ')[1]
if (!token) return res.status(401).send("No authorization token supplied");
if (!jwt.verify(token, config.secret)) return res.status(403).send("Authorization token is incorrect");
next();
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/authenticate: ${e}`)); }
}
const authorizeGroupOwner = async (req, res, next) => {
if (req.method == "OPTIONS") next();
try {
const token = req.headers.authorization.split(' ')[1]
if (!token) return res.status(401).send("No authorization token supplied");
const { id } = req.params;
let user = jwt.decode(token, config.secret)
let adminId = await GroupService.getAdminId(id);
if (user.login.id != adminId) return res.status(403).send("Not your group");
next();
} catch (e) { return res.status(500).send(log.unknownError(`${TAG}/authorizeGroupOwner: ${e}`)); }
}
const checkGroupPassword = async (req, res, next) => {
if (req.method == "OPTIONS") next();
try {
const { id } = req.params;
const { password } = req.body;
const groupPassword = await GroupService.getPassword(id);
if (groupPassword != password) return res.status(403).send("Wrong password");
next();
} catch (e) {return res.status(500).send(log.unknownError(`${TAG}/checkGroupPassword: ${e}`));}
}
export default { requireUsernameAndPassword, authenticate, authorizeGroupOwner, checkGroupPassword }