summaryrefslogtreecommitdiffstats
path: root/server/models/Session.js
blob: 06a43698dc7d6a7564c825a371aca24c4f637336 (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
const mongoose = require("mongoose");
const jwt = require('jsonwebtoken');

const sessionSchema = new mongoose.Schema({
  userId: {
    type : mongoose.Schema.Types.ObjectId,
    ref : 'User'
  },
  lastAccess: {
    type: Date,
    default: Date.now(),
    index: { expires: parseInt(process.env.DB_SESSION_MAX_AGE) }
  }
});

sessionSchema.methods.setAccessDate = function (user) {
  this.lastAccess = Date.now();
  console.log('refreshing time in db')
  this.save();
}

sessionSchema.methods.generateJwtToken = function (user) {
  return jwt.sign(
    { sessionId: this._id.toString(), user: JSON.stringify(user) },
    process.env.JWT_SECRET,
    { expiresIn: parseInt(process.env.JWT_TOKEN_MAX_AGE) }
  );
};

module.exports = mongoose.model('Session', sessionSchema);