wiki/server/graph/resolvers/system.js
/**
     * Import Users from a v1 installation
     */
Import Users from a v1 installation
Import Users from a v1 installation
async importUsersFromV1(obj, args, context) {
      try {
        const MongoClient = require('mongodb').MongoClient
        if (args.mongoDbConnString && args.mongoDbConnString.length > 10) {
          const client = await MongoClient.connect(args.mongoDbConnString, {
            appname: `Wiki.js ${WIKI.version} Migration Tool`
          })
          const dbUsers = client.db().collection('users')
          const userCursor = dbUsers.find({ email: { '$ne': 'guest' } })
          const curDateISO = new Date().toISOString()
          let failed = []
          let usersCount = 0
          let groupsCount = 0
          let assignableGroups = []
          let reuseGroups = []
          if (args.groupMode === `SINGLE`) {
            const singleGroup = await WIKI.models.groups.query().insert({
              name: `Import_${curDateISO}`,
              permissions: JSON.stringify(WIKI.data.groups.defaultPermissions),
              pageRules: JSON.stringify(WIKI.data.groups.defaultPageRules)
            })
            groupsCount++
            assignableGroups.push(singleGroup.id)
          }
          while (await userCursor.hasNext()) {
            const usr = await userCursor.next()
            let usrGroup = []
            if (args.groupMode === `MULTI`) {
              if (_.some(usr.rights, ['role', 'admin'])) {
                usrGroup.push(1)
              } else {
                const currentRights = _.sortBy(_.map(usr.rights, r => _.pick(r, ['role', 'path', 'exact', 'deny'])), ['role', 'path', 'exact', 'deny'])
                const ruleSetId = crypto.createHash('sha1').update(JSON.stringify(currentRights)).digest('base64')
                const existingGroup = _.find(reuseGroups, ['hash', ruleSetId])
                if (existingGroup) {
                  usrGroup.push(existingGroup.groupId)
                } else {
                  const pageRules = _.map(usr.rights, r => {
                    let roles = ['read:pages', 'read:assets', 'read:comments', 'write:comments']
                    if (r.role === `write`) {
                      roles = _.concat(roles, ['write:pages', 'manage:pages', 'read:source', 'read:history', 'write:assets', 'manage:assets'])
                    }
                    return {
                      id: nanoid(),
                      roles: roles,
                      match: r.exact ? 'EXACT' : 'START',
                      deny: r.deny,
                      path: (r.path.indexOf('/') === 0) ? r.path.substring(1) : r.path,
                      locales: []
                    }
                  })
                  const perms = _.chain(pageRules).reject('deny').map('roles').union().flatten().value()
                  const newGroup = await WIKI.models.groups.query().insert({
                    name: `Import_${curDateISO}_${groupsCount + 1}`,
                    permissions: JSON.stringify(perms),
                    pageRules: JSON.stringify(pageRules)
                  })
                  reuseGroups.push({
                    groupId: newGroup.id,
                    hash: ruleSetId
                  })
                  groupsCount++
                  usrGroup.push(newGroup.id)
                }
              }
            }
            try {
              await WIKI.models.users.createNewUser({
                providerKey: usr.provider,
                email: usr.email,
                name: usr.name,
                passwordRaw: usr.password,
                groups: (usrGroup.length > 0) ? usrGroup : assignableGroups,
                mustChangePassword: false,
                sendWelcomeEmail: false
              })
              usersCount++
            } catch (err) {
              failed.push({
                provider: usr.provider,
                email: usr.email,
                error: err.message
              })
              WIKI.logger.warn(`${usr.email}: ${err}`)
            }
          }
          if (args.groupMode !== `NONE`) {
            await WIKI.auth.reloadGroups()
            WIKI.events.outbound.emit('reloadGroups')
          }
          client.close()
          return {
            responseResult: graphHelper.generateSuccess('Import completed.'),
            usersCount: usersCount,
            groupsCount: groupsCount,
            failed: failed
          }
        } else {
          throw new Error('MongoDB Connection String is missing or invalid.')
        }
      } catch (err) {
        return graphHelper.generateError(err)
      }
    }
