-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession.js
More file actions
98 lines (81 loc) · 2.14 KB
/
session.js
File metadata and controls
98 lines (81 loc) · 2.14 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
import crypto from "node:crypto";
import database from "infra/database.js";
import { UnauthorizedError } from "infra/errors";
const EXPIRATION_IN_MILLISECONDS = 60 * 60 * 24 * 30 * 1000; // 30 Days
async function create(userId) {
const token = crypto.randomBytes(48).toString("hex");
const expiresAt = new Date(Date.now() + EXPIRATION_IN_MILLISECONDS);
const newSession = await runInsertQuery(token, userId, expiresAt);
return newSession;
async function runInsertQuery(token, userId, expiresAt) {
const result = await database.query({
text: `
INSERT INTO
sessions (token, user_id, expires_at)
VALUES
($1, $2, $3)
RETURNING
*
;`,
values: [token, userId, expiresAt],
});
return result.rows[0];
}
}
async function findOneValidByToken(sessionToken) {
const sessionFound = await runSelectQuery(sessionToken);
return sessionFound;
async function runSelectQuery(sessionToken) {
const result = await database.query({
text: `
SELECT
*
FROM
sessions
WHERE
token = $1
AND
expires_at > NOW()
LIMIT
1
;`,
values: [sessionToken],
});
if (result.rowCount === 0) {
throw new UnauthorizedError({
message: "User do not have an active session.",
action: "Verify if you are logged in and try again.",
});
}
return result.rows[0];
}
}
async function renew(sessionId) {
const expiresAt = new Date(Date.now() + EXPIRATION_IN_MILLISECONDS);
const renewedSessionObject = await runUpdateQuery(sessionId, expiresAt);
return renewedSessionObject;
async function runUpdateQuery(sessionId, expiresAt) {
const result = await database.query({
text: `
UPDATE
sessions
SET
expires_at = $2,
updated_at = NOW()
WHERE
id = $1
RETURNING
*
;`,
values: [sessionId, expiresAt],
});
return result.rows[0];
}
}
const session = {
EXPIRATION_IN_MILLISECONDS,
create,
findOneValidByToken,
renew,
};
export default session;