-
-
Notifications
You must be signed in to change notification settings - Fork 520
/
Copy pathsocial.test.ts
278 lines (254 loc) · 10.1 KB
/
social.test.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
import { ConnectorType, type CreateUser, type User } from '@logto/schemas';
import { pickDefault } from '@logto/shared/esm';
import { removeUndefinedKeys } from '@silverhand/essentials';
import {
mockConnector0,
mockLogtoConnector,
mockLogtoConnectorList,
mockMetadata0,
} from '#src/__mocks__/index.js';
import { mockUser } from '#src/__mocks__/user.js';
import RequestError from '#src/errors/RequestError/index.js';
import { type InsertUserResult } from '#src/libraries/user.js';
import type Libraries from '#src/tenants/Libraries.js';
import type Queries from '#src/tenants/Queries.js';
import { MockTenant, type Partial2 } from '#src/test-utils/tenant.js';
import assertThat from '#src/utils/assert-that.js';
import { createRequester } from '#src/utils/test-utils.js';
const { jest } = import.meta;
const notExistedUserId = 'notExistedUserId';
const newTarget = 'newTarget';
const newIdentity = {
userId: 'newUserId',
};
const mockHasUserWithIdentity = jest.fn(async () => false);
const mockedQueries = {
users: {
findUserById: jest.fn(async (id: string) => {
if (id === notExistedUserId) {
throw new RequestError({ code: 'entity.not_exists', status: 404 });
}
return mockUser;
}),
hasUserWithIdentity: mockHasUserWithIdentity,
deleteUserById: jest.fn(),
deleteUserIdentity: jest.fn(),
},
} satisfies Partial2<Queries>;
const usersLibraries = {
generateUserId: jest.fn(async () => 'fooId'),
insertUser: jest.fn(
async (user: CreateUser): Promise<InsertUserResult> => [
{
...mockUser,
...removeUndefinedKeys(user), // No undefined values will be returned from database
},
{ organizationIds: [] },
]
),
updateUserById: jest.fn(
async (_, data: Partial<CreateUser>): Promise<User> => ({
...mockUser,
...data,
})
),
} satisfies Partial<Libraries['users']>;
const mockGetLogtoConnectors = jest.fn(async () => mockLogtoConnectorList);
const mockedConnectors = {
getLogtoConnectors: mockGetLogtoConnectors,
getLogtoConnectorById: async (connectorId: string) => {
const connectors = await mockGetLogtoConnectors();
const connector = connectors.find(({ dbEntry }) => dbEntry.id === connectorId);
assertThat(
connector,
new RequestError({
code: 'entity.not_found',
connectorId,
status: 404,
})
);
return connector;
},
};
const { findUserById, deleteUserIdentity } = mockedQueries.users;
const { updateUserById } = usersLibraries;
const adminUserSocialRoutes = await pickDefault(import('./social.js'));
describe('Admin user social identities APIs', () => {
const tenantContext = new MockTenant(undefined, mockedQueries, mockedConnectors, {
users: usersLibraries,
});
const userRequest = createRequester({ authedRoutes: adminUserSocialRoutes, tenantContext });
describe('PUT /users/:userId/identities/:target', () => {
afterEach(() => {
jest.clearAllMocks();
});
it('should throw if user cannot be found', async () => {
await expect(
userRequest.put(`/users/${notExistedUserId}/identities/${newTarget}`).send(newIdentity)
).resolves.toHaveProperty('status', 404);
expect(updateUserById).not.toHaveBeenCalled();
});
it('should throw if user already has the social identity', async () => {
mockHasUserWithIdentity.mockResolvedValueOnce(true);
const mockedFindUserById = findUserById as jest.Mock;
mockedFindUserById.mockImplementationOnce(() => ({
...mockUser,
identities: {},
}));
await expect(
userRequest.put(`/users/foo/identities/${newTarget}`).send(newIdentity)
).resolves.toHaveProperty('status', 422);
expect(updateUserById).not.toHaveBeenCalled();
});
it('should update user with new social identity (response status 200)', async () => {
const mockedFindUserById = findUserById as jest.Mock;
mockedFindUserById.mockImplementationOnce(() => ({
...mockUser,
identities: { [newTarget]: { userId: 'socialIdForTarget1' } },
}));
await expect(
userRequest.put(`/users/foo/identities/${newTarget}`).send(newIdentity)
).resolves.toHaveProperty('status', 200);
expect(updateUserById).toHaveBeenCalledWith('foo', {
identities: {
[newTarget]: newIdentity,
},
});
});
it('should add new social identity to the user (response status 201)', async () => {
const mockedFindUserById = findUserById as jest.Mock;
mockedFindUserById.mockImplementationOnce(() => ({
...mockUser,
identities: { connectorTarget1: { userId: 'socialIdForTarget1' } },
}));
await expect(
userRequest.put(`/users/foo/identities/${newTarget}`).send(newIdentity)
).resolves.toHaveProperty('status', 201);
expect(updateUserById).toHaveBeenCalledWith('foo', {
identities: {
connectorTarget1: { userId: 'socialIdForTarget1' },
[newTarget]: newIdentity,
},
});
});
});
describe('POST /users/:userId/identities', () => {
it('should throw if user cannot be found', async () => {
// Mock connector with id 'id0' is declared in mockLogtoConnectorList
await expect(
userRequest
.post(`/users/${notExistedUserId}/identities`)
.send({ connectorId: 'id0', connectorData: { code: 'random_code' } })
).resolves.toHaveProperty('status', 404);
expect(updateUserById).not.toHaveBeenCalled();
});
it('should throw if user is found but connector cannot be found', async () => {
const nonExistConnectorId = 'non_exist_connector_id';
await expect(
userRequest
.post(`/users/foo/identities`)
.send({ connectorId: nonExistConnectorId, connectorData: { code: 'random_code' } })
).resolves.toHaveProperty('status', 404);
expect(updateUserById).not.toHaveBeenCalled();
});
it('should throw if connector type is not social', async () => {
// Mock connector with id 'id1' is declared in mockLogtoConnectorList, whose type is sms (not social)
await expect(
userRequest
.post(`/users/foo/identities`)
.send({ connectorId: 'id1', connectorData: { code: 'random_code' } })
).resolves.toHaveProperty('status', 422);
expect(updateUserById).not.toHaveBeenCalled();
});
it('should throw if user already has the social identity', async () => {
mockHasUserWithIdentity.mockResolvedValueOnce(true);
mockGetLogtoConnectors.mockResolvedValueOnce([
{
dbEntry: mockConnector0,
metadata: { ...mockMetadata0 },
type: ConnectorType.Social,
...mockLogtoConnector,
getAuthorizationUri: async () => 'http://example.com',
getUserInfo: async () => ({ id: 'foo' }),
},
]);
const mockedFindUserById = findUserById as jest.Mock;
mockedFindUserById.mockImplementationOnce(() => ({
...mockUser,
identities: { connector_0: {} }, // This value 'connector_0' is declared in mockLogtoConnectorList
}));
await expect(
userRequest
.post(`/users/foo/identities`)
.send({ connectorId: 'id0', connectorData: { code: 'random_code' } })
).resolves.toHaveProperty('status', 422);
expect(updateUserById).not.toHaveBeenCalled();
});
it('should update user with new social identity', async () => {
const mockedSocialUserInfo = { id: 'socialId' };
mockGetLogtoConnectors.mockResolvedValueOnce([
{
dbEntry: mockConnector0,
metadata: { ...mockMetadata0 },
type: ConnectorType.Social,
...mockLogtoConnector,
getAuthorizationUri: async () => 'http://example.com',
getUserInfo: async () => mockedSocialUserInfo,
},
]);
const mockedFindUserById = findUserById as jest.Mock;
mockedFindUserById.mockImplementationOnce(() => ({
...mockUser,
identities: { connectorTarget1: { userId: 'socialIdForTarget1' } },
}));
await expect(
userRequest
.post(`/users/foo/identities`)
.send({ connectorId: 'id0', connectorData: { code: 'random_code' } })
).resolves.toHaveProperty('status', 200);
expect(updateUserById).toHaveBeenCalledWith('foo', {
identities: {
connectorTarget1: { userId: 'socialIdForTarget1' },
connector_0: { userId: 'socialId', details: mockedSocialUserInfo },
},
});
});
});
describe('DELETE /users/:userId/identities/:target', () => {
it('should throw if user cannot be found', async () => {
const arbitraryTarget = 'arbitraryTarget';
await expect(
userRequest.delete(`/users/foo/identities/${arbitraryTarget}`)
).resolves.toHaveProperty('status', 404);
expect(deleteUserIdentity).not.toHaveBeenCalled();
});
it('should throw if user is found but connector cannot be found', async () => {
const arbitraryUserId = 'arbitraryUserId';
const nonExistedTarget = 'nonExistedTarget';
const mockedFindUserById = findUserById as jest.Mock;
mockedFindUserById.mockImplementationOnce((userId) => {
if (userId === arbitraryUserId) {
return { identities: { connector1: {}, connector2: {} } };
}
});
await expect(
userRequest.delete(`/users/${arbitraryUserId}/identities/${nonExistedTarget}`)
).resolves.toHaveProperty('status', 404);
expect(deleteUserIdentity).not.toHaveBeenCalled();
});
it('should delete identity from user', async () => {
const arbitraryUserId = 'arbitraryUserId';
const arbitraryTarget = 'arbitraryTarget';
const mockedFindUserById = findUserById as jest.Mock;
mockedFindUserById.mockImplementationOnce((userId) => {
if (userId === arbitraryUserId) {
return {
identities: { connectorTarget1: {}, connectorTarget2: {}, arbitraryTarget: {} },
};
}
});
await userRequest.delete(`/users/${arbitraryUserId}/identities/${arbitraryTarget}`);
expect(deleteUserIdentity).toHaveBeenCalledWith(arbitraryUserId, arbitraryTarget);
});
});
});