Advertisement
Guest User

Untitled

a guest
Feb 2nd, 2016
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. import assign from 'lodash.assign'
  2. import bcrypt from 'bcryptjs'
  3. import Joi from 'joi'
  4.  
  5. import hash from 'lib/hash'
  6. import orm from 'db'
  7. import { AuthenticationError } from 'errors'
  8. import { userValidation } from 'validations'
  9.  
  10. const destroyDependencies = (model) => {
  11. const tokens = model.tokens()
  12.  
  13. tokens.fetch()
  14. then(() => tokens.invokeThen('destroy'))
  15. }
  16.  
  17. const validate = (model) => {
  18. return Joi.validate(model.attributes, userValidation)
  19. }
  20.  
  21. const comparePassword = (password, user) => new Promise((res, rej) => {
  22. bcrypt.compare(password, user.get('password'), (err, same) => {
  23. if (err || !same) {
  24. rej(new AuthenticationError('Invalid password!'))
  25. return
  26. }
  27.  
  28. res(user)
  29. })
  30. })
  31.  
  32. const convertPassword = (model) => new Promise((res, rej) => {
  33. if (!model.hasChanged('password') || !model.isNew()) {
  34. res()
  35. return
  36. }
  37.  
  38. hash(model.get('password'))
  39. .then((password) => model.set({ password }))
  40. .then(() => res())
  41. .catch((err) => rej(err))
  42. })
  43.  
  44. const buildProfile = (user, bots) => {
  45. return assign({}, user.omit(['password']))
  46. }
  47.  
  48. const config = {
  49. tableName: 'users',
  50.  
  51. hasTimestamps: true,
  52.  
  53. initialize() {
  54. this.on('creating', (model) => convertPassword(model))
  55. this.on('destroying', (model) => destroyDependencies(model))
  56. this.on('saving', (model) => validate(model))
  57. },
  58.  
  59. activeTokens() {
  60. const today = new Date()
  61. const thirtyDays = new Date().setDate(today.getDate() - 30)
  62.  
  63. return this.hasMany('Token').query((queryBuilder) => {
  64. queryBuilder.where('last_updated', '>', thirtyDays)
  65. })
  66. },
  67.  
  68. tokens() {
  69. return this.hasMany('Token')
  70. }
  71.  
  72. authenticate(password) {
  73. return comparePassword(password, this)
  74. }
  75. }
  76.  
  77. const virtuals = {
  78. profile(id, email) {
  79. return new this({ id: id, email: email })
  80. .fetch({ require: true })
  81. .then((user) => user.profile())
  82. },
  83.  
  84. authenticate(username, password) {
  85. if (!username || !password) {
  86. return Promise.reject(new AuthenticationError('Username and password are both required!'))
  87. }
  88.  
  89. return new this({ username })
  90. .fetch({ require: true })
  91. .then((user) => user.authenticate(password))
  92. },
  93. }
  94.  
  95. const User = orm.Model.extend(config, virtuals)
  96. orm.model('User', User)
  97.  
  98. export default User
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement