forked from TomDoesTech/Testing-Express-REST-API
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession.controller.ts
More file actions
57 lines (43 loc) · 1.49 KB
/
Copy pathsession.controller.ts
File metadata and controls
57 lines (43 loc) · 1.49 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
import { Request, Response } from "express";
import config from "config";
import {
createSession,
findSessions,
updateSession,
} from "../service/session.service";
import { validatePassword } from "../service/user.service";
import { signJwt } from "../utils/jwt.utils";
export async function createUserSessionHandler(req: Request, res: Response) {
// Validate the user's password
const user = await validatePassword(req.body);
if (!user) {
return res.status(401).send("Invalid email or password");
}
// create a session
const session = await createSession(user._id, req.get("user-agent") || "");
// create an access token
const accessToken = signJwt(
{ ...user, session: session._id },
{ expiresIn: config.get("accessTokenTtl") } // 15 minutes
);
// create a refresh token
const refreshToken = signJwt(
{ ...user, session: session._id },
{ expiresIn: config.get("refreshTokenTtl") } // 15 minutes
);
// return access & refresh tokens
return res.send({ accessToken, refreshToken });
}
export async function getUserSessionsHandler(req: Request, res: Response) {
const userId = res.locals.user._id;
const sessions = await findSessions({ user: userId, valid: true });
return res.send(sessions);
}
export async function deleteSessionHandler(req: Request, res: Response) {
const sessionId = res.locals.user.session;
await updateSession({ _id: sessionId }, { valid: false });
return res.send({
accessToken: null,
refreshToken: null,
});
}