authentication.mjs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /* global WIKI */
  2. import bcrypt from 'bcryptjs'
  3. // ------------------------------------
  4. // Local Account
  5. // ------------------------------------
  6. import { Strategy } from 'passport-local'
  7. export default {
  8. init (passport, strategyId, conf) {
  9. passport.use(strategyId,
  10. new Strategy({
  11. usernameField: 'email',
  12. passwordField: 'password'
  13. }, async (uEmail, uPassword, done) => {
  14. try {
  15. const user = await WIKI.db.users.query().findOne({
  16. email: uEmail.toLowerCase()
  17. })
  18. if (user) {
  19. const authStrategyData = user.auth[strategyId]
  20. if (!authStrategyData) {
  21. throw new Error('ERR_INVALID_STRATEGY')
  22. } else if (await bcrypt.compare(uPassword, authStrategyData.password) !== true) {
  23. throw new Error('ERR_LOGIN_FAILED')
  24. } else if (!user.isActive) {
  25. throw new Error('ERR_INACTIVE_USER')
  26. } else if (authStrategyData.restrictLogin) {
  27. throw new Error('ERR_LOGIN_RESTRICTED')
  28. } else if (!user.isVerified) {
  29. throw new Error('ERR_USER_NOT_VERIFIED')
  30. } else {
  31. done(null, user)
  32. }
  33. } else {
  34. throw new Error('ERR_LOGIN_FAILED')
  35. }
  36. } catch (err) {
  37. done(err, null)
  38. }
  39. })
  40. )
  41. }
  42. }