diff --git a/src/migrations/20210428062103-user-permission-to-rbac.js b/src/migrations/20210428062103-user-permission-to-rbac.js index 36d5e75efd..1500ddd7df 100644 --- a/src/migrations/20210428062103-user-permission-to-rbac.js +++ b/src/migrations/20210428062103-user-permission-to-rbac.js @@ -2,8 +2,8 @@ const async = require('async'); -function resolveRoleName(permissions = []) { - if (permissions.length === 0) { +function resolveRoleName(permissions) { + if (!permissions || permissions.length === 0) { return 'Viewer'; } if (permissions.includes('ADMIN')) { @@ -13,24 +13,27 @@ function resolveRoleName(permissions = []) { } exports.up = function(db, cb) { - db.runSql(`SELECT id, permissions from users;`, (err, results) => { - if (results.rowCount > 0) { - const users = results.rows; - const insertRootRole = users.map(u => { - const roleName = resolveRoleName(u.permissions); - return db.runSql.bind( - db, - `INSERT INTO role_user (role_id, user_id) + db.runSql( + `SELECT id, permissions from users WHERE id NOT IN (select user_id from role_user);`, + (err, results) => { + if (results.rowCount > 0) { + const users = results.rows; + const insertRootRole = users.map(u => { + const roleName = resolveRoleName(u.permissions); + return db.runSql.bind( + db, + `INSERT INTO role_user (role_id, user_id) SELECT id, '${u.id}' FROM roles WHERE name = '${roleName}' AND type = 'root';`, - ); - }); - async.series(insertRootRole, cb); - } else { - cb(); - } - }); + ); + }); + async.series(insertRootRole, cb); + } else { + cb(); + } + }, + ); }; exports.down = function(db, cb) {