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

AuthSessions.ts

282 lines8.6 KB

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