/
session.js
104 lines (93 loc) · 2.59 KB
/
session.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
import Router from 'next/router'
import axios from 'axios'
export default class Session {
constructor() {
this._session = {}
this.isValid = this.isValid.bind(this)
this.createRequest = this.createRequest.bind(this)
this.login = this.login.bind(this)
this.redirectIfInvalid = this.redirectIfInvalid.bind(this)
this.getSession()
}
isValid() {
if (this._session && Object.keys(this._session).length > 0 && this._session.expire && this._session.expire - Date.now() >= 0) {
return true
}
return false
}
redirectIfInvalid () {
if (this.isValid() === false) {
Router.push({
pathname: '/admin/login',
query: { 'from': Router.pathname}
})
return true
}
return false
}
createRequest(config = {}) {
console.log('creating request')
config.headers = {
'Authorization': `Bearer ${this._session.token}`
}
return axios.create(config)
}
getSession() {
if (typeof window === 'undefined') {
return
}
this._session = this._getLocalStore('session')
}
async login(username, password) {
return new Promise(async (resolve, reject) => {
if (typeof window === 'undefined') {
return reject(Error('This method is called only in the client'))
}
let xhr = new XMLHttpRequest()
xhr.open('POST', process.env.REGISTRY_URL + '/api/v1/login')
xhr.setRequestHeader('Content-type', 'application/json')
xhr.onreadystatechange = async () => {
if (xhr.readyState === 4) {
if (xhr.status !== 200) {
return reject(Error('XMLHttpRequest error: error while logging in'))
}
this._session = JSON.parse(xhr.responseText)
this._session.expire = new Date(this._session.expire)
this._session.username = username
this._saveLocalStore('session', this._session)
return resolve(true)
}
}
xhr.onerror = () => {
return reject(Error('XMLHttpRequest error: unable to login'))
}
xhr.send(JSON.stringify({username, password}))
})
}
_getLocalStore(name) {
let session = {}
try {
session = JSON.parse(localStorage.getItem(name))
session.expire = new Date(session.expire)
return session
} catch (err) {
return session
}
}
_saveLocalStore(name, data) {
try {
localStorage.setItem(name, JSON.stringify(data))
return true
} catch (err) {
return false
}
}
_removeLocalStore(name) {
try {
localStorage.removeItem(name)
return true
} catch(err) {
return false
}
}
}