-
Notifications
You must be signed in to change notification settings - Fork 1
/
authentication.ts
64 lines (52 loc) · 1.75 KB
/
authentication.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import { FastifyInstance, FastifyRequest } from 'fastify';
import Auth from '../lib/authentication';
import { ChtApi } from '../lib/cht-api';
import { Config } from '../config';
import { version as appVersion } from '../package.json';
export default async function authentication(fastify: FastifyInstance) {
const unauthenticatedOptions = {
preParsing: async (req : FastifyRequest) => {
req.unauthenticated = true;
},
};
fastify.get('/login', unauthenticatedOptions, async (req, resp) => {
const tmplData = {
logo: Config.getLogoBase64(),
domains: Config.getDomains,
};
return resp.view('src/public/auth/view.html', tmplData);
});
fastify.get('/logout', unauthenticatedOptions, async (req, resp) => {
resp.clearCookie(Auth.AUTH_COOKIE_NAME);
return resp.redirect('/login');
});
fastify.post('/authenticate', unauthenticatedOptions, async (req, resp) => {
const data: any = req.body;
const { username, password, domain } = data;
const authInfo = Config.getAuthenticationInfo(domain);
let session;
try {
session = await ChtApi.createSession(authInfo, username, password);
} catch (e: any) {
return resp.view('src/public/auth/authentication_form.html', {
domains: Config.getDomains,
errors: true,
});
}
const tokenizedSession = Auth.encodeToken(session);
const expires = Auth.cookieExpiry();
resp.setCookie(Auth.AUTH_COOKIE_NAME, tokenizedSession, {
signed: false,
httpOnly: true,
expires,
secure: true
});
resp.header('HX-Redirect', `/`);
});
fastify.get('/_healthz', unauthenticatedOptions, () => {
return 'OK';
});
fastify.get('/version', unauthenticatedOptions, () => {
return appVersion;
});
}