Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import assign from 'lodash.assign'
- import bcrypt from 'bcryptjs'
- import Joi from 'joi'
- import hash from 'lib/hash'
- import orm from 'db'
- import { AuthenticationError } from 'errors'
- import { userValidation } from 'validations'
- const destroyDependencies = (model) => {
- const tokens = model.tokens()
- tokens.fetch()
- then(() => tokens.invokeThen('destroy'))
- }
- const validate = (model) => {
- return Joi.validate(model.attributes, userValidation)
- }
- const comparePassword = (password, user) => new Promise((res, rej) => {
- bcrypt.compare(password, user.get('password'), (err, same) => {
- if (err || !same) {
- rej(new AuthenticationError('Invalid password!'))
- return
- }
- res(user)
- })
- })
- const convertPassword = (model) => new Promise((res, rej) => {
- if (!model.hasChanged('password') || !model.isNew()) {
- res()
- return
- }
- hash(model.get('password'))
- .then((password) => model.set({ password }))
- .then(() => res())
- .catch((err) => rej(err))
- })
- const buildProfile = (user, bots) => {
- return assign({}, user.omit(['password']))
- }
- const config = {
- tableName: 'users',
- hasTimestamps: true,
- initialize() {
- this.on('creating', (model) => convertPassword(model))
- this.on('destroying', (model) => destroyDependencies(model))
- this.on('saving', (model) => validate(model))
- },
- activeTokens() {
- const today = new Date()
- const thirtyDays = new Date().setDate(today.getDate() - 30)
- return this.hasMany('Token').query((queryBuilder) => {
- queryBuilder.where('last_updated', '>', thirtyDays)
- })
- },
- tokens() {
- return this.hasMany('Token')
- }
- authenticate(password) {
- return comparePassword(password, this)
- }
- }
- const virtuals = {
- profile(id, email) {
- return new this({ id: id, email: email })
- .fetch({ require: true })
- .then((user) => user.profile())
- },
- authenticate(username, password) {
- if (!username || !password) {
- return Promise.reject(new AuthenticationError('Username and password are both required!'))
- }
- return new this({ username })
- .fetch({ require: true })
- .then((user) => user.authenticate(password))
- },
- }
- const User = orm.Model.extend(config, virtuals)
- orm.model('User', User)
- export default User
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement