Add device tokens for resuming user sessions
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone Build is passing

This commit is contained in:
Garrett Mills 2020-10-21 23:51:12 -05:00
parent b0b62cc50d
commit b37faa87b3
Signed by: garrettmills
GPG Key ID: D2BF5FBA8298F246
5 changed files with 79 additions and 2 deletions

1
app/assets/version.html Normal file
View File

@ -0,0 +1 @@
796aaedc-91d9-4831-ae47-de330967e7b4

View File

@ -2,7 +2,7 @@ const { Controller } = require('libflitter')
class SessionController extends Controller {
static get services() {
return [...super.services, 'configs']
return [...super.services, 'configs', 'models', 'auth']
}
async get_session(req, res, next) {
@ -38,6 +38,41 @@ class SessionController extends Controller {
},
}
}
async get_device_token(req, res, next) {
const DeviceToken = this.models.get('api:DeviceToken')
const token = await DeviceToken.grant_user(req.user)
return res.api({
token: token.token,
expiration_date: token.expiration_date,
})
}
async resume(req, res, next) {
const DeviceToken = this.models.get('api:DeviceToken')
const User = this.models.get('auth:User')
const token = await DeviceToken.findOne({
token: req.params.token,
expiration_date: { $gt: new Date },
});
if ( !token ) {
return res.status(404)
.message('Device token expired or invalid.')
.api()
}
const user = await User.findById(token.user_id);
if ( !user ) {
return res.status(404)
.message('Device token expired or invalid.')
.api()
}
await this.auth.get_provider().session(req, user)
return res.api()
}
}
module.exports = exports = SessionController

View File

@ -0,0 +1,36 @@
const { Model } = require('flitter-orm')
const uuid = require('uuid/v4')
class DeviceTokenModel extends Model {
static get schema() {
return {
user_id: String,
create_date: { type: Date, default: () => new Date },
expiration_date: {
type: Date,
default: () => {
const date = new Date();
date.setMonth(date.getMonth() + 1);
return date;
}
},
token: {
type: String,
default: () => {
return Array(5).fill('').map(_ => uuid()).join('').replace(/-/g, '')
}
},
}
}
static async grant_user(user) {
const tok = new this({
user_id: user.id,
})
await tok.save()
return tok
}
}
module.exports = exports = DeviceTokenModel

View File

@ -8,6 +8,7 @@ const index = {
get: {
'/': [ 'controller::api:v1:Session.get_session' ],
'/device-token': [ 'controller::api:v1:Session.get_device_token' ],
},
post: {

View File

@ -60,7 +60,11 @@ const index = {
* an array of canonical references to controller methods
* or middleware that are applied in order.
*/
post: {}
post: {
'/api/v1/session/resume/:token': [
'middleware::auth:GuestOnly', 'controller::api:v1:Session.resume',
],
}
};
module.exports = exports = index;