2020-10-13 01:31:57 +00:00
|
|
|
const { Controller } = require('libflitter')
|
|
|
|
|
|
|
|
class SessionController extends Controller {
|
|
|
|
static get services() {
|
2020-10-22 04:51:12 +00:00
|
|
|
return [...super.services, 'configs', 'models', 'auth']
|
2020-10-13 01:31:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async get_session(req, res, next) {
|
|
|
|
return res.api(await this.session_data(req.user))
|
|
|
|
}
|
|
|
|
|
2020-10-20 15:12:25 +00:00
|
|
|
async save_session(req, res, next) {
|
|
|
|
if ( req?.body?.user?.preferences ) {
|
|
|
|
const save_prefs = req.body.user.preferences;
|
|
|
|
req.user.preferences.dark_mode = !!save_prefs.dark_mode;
|
|
|
|
|
|
|
|
if ( save_prefs.default_page ) {
|
|
|
|
req.user.preferences.default_page = save_prefs.default_page;
|
|
|
|
} else {
|
|
|
|
req.user.preferences.default_page = '';
|
|
|
|
}
|
2020-10-29 04:48:31 +00:00
|
|
|
|
|
|
|
req.user.preferences.auto_prefetch = !!save_prefs.auto_prefetch
|
2020-10-20 15:12:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
await req.user.save()
|
|
|
|
return res.api()
|
|
|
|
}
|
|
|
|
|
2020-10-13 01:31:57 +00:00
|
|
|
async session_data(user) {
|
|
|
|
return {
|
|
|
|
user: {
|
|
|
|
id: user.id,
|
|
|
|
username: user.uid,
|
2020-10-20 15:12:25 +00:00
|
|
|
preferences: user.preferences || {},
|
2020-10-13 01:31:57 +00:00
|
|
|
},
|
|
|
|
app: {
|
|
|
|
name: this.configs.get('app.name'),
|
|
|
|
url: this.configs.get('app.url'),
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
2020-10-22 04:51:12 +00:00
|
|
|
|
|
|
|
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()
|
|
|
|
}
|
2020-10-13 01:31:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = exports = SessionController
|