-
Notifications
You must be signed in to change notification settings - Fork 582
/
index.ts
225 lines (189 loc) · 7.64 KB
/
index.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
import CognitoIdentityServiceProvider from "aws-sdk/clients/cognitoidentityserviceprovider";
import { ApiKey, Group, SecurityContext } from "@webiny/api-security/types";
import {
createApiKeyEntity,
createGroupEntity,
createUserEntity,
createLinkEntity
} from "./entities";
import { AdminUser, AdminUsersContext, CreateUserInput } from "~/types";
import { TenancyContext } from "@webiny/api-tenancy/types";
import { queryAll } from "@webiny/db-dynamodb/utils/query";
import { batchReadAll } from "@webiny/db-dynamodb/utils/batchRead";
type Context = SecurityContext & TenancyContext & AdminUsersContext;
interface OldLink {
id: string;
group: {
slug: string;
};
}
const userPoolId = process.env.COGNITO_USER_POOL_ID;
async function listAllCognitoUsers(cognito: CognitoIdentityServiceProvider) {
const users = [];
let paginationToken = null;
while (true) {
const { Users, PaginationToken } = await cognito
.listUsers({
UserPoolId: userPoolId,
AttributesToGet: ["sub", "email"],
PaginationToken: paginationToken
})
.promise();
Users.forEach(user => users.push(user));
if (PaginationToken) {
paginationToken = PaginationToken;
} else {
break;
}
}
return users;
}
export const migration = (context: Context) => {
const { security, tenancy, adminUsers } = context;
if (!tenancy.getCurrentTenant()) {
return;
}
// Override `getVersion` method for this migration only.
const getVersion = adminUsers.getVersion;
adminUsers.getVersion = async () => {
const version = await getVersion();
if (version) {
return version;
}
const securityVersion = await security.getVersion();
// If it's a new project, `securityVersion` should match the current Webiny version.
// If so, we let installers work as intended, by returning `null`, which means "not installed".
if (securityVersion === context.WEBINY_VERSION || !securityVersion) {
return null;
}
// Pretend `adminUsers` app is installed, and let the first `login` mutation trigger the migration.
return context.WEBINY_VERSION;
};
security.onLogin.subscribe(async ({ identity }) => {
security.disableAuthorization();
// Try loading user by ID.
const user = await adminUsers.getUser({ where: { id: identity.id } });
// If it exists, the data is already migrated.
if (user) {
return;
}
// Make sure this really is a previously installed system.
const securityVersion = await security.getVersion();
// If it's a new project, `securityVersion` should match the current Webiny version.
// If so, migration is not executed.
if (securityVersion === context.WEBINY_VERSION) {
return;
}
const adminUsersStorage = adminUsers.getStorageOperations();
const securityStorage = security.getStorageOperations();
// @ts-ignore
const table = adminUsersStorage.getTable();
const tenant = tenancy.getCurrentTenant();
// Setup entities that match the old data structure
const legacyUsers = createUserEntity(table);
const legacyLinks = createLinkEntity(table);
const legacyGroups = createGroupEntity(table);
const legacyApiKeys = createApiKeyEntity(table);
// Migrate groups
// 1. Load legacy groups using a dedicated entity
const oldGroups = await queryAll<Group>({
entity: legacyGroups,
partitionKey: `T#${tenant.id}`,
options: {
beginsWith: "G#"
}
});
// 2. Store groups using the new `security` app
const newGroupsBySlug: Record<string, Group> = {};
for (const group of oldGroups) {
const newGroup = await security.createGroup({
name: group.name,
slug: group.slug,
description: group.description,
system: group.system,
// Rename user permission
permissions: group.permissions.map(permission => {
if (permission.name === "security.user") {
permission.name = "adminUsers.user";
}
return permission;
})
});
newGroupsBySlug[newGroup.slug] = newGroup;
}
// Migrate users
// 1. Load links to tenants
const oldLinks = await queryAll<OldLink>({
entity: legacyLinks,
partitionKey: `T#${tenant.id}`,
options: {
index: "GSI1",
beginsWith: "G#"
}
});
// Create a map of old user ids to group slug
const oldUser2group = oldLinks.reduce(
(acc, item) => ({ ...acc, [item.id]: item.group.slug }),
{}
);
// 2. Load legacy users using a dedicated dynamodb-toolbox entity
const oldUserItems = Object.keys(oldUser2group).map(userId => {
return legacyUsers.getBatch({ PK: `U#${userId}`, SK: "A" });
});
const oldUsers = await batchReadAll<AdminUser>({ table, items: oldUserItems });
// 3. Fetch data from Cognito, and use user's `sub` as the new user `id`
const cognito = new CognitoIdentityServiceProvider({ region: process.env.COGNITO_REGION });
const cognitoUsers = await listAllCognitoUsers(cognito);
// 4. Store users using the new `adminUsers` app
const newUsers: CreateUserInput[] = oldUsers.map(oldUser => {
const cognitoUser = cognitoUsers.find(cu => {
return !!cu.Attributes.find(
attr => attr.Name === "email" && attr.Value === oldUser.id
);
});
const sub = cognitoUser.Attributes.find(attr => attr.Name === "sub").Value;
return {
id: sub,
email: oldUser.id,
avatar: oldUser.avatar,
firstName: oldUser.firstName,
lastName: oldUser.lastName,
group: newGroupsBySlug[oldUser2group[oldUser.id]].id,
createdBy: oldUser.createdBy,
createdOn: oldUser.createdOn,
// Set any password value to make TS happy. It will not be used anyway.
password: ""
};
});
// Cognito users already exist, and we should not abort user creation when Cognito throws an error.
const originalPublish = adminUsers.onUserBeforeCreate.publish;
adminUsers.onUserBeforeCreate.publish = async event => {
try {
await originalPublish(event);
} catch (err) {
// Ignore error
}
};
for (const user of newUsers) {
await adminUsers.createUser(user);
}
// Migrate API keys
// 1. Load legacy API keys using a dedicated entity
const oldApiKeys = await queryAll<ApiKey>({
entity: legacyApiKeys,
partitionKey: `T#${tenant.id}`,
options: {
index: "GSI1",
beginsWith: "API_KEY#"
}
});
// 2. Store API keys using the new `security` app
for (const apiKey of oldApiKeys) {
await securityStorage.createApiKey({ apiKey });
}
// Set new app versions
await security.setVersion(context.WEBINY_VERSION);
await adminUsers.setVersion(context.WEBINY_VERSION);
security.enableAuthorization();
});
};