forked from nuxt-community/auth-module
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstorage.ts
383 lines (311 loc) · 8.95 KB
/
storage.ts
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
import type { Context } from '@nuxt/types'
import Vue from 'vue'
import cookie from 'cookie'
import type { ModuleOptions } from '../options'
import { isUnset, isSet, decodeValue, encodeValue, getProp } from '../utils'
// TODO: Normalize type at module itself
export type StorageOptions = ModuleOptions & {
initialState: {
user: null
loggedIn: boolean
}
}
// TODO: Improve type of storages: Universal / Cookie / Local / State
export class Storage {
public ctx: Context
public options: StorageOptions
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public state: any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private _state: any
private _useVuex: boolean
constructor(ctx: Context, options: StorageOptions) {
this.ctx = ctx
this.options = options
this._initState()
}
// ------------------------------------
// Universal
// ------------------------------------
setUniversal<V extends unknown>(key: string, value: V): V | void {
// Unset null, undefined
if (isUnset(value)) {
return this.removeUniversal(key)
}
// Cookies
this.setCookie(key, value)
// Local Storage
this.setLocalStorage(key, value)
// Local state
this.setState(key, value)
return value
}
getUniversal(key: string): unknown {
let value
// Local state
if (process.server) {
value = this.getState(key)
}
// Cookies
if (isUnset(value)) {
value = this.getCookie(key)
}
// Local Storage
if (isUnset(value)) {
value = this.getLocalStorage(key)
}
// Local state
if (isUnset(value)) {
value = this.getState(key)
}
return value
}
syncUniversal(key: string, defaultValue?: unknown): unknown {
let value = this.getUniversal(key)
if (isUnset(value) && isSet(defaultValue)) {
value = defaultValue
}
if (isSet(value)) {
this.setUniversal(key, value)
}
return value
}
removeUniversal(key: string): void {
this.removeState(key)
this.removeLocalStorage(key)
this.removeCookie(key)
}
// ------------------------------------
// Local state (reactive)
// ------------------------------------
_initState(): void {
// Private state is suitable to keep information not being exposed to Vuex store
// This helps prevent stealing token from SSR response HTML
Vue.set(this, '_state', {})
// Use vuex for local state's if possible
this._useVuex = this.options.vuex && !!this.ctx.store
if (this._useVuex) {
const storeModule = {
namespaced: true,
state: () => this.options.initialState,
mutations: {
SET(state, payload) {
Vue.set(state, payload.key, payload.value)
}
}
}
this.ctx.store.registerModule(this.options.vuex.namespace, storeModule, {
preserveState: Boolean(
this.ctx.store.state[this.options.vuex.namespace]
)
})
this.state = this.ctx.store.state[this.options.vuex.namespace]
} else {
Vue.set(this, 'state', {})
// eslint-disable-next-line no-console
console.warn(
'[AUTH] The Vuex Store is not activated. This might cause issues in auth module behavior, like redirects not working properly.' +
'To activate it, see https://nuxtjs.org/docs/2.x/directory-structure/store'
)
}
}
setState<V extends unknown>(key: string, value: V): V {
if (key[0] === '_') {
Vue.set(this._state, key, value)
} else if (this._useVuex) {
this.ctx.store.commit(this.options.vuex.namespace + '/SET', {
key,
value
})
} else {
Vue.set(this.state, key, value)
}
return value
}
getState(key: string): unknown {
if (key[0] !== '_') {
return this.state[key]
} else {
return this._state[key]
}
}
watchState(
key: string,
fn: (value: unknown, oldValue: unknown) => void
): () => void {
if (this._useVuex) {
return this.ctx.store.watch(
(state) => getProp(state[this.options.vuex.namespace], key),
fn
)
}
}
removeState(key: string): void {
this.setState(key, undefined)
}
// ------------------------------------
// Local storage
// ------------------------------------
setLocalStorage<V extends unknown>(key: string, value: V): V | void {
// Unset null, undefined
if (isUnset(value)) {
return this.removeLocalStorage(key)
}
if (!this.isLocalStorageEnabled()) {
return
}
const _key = this.getPrefix() + key
try {
localStorage.setItem(_key, encodeValue(value))
} catch (e) {
if (!this.options.ignoreExceptions) {
throw e
}
}
return value
}
getLocalStorage(key: string): unknown {
if (!this.isLocalStorageEnabled()) {
return
}
const _key = this.getPrefix() + key
const value = localStorage.getItem(_key)
return decodeValue(value)
}
removeLocalStorage(key: string): void {
if (!this.isLocalStorageEnabled()) {
return
}
const _key = this.getPrefix() + key
localStorage.removeItem(_key)
}
// ------------------------------------
// Cookies
// ------------------------------------
getCookies(): Record<string, unknown> {
if (!this.isCookiesEnabled()) {
return
}
const cookieStr = process.client
? document.cookie
: this.ctx.req.headers.cookie
return cookie.parse(cookieStr || '') || {}
}
setCookie<V extends unknown>(
key: string,
value: V,
options: { prefix?: string } = {}
): V {
if (!this.options.cookie || (process.server && !this.ctx.res)) {
return
}
if (!this.isCookiesEnabled()) {
return
}
const _prefix =
options.prefix !== undefined ? options.prefix : this.options.cookie.prefix
const _key = _prefix + key
const _options = Object.assign({}, this.options.cookie.options, options)
const _value = encodeValue(value)
// Unset null, undefined
if (isUnset(value)) {
_options.maxAge = -1
}
// Accept expires as a number for js-cookie compatiblity
if (typeof _options.expires === 'number') {
_options.expires = new Date(Date.now() + _options.expires * 864e5)
}
const serializedCookie = cookie.serialize(_key, _value, _options)
if (process.client) {
// Set in browser
document.cookie = serializedCookie
} else if (process.server && this.ctx.res) {
// Send Set-Cookie header from server side
let cookies = (this.ctx.res.getHeader('Set-Cookie') as string[]) || []
if (!Array.isArray(cookies)) cookies = [cookies]
cookies.unshift(serializedCookie)
this.ctx.res.setHeader(
'Set-Cookie',
cookies.filter(
(v, i, arr) =>
arr.findIndex((val) =>
val.startsWith(v.substr(0, v.indexOf('=')))
) === i
)
)
}
return value
}
getCookie(key: string): unknown {
if (!this.options.cookie || (process.server && !this.ctx.req)) {
return
}
if (!this.isCookiesEnabled()) {
return
}
const _key = this.options.cookie.prefix + key
const cookies = this.getCookies()
const value = cookies[_key]
? decodeURIComponent(cookies[_key] as string)
: undefined
return decodeValue(value)
}
removeCookie(key: string, options?: { prefix?: string }): void {
this.setCookie(key, undefined, options)
}
getPrefix(): string {
if (!this.options.localStorage) {
throw new Error('Cannot get prefix; localStorage is off')
}
return this.options.localStorage.prefix
}
isLocalStorageEnabled(): boolean {
// Disabled by configuration
if (!this.options.localStorage) {
return false
}
// Local Storage only exists in the browser
if (!process.client) {
return false
}
// There's no great way to check if localStorage is enabled; most solutions
// error out. So have to use this hacky approach :\
// https://stackoverflow.com/questions/16427636/check-if-localstorage-is-available
const test = 'test'
try {
localStorage.setItem(test, test)
localStorage.removeItem(test)
return true
} catch (e) {
if (!this.options.ignoreExceptions) {
// eslint-disable-next-line no-console
console.warn(
"[AUTH] Local storage is enabled in config, but browser doesn't" +
' support it'
)
}
return false
}
}
isCookiesEnabled(): boolean {
// Disabled by configuration
if (!this.options.cookie) {
return false
}
// Server can only assume cookies are enabled, it's up to the client browser
// to create them or not
if (process.server) {
return true
}
if (window.navigator.cookieEnabled) {
return true
} else {
// eslint-disable-next-line no-console
console.warn(
"[AUTH] Cookies is enabled in config, but browser doesn't" +
' support it'
)
return false
}
}
}