-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathsession.controller.ts
More file actions
99 lines (94 loc) · 2.15 KB
/
session.controller.ts
File metadata and controls
99 lines (94 loc) · 2.15 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import passport from 'passport';
import { RequestHandler } from 'express';
import { userResponse } from './user.controller';
import type { UserDocument } from '../types';
import {
CreateSessionRequestBody,
CreateSessionResponseBody,
GetSessionResponseBody,
DestroySessionResponseBody
} from '../types';
/**
* - Method: `POST`
* - Endpoint: `/login`
* - Authenticated: `false`
* - Id: `SessionController.createSession`
*
* Description:
* - Authenticate a user with local strategy and create a session
*/
export const createSession: RequestHandler<
{},
CreateSessionResponseBody,
CreateSessionRequestBody
> = (req, res, next) => {
passport.authenticate(
'local',
(err: Error | null, user: UserDocument | false) => {
if (err) {
next(err);
return;
}
if (!user) {
res.status(401).json({ message: 'Invalid username or password.' });
return;
}
req.logIn(user, (innerErr) => {
if (innerErr) {
next(innerErr);
return;
}
res.json(userResponse(user));
});
}
)(req, res, next);
};
/**
* - Method: `GET`
* - Endpoint: `/session`
* - Authenticated: `false`
* - Id: `SessionController.getSession`
*
* Description:
* - Returns the current session user, or null if not logged in
*/
export const getSession: RequestHandler<{}, GetSessionResponseBody> = (
req,
res
) => {
if (!req.user) {
return res.status(200).send({ user: null });
}
if (req.user.banned) {
return res.status(403).send({ message: 'Forbidden: User is banned.' });
}
return res.json(userResponse(req.user));
};
/**
* - Method: `GET`
* - Endpoint: `/logout`
* - Authenticated: `false`
* - Id: `SessionController.destroySession`
*
* Description:
* - Logs out the user and destroys the session
*/
export const destroySession: RequestHandler<{}, DestroySessionResponseBody> = (
req,
res,
next
) => {
req.logout((err: Error | null) => {
if (err) {
next(err);
return;
}
req.session.destroy((error: Error | null) => {
if (error) {
next(error);
return;
}
res.json({ success: true });
});
});
};