2024-04-07 15:17:45 +03:00
|
|
|
import becca = require('../becca/becca');
|
|
|
|
import eu = require('./etapi_utils');
|
|
|
|
import passwordEncryptionService = require('../services/encryption/password_encryption');
|
|
|
|
import etapiTokenService = require('../services/etapi_tokens');
|
|
|
|
import { RequestHandler, Router } from 'express';
|
2022-01-10 17:09:20 +01:00
|
|
|
|
2024-04-07 15:17:45 +03:00
|
|
|
function register(router: Router, loginMiddleware: RequestHandler[]) {
|
2022-08-22 11:50:58 +02:00
|
|
|
eu.NOT_AUTHENTICATED_ROUTE(router, 'post', '/etapi/auth/login', loginMiddleware, (req, res, next) => {
|
2022-01-10 17:09:20 +01:00
|
|
|
const {password, tokenName} = req.body;
|
|
|
|
|
|
|
|
if (!passwordEncryptionService.verifyPassword(password)) {
|
|
|
|
throw new eu.EtapiError(401, "WRONG_PASSWORD", "Wrong password.");
|
|
|
|
}
|
|
|
|
|
|
|
|
const {authToken} = etapiTokenService.createToken(tokenName || "ETAPI login");
|
2022-01-12 21:14:12 +01:00
|
|
|
|
|
|
|
res.status(201).json({
|
2022-01-10 17:09:20 +01:00
|
|
|
authToken
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
eu.route(router, 'post', '/etapi/auth/logout', (req, res, next) => {
|
|
|
|
const parsed = etapiTokenService.parseAuthToken(req.headers.authorization);
|
|
|
|
|
|
|
|
if (!parsed || !parsed.etapiTokenId) {
|
|
|
|
throw new eu.EtapiError(400, eu.GENERIC_CODE, "Cannot logout this token.");
|
|
|
|
}
|
|
|
|
|
|
|
|
const etapiToken = becca.getEtapiToken(parsed.etapiTokenId);
|
2022-01-12 21:14:12 +01:00
|
|
|
|
2022-01-10 17:09:20 +01:00
|
|
|
if (!etapiToken) {
|
|
|
|
// shouldn't happen since this already passed auth validation
|
2023-05-04 22:16:18 +02:00
|
|
|
throw new Error(`Cannot find the token '${parsed.etapiTokenId}'.`);
|
2022-01-10 17:09:20 +01:00
|
|
|
}
|
2022-01-12 21:14:12 +01:00
|
|
|
|
2022-01-10 17:09:20 +01:00
|
|
|
etapiToken.markAsDeletedSimple();
|
2022-01-12 21:14:12 +01:00
|
|
|
|
2022-01-10 17:09:20 +01:00
|
|
|
res.sendStatus(204);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2024-04-07 15:17:45 +03:00
|
|
|
export = {
|
2022-01-10 17:09:20 +01:00
|
|
|
register
|
2022-01-12 21:14:12 +01:00
|
|
|
}
|