60 lines
1.6 KiB
JavaScript
60 lines
1.6 KiB
JavaScript
import jwt from '../utils/jwt.js';
|
|
import User from '../models/user.js';
|
|
import Case from '../models/case.js';
|
|
import Team from '../models/team.js';
|
|
import Mark from '../models/mark.js';
|
|
import { AppErrorInvalid, asyncRoute } from '../utils/errors.js';
|
|
import admin from '../config/admin.js';
|
|
|
|
export default asyncRoute(async (req, res, next) => {
|
|
if (!req.headers.authorization || req.headers.authorization.split(' ')[0] !== 'Bearer')
|
|
throw new AppErrorInvalid('token', 401);
|
|
|
|
try {
|
|
req.user = jwt.verify(req.headers.authorization.split(' ')[1]);
|
|
} catch (e) {
|
|
console.log(e);
|
|
throw new AppErrorInvalid('token', 401);
|
|
}
|
|
|
|
if (req.user.id === admin.id) {
|
|
if (req.user.sessionId !== admin.sessionId) throw new AppErrorInvalid('token', 401);
|
|
req.isAdmin = true;
|
|
next();
|
|
return;
|
|
}
|
|
|
|
const user = await User.findByPk(req.user.id, {
|
|
order: [
|
|
[{ model: Case, as: 'cases' }, 'name'],
|
|
[{ model: Case, as: 'cases' }, { model: Team, as: 'teams' }, 'name'],
|
|
],
|
|
include: {
|
|
model: Case,
|
|
as: 'cases',
|
|
attributes: ['id', 'name', 'description', 'icon'],
|
|
through: { attributes: [] },
|
|
include: {
|
|
model: Team,
|
|
as: 'teams',
|
|
order: 'name',
|
|
attributes: ['id', 'name', 'description'],
|
|
through: { attributes: ['technicalComment'] },
|
|
include: {
|
|
model: Mark,
|
|
as: 'marks',
|
|
attributes: ['id', 'markType', 'mark'],
|
|
required: false,
|
|
where: { userId: req.user.id },
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
if (!user || req.user.iat !== +user.iat || (user.sessionId && req.user.sessionId !== user.sessionId))
|
|
throw new AppErrorInvalid('token', 401);
|
|
|
|
req.user = user;
|
|
next();
|
|
});
|