/
auth.class.js
338 lines (267 loc) · 6.75 KB
/
auth.class.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
import Cookies from 'js-cookie'
import { parse as parseCookie } from 'cookie'
import { routeOption } from './auth.utilities'
import getProp from 'dotprop'
import Vue from 'vue'
const RELATIVE_URL_REGEX = /^\/[a-zA-Z0-9@\-%_~][\/a-zA-Z0-9@\-%_~]{1,200}$/
export default class Auth {
constructor (ctx, options) {
this.ctx = ctx
this.app = ctx.app
this.options = options
// Error listeners
this._errorListeners = []
// Keep token out of the store for security reasons
Vue.set(this, 'token', null)
// Register vuex store
this._registerVuexStore()
// Reset on error
if (this.options.resetOnError) {
this._resetOnError()
}
// Watch for loggedIn changes only in client side
if (this.options.watchLoggedIn && process.browser) {
this._watchLoggedIn()
}
}
_registerVuexStore () {
const authModule = {
namespaced: true,
state: () => ({
user: null,
loggedIn: false
}),
mutations: {
SET (state, payload) {
Vue.set(state, payload.key, payload.value)
}
}
}
this.$store.registerModule(this.options.namespace, authModule, {
preserveState: Boolean(this.$store.state[this.options.namespace])
})
}
_resetOnError () {
this.onError(() => {
this.reset()
})
}
_watchLoggedIn () {
this._loggedInWatcher =
this._loggedInWatcher ||
this.watchState('loggedIn', () => {
if (routeOption(this.$route, 'auth', false)) {
return
}
this.redirect('home')
})
return this._loggedInWatcher
}
onError (listener) {
this._errorListeners.push(listener)
}
_onError () {
for (let fn of this._errorListeners) {
fn.apply(this, arguments)
}
}
get $axios () {
if (!this.app.$axios) {
throw new Error('$axios is not available')
}
return this.app.$axios
}
get $store () {
return this.ctx.store
}
get $route () {
return this.ctx.route
}
get $req () {
return this.app.context.req
}
get $res () {
return this.app.context.res
}
get isAPIRequest () {
return (
process.server &&
this.$req.url.indexOf(this.options.endpoints.user.url) === 0
)
}
get state () {
return this.$store.state[this.options.namespace]
}
reset () {
this.setState('loggedIn', false)
this.setState('token', null)
this.setState('user', null)
if (this.options.cookie) {
this.setCookie(this.options.cookie.name, null)
}
if (this.options.token.name) {
this.setLocalStorage(this.options.token.name, null)
}
}
setState (key, value) {
if (key === 'token') {
this.token = value
return
}
this.$store.commit(this.options.namespace + '/SET', { key, value })
}
getState (key) {
if (key === 'token') {
return this.token
}
return this.state[key]
}
watchState (key, fn) {
return this.$store.watch(
state => getProp(state[this.options.namespace], key),
fn
)
}
setLocalStorage (name, value) {
if (typeof localStorage !== 'undefined') {
if (value) {
localStorage.setItem(name, value)
} else {
localStorage.removeItem(name)
}
}
}
getLocalStorage (name) {
if (typeof localStorage !== 'undefined') {
return localStorage.getItem(name)
}
}
setCookie (name, value, options = {}) {
if (!this.options.cookie || !process.browser) {
return
}
const _options = Object.assign({}, this.options.cookie.options, options)
if (value) {
Cookies.set(name, value, _options)
} else {
Cookies.remove(name, _options)
}
}
getCookie (name) {
const cookieStr = process.browser
? document.cookie
: this.$req.headers.cookie
const cookies = parseCookie(cookieStr || '') || {}
return cookies[name]
}
async _request (name, endpoint) {
if (!this.options.endpoints[name]) {
return
}
const opts = Object.assign({}, this.options.endpoints[name], endpoint)
try {
const { data } = await this.$axios.request(opts)
return opts.propertyName ? getProp(data, opts.propertyName) : data
} catch (err) {
this._onError({ name, err, endpoint })
if (process.browser) {
throw err
}
}
}
async login (endpoint) {
const data = await this._request('login', endpoint)
if (!data) {
return
}
// Extract and set token
this.setToken(data)
// Fetch User
if (this.options.fetchUserOnLogin && this.options.endpoints.user) {
return this.fetchUser()
}
// Set loggedIn to true
this.setState('loggedIn', true)
}
async fetchUser (endpoint) {
if (this.options.token && !this.getState('token')) {
return
}
const data = await this._request('user', endpoint)
if (!data) {
return
}
this.setState('user', data)
this.setState('loggedIn', true)
}
async logout (endpoint) {
await this._request('logout', endpoint)
this.reset()
}
setToken (token) {
if (!this.options.token) {
return
}
// Update local state
this.setState('token', token)
// Set Authorization token for all axios requests
this.$axios.setToken(token, this.options.token.type)
// Save it in cookies
if (this.options.cookie) {
this.setCookie(this.options.cookie.name, token)
}
// Save it in localSotage
if (this.options.token.name) {
this.setLocalStorage(this.options.token.name, token)
}
}
syncToken () {
if (!this.options.token) {
return
}
let token = this.getState('token')
if (!token && this.options.cookie) {
token = this.getCookie(this.options.cookie.name)
}
if (!token && this.options.token.name) {
token = this.getLocalStorage(this.options.token.name)
}
this.setToken(token)
}
redirect (name) {
let to = this.options.redirect[name]
const from = this.$route.path
if (!to) {
return
}
// Apply rewrites
if (this.options.rewriteRedirects) {
if (name === 'login') {
to = to + '?redirect=' + encodeURIComponent(from)
}
if (name === 'home' && this.$route.query.redirect) {
// Decode
const redirect = decodeURIComponent(this.$route.query.redirect)
// Validate
if (RELATIVE_URL_REGEX.test(redirect)) {
to = redirect
}
}
}
// Prevent infinity redirects
if (to.split('?')[0] === from) {
return
}
this.ctx.redirect(to)
}
hasScope (scope) {
const userScopes = getProp(this.state.user, this.options.scopeKey)
if (!userScopes) {
return
}
if (Array.isArray(userScopes)) {
return userScopes.includes(scope)
}
return Boolean(getProp(userScopes, scope))
}
}