Add support for authenticating user against custom request-proof matching
This commit is contained in:
parent
3c8e04f06e
commit
6026037aa8
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "wms-core",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.1",
|
||||
"description": "Node web framework",
|
||||
"repository": "git@gitlab.com:ArisuOngaku/wms-core.git",
|
||||
"author": "Alice Gaudon <alice@gaudon.pro>",
|
||||
|
@ -26,6 +26,10 @@ export default class AuthComponent extends ApplicationComponent<void> {
|
||||
|
||||
|
||||
export const REQUIRE_AUTH_MIDDLEWARE = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
||||
if (await req.authGuard.isAuthenticatedViaRequest(req)) {
|
||||
req.models.user = await req.authGuard.getUserForRequest(req);
|
||||
next();
|
||||
} else {
|
||||
if (!await req.authGuard.isAuthenticated(req.session!)) {
|
||||
req.flash('error', `You must be logged in to access ${req.url}.`);
|
||||
res.redirect(Controller.route('auth') || '/');
|
||||
@ -34,6 +38,7 @@ export const REQUIRE_AUTH_MIDDLEWARE = async (req: Request, res: Response, next:
|
||||
|
||||
req.models.user = await req.authGuard.getUserForSession(req.session!);
|
||||
next();
|
||||
}
|
||||
};
|
||||
export const REQUIRE_GUEST_MIDDLEWARE = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
||||
if (await req.authGuard.isAuthenticated(req.session!)) {
|
||||
|
@ -3,10 +3,15 @@ import MysqlConnectionManager from "../db/MysqlConnectionManager";
|
||||
import User from "./models/User";
|
||||
import UserEmail from "./models/UserEmail";
|
||||
import {Connection} from "mysql";
|
||||
import {Request} from "express";
|
||||
|
||||
export default abstract class AuthGuard<P extends AuthProof> {
|
||||
public abstract async getProofForSession(session: Express.Session): Promise<P | null>;
|
||||
|
||||
public async getProofForRequest(req: Request): Promise<P | null> {
|
||||
return null;
|
||||
}
|
||||
|
||||
public async getUserForSession(session: Express.Session): Promise<User | null> {
|
||||
if (!await this.isAuthenticated(session)) return null;
|
||||
return await User.getById<User>(`${session.auth_id}`);
|
||||
@ -77,6 +82,21 @@ export default abstract class AuthGuard<P extends AuthProof> {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public async isAuthenticatedViaRequest(req: Request): Promise<boolean> {
|
||||
const proof = await this.getProofForRequest(req);
|
||||
if (proof && await proof.isValid() && await proof.isAuthorized()) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async getUserForRequest(req: Request): Promise<User | null> {
|
||||
const proof = await this.getProofForRequest(req);
|
||||
return proof ? await proof.getUser() : null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export class AuthError extends Error {
|
||||
|
Loading…
Reference in New Issue
Block a user