summaryrefslogtreecommitdiffstats
path: root/server/models/User.js
blob: ef3d94e4b62cb5202d6f7b5d7f51bb1a6e374a88 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const mongoose = require("mongoose");
const bcrypt = require('bcryptjs');
const randtoken = require('rand-token');
const jwt = require('jsonwebtoken');
const Session = require('./Session');

const userSchema = new mongoose.Schema({
  email: {
    type: String,
    trim: true,
    lowercase: true,
    unique: true,
    required: true,
    min: 4,
    max: 255,
    validate(value) {
      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
        throw new Error('Wrong email address');
      }
    }
  },
  password: {
    type: String,
    required: true,
    min: 4,
    max: 1024,
  },
});

userSchema.methods.generateJwtToken = async function (currentRefToken) {
  const refreshToken = currentRefToken ? currentRefToken : randtoken.uid(256);

  if (!currentRefToken) {
    const session = new Session({ user: this, refreshToken });
    await session.save();
  }

  return jwt.sign(
    { _id: this._id.toString(), refreshToken },
    process.env.JWT_SECRET,
    { expiresIn: parseInt(process.env.JWT_TOKEN_MAX_AGE) }
  );
}

userSchema.methods.endSession = async function (ref) {
  this.sessions = this.sessions.filter((session) => {
    return session.ref !== ref;
  });

  await this.save();
  return null;
}

userSchema.statics.findByCredentials = async (email, password) => {
  const user = await User.findOne({ email });

  if (!user) {
    throw new Error('Unable to login');
  }

  const isMatch = await bcrypt.compare(password, user.password);

  if (!isMatch) {
    throw new Error('Unable to login');
  }

  return user;
}

userSchema.pre('save', async function(next){
  const user = this;

  if (user.isModified('password')) {
    user.password = await bcrypt.hash(user.password, 8);
  }

  next();
})

const User = mongoose.model('User', userSchema);

module.exports = User;