-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy path019-move-user-authentication.js
59 lines (46 loc) · 1.86 KB
/
019-move-user-authentication.js
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
"use strict";
const log = require('winston');
exports.id = 'move-user-authentication';
exports.up = async function (done) {
try {
log.info('Moving authentication from user model to authentication model');
const authenticationCollection = await this.db.collection('authentications');
const userCollection = await this.db.collection('users');
migrateAuthentication(authenticationCollection, userCollection)
.then(() => done())
.catch(err => done(err));
} catch (err) {
log.warn('Failed moving authentication to new model', err);
done(err);
}
};
exports.down = function (done) {
done();
};
async function migrateAuthentication(authenticationCollection, userCollection) {
const cursor = userCollection.find({});
let hasNext = true;
while (hasNext === true) {
hasNext = await cursor.hasNext()
if (hasNext !== true) break;
const user = await cursor.next()
if (user.hasOwnProperty('authentication')) {
const userAuthentication = user.authentication;
delete user.authentication;
delete userAuthentication._id;
log.info("Creating new authentication record for user " + user.username);
await authenticationCollection.insertOne(userAuthentication);
log.info('Authentication record successfully created for user ' + user.username);
user.authenticationId = userAuthentication._id;
log.info("Removing authentication section for user " + user.username);
await userCollection.updateOne({ _id: user._id }, user);
log.info("Successfully removed authentication section for user " + user.username);
} else {
log.info("Authentication section has already been moved for " + user.username);
}
}
// Close the cursor, this is the same as reseting the query
cursor.close(function (err) {
if (err) log.warn("Failed closing authentication move cursor", err);
});
}