52 lines
2.0 KiB
TypeScript
52 lines
2.0 KiB
TypeScript
import * as jwt from "jsonwebtoken";
|
|
import { Action } from "routing-controllers";
|
|
import { getConnectionManager } from 'typeorm';
|
|
import { config } from './config';
|
|
import { IllegalJWTError, NoPermissionError, UserNonexistantOrRefreshtokenInvalidError } from './errors/AuthError';
|
|
import { User } from './models/entities/User';
|
|
// -----------
|
|
const authchecker = async (action: Action, permissions: string | string[]) => {
|
|
let required_permissions = undefined
|
|
if (typeof permissions === "string") {
|
|
required_permissions = [permissions]
|
|
} else {
|
|
required_permissions = permissions
|
|
}
|
|
// const token = action.request.headers["authorization"];
|
|
const provided_token = action.request.query["auth"];
|
|
let jwtPayload = undefined
|
|
try {
|
|
jwtPayload = <any>jwt.verify(provided_token, config.jwt_secret);
|
|
} catch (error) {
|
|
console.log(error);
|
|
throw new IllegalJWTError()
|
|
}
|
|
const count = await getConnectionManager().get().getRepository(User).count({ id: jwtPayload["userdetails"]["id"], refreshTokenCount: jwtPayload["userdetails"]["refreshTokenCount"] })
|
|
if (count !== 1) {
|
|
throw new UserNonexistantOrRefreshtokenInvalidError()
|
|
}
|
|
if (jwtPayload.permissions) {
|
|
action.response.local = {}
|
|
action.response.local.jwtPayload = jwtPayload.permissions
|
|
required_permissions.forEach(r => {
|
|
const permission_key = r.split(":")[0]
|
|
const actual_accesslevel_for_permission = jwtPayload.permissions[permission_key]
|
|
const permission_access_level = r.split(":")[1]
|
|
if (actual_accesslevel_for_permission.includes(permission_access_level)) {
|
|
return true;
|
|
} else {
|
|
throw new NoPermissionError()
|
|
}
|
|
});
|
|
} else {
|
|
throw new NoPermissionError()
|
|
}
|
|
//
|
|
try {
|
|
jwt.verify(provided_token, config.jwt_secret);
|
|
return true
|
|
} catch (error) {
|
|
return false
|
|
}
|
|
}
|
|
export default authchecker |