|
|
@@ -1,6 +1,6 @@
|
|
|
const decode = require('jsonwebtoken/decode')
|
|
|
const app = require('./app')
|
|
|
-app.service('api', function($http) {
|
|
|
+app.service('api', function($http, $location, $mdToast) {
|
|
|
window.api = this
|
|
|
this.opts = {
|
|
|
headers: {},
|
|
|
@@ -41,6 +41,24 @@ app.service('api', function($http) {
|
|
|
clearUser()
|
|
|
}
|
|
|
|
|
|
+ this.renew = async () => {
|
|
|
+ console.info('Renewing session...')
|
|
|
+ const res = await this.post('/api/auth/renew', {})
|
|
|
+ setUser(res.user, res.token)
|
|
|
+ }
|
|
|
+
|
|
|
+ this.checkRenew = async () => {
|
|
|
+ if (!this.user) {
|
|
|
+ throw new Error('Not logged in')
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ await this.renew()
|
|
|
+ } catch (e) {
|
|
|
+ clearUser()
|
|
|
+ throw e
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
this.restore = () => {
|
|
|
const token = localStorage.getItem('token')
|
|
|
const userJson = localStorage.getItem('user')
|
|
|
@@ -56,6 +74,32 @@ app.service('api', function($http) {
|
|
|
|
|
|
this.restore()
|
|
|
|
|
|
+ const renewTimer = () => {
|
|
|
+ if (this.user) {
|
|
|
+ this.renew().catch(err => {
|
|
|
+ console.warn('Login session could not be renewed:', err)
|
|
|
+ $mdToast.show(
|
|
|
+ $mdToast.simple()
|
|
|
+ .textContent(`You are not logged in: ${err.statusText || err.message}.`)
|
|
|
+ .action('Return to login page')
|
|
|
+ .hideDelay(60000)
|
|
|
+ .position('top middle')
|
|
|
+ .highlightAction(true)
|
|
|
+ .highlightClass('md-warn')
|
|
|
+ )
|
|
|
+ .then(res => {
|
|
|
+ if (res === 'ok') {
|
|
|
+ clearUser()
|
|
|
+ $location.url('/login')
|
|
|
+ }
|
|
|
+ })
|
|
|
+ })
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ setInterval(renewTimer, 15000)
|
|
|
+ renewTimer()
|
|
|
+
|
|
|
this.crud = (apiPrefix) => ({
|
|
|
list: () => this.get(apiPrefix),
|
|
|
create: data => this.post(apiPrefix, data),
|