-
Notifications
You must be signed in to change notification settings - Fork 925
/
refresh.ts
242 lines (205 loc) · 6.06 KB
/
refresh.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
import type {
RefreshableScheme,
SchemePartialOptions,
SchemeCheck,
HTTPResponse,
HTTPRequest,
RefreshableSchemeOptions
} from '../types'
import type { Auth } from '../core'
import { cleanObj, getResponseProp } from '../utils'
import {
RefreshController,
RefreshToken,
ExpiredAuthSessionError
} from '../inc'
import { LocalScheme, LocalSchemeEndpoints, LocalSchemeOptions } from './local'
export interface RefreshSchemeEndpoints extends LocalSchemeEndpoints {
refresh: HTTPRequest
}
export interface RefreshSchemeOptions
extends LocalSchemeOptions,
RefreshableSchemeOptions {
endpoints: RefreshSchemeEndpoints
autoLogout: boolean
}
const DEFAULTS: SchemePartialOptions<RefreshSchemeOptions> = {
name: 'refresh',
endpoints: {
refresh: {
url: '/api/auth/refresh',
method: 'post'
}
},
refreshToken: {
property: 'refresh_token',
data: 'refresh_token',
maxAge: 60 * 60 * 24 * 30,
required: true,
tokenRequired: false,
prefix: '_refresh_token.',
expirationPrefix: '_refresh_token_expiration.'
},
autoLogout: false
}
export class RefreshScheme<
OptionsT extends RefreshSchemeOptions = RefreshSchemeOptions
>
extends LocalScheme<OptionsT>
implements RefreshableScheme<OptionsT> {
public refreshToken: RefreshToken
public refreshController: RefreshController
constructor(
$auth: Auth,
options: SchemePartialOptions<RefreshSchemeOptions>
) {
super($auth, options, DEFAULTS)
// Initialize Refresh Token instance
this.refreshToken = new RefreshToken(this, this.$auth.$storage)
// Initialize Refresh Controller
this.refreshController = new RefreshController(this)
}
check(checkStatus = false): SchemeCheck {
const response = {
valid: false,
tokenExpired: false,
refreshTokenExpired: false,
isRefreshable: true
}
// Sync tokens
const token = this.token.sync()
const refreshToken = this.refreshToken.sync()
// Token and refresh token are required but not available
if (!token || !refreshToken) {
return response
}
// Check status wasn't enabled, let it pass
if (!checkStatus) {
response.valid = true
return response
}
// Get status
const tokenStatus = this.token.status()
const refreshTokenStatus = this.refreshToken.status()
// Refresh token has expired. There is no way to refresh. Force reset.
if (refreshTokenStatus.expired()) {
response.refreshTokenExpired = true
return response
}
// Token has expired, Force reset.
if (tokenStatus.expired()) {
response.tokenExpired = true
return response
}
response.valid = true
return response
}
mounted(): Promise<HTTPResponse | void> {
return super.mounted({
tokenCallback: () => {
if (this.options.autoLogout) {
this.$auth.reset()
}
},
refreshTokenCallback: () => {
this.$auth.reset()
}
})
}
refreshTokens(): Promise<HTTPResponse | void> {
// Refresh endpoint is disabled
if (!this.options.endpoints.refresh) {
return Promise.resolve()
}
// Token and refresh token are required but not available
if (!this.check().valid) {
return Promise.resolve()
}
// Get refresh token status
const refreshTokenStatus = this.refreshToken.status()
// Refresh token is expired. There is no way to refresh. Force reset.
if (refreshTokenStatus.expired()) {
this.$auth.reset()
throw new ExpiredAuthSessionError()
}
// Delete current token from the request header before refreshing, if `tokenRequired` is disabled
if (!this.options.refreshToken.tokenRequired) {
this.requestHandler.clearHeader()
}
const endpoint = {
data: {
client_id: undefined,
grant_type: undefined
}
}
// Add refresh token to payload if required
if (this.options.refreshToken.required && this.options.refreshToken.data) {
endpoint.data[this.options.refreshToken.data] = this.refreshToken.get()
}
// Add client id to payload if defined
if (this.options.clientId) {
endpoint.data.client_id = this.options.clientId
}
// Add grant type to payload if defined
if (this.options.grantType) {
endpoint.data.grant_type = 'refresh_token'
}
cleanObj(endpoint.data)
// Make refresh request
return this.$auth
.request(endpoint, this.options.endpoints.refresh)
.then((response) => {
// Update tokens
this.updateTokens(response, { isRefreshing: true })
return response
})
.catch((error) => {
this.$auth.callOnError(error, { method: 'refreshToken' })
return Promise.reject(error)
})
}
setUserToken(
token: string | boolean,
refreshToken?: string | boolean
): Promise<HTTPResponse | void> {
this.token.set(token)
if (refreshToken) {
this.refreshToken.set(refreshToken)
}
// Fetch user
return this.fetchUser()
}
reset({ resetInterceptor = true } = {}): void {
this.$auth.setUser(false)
this.token.reset()
this.refreshToken.reset()
if (resetInterceptor) {
this.requestHandler.reset()
}
}
protected updateTokens(
response: HTTPResponse,
{ isRefreshing = false, updateOnRefresh = true } = {}
): void {
const token = this.options.token.required
? (getResponseProp(response, this.options.token.property) as string)
: true
const refreshToken = this.options.refreshToken.required
? (getResponseProp(
response,
this.options.refreshToken.property
) as string)
: true
this.token.set(token)
// Update refresh token if defined and if `isRefreshing` is `false`
// If `isRefreshing` is `true`, then only update if `updateOnRefresh` is also `true`
if (refreshToken && (!isRefreshing || (isRefreshing && updateOnRefresh))) {
this.refreshToken.set(refreshToken)
}
}
protected initializeRequestInterceptor(): void {
this.requestHandler.initializeRequestInterceptor(
this.options.endpoints.refresh.url
)
}
}