forked from juampi92/adonis-mongoose-model
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTokenMongoose.js
119 lines (108 loc) · 2.42 KB
/
TokenMongoose.js
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/* global use */
'use strict'
const Model = require('./Base')
const { ObjectId } = use('mongoose').Schema.Types
const utils = require('../utils')
/**
* Token's instance and static methods
* @class
*/
class Token extends Model {
/**
* Make the token an index on the boot method
*
* @static
*/
static boot () {
// Create a token index
this.index({ token: 1 })
}
/**
* Disable timestamps for the Token Model
*
* @readonly
* @static
*/
static get timestamps () {
return false
}
/**
* Defines the amount of days
*
* @static
* @returns {Number}
*/
static expires () {
return 5
}
/**
* Define User's schema internally using Model's schema property
*/
static get schema () {
return {
uid: { type: ObjectId, ref: 'User' },
token: { type: String, required: true },
type: { type: String, required: true },
expires: { type: Date, default: () => utils.nowAddDays(this.expires()) }
}
}
/**
* Customize the fields populated by the user.
* Return string of fields separated by a space
*
* Read Query field selection: http://mongoosejs.com/docs/api.html#query_Query-select
*
* @static
* @param {String} type
* @returns {String}
*/
static getUserFields (type) {
return null
}
/**
* Fetches session that matches that token, with the populated user
*
* @static
* @param {String} token
* @param {String} type
* @returns {Object} returns the token object with the populated user
*/
static async fetchSession (token, type) {
return this
.findOneAndUpdate({
token,
type,
expires: {
$gte: new Date()
}
}, {
expires: utils.nowAddDays(this.expires())
})
.populate('uid', this.getUserFields(type))
}
/**
* Remove sessions that match that token
*
* @static
* @param uid
* @param tokens Array of tokens to delete or preserve.
* @param inverse Delete all but the specified tokens.
* @returns
*/
static async dispose (uid, tokens = null, inverse = false) {
// Remove some tokens
if (tokens) {
// Remove all but selected, or just selected
const selector = inverse ? '$nin' : '$in'
return this.remove({
uid,
token: { [selector]: tokens }
}).exec()
}
// Remove all tokens
return this.remove({
uid
}).exec()
}
}
module.exports = Token