Skip to content

Commit bbe71b9

Browse files
committed
refactor(server): use session model in auth service
1 parent 638d63e commit bbe71b9

File tree

3 files changed

+23
-36
lines changed

3 files changed

+23
-36
lines changed

packages/backend/server/src/__tests__/auth/guard.spec.ts

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import request from 'supertest';
66

77
import { AuthModule, CurrentUser, Public, Session } from '../../core/auth';
88
import { AuthService } from '../../core/auth/service';
9+
import { Models } from '../../models';
910
import { createTestingApp } from '../utils';
1011

1112
@Controller('/')
@@ -35,6 +36,8 @@ let server!: any;
3536
let auth!: AuthService;
3637
let u1!: CurrentUser;
3738

39+
let sessionId = '';
40+
3841
test.before(async t => {
3942
const { app } = await createTestingApp({
4043
imports: [AuthModule],
@@ -44,13 +47,10 @@ test.before(async t => {
4447
auth = app.get(AuthService);
4548
u1 = await auth.signUp('u1@affine.pro', '1');
4649

47-
const db = app.get(PrismaClient);
48-
await db.session.create({
49-
data: {
50-
id: '1',
51-
},
52-
});
53-
await auth.createUserSession(u1.id, '1');
50+
const models = app.get(Models);
51+
const session = await models.session.create();
52+
sessionId = session.id;
53+
await auth.createUserSession(u1.id, sessionId);
5454

5555
server = app.getHttpServer();
5656
t.context.app = app;
@@ -69,7 +69,7 @@ test('should be able to visit public api if not signed in', async t => {
6969
test('should be able to visit public api if signed in', async t => {
7070
const res = await request(server)
7171
.get('/public')
72-
.set('Cookie', `${AuthService.sessionCookieName}=1`)
72+
.set('Cookie', `${AuthService.sessionCookieName}=${sessionId}`)
7373
.expect(HttpStatus.OK);
7474

7575
t.is(res.body.user.id, u1.id);
@@ -90,7 +90,7 @@ test('should not be able to visit private api if not signed in', async t => {
9090
test('should be able to visit private api if signed in', async t => {
9191
const res = await request(server)
9292
.get('/private')
93-
.set('Cookie', `${AuthService.sessionCookieName}=1`)
93+
.set('Cookie', `${AuthService.sessionCookieName}=${sessionId}`)
9494
.expect(HttpStatus.OK);
9595

9696
t.is(res.body.user.id, u1.id);
@@ -100,10 +100,10 @@ test('should be able to parse session cookie', async t => {
100100
const spy = Sinon.spy(auth, 'getUserSession');
101101
await request(server)
102102
.get('/public')
103-
.set('cookie', `${AuthService.sessionCookieName}=1`)
103+
.set('cookie', `${AuthService.sessionCookieName}=${sessionId}`)
104104
.expect(200);
105105

106-
t.deepEqual(spy.firstCall.args, ['1', undefined]);
106+
t.deepEqual(spy.firstCall.args, [sessionId, undefined]);
107107
spy.restore();
108108
});
109109

@@ -112,17 +112,17 @@ test('should be able to parse bearer token', async t => {
112112

113113
await request(server)
114114
.get('/public')
115-
.auth('1', { type: 'bearer' })
115+
.auth(sessionId, { type: 'bearer' })
116116
.expect(200);
117117

118-
t.deepEqual(spy.firstCall.args, ['1', undefined]);
118+
t.deepEqual(spy.firstCall.args, [sessionId, undefined]);
119119
spy.restore();
120120
});
121121

122122
test('should be able to refresh session if needed', async t => {
123123
await t.context.app.get(PrismaClient).userSession.updateMany({
124124
where: {
125-
sessionId: '1',
125+
sessionId,
126126
},
127127
data: {
128128
expiresAt: new Date(Date.now() + 1000 * 60 * 60 /* expires in 1 hour */),
@@ -131,7 +131,7 @@ test('should be able to refresh session if needed', async t => {
131131

132132
const res = await request(server)
133133
.get('/session')
134-
.set('cookie', `${AuthService.sessionCookieName}=1`)
134+
.set('cookie', `${AuthService.sessionCookieName}=${sessionId}`)
135135
.expect(200);
136136

137137
const cookie = res

packages/backend/server/src/core/auth/service.ts

Lines changed: 7 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import type { CookieOptions, Request, Response } from 'express';
66
import { assign, pick } from 'lodash-es';
77

88
import { Config, MailService, SignUpForbidden } from '../../base';
9+
import { Models } from '../../models';
910
import { FeatureManagementService } from '../features/management';
1011
import { QuotaService } from '../quota/service';
1112
import { QuotaType } from '../quota/types';
@@ -47,6 +48,7 @@ export class AuthService implements OnApplicationBootstrap {
4748
constructor(
4849
private readonly config: Config,
4950
private readonly db: PrismaClient,
51+
private readonly models: Models,
5052
private readonly mailer: MailService,
5153
private readonly feature: FeatureManagementService,
5254
private readonly quota: QuotaService,
@@ -103,11 +105,7 @@ export class AuthService implements OnApplicationBootstrap {
103105
async signOut(sessionId: string, userId?: string) {
104106
// sign out all users in the session
105107
if (!userId) {
106-
await this.db.session.deleteMany({
107-
where: {
108-
id: sessionId,
109-
},
110-
});
108+
await this.models.session.delete(sessionId);
111109
} else {
112110
await this.db.userSession.deleteMany({
113111
where: {
@@ -138,8 +136,7 @@ export class AuthService implements OnApplicationBootstrap {
138136
// fallback to the first valid session if user provided userId is invalid
139137
if (!userSession) {
140138
// checked
141-
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
142-
userSession = sessions.at(-1)!;
139+
userSession = sessions.at(-1) as UserSession;
143140
}
144141

145142
const user = await this.user.findUserById(userSession.userId);
@@ -170,11 +167,7 @@ export class AuthService implements OnApplicationBootstrap {
170167
) {
171168
// check whether given session is valid
172169
if (sessionId) {
173-
const session = await this.db.session.findFirst({
174-
where: {
175-
id: sessionId,
176-
},
177-
});
170+
const session = await this.getSession(sessionId);
178171

179172
if (!session) {
180173
sessionId = undefined;
@@ -233,17 +226,11 @@ export class AuthService implements OnApplicationBootstrap {
233226
}
234227

235228
async createSession() {
236-
return this.db.session.create({
237-
data: {},
238-
});
229+
return await this.models.session.create();
239230
}
240231

241232
async getSession(sessionId: string) {
242-
return this.db.session.findFirst({
243-
where: {
244-
id: sessionId,
245-
},
246-
});
233+
return await this.models.session.get(sessionId);
247234
}
248235

249236
async refreshUserSessionIfNeeded(

packages/backend/server/src/models/user.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import {
1414
} from '../base';
1515
import type { Payload } from '../base/event/def';
1616
import { Permission } from '../core/permission';
17-
import { Quota_FreePlanV1_1 } from '../core/quota';
17+
import { Quota_FreePlanV1_1 } from '../core/quota/schema';
1818

1919
const publicUserSelect = {
2020
id: true,

0 commit comments

Comments
 (0)