2017-06-06 12:40:51 +00:00
|
|
|
const mongoose = require('mongoose')
|
2017-06-02 14:53:34 +00:00
|
|
|
|
|
|
|
const tokenSchema = mongoose.Schema({
|
2017-06-06 12:40:51 +00:00
|
|
|
object: Object,
|
|
|
|
expire: {
|
|
|
|
type: Number,
|
|
|
|
default: Date.now
|
|
|
|
}
|
|
|
|
})
|
2017-06-04 13:38:14 +00:00
|
|
|
tokenSchema.statics.clearExpire = function (cb) {
|
2017-06-06 12:40:51 +00:00
|
|
|
console.log(Date.now())
|
|
|
|
return this.remove({ expire: { $lte: Date.now() } }, cb)
|
2017-06-03 13:20:34 +00:00
|
|
|
}
|
2017-06-04 13:38:14 +00:00
|
|
|
tokenSchema.statics.renewToken = function (id, expire, cb) {
|
2017-06-06 12:40:51 +00:00
|
|
|
return this.update({ _id: mongoose.Schema.Types.ObjectId(id) }, { $set: { expire: Date.now() + 86400000 } }, cb)
|
2017-06-03 13:20:34 +00:00
|
|
|
}
|
2017-06-04 13:38:14 +00:00
|
|
|
tokenSchema.statics.checkToken = async function (str) {
|
2017-06-06 12:40:51 +00:00
|
|
|
let self = this
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
self.findOne({ _id: str, expire: { $gte: Date.now() } }, (err, row) => {
|
|
|
|
if (err || !row) return resolve(false)
|
|
|
|
return resolve(true)
|
2017-06-04 13:38:14 +00:00
|
|
|
})
|
2017-06-06 12:40:51 +00:00
|
|
|
})
|
2017-06-04 13:38:14 +00:00
|
|
|
}
|
|
|
|
tokenSchema.statics.getToken = async function (str) {
|
2017-06-06 12:40:51 +00:00
|
|
|
let self = this
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
self.findOne({ _id: str, expire: { $gte: Date.now() } }, (err, row) => {
|
|
|
|
if (err) return reject(err)
|
|
|
|
return resolve(row)
|
2017-06-04 13:38:14 +00:00
|
|
|
})
|
2017-06-06 12:40:51 +00:00
|
|
|
})
|
2017-06-04 13:38:14 +00:00
|
|
|
}
|
2017-06-02 14:53:34 +00:00
|
|
|
|
2017-06-06 12:40:51 +00:00
|
|
|
const Token = mongoose.model('token', tokenSchema, 'token')
|
2017-06-02 14:53:34 +00:00
|
|
|
|
|
|
|
module.exports = {
|
2017-06-06 12:40:51 +00:00
|
|
|
Token
|
|
|
|
}
|