-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathauth.js
More file actions
158 lines (140 loc) · 5.01 KB
/
Copy pathauth.js
File metadata and controls
158 lines (140 loc) · 5.01 KB
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
/*
* Copyright 2018 data.world, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This product includes software developed at
* data.world, Inc. (http://data.world/).
*/
import * as api from './api'
import crypto from 'crypto'
import uuidv1 from 'uuid/v1'
import { parseJSON, log } from './util.js'
const refreshTokenKey = 'DW-REFRESH-TOKEN-KEY'
const codeVerifierKey = 'DW-CODE-VERIFIER'
const generateCodeVerifier = () => {
const lowerCase = 'abcdefghijklmnopqrstuvwxyz'
const upperCase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
const numbers = '1234567890'
const specialCharacters = '-._~'
const characters = lowerCase + upperCase + numbers + specialCharacters
const minLength = 43
const maxLength = 128
const stringLength = Math.floor(Math.random() * (maxLength - minLength + 1)) + minLength
let codeVerifier = ''
for (let i = 0; i < stringLength; i++) {
const randomIndex = Math.floor(Math.random() * characters.length)
codeVerifier += characters.charAt(randomIndex)
}
return codeVerifier
}
const storeRefreshToken = (refreshToken) => {
if (window.localStorage) {
window.localStorage.setItem(refreshTokenKey, refreshToken)
if (window.tableau) {
window.tableau.password = refreshToken
}
return refreshToken
}
return null
}
const getRefreshToken = (useTableauPassword = false) => {
if (window.localStorage) {
let refreshToken = window.localStorage.getItem(refreshTokenKey)
if (window.tableau && useTableauPassword) {
refreshToken = window.tableau.password || refreshToken
}
return refreshToken
}
return null
}
const getAccessToken = async (useTableauPassword = false) => {
const refreshToken = getRefreshToken(useTableauPassword)
if (refreshToken) {
// exchange refresh token for access token
try {
const response = await api.getRefreshedTokens(refreshToken)
// store new refresh token
storeRefreshToken(response.data.refresh_token)
return response.data.access_token
} catch (error) {
log(`ERROR : Failed to refresh tokens - ${error.message}`)
return null
}
}
return null
}
const getStateObject = (state) => {
if (window.localStorage) {
state = window.localStorage.getItem(state) || state
}
// Parse state with care, state might be a UUID string in a situation where window.localStorage is truthy, but cache was cleared
// Or window.localStorage is falsy at read time (very unlikely)
return parseJSON(state)
}
const storeStateObject = (state) => { // state at this point is a js object.
// Must be stringified cos it will either end up cached in local storage or encoded in the url if window.localStorage is falsy.
const stringifiedState = JSON.stringify(state)
if (window.localStorage) {
const key = uuidv1()
window.localStorage.setItem(key, stringifiedState)
return key
}
return stringifiedState
}
const storeCodeVerifier = (codeVerifier) => {
if (window.localStorage) {
window.localStorage.setItem(codeVerifierKey, codeVerifier)
return codeVerifier
}
return null
}
const useCodeVerifier = () => {
if (window.localStorage) {
const codeVerifier = window.localStorage.getItem(codeVerifierKey)
window.localStorage.removeItem(codeVerifierKey)
return codeVerifier
}
return null
}
const generateCodeChallenge = (codeVerifier) => {
const base64hash = crypto.createHash('sha256')
.update(codeVerifier)
.digest('base64')
return encodeURIComponent(base64hash)
}
const getAuthUrl = (codeVerifier, state) => {
const codeChallenge = generateCodeChallenge(codeVerifier)
const nonce = storeStateObject(state)
return `https://data.world/oauth/authorize?client_id=${process.env.REACT_APP_OAUTH_CLIENT_ID}` +
`&redirect_uri=${process.env.REACT_APP_OAUTH_REDIRECT_URI}` +
`&response_type=code&code_challenge_method=S256&code_challenge=${codeChallenge}` +
`&state=${encodeURIComponent(nonce)}`
}
const redirectToAuth = (state) => {
const codeVerifier = storeCodeVerifier(generateCodeVerifier())
window.location = getAuthUrl(codeVerifier, state)
}
const exchangeCodeForTokens = (code) => {
return api.exchangeCodeForTokens(code, useCodeVerifier()).then(response => {
let refreshToken = ''
let accessToken = ''
if (response.data) {
refreshToken = response.data.refresh_token
accessToken = response.data.access_token
}
storeRefreshToken(refreshToken)
return Promise.resolve({accessToken, refreshToken})
})
}
export { redirectToAuth, exchangeCodeForTokens, getAccessToken, storeRefreshToken, getRefreshToken, getStateObject }