users.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. /* global WIKI */
  2. const bcrypt = require('bcryptjs-then')
  3. const _ = require('lodash')
  4. const tfa = require('node-2fa')
  5. const securityHelper = require('../../helpers/security')
  6. const Model = require('objection').Model
  7. const bcryptRegexp = /^\$2[ayb]\$[0-9]{2}\$[A-Za-z0-9./]{53}$/
  8. /**
  9. * Users model
  10. */
  11. module.exports = class User extends Model {
  12. static get tableName() { return 'users' }
  13. static get jsonSchema () {
  14. return {
  15. type: 'object',
  16. required: ['email', 'name', 'provider'],
  17. properties: {
  18. id: {type: 'integer'},
  19. email: {type: 'string', format: 'email'},
  20. name: {type: 'string', minLength: 1, maxLength: 255},
  21. provider: {type: 'string', minLength: 1, maxLength: 255},
  22. providerId: {type: 'number'},
  23. password: {type: 'string'},
  24. role: {type: 'string', enum: ['admin', 'guest', 'user']},
  25. tfaIsActive: {type: 'boolean', default: false},
  26. tfaSecret: {type: 'string'},
  27. locale: {type: 'string'},
  28. jobTitle: {type: 'string'},
  29. location: {type: 'string'},
  30. pictureUrl: {type: 'string'},
  31. createdAt: {type: 'string'},
  32. updatedAt: {type: 'string'}
  33. }
  34. }
  35. }
  36. static get relationMappings() {
  37. return {
  38. groups: {
  39. relation: Model.ManyToManyRelation,
  40. modelClass: require('./groups'),
  41. join: {
  42. from: 'users.id',
  43. through: {
  44. from: 'userGroups.userId',
  45. to: 'userGroups.groupId'
  46. },
  47. to: 'groups.id'
  48. }
  49. }
  50. }
  51. }
  52. async $beforeUpdate(opt, context) {
  53. await super.$beforeUpdate(opt, context)
  54. this.updatedAt = new Date().toISOString()
  55. if (!(opt.patch && this.password === undefined)) {
  56. await this.generateHash()
  57. }
  58. }
  59. async $beforeInsert(context) {
  60. await super.$beforeInsert(context)
  61. this.createdAt = new Date().toISOString()
  62. this.updatedAt = new Date().toISOString()
  63. await this.generateHash()
  64. }
  65. async generateHash() {
  66. if (this.password) {
  67. if (bcryptRegexp.test(this.password)) { return }
  68. this.password = await bcrypt.hash(this.password, 12)
  69. }
  70. }
  71. async verifyPassword(pwd) {
  72. if (await bcrypt.compare(pwd, this.password) === true) {
  73. return true
  74. } else {
  75. throw new WIKI.Error.AuthLoginFailed()
  76. }
  77. }
  78. async enableTFA() {
  79. let tfaInfo = tfa.generateSecret({
  80. name: WIKI.config.site.title
  81. })
  82. return this.$query.patch({
  83. tfaIsActive: true,
  84. tfaSecret: tfaInfo.secret
  85. })
  86. }
  87. async disableTFA() {
  88. return this.$query.patch({
  89. tfaIsActive: false,
  90. tfaSecret: ''
  91. })
  92. }
  93. async verifyTFA(code) {
  94. let result = tfa.verifyToken(this.tfaSecret, code)
  95. return (result && _.has(result, 'delta') && result.delta === 0)
  96. }
  97. static async processProfile(profile) {
  98. let primaryEmail = ''
  99. if (_.isArray(profile.emails)) {
  100. let e = _.find(profile.emails, ['primary', true])
  101. primaryEmail = (e) ? e.value : _.first(profile.emails).value
  102. } else if (_.isString(profile.email) && profile.email.length > 5) {
  103. primaryEmail = profile.email
  104. } else if (_.isString(profile.mail) && profile.mail.length > 5) {
  105. primaryEmail = profile.mail
  106. } else if (profile.user && profile.user.email && profile.user.email.length > 5) {
  107. primaryEmail = profile.user.email
  108. } else {
  109. return Promise.reject(new Error(WIKI.lang.t('auth:errors.invaliduseremail')))
  110. }
  111. profile.provider = _.lowerCase(profile.provider)
  112. primaryEmail = _.toLower(primaryEmail)
  113. let user = await WIKI.db.users.query().findOne({
  114. email: primaryEmail,
  115. provider: profile.provider
  116. })
  117. if (user) {
  118. user.$query().patchAdnFetch({
  119. email: primaryEmail,
  120. provider: profile.provider,
  121. providerId: profile.id,
  122. name: profile.displayName || _.split(primaryEmail, '@')[0]
  123. })
  124. } else {
  125. user = await WIKI.db.users.query().insertAndFetch({
  126. email: primaryEmail,
  127. provider: profile.provider,
  128. providerId: profile.id,
  129. name: profile.displayName || _.split(primaryEmail, '@')[0]
  130. })
  131. }
  132. // Handle unregistered accounts
  133. // if (!user && profile.provider !== 'local' && (WIKI.config.auth.defaultReadAccess || profile.provider === 'ldap' || profile.provider === 'azure')) {
  134. // let nUsr = {
  135. // email: primaryEmail,
  136. // provider: profile.provider,
  137. // providerId: profile.id,
  138. // password: '',
  139. // name: profile.displayName || profile.name || profile.cn,
  140. // rights: [{
  141. // role: 'read',
  142. // path: '/',
  143. // exact: false,
  144. // deny: false
  145. // }]
  146. // }
  147. // return WIKI.db.users.query().insert(nUsr)
  148. // }
  149. return user
  150. }
  151. static async login (opts, context) {
  152. if (_.has(WIKI.config.auth.strategies, opts.provider)) {
  153. _.set(context.req, 'body.email', opts.username)
  154. _.set(context.req, 'body.password', opts.password)
  155. // Authenticate
  156. return new Promise((resolve, reject) => {
  157. WIKI.auth.passport.authenticate(opts.provider, async (err, user, info) => {
  158. if (err) { return reject(err) }
  159. if (!user) { return reject(new WIKI.Error.AuthLoginFailed()) }
  160. // Is 2FA required?
  161. if (user.tfaIsActive) {
  162. try {
  163. let loginToken = await securityHelper.generateToken(32)
  164. await WIKI.redis.set(`tfa:${loginToken}`, user.id, 'EX', 600)
  165. return resolve({
  166. tfaRequired: true,
  167. tfaLoginToken: loginToken
  168. })
  169. } catch (err) {
  170. WIKI.logger.warn(err)
  171. return reject(new WIKI.Error.AuthGenericError())
  172. }
  173. } else {
  174. // No 2FA, log in user
  175. return context.req.logIn(user, err => {
  176. if (err) { return reject(err) }
  177. resolve({
  178. tfaRequired: false
  179. })
  180. })
  181. }
  182. })(context.req, context.res, () => {})
  183. })
  184. } else {
  185. throw new WIKI.Error.AuthProviderInvalid()
  186. }
  187. }
  188. static async loginTFA(opts, context) {
  189. if (opts.securityCode.length === 6 && opts.loginToken.length === 64) {
  190. let result = await WIKI.redis.get(`tfa:${opts.loginToken}`)
  191. if (result) {
  192. let userId = _.toSafeInteger(result)
  193. if (userId && userId > 0) {
  194. let user = await WIKI.db.users.query().findById(userId)
  195. if (user && user.verifyTFA(opts.securityCode)) {
  196. return Promise.fromCallback(clb => {
  197. context.req.logIn(user, clb)
  198. }).return({
  199. succeeded: true,
  200. message: 'Login Successful'
  201. }).catch(err => {
  202. WIKI.logger.warn(err)
  203. throw new WIKI.Error.AuthGenericError()
  204. })
  205. } else {
  206. throw new WIKI.Error.AuthTFAFailed()
  207. }
  208. }
  209. }
  210. }
  211. throw new WIKI.Error.AuthTFAInvalid()
  212. }
  213. }