-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathsession.service.ts
319 lines (296 loc) · 12.9 KB
/
session.service.ts
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import { Injectable } from '@nestjs/common';
import { ID } from '@vendure/common/lib/shared-types';
import crypto from 'crypto';
import ms from 'ms';
import { EntitySubscriberInterface, InsertEvent, RemoveEvent, UpdateEvent } from 'typeorm';
import { RequestContext } from '../../api/common/request-context';
import { ConfigService } from '../../config/config.service';
import { CachedSession, SessionCacheStrategy } from '../../config/session-cache/session-cache-strategy';
import { TransactionalConnection } from '../../connection/transactional-connection';
import { Channel } from '../../entity/channel/channel.entity';
import { Order } from '../../entity/order/order.entity';
import { Role } from '../../entity/role/role.entity';
import { AnonymousSession } from '../../entity/session/anonymous-session.entity';
import { AuthenticatedSession } from '../../entity/session/authenticated-session.entity';
import { Session } from '../../entity/session/session.entity';
import { User } from '../../entity/user/user.entity';
import { getUserChannelsPermissions } from '../helpers/utils/get-user-channels-permissions';
import { OrderService } from './order.service';
/**
* @description
* Contains methods relating to {@link Session} entities.
*
* @docsCategory services
*/
@Injectable()
export class SessionService implements EntitySubscriberInterface {
private sessionCacheStrategy: SessionCacheStrategy;
private readonly sessionDurationInMs: number;
constructor(
private connection: TransactionalConnection,
private configService: ConfigService,
private orderService: OrderService,
) {
this.sessionCacheStrategy = this.configService.authOptions.sessionCacheStrategy;
this.sessionDurationInMs = ms(this.configService.authOptions.sessionDuration as string);
// This allows us to register this class as a TypeORM Subscriber while also allowing
// the injection on dependencies. See https://docs.nestjs.com/techniques/database#subscribers
this.connection.rawConnection.subscribers.push(this);
}
/** @internal */
afterInsert(event: InsertEvent<any>): Promise<any> | void {
this.clearSessionCacheOnDataChange(event);
}
/** @internal */
afterRemove(event: RemoveEvent<any>): Promise<any> | void {
this.clearSessionCacheOnDataChange(event);
}
/** @internal */
afterUpdate(event: UpdateEvent<any>): Promise<any> | void {
this.clearSessionCacheOnDataChange(event);
}
private async clearSessionCacheOnDataChange(
event: InsertEvent<any> | RemoveEvent<any> | UpdateEvent<any>,
) {
if (event.entity) {
// If a Channel or Role changes, potentially all the cached permissions in the
// session cache will be wrong, so we just clear the entire cache. It should however
// be a very rare occurrence in normal operation, once initial setup is complete.
if (event.entity instanceof Channel || event.entity instanceof Role) {
await this.sessionCacheStrategy.clear();
}
}
}
/**
* @description
* Creates a new {@link AuthenticatedSession}. To be used after successful authentication.
*/
async createNewAuthenticatedSession(
ctx: RequestContext,
user: User,
authenticationStrategyName: string,
): Promise<AuthenticatedSession> {
const token = await this.generateSessionToken();
const guestOrder =
ctx.session && ctx.session.activeOrderId
? await this.orderService.findOne(ctx, ctx.session.activeOrderId)
: undefined;
const existingOrder = await this.orderService.getActiveOrderForUser(ctx, user.id);
const activeOrder = await this.orderService.mergeOrders(ctx, user, guestOrder, existingOrder);
const authenticatedSession = await this.connection.getRepository(ctx, AuthenticatedSession).save(
new AuthenticatedSession({
token,
user,
activeOrder,
authenticationStrategy: authenticationStrategyName,
expires: this.getExpiryDate(this.sessionDurationInMs),
invalidated: false,
}),
);
await this.sessionCacheStrategy.set(this.serializeSession(authenticatedSession));
return authenticatedSession;
}
/**
* @description
* Create an {@link AnonymousSession} and caches it using the configured {@link SessionCacheStrategy},
* and returns the cached session object.
*/
async createAnonymousSession(): Promise<CachedSession> {
const token = await this.generateSessionToken();
const anonymousSessionDurationInMs = ms('1y');
const session = new AnonymousSession({
token,
expires: this.getExpiryDate(anonymousSessionDurationInMs),
invalidated: false,
});
// save the new session
const newSession = await this.connection.getRepository(AnonymousSession).save(session);
const serializedSession = this.serializeSession(newSession);
await this.sessionCacheStrategy.set(serializedSession);
return serializedSession;
}
/**
* @description
* Returns the cached session object matching the given session token.
*/
async getSessionFromToken(sessionToken: string): Promise<CachedSession | undefined> {
let serializedSession = await this.sessionCacheStrategy.get(sessionToken);
const stale = !!(serializedSession && serializedSession.cacheExpiry < new Date().getTime() / 1000);
const expired = !!(serializedSession && serializedSession.expires < new Date());
if (!serializedSession || stale || expired) {
const session = await this.findSessionByToken(sessionToken);
if (session) {
serializedSession = this.serializeSession(session);
await this.sessionCacheStrategy.set(serializedSession);
return serializedSession;
} else {
return;
}
}
return serializedSession;
}
/**
* @description
* Serializes a {@link Session} instance into a simplified plain object suitable for caching.
*/
serializeSession(session: AuthenticatedSession | AnonymousSession): CachedSession {
const expiry =
Math.floor(new Date().getTime() / 1000) + this.configService.authOptions.sessionCacheTTL;
const serializedSession: CachedSession = {
cacheExpiry: expiry,
id: session.id,
token: session.token,
expires: session.expires,
activeOrderId: session.activeOrderId,
activeChannelId: session.activeChannelId,
};
if (this.isAuthenticatedSession(session)) {
serializedSession.authenticationStrategy = session.authenticationStrategy;
const { user } = session;
serializedSession.user = {
id: user.id,
identifier: user.identifier,
verified: user.verified,
channelPermissions: getUserChannelsPermissions(user),
};
}
return serializedSession;
}
/**
* Looks for a valid session with the given token and returns one if found.
*/
private async findSessionByToken(token: string): Promise<Session | undefined> {
const session = await this.connection
.getRepository(Session)
.createQueryBuilder('session')
.leftJoinAndSelect('session.user', 'user')
.leftJoinAndSelect('user.roles', 'roles')
.leftJoinAndSelect('roles.channels', 'channels')
.where('session.token = :token', { token })
.andWhere('session.invalidated = false')
.getOne();
if (session && session.expires > new Date()) {
await this.updateSessionExpiry(session);
return session;
}
}
/**
* @description
* Sets the `activeOrder` on the given cached session object and updates the cache.
*/
async setActiveOrder(
ctx: RequestContext,
serializedSession: CachedSession,
order: Order,
): Promise<CachedSession> {
const session = await this.connection
.getRepository(Session)
.findOne(serializedSession.id, { relations: ['user', 'user.roles', 'user.roles.channels'] });
if (session) {
session.activeOrder = order;
await this.connection.getRepository(ctx, Session).save(session, { reload: false });
const updatedSerializedSession = this.serializeSession(session);
await this.sessionCacheStrategy.set(updatedSerializedSession);
return updatedSerializedSession;
}
return serializedSession;
}
/**
* @description
* Clears the `activeOrder` on the given cached session object and updates the cache.
*/
async unsetActiveOrder(ctx: RequestContext, serializedSession: CachedSession): Promise<CachedSession> {
if (serializedSession.activeOrderId) {
const session = await this.connection
.getRepository(Session)
.findOne(serializedSession.id, { relations: ['user', 'user.roles', 'user.roles.channels'] });
if (session) {
session.activeOrder = null;
await this.connection.getRepository(ctx, Session).save(session);
const updatedSerializedSession = this.serializeSession(session);
await this.configService.authOptions.sessionCacheStrategy.set(updatedSerializedSession);
return updatedSerializedSession;
}
}
return serializedSession;
}
/**
* @description
* Sets the `activeChannel` on the given cached session object and updates the cache.
*/
async setActiveChannel(serializedSession: CachedSession, channel: Channel): Promise<CachedSession> {
const session = await this.connection
.getRepository(Session)
.findOne(serializedSession.id, { relations: ['user', 'user.roles', 'user.roles.channels'] });
if (session) {
session.activeChannel = channel;
await this.connection.getRepository(Session).save(session, { reload: false });
const updatedSerializedSession = this.serializeSession(session);
await this.sessionCacheStrategy.set(updatedSerializedSession);
return updatedSerializedSession;
}
return serializedSession;
}
/**
* @description
* Deletes all existing sessions for the given user.
*/
async deleteSessionsByUser(ctx: RequestContext, user: User): Promise<void> {
const userSessions = await this.connection
.getRepository(ctx, AuthenticatedSession)
.find({ where: { user } });
await this.connection.getRepository(ctx, AuthenticatedSession).remove(userSessions);
for (const session of userSessions) {
await this.sessionCacheStrategy.delete(session.token);
}
}
/**
* @description
* Deletes all existing sessions with the given activeOrder.
*/
async deleteSessionsByActiveOrderId(ctx: RequestContext, activeOrderId: ID): Promise<void> {
const sessions = await this.connection.getRepository(ctx, Session).find({ where: { activeOrderId } });
await this.connection.getRepository(ctx, Session).remove(sessions);
for (const session of sessions) {
await this.sessionCacheStrategy.delete(session.token);
}
}
/**
* If we are over half way to the current session's expiry date, then we update it.
*
* This ensures that the session will not expire when in active use, but prevents us from
* needing to run an update query on *every* request.
*/
private async updateSessionExpiry(session: Session) {
const now = new Date().getTime();
if (session.expires.getTime() - now < this.sessionDurationInMs / 2) {
const newExpiryDate = this.getExpiryDate(this.sessionDurationInMs);
session.expires = newExpiryDate;
await this.connection
.getRepository(Session)
.update({ id: session.id }, { expires: newExpiryDate });
}
}
/**
* Returns a future expiry date according timeToExpireInMs in the future.
*/
private getExpiryDate(timeToExpireInMs: number): Date {
return new Date(Date.now() + timeToExpireInMs);
}
/**
* Generates a random session token.
*/
private generateSessionToken(): Promise<string> {
return new Promise((resolve, reject) => {
crypto.randomBytes(32, (err, buf) => {
if (err) {
reject(err);
}
resolve(buf.toString('hex'));
});
});
}
private isAuthenticatedSession(session: Session): session is AuthenticatedSession {
return session.hasOwnProperty('user');
}
}