2018-05-19 20:40:07 +00:00
/* global WIKI */
const bcrypt = require ( 'bcryptjs-then' )
const _ = require ( 'lodash' )
const tfa = require ( 'node-2fa' )
2018-07-30 02:23:33 +00:00
const securityHelper = require ( '../helpers/security' )
2018-10-08 04:17:31 +00:00
const jwt = require ( 'jsonwebtoken' )
2018-05-19 20:40:07 +00:00
const Model = require ( 'objection' ) . Model
2018-12-21 04:02:17 +00:00
const validate = require ( 'validate.js' )
2018-05-19 20:40:07 +00:00
const bcryptRegexp = /^\$2[ayb]\$[0-9]{2}\$[A-Za-z0-9./]{53}$/
/ * *
* Users model
* /
module . exports = class User extends Model {
static get tableName ( ) { return 'users' }
static get jsonSchema ( ) {
return {
type : 'object' ,
required : [ 'email' , 'name' , 'provider' ] ,
properties : {
id : { type : 'integer' } ,
email : { type : 'string' , format : 'email' } ,
name : { type : 'string' , minLength : 1 , maxLength : 255 } ,
providerId : { type : 'number' } ,
password : { type : 'string' } ,
role : { type : 'string' , enum : [ 'admin' , 'guest' , 'user' ] } ,
tfaIsActive : { type : 'boolean' , default : false } ,
tfaSecret : { type : 'string' } ,
2018-05-28 18:46:55 +00:00
jobTitle : { type : 'string' } ,
location : { type : 'string' } ,
pictureUrl : { type : 'string' } ,
2018-12-15 22:15:13 +00:00
isSystem : { type : 'boolean' } ,
2018-12-22 21:18:16 +00:00
isActive : { type : 'boolean' } ,
isVerified : { type : 'boolean' } ,
2018-05-19 20:40:07 +00:00
createdAt : { type : 'string' } ,
updatedAt : { type : 'string' }
}
}
}
static get relationMappings ( ) {
return {
groups : {
relation : Model . ManyToManyRelation ,
2018-05-20 22:50:51 +00:00
modelClass : require ( './groups' ) ,
2018-05-19 20:40:07 +00:00
join : {
from : 'users.id' ,
through : {
from : 'userGroups.userId' ,
to : 'userGroups.groupId'
} ,
to : 'groups.id'
}
2018-07-22 04:29:39 +00:00
} ,
provider : {
relation : Model . BelongsToOneRelation ,
modelClass : require ( './authentication' ) ,
join : {
from : 'users.providerKey' ,
to : 'authentication.key'
}
} ,
defaultEditor : {
relation : Model . BelongsToOneRelation ,
modelClass : require ( './editors' ) ,
join : {
from : 'users.editorKey' ,
to : 'editors.key'
}
} ,
locale : {
relation : Model . BelongsToOneRelation ,
modelClass : require ( './locales' ) ,
join : {
from : 'users.localeCode' ,
to : 'locales.code'
}
2018-05-19 20:40:07 +00:00
}
}
}
async $beforeUpdate ( opt , context ) {
await super . $beforeUpdate ( opt , context )
this . updatedAt = new Date ( ) . toISOString ( )
if ( ! ( opt . patch && this . password === undefined ) ) {
await this . generateHash ( )
}
}
async $beforeInsert ( context ) {
await super . $beforeInsert ( context )
this . createdAt = new Date ( ) . toISOString ( )
this . updatedAt = new Date ( ) . toISOString ( )
await this . generateHash ( )
}
2019-01-12 23:33:30 +00:00
// ------------------------------------------------
// Instance Methods
// ------------------------------------------------
2018-05-19 20:40:07 +00:00
async generateHash ( ) {
if ( this . password ) {
if ( bcryptRegexp . test ( this . password ) ) { return }
this . password = await bcrypt . hash ( this . password , 12 )
}
}
async verifyPassword ( pwd ) {
2018-05-20 22:50:51 +00:00
if ( await bcrypt . compare ( pwd , this . password ) === true ) {
2018-05-19 20:40:07 +00:00
return true
} else {
throw new WIKI . Error . AuthLoginFailed ( )
}
}
async enableTFA ( ) {
let tfaInfo = tfa . generateSecret ( {
name : WIKI . config . site . title
} )
return this . $query . patch ( {
tfaIsActive : true ,
tfaSecret : tfaInfo . secret
} )
}
async disableTFA ( ) {
return this . $query . patch ( {
tfaIsActive : false ,
tfaSecret : ''
} )
}
async verifyTFA ( code ) {
let result = tfa . verifyToken ( this . tfaSecret , code )
return ( result && _ . has ( result , 'delta' ) && result . delta === 0 )
}
2019-01-12 23:33:30 +00:00
getGlobalPermissions ( ) {
return _ . uniq ( _ . flatten ( _ . map ( this . groups , 'permissions' ) ) )
}
getGroups ( ) {
return _ . uniq ( _ . map ( this . groups , 'id' ) )
2019-01-07 03:03:34 +00:00
}
2019-01-12 23:33:30 +00:00
// ------------------------------------------------
// Model Methods
// ------------------------------------------------
2018-05-19 20:40:07 +00:00
static async processProfile ( profile ) {
let primaryEmail = ''
if ( _ . isArray ( profile . emails ) ) {
let e = _ . find ( profile . emails , [ 'primary' , true ] )
primaryEmail = ( e ) ? e . value : _ . first ( profile . emails ) . value
} else if ( _ . isString ( profile . email ) && profile . email . length > 5 ) {
primaryEmail = profile . email
} else if ( _ . isString ( profile . mail ) && profile . mail . length > 5 ) {
primaryEmail = profile . mail
} else if ( profile . user && profile . user . email && profile . user . email . length > 5 ) {
primaryEmail = profile . user . email
} else {
return Promise . reject ( new Error ( WIKI . lang . t ( 'auth:errors.invaliduseremail' ) ) )
}
profile . provider = _ . lowerCase ( profile . provider )
primaryEmail = _ . toLower ( primaryEmail )
2018-07-30 02:23:33 +00:00
let user = await WIKI . models . users . query ( ) . findOne ( {
2018-05-19 20:40:07 +00:00
email : primaryEmail ,
provider : profile . provider
} )
if ( user ) {
user . $query ( ) . patchAdnFetch ( {
email : primaryEmail ,
provider : profile . provider ,
providerId : profile . id ,
name : profile . displayName || _ . split ( primaryEmail , '@' ) [ 0 ]
} )
} else {
2018-07-30 02:23:33 +00:00
user = await WIKI . models . users . query ( ) . insertAndFetch ( {
2018-05-19 20:40:07 +00:00
email : primaryEmail ,
provider : profile . provider ,
providerId : profile . id ,
name : profile . displayName || _ . split ( primaryEmail , '@' ) [ 0 ]
} )
}
// Handle unregistered accounts
// if (!user && profile.provider !== 'local' && (WIKI.config.auth.defaultReadAccess || profile.provider === 'ldap' || profile.provider === 'azure')) {
// let nUsr = {
// email: primaryEmail,
// provider: profile.provider,
// providerId: profile.id,
// password: '',
// name: profile.displayName || profile.name || profile.cn,
// rights: [{
// role: 'read',
// path: '/',
// exact: false,
// deny: false
// }]
// }
2018-07-30 02:23:33 +00:00
// return WIKI.models.users.query().insert(nUsr)
2018-05-19 20:40:07 +00:00
// }
return user
}
static async login ( opts , context ) {
2018-06-17 15:12:11 +00:00
if ( _ . has ( WIKI . auth . strategies , opts . strategy ) ) {
2018-05-19 20:40:07 +00:00
_ . set ( context . req , 'body.email' , opts . username )
_ . set ( context . req , 'body.password' , opts . password )
// Authenticate
return new Promise ( ( resolve , reject ) => {
2018-10-08 04:17:31 +00:00
WIKI . auth . passport . authenticate ( opts . strategy , { session : false } , async ( err , user , info ) => {
2018-05-19 20:40:07 +00:00
if ( err ) { return reject ( err ) }
if ( ! user ) { return reject ( new WIKI . Error . AuthLoginFailed ( ) ) }
// Is 2FA required?
if ( user . tfaIsActive ) {
try {
let loginToken = await securityHelper . generateToken ( 32 )
await WIKI . redis . set ( ` tfa: ${ loginToken } ` , user . id , 'EX' , 600 )
return resolve ( {
tfaRequired : true ,
tfaLoginToken : loginToken
} )
} catch ( err ) {
WIKI . logger . warn ( err )
return reject ( new WIKI . Error . AuthGenericError ( ) )
}
} else {
// No 2FA, log in user
2018-10-08 04:17:31 +00:00
return context . req . logIn ( user , { session : false } , async err => {
2018-05-19 20:40:07 +00:00
if ( err ) { return reject ( err ) }
2018-10-08 04:17:31 +00:00
const jwtToken = await WIKI . models . users . refreshToken ( user )
2018-05-19 20:40:07 +00:00
resolve ( {
2018-10-08 04:17:31 +00:00
jwt : jwtToken . token ,
2018-05-19 20:40:07 +00:00
tfaRequired : false
} )
} )
}
} ) ( context . req , context . res , ( ) => { } )
} )
} else {
throw new WIKI . Error . AuthProviderInvalid ( )
}
}
2018-10-08 04:17:31 +00:00
static async refreshToken ( user ) {
if ( _ . isSafeInteger ( user ) ) {
2019-01-12 23:33:30 +00:00
user = await WIKI . models . users . query ( ) . findById ( user ) . eager ( 'groups' ) . modifyEager ( 'groups' , builder => {
builder . select ( 'groups.id' , 'permissions' )
} )
2018-10-08 04:17:31 +00:00
if ( ! user ) {
WIKI . logger . warn ( ` Failed to refresh token for user ${ user } : Not found. ` )
throw new WIKI . Error . AuthGenericError ( )
}
2019-03-19 19:15:40 +00:00
} else if ( _ . isNil ( user . groups ) ) {
2019-01-12 23:33:30 +00:00
await user . $relatedQuery ( 'groups' ) . select ( 'groups.id' , 'permissions' )
2018-10-08 04:17:31 +00:00
}
2019-01-12 23:33:30 +00:00
2018-10-08 04:17:31 +00:00
return {
token : jwt . sign ( {
id : user . id ,
email : user . email ,
name : user . name ,
pictureUrl : user . pictureUrl ,
timezone : user . timezone ,
localeCode : user . localeCode ,
defaultEditor : user . defaultEditor ,
2019-01-12 23:33:30 +00:00
permissions : user . getGlobalPermissions ( ) ,
groups : user . getGroups ( )
2018-12-03 02:42:43 +00:00
} , {
key : WIKI . config . certs . private ,
passphrase : WIKI . config . sessionSecret
} , {
algorithm : 'RS256' ,
2019-01-07 03:03:34 +00:00
expiresIn : WIKI . config . auth . tokenExpiration ,
audience : WIKI . config . auth . audience ,
2018-10-08 04:17:31 +00:00
issuer : 'urn:wiki.js'
} ) ,
user
}
}
2018-05-19 20:40:07 +00:00
static async loginTFA ( opts , context ) {
if ( opts . securityCode . length === 6 && opts . loginToken . length === 64 ) {
2019-02-13 22:20:46 +00:00
let result = null // await WIKI.redis.get(`tfa:${opts.loginToken}`)
2018-05-19 20:40:07 +00:00
if ( result ) {
let userId = _ . toSafeInteger ( result )
if ( userId && userId > 0 ) {
2018-07-30 02:23:33 +00:00
let user = await WIKI . models . users . query ( ) . findById ( userId )
2018-05-19 20:40:07 +00:00
if ( user && user . verifyTFA ( opts . securityCode ) ) {
return Promise . fromCallback ( clb => {
context . req . logIn ( user , clb )
} ) . return ( {
succeeded : true ,
message : 'Login Successful'
} ) . catch ( err => {
WIKI . logger . warn ( err )
throw new WIKI . Error . AuthGenericError ( )
} )
} else {
throw new WIKI . Error . AuthTFAFailed ( )
}
}
}
}
throw new WIKI . Error . AuthTFAInvalid ( )
}
2018-12-17 05:51:52 +00:00
2019-01-01 06:40:31 +00:00
static async register ( { email , password , name , verify = false , bypassChecks = false } , context ) {
2018-12-21 04:02:17 +00:00
const localStrg = await WIKI . models . authentication . getStrategy ( 'local' )
// Check if self-registration is enabled
2019-01-01 06:40:31 +00:00
if ( localStrg . selfRegistration || bypassChecks ) {
// Input sanitization
email = _ . toLower ( email )
2018-12-21 04:02:17 +00:00
// Input validation
const validation = validate ( {
2018-12-17 05:51:52 +00:00
email ,
password ,
2018-12-21 04:02:17 +00:00
name
} , {
email : {
email : true ,
length : {
maximum : 255
}
} ,
password : {
presence : {
allowEmpty : false
} ,
length : {
minimum : 6
}
} ,
name : {
presence : {
allowEmpty : false
} ,
length : {
minimum : 2 ,
maximum : 255
}
2019-03-19 19:15:40 +00:00
}
2018-12-21 04:02:17 +00:00
} , { format : 'flat' } )
if ( validation && validation . length > 0 ) {
throw new WIKI . Error . InputInvalid ( validation [ 0 ] )
}
// Check if email domain is whitelisted
2019-01-01 06:40:31 +00:00
if ( _ . get ( localStrg , 'domainWhitelist.v' , [ ] ) . length > 0 && ! bypassChecks ) {
2018-12-21 04:02:17 +00:00
const emailDomain = _ . last ( email . split ( '@' ) )
if ( ! _ . includes ( localStrg . domainWhitelist . v , emailDomain ) ) {
throw new WIKI . Error . AuthRegistrationDomainUnauthorized ( )
}
}
// Check if email already exists
const usr = await WIKI . models . users . query ( ) . findOne ( { email , providerKey : 'local' } )
if ( ! usr ) {
// Create the account
2018-12-24 06:03:10 +00:00
const newUsr = await WIKI . models . users . query ( ) . insert ( {
2018-12-21 04:02:17 +00:00
provider : 'local' ,
email ,
name ,
password ,
locale : 'en' ,
defaultEditor : 'markdown' ,
tfaIsActive : false ,
2018-12-22 21:18:16 +00:00
isSystem : false ,
isActive : true ,
isVerified : false
} )
2019-01-01 06:40:31 +00:00
if ( verify ) {
// Create verification token
const verificationToken = await WIKI . models . userKeys . generateToken ( {
kind : 'verify' ,
userId : newUsr . id
} )
2018-12-24 06:03:10 +00:00
2019-01-01 06:40:31 +00:00
// Send verification email
await WIKI . mail . send ( {
template : 'accountVerify' ,
to : email ,
subject : 'Verify your account' ,
data : {
preheadertext : 'Verify your account in order to gain access to the wiki.' ,
title : 'Verify your account' ,
content : 'Click the button below in order to verify your account and gain access to the wiki.' ,
buttonLink : ` ${ WIKI . config . host } /verify/ ${ verificationToken } ` ,
buttonText : 'Verify'
} ,
text : ` You must open the following link in your browser to verify your account and gain access to the wiki: ${ WIKI . config . host } /verify/ ${ verificationToken } `
} )
}
2018-12-21 04:02:17 +00:00
return true
} else {
throw new WIKI . Error . AuthAccountAlreadyExists ( )
}
2018-12-17 05:51:52 +00:00
} else {
2018-12-21 04:02:17 +00:00
throw new WIKI . Error . AuthRegistrationDisabled ( )
2018-12-17 05:51:52 +00:00
}
}
2019-01-07 03:03:34 +00:00
static async getGuestUser ( ) {
2019-01-12 23:33:30 +00:00
const user = await WIKI . models . users . query ( ) . findById ( 2 ) . eager ( 'groups' ) . modifyEager ( 'groups' , builder => {
builder . select ( 'groups.id' , 'permissions' )
} )
if ( ! user ) {
WIKI . logger . error ( 'CRITICAL ERROR: Guest user is missing!' )
process . exit ( 1 )
}
2019-03-19 19:15:40 +00:00
user . permissions = user . getGlobalPermissions ( )
2019-01-07 03:03:34 +00:00
return user
}
2018-05-19 20:40:07 +00:00
}