-
-
Notifications
You must be signed in to change notification settings - Fork 139
/
groups-and-permissions.spec.ts
103 lines (84 loc) · 2.67 KB
/
groups-and-permissions.spec.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
// 3p
import { createConnection, Entity, getConnection, getRepository } from '@foal/typeorm/node_modules/typeorm';
import * as request from 'supertest';
// FoalTS
import {
createApp,
createService,
Get,
HttpResponseNoContent,
TokenRequired,
} from '@foal/core';
import {
fetchUserWithPermissions,
Group,
Permission,
PermissionRequired,
TypeORMStore,
UserWithPermissions
} from '@foal/typeorm';
describe('[Authorization|permissions] Users', () => {
let app;
let tokenUser1: string;
let tokenUser2: string;
@Entity()
class User extends UserWithPermissions {}
@TokenRequired({ user: fetchUserWithPermissions(User), store: TypeORMStore })
class AppController {
@Get('/bar')
@PermissionRequired('access-bar')
bar() {
return new HttpResponseNoContent();
}
@Get('/foo')
@PermissionRequired('access-foo')
foo() {
return new HttpResponseNoContent();
}
}
before(async () => {
process.env.SETTINGS_SESSION_SECRET = 'session-secret';
await createConnection({
database: 'e2e_db.sqlite',
dropSchema: true,
entities: [ User, Permission, Group ],
synchronize: true,
type: 'sqlite',
});
const user1 = new User();
const user2 = new User();
const perm = new Permission();
perm.codeName = 'access-foo';
perm.name = 'Foo permission';
await getRepository(Permission).save(perm);
const group = new Group();
group.name = 'Administrators';
group.codeName = 'administrators';
group.permissions = [ perm ];
await getRepository(Group).save(group);
user1.userPermissions = [ perm ];
user2.groups = [ group ];
await getRepository(User).save([ user1, user2 ]);
const session1 = await createService(TypeORMStore).createAndSaveSessionFromUser(user1);
tokenUser1 = session1.getToken();
const session2 = await createService(TypeORMStore).createAndSaveSessionFromUser(user2);
tokenUser2 = session2.getToken();
app = createApp(AppController);
});
after(async () => {
await getConnection().close();
delete process.env.SETTINGS_SESSION_SECRET;
});
it('cannot access protected routes if they do not have the permission.', () => {
return Promise.all([
request(app).get('/bar').set('Authorization', `Bearer ${tokenUser1}`).expect(403),
request(app).get('/bar').set('Authorization', `Bearer ${tokenUser2}`).expect(403),
]);
});
it('can access protected routes if they have the permission.', () => {
return Promise.all([
request(app).get('/foo').set('Authorization', `Bearer ${tokenUser1}`).expect(204),
request(app).get('/foo').set('Authorization', `Bearer ${tokenUser2}`).expect(204),
]);
});
});