users.js 6.8 KB

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