40 lines
1.7 KiB
TypeScript
40 lines
1.7 KiB
TypeScript
import Controller from "swaf/Controller";
|
|
import {RequireAuthMiddleware} from "swaf/auth/AuthComponent";
|
|
import {Request, Response} from "express";
|
|
import AuthToken from "../models/AuthToken";
|
|
import {BadRequestError, ForbiddenHttpError, NotFoundHttpError} from "swaf/HttpError";
|
|
|
|
export default class AuthTokenController extends Controller {
|
|
public routes(): void {
|
|
this.post('/gen-auth-token', this.postGenAuthToken, 'generate-token', RequireAuthMiddleware);
|
|
this.post('/revoke-auth-token/:id', this.postRevokeAuthToken, 'revoke-token', RequireAuthMiddleware);
|
|
}
|
|
|
|
protected async postGenAuthToken(req: Request, res: Response): Promise<void> {
|
|
const user = req.as(RequireAuthMiddleware).getUser();
|
|
const authToken = AuthToken.create({
|
|
user_id: user.id,
|
|
ttl: req.body.ttl ? parseInt(req.body.ttl) : 365 * 24 * 3600,
|
|
});
|
|
await authToken.save();
|
|
req.flash('success', 'Successfully created auth token.');
|
|
res.redirectBack(Controller.route('file-upload'));
|
|
}
|
|
|
|
protected async postRevokeAuthToken(req: Request, res: Response): Promise<void> {
|
|
const id = req.params.id;
|
|
if (!id) throw new BadRequestError('Cannot revoke token without an id.', 'Please provide an id.', req.url);
|
|
|
|
const authToken = await AuthToken.getById<AuthToken>(parseInt(id));
|
|
if (!authToken) throw new NotFoundHttpError('Auth token', req.url);
|
|
|
|
const user = req.as(RequireAuthMiddleware).getUser();
|
|
if (!authToken.canDelete(user.getOrFail('id'))) throw new ForbiddenHttpError('auth token', req.url);
|
|
|
|
await authToken.delete();
|
|
|
|
req.flash('success', 'Successfully deleted auth token.');
|
|
res.redirectBack(Controller.route('file-upload'));
|
|
}
|
|
}
|