async importUsersFromV1 ( obj , args , context ) { try { const MongoClient = require ( 'mongodb' ) . MongoClient if ( args . mongoDbConnString && args . mongoDbConnString . length > 10 ) { const client = await MongoClient . connect ( args . mongoDbConnString , { appname : ` ${ WIKI . version } ` } ) const dbUsers = client . db ( ) . collection ( 'users' ) const userCursor = dbUsers . find ( { email : { '$ne' : 'guest' } } ) const curDateISO = new Date ( ) . toISOString ( ) let failed = [ ] let usersCount = 0 let groupsCount = 0 let assignableGroups = [ ] let reuseGroups = [ ] if ( args . groupMode === ` ` ) { const singleGroup = await WIKI . models . groups . query ( ) . insert ( { name : ` ${ curDateISO } ` , permissions : JSON . stringify ( WIKI . data . groups . defaultPermissions ) , pageRules : JSON . stringify ( WIKI . data . groups . defaultPageRules ) } ) groupsCount ++ assignableGroups . push ( singleGroup . id ) } while ( await userCursor . hasNext ( ) ) { const usr = await userCursor . next ( ) let usrGroup = [ ] if ( args . groupMode === ` ` ) { if ( _ . some ( usr . rights , [ 'role' , 'admin' ] ) ) { usrGroup . push ( 1 ) } else { const currentRights = _ . sortBy ( _ . map ( usr . rights , r => _ . pick ( r , [ 'role' , 'path' , 'exact' , 'deny' ] ) ) , [ 'role' , 'path' , 'exact' , 'deny' ] ) const ruleSetId = crypto . createHash ( 'sha1' ) . update ( JSON . stringify ( currentRights ) ) . digest ( 'base64' ) const existingGroup = _ . find ( reuseGroups , [ 'hash' , ruleSetId ] ) if ( existingGroup ) { usrGroup . push ( existingGroup . groupId ) } else { const pageRules = _ . map ( usr . rights , r => { let roles = [ 'read:pages' , 'read:assets' , 'read:comments' , 'write:comments' ] if ( r . role === ` ` ) { roles = _ . concat ( roles , [ 'write:pages' , 'manage:pages' , 'read:source' , 'read:history' , 'write:assets' , 'manage:assets' ] ) } return { id : nanoid ( ) , roles : roles , match : r . exact ? 'EXACT' : 'START' , deny : r . deny , path : ( r . path . indexOf ( '/' ) === 0 ) ? r . path . substring ( 1 ) : r . path , locales : [ ] } } ) const perms = _ . chain ( pageRules ) . reject ( 'deny' ) . map ( 'roles' ) . union ( ) . flatten ( ) . value ( ) const newGroup = await WIKI . models . groups . query ( ) . insert ( { name : ` ${ curDateISO } ${ groupsCount + 1 } ` , permissions : JSON . stringify ( perms ) , pageRules : JSON . stringify ( pageRules ) } ) reuseGroups . push ( { groupId : newGroup . id , hash : ruleSetId } ) groupsCount ++ usrGroup . push ( newGroup . id ) } } } try { await WIKI . models . users . createNewUser ( { providerKey : usr . provider , email : usr . email , name : usr . name , passwordRaw : usr . password , groups : ( usrGroup . length > 0 ) ? usrGroup : assignableGroups , mustChangePassword : false , sendWelcomeEmail : false } ) usersCount ++ } catch ( err ) { failed . push ( { provider : usr . provider , email : usr . email , error : err . message } ) WIKI . logger . warn ( ` ${ usr . email } ${ err } ` ) } } if ( args . groupMode !== ` ` ) { await WIKI . auth . reloadGroups ( ) WIKI . events . outbound . emit ( 'reloadGroups' ) } client . close ( ) return { responseResult : graphHelper . generateSuccess ( 'Import completed.' ) , usersCount : usersCount , groupsCount : groupsCount , failed : failed } } else { throw new Error ( 'MongoDB Connection String is missing or invalid.' ) } } catch ( err ) { return graphHelper . generateError ( err ) } }
Import Users from a v1 installation
Import Users from a v1 installation
// -> Connect to DB // -> Create SINGLE group // -> Iterate all users // -> Check if global admin // -> Check if identical group already exists // -> Build new group // -> Create new group // -> Create User // -> Reload group permissions