UNPKG

2.64 kBJavaScriptView Raw
1require('./utils/trxify-tests')
2
3const ACLs = require('./acls')
4const BaseUser = require('./models/user')
5const authorizePlugin = require('../src')
6
7describe.each(ACLs)('Update queries (%s)', (library, acl) => {
8 class User extends authorizePlugin(acl, library)(BaseUser) {}
9
10 test('restrict access with automatically fetched context', async () => {
11 // you shouldn't be able to change a user as someone else...
12 // for update, need to "filter out" fields from the item that are the same
13 await expect(
14 User.query()
15 .findById(1)
16 .update({ id: 1, metadata: { mutableField: 'hello!' } })
17 .authorize({ id: 2, role: 'user' })
18 .fetchResourceContextFromDB()
19 .diffInputFromResource()
20 ).rejects.toThrow()
21
22 // but a user should be able to change their own account
23 await User.query()
24 .findById(2)
25 .update({ id: 2, metadata: { mutableField: 'hello!' } })
26 .authorize({ id: 2, role: 'user' })
27 .fetchResourceContextFromDB()
28 .diffInputFromResource()
29 })
30
31 test('restrict access with manually passed context', async () => {
32 // you shouldn't be able to change a user as someone else...
33 await expect(
34 User.query()
35 .findById(1)
36 .update({ id: 1, metadata: { mutableField: 'hello!' } })
37 .authorize({ id: 2, role: 'user' }, { id: 1 })
38 .diffInputFromResource()
39 ).rejects.toThrow()
40
41 // but a user should be able to change their own account
42 await User.query()
43 .findById(2)
44 .update({ id: 2, metadata: { mutableField: 'hello!' } })
45 .authorize({ id: 2, role: 'user' }, { id: 2 })
46 .diffInputFromResource()
47 })
48
49 test('fetches resource from model instance', async () => {
50 const user = await User.query().findById(1)
51
52 await expect(
53 user
54 .$query()
55 .update({ id: 1, metadata: { mutableField: 'hello' } })
56 .authorize({ id: 2, role: 'user' })
57 .diffInputFromResource()
58 ).rejects.toThrow()
59
60 await user
61 .$query()
62 .update({ id: 1, metadata: { mutableField: 'hello!' } })
63 .authorize({ id: 1, role: 'user' })
64 .diffInputFromResource()
65 })
66
67 test('prevent setting an invalid field', async () => {
68 await expect(
69 User.query()
70 .updateAndFetchById(1, { id: 1, metadata: { fixedField: 'whoops!' } })
71 .authorize({ id: 1, role: 'user' }, { id: 1 })
72 .diffInputFromResource()
73 ).rejects.toThrow()
74
75 await User.query()
76 .updateAndFetchById(1, { id: 1, metadata: { mutableField: 'hello' } })
77 .authorize({ id: 1, role: 'user' }, { id: 1 })
78 .diffInputFromResource()
79 })
80})