Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AuthSessions.ts

279 lines8.5 KB

1import { AuthSessionId } from "@t3tools/contracts";
2import * as SqlClient from "effect/unstable/sql/SqlClient";
3import * as SqlSchema from "effect/unstable/sql/SqlSchema";
4import { Effect, Layer, Option, Schema } from "effect";
5​
6import {
7 toPersistenceDecodeError,
8 toPersistenceSqlError,
9 type AuthSessionRepositoryError,
10} from "../Errors.ts";
11import {
12 AuthSessionRecord,
13 AuthSessionRepository,
14 type AuthSessionRepositoryShape,
15 CreateAuthSessionInput,
16 GetAuthSessionByIdInput,
17 ListActiveAuthSessionsInput,
18 RevokeAuthSessionInput,
19 RevokeOtherAuthSessionsInput,
20 SetAuthSessionLastConnectedAtInput,
21} from "../Services/AuthSessions.ts";
22​
23const AuthSessionDbRow = Schema.Struct({
24 sessionId: AuthSessionId,
25 subject: Schema.String,
26 role: Schema.Literals(["owner", "client"]),
27 method: Schema.Literals(["browser-session-cookie", "bearer-session-token"]),
28 clientLabel: Schema.NullOr(Schema.String),
29 clientIpAddress: Schema.NullOr(Schema.String),
30 clientUserAgent: Schema.NullOr(Schema.String),
31 clientDeviceType: Schema.Literals(["desktop", "mobile", "tablet", "bot", "unknown"]),
32 clientOs: Schema.NullOr(Schema.String),
33 clientBrowser: Schema.NullOr(Schema.String),
34 issuedAt: Schema.DateTimeUtcFromString,
35 expiresAt: Schema.DateTimeUtcFromString,
36 lastConnectedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
37 revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
38});
39​
40function toAuthSessionRecord(row: typeof AuthSessionDbRow.Type): typeof AuthSessionRecord.Type {
41 return {
42 sessionId: row.sessionId,
43 subject: row.subject,
44 role: row.role,
45 method: row.method,
46 client: {
47 label: row.clientLabel,
48 ipAddress: row.clientIpAddress,
49 userAgent: row.clientUserAgent,
50 deviceType: row.clientDeviceType,
51 os: row.clientOs,
52 browser: row.clientBrowser,
53 },
54 issuedAt: row.issuedAt,
55 expiresAt: row.expiresAt,
56 lastConnectedAt: row.lastConnectedAt,
57 revokedAt: row.revokedAt,
58 };
60​
61function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
62 return (cause: unknown): AuthSessionRepositoryError =>
63 Schema.isSchemaError(cause)
64 ? toPersistenceDecodeError(decodeOperation)(cause)
65 : toPersistenceSqlError(sqlOperation)(cause);
67​
68const makeAuthSessionRepository = Effect.gen(function* () {
69 const sql = yield* SqlClient.SqlClient;
70​
71 const createSessionRow = SqlSchema.void({
72 Request: CreateAuthSessionInput,
73 execute: (input) =>
74 sql`
75 INSERT INTO auth_sessions (
76 session_id,
77 subject,
78 role,
79 method,
80 client_label,
81 client_ip_address,
82 client_user_agent,
83 client_device_type,
84 client_os,
85 client_browser,
86 issued_at,
87 expires_at,
88 revoked_at
89 )
90 VALUES (
91 ${input.sessionId},
92 ${input.subject},
93 ${input.role},
94 ${input.method},
95 ${input.client.label},
96 ${input.client.ipAddress},
97 ${input.client.userAgent},
98 ${input.client.deviceType},
99 ${input.client.os},
100 ${input.client.browser},
101 ${input.issuedAt},
102 ${input.expiresAt},
103 NULL
104 )
105 `,
106 });
107​
108 const getSessionRowById = SqlSchema.findOneOption({
109 Request: GetAuthSessionByIdInput,
110 Result: AuthSessionDbRow,
111 execute: ({ sessionId }) =>
112 sql`
113 SELECT
114 session_id AS "sessionId",
115 subject AS "subject",
116 role AS "role",
117 method AS "method",
118 client_label AS "clientLabel",
119 client_ip_address AS "clientIpAddress",
120 client_user_agent AS "clientUserAgent",
121 client_device_type AS "clientDeviceType",
122 client_os AS "clientOs",
123 client_browser AS "clientBrowser",
124 issued_at AS "issuedAt",
125 expires_at AS "expiresAt",
126 last_connected_at AS "lastConnectedAt",
127 revoked_at AS "revokedAt"
128 FROM auth_sessions
129 WHERE session_id = ${sessionId}
130 `,
131 });
132​
133 const listActiveSessionRows = SqlSchema.findAll({
134 Request: ListActiveAuthSessionsInput,
135 Result: AuthSessionDbRow,
136 execute: ({ now }) =>
137 sql`
138 SELECT
139 session_id AS "sessionId",
140 subject AS "subject",
141 role AS "role",
142 method AS "method",
143 client_label AS "clientLabel",
144 client_ip_address AS "clientIpAddress",
145 client_user_agent AS "clientUserAgent",
146 client_device_type AS "clientDeviceType",
147 client_os AS "clientOs",
148 client_browser AS "clientBrowser",
149 issued_at AS "issuedAt",
150 expires_at AS "expiresAt",
151 last_connected_at AS "lastConnectedAt",
152 revoked_at AS "revokedAt"
153 FROM auth_sessions
154 WHERE revoked_at IS NULL
155 AND expires_at > ${now}
156 ORDER BY issued_at DESC, session_id DESC
157 `,
158 });
159​
160 const setLastConnectedAtRow = SqlSchema.void({
161 Request: SetAuthSessionLastConnectedAtInput,
162 execute: ({ sessionId, lastConnectedAt }) =>
163 sql`
164 UPDATE auth_sessions
165 SET last_connected_at = ${lastConnectedAt}
166 WHERE session_id = ${sessionId}
167 AND revoked_at IS NULL
168 `,
169 });
170​
171 const revokeSessionRows = SqlSchema.findAll({
172 Request: RevokeAuthSessionInput,
173 Result: Schema.Struct({ sessionId: AuthSessionId }),
174 execute: ({ sessionId, revokedAt }) =>
175 sql`
176 UPDATE auth_sessions
177 SET revoked_at = ${revokedAt}
178 WHERE session_id = ${sessionId}
179 AND revoked_at IS NULL
180 RETURNING session_id AS "sessionId"
181 `,
182 });
183​
184 const revokeOtherSessionRows = SqlSchema.findAll({
185 Request: RevokeOtherAuthSessionsInput,
186 Result: Schema.Struct({ sessionId: AuthSessionId }),
187 execute: ({ currentSessionId, revokedAt }) =>
188 sql`
189 UPDATE auth_sessions
190 SET revoked_at = ${revokedAt}
191 WHERE session_id <> ${currentSessionId}
192 AND revoked_at IS NULL
193 RETURNING session_id AS "sessionId"
194 `,
195 });
196​
197 const create: AuthSessionRepositoryShape["create"] = (input) =>
198 createSessionRow(input).pipe(
199 Effect.mapError(
200 toPersistenceSqlOrDecodeError(
201 "AuthSessionRepository.create:query",
202 "AuthSessionRepository.create:encodeRequest",
203 ),
204 ),
205 );
206​
207 const getById: AuthSessionRepositoryShape["getById"] = (input) =>
208 getSessionRowById(input).pipe(
209 Effect.mapError(
210 toPersistenceSqlOrDecodeError(
211 "AuthSessionRepository.getById:query",
212 "AuthSessionRepository.getById:decodeRow",
213 ),
214 ),
215 Effect.flatMap((rowOption) =>
216 Option.match(rowOption, {
217 onNone: () => Effect.succeed(Option.none()),
218 onSome: (row) => Effect.succeed(Option.some(toAuthSessionRecord(row))),
219 }),
220 ),
221 );
222​
223 const listActive: AuthSessionRepositoryShape["listActive"] = (input) =>
224 listActiveSessionRows(input).pipe(
225 Effect.mapError(
226 toPersistenceSqlOrDecodeError(
227 "AuthSessionRepository.listActive:query",
228 "AuthSessionRepository.listActive:decodeRows",
229 ),
230 ),
231 Effect.flatMap((rows) => Effect.succeed(rows.map((row) => toAuthSessionRecord(row)))),
232 );
233​
234 const revoke: AuthSessionRepositoryShape["revoke"] = (input) =>
235 revokeSessionRows(input).pipe(
236 Effect.mapError(
237 toPersistenceSqlOrDecodeError(
238 "AuthSessionRepository.revoke:query",
239 "AuthSessionRepository.revoke:decodeRows",
240 ),
241 ),
242 Effect.map((rows) => rows.length > 0),
243 );
244​
245 const revokeAllExcept: AuthSessionRepositoryShape["revokeAllExcept"] = (input) =>
246 revokeOtherSessionRows(input).pipe(
247 Effect.mapError(
248 toPersistenceSqlOrDecodeError(
249 "AuthSessionRepository.revokeAllExcept:query",
250 "AuthSessionRepository.revokeAllExcept:decodeRows",
251 ),
252 ),
253 Effect.map((rows) => rows.map((row) => row.sessionId)),
254 );
255​
256 const setLastConnectedAt: AuthSessionRepositoryShape["setLastConnectedAt"] = (input) =>
257 setLastConnectedAtRow(input).pipe(
258 Effect.mapError(
259 toPersistenceSqlOrDecodeError(
260 "AuthSessionRepository.setLastConnectedAt:query",
261 "AuthSessionRepository.setLastConnectedAt:encodeRequest",
262 ),
263 ),
264 );
265​
266 return {
267 create,
268 getById,
269 listActive,
270 revoke,
271 revokeAllExcept,
272 setLastConnectedAt,
273 } satisfies AuthSessionRepositoryShape;
274});
275​
276export const AuthSessionRepositoryLive = Layer.effect(
277 AuthSessionRepository,
278 makeAuthSessionRepository,
279);