-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Login middlend #10
Merged
Merged
Login middlend #10
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
8dc9e13
setup middle end client
b1121e1
middle end client implementation
731916f
auth-token utilities
434d8c6
implement fetchCurrentUser and login actions
75bcc93
sync with create-login-route branch
c20f75e
Merge branch 'create-login-route' of https://github.com/BigRoomStudio…
File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
'use strict'; | ||
|
||
// https://docs.expo.io/guides/environment-variables | ||
// https://docs.expo.io/workflow/configuration/ | ||
|
||
module.exports = ({ config }) => ({ | ||
...config, | ||
extra: { | ||
apiUrl: process.env.API_URL | ||
} | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,134 @@ | ||
const { default: Axios } = require('axios'); | ||
const AuthTokenUtils = require('../utils/auth-token'); | ||
|
||
const internals = {}; | ||
|
||
module.exports = (m, options) => { | ||
|
||
const { apiBaseUrl } = options; | ||
|
||
const client = internals.createClient({ baseURL: apiBaseUrl }); | ||
|
||
return { | ||
client | ||
}; | ||
}; | ||
|
||
internals.createClient = (options) => { | ||
|
||
const client = Axios.create({ | ||
headers: { common: {} }, | ||
// Needed for refresh token, esp. in local development | ||
withCredentials: true, | ||
paramsSerializer: { | ||
serialize: (obj) => { | ||
// The default serializer turns array params into ?trades[]=A&trades[]=B | ||
// which is not compatible with node's querystring parser which wants ?trades=A&trades=B. | ||
// Luckily URLSearchParams and node are in agreement, so we can customize for it below. | ||
|
||
if (!obj) { | ||
return ''; | ||
} | ||
|
||
if (typeof obj === 'string') { | ||
return obj; | ||
} | ||
|
||
const params = new URLSearchParams(); | ||
const append = (key, val) => { | ||
|
||
val = val instanceof Date ? val.toISOString() : val; | ||
|
||
params.append(key, val); | ||
}; | ||
|
||
Object.entries(obj).forEach(([key, value]) => { | ||
|
||
if (Array.isArray(value)) { | ||
value.forEach((val) => append(key, val)); | ||
} | ||
else { | ||
append(key, value); | ||
} | ||
}); | ||
|
||
return params.toString(); | ||
} | ||
}, | ||
...options | ||
}); | ||
|
||
client.interceptors.request.use( | ||
async (config) => { | ||
|
||
const accessToken = await AuthTokenUtils.get('accessToken'); | ||
|
||
if (accessToken) { | ||
config.headers.Authorization = `Bearer ${accessToken}`; | ||
} | ||
|
||
return config; | ||
} | ||
); | ||
|
||
client.logout = async (opts) => { | ||
|
||
try { | ||
await client.post('/logout', null, opts); | ||
} | ||
finally { | ||
AuthTokenUtils.clear(); | ||
} | ||
}; | ||
|
||
client.interceptors.response.use(null, async (error) => { | ||
|
||
if (error.config?._isRetry) { | ||
throw error; | ||
} | ||
|
||
const accessToken = await AuthTokenUtils.get('accessToken'); | ||
const refreshToken = await AuthTokenUtils.get('refreshToken'); | ||
|
||
// If we receive a 401, hit '/reauthorize', | ||
// store the new token and retry the request | ||
if ( | ||
error.config && | ||
error.config.reauthorize !== false && | ||
error.response?.status === 401 && | ||
accessToken && | ||
refreshToken | ||
) { | ||
|
||
error.config._isRetry = true; | ||
|
||
try { | ||
const { data: results } = await client.post('/reauthorize', { refreshToken }, { | ||
reauthorize: false, | ||
logoutOnFailure: true | ||
}); | ||
if (results.data) { | ||
await AuthTokenUtils.store(results.data); | ||
} | ||
} | ||
catch (reauthErr) { | ||
|
||
if (Axios.isAxiosError(reauthErr)) { | ||
// Rethrow the original error if /reauthorize fails so that | ||
// consumers don't have to worry about this case. | ||
throw error; | ||
} | ||
|
||
// Something unexpected, non-HTTP went wrong during reauth | ||
throw reauthErr; | ||
} | ||
|
||
// Retry after successful | ||
return client.request(error.config); | ||
} | ||
|
||
throw error; | ||
}); | ||
|
||
return client; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
const MiddleEnd = require('strange-middle-end'); | ||
|
||
module.exports = MiddleEnd.createTypes('auth', { | ||
FETCH_CURRENT_USER: MiddleEnd.type.async, | ||
LOGIN: MiddleEnd.type.async | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
const MiddleEnd = require('strange-middle-end'); | ||
const AuthTokenUtils = require('../../utils/auth-token'); | ||
|
||
const { | ||
FETCH_CURRENT_USER, | ||
LOGIN | ||
} = require('./action-types'); | ||
|
||
const { createAction } = MiddleEnd; | ||
|
||
module.exports = (m) => { | ||
|
||
const getClient = () => { | ||
|
||
const { client } = m.mods.app; | ||
return client; | ||
}; | ||
|
||
return { | ||
initialize: () => m.dispatch.auth.fetchCurrentUser(), | ||
actions: { | ||
fetchCurrentUser: createAction(FETCH_CURRENT_USER, { | ||
index: true, | ||
handler: async () => { | ||
|
||
const client = getClient(); | ||
const { data: results } = await client.get('/validate'); | ||
|
||
|
||
return results.pallie; | ||
} | ||
}), | ||
login: createAction(LOGIN, { | ||
handler: async ({ username, password }) => { | ||
|
||
const client = getClient(); | ||
|
||
const { data: results } = await client.post('/login', { | ||
username, | ||
password | ||
}, { | ||
reauthorize: false | ||
}); | ||
|
||
await AuthTokenUtils.store(results); | ||
|
||
const [err, user] = await m.dispatch.auth.fetchCurrentUser(); | ||
|
||
if (err) { | ||
throw err; | ||
} | ||
|
||
return user; | ||
} | ||
}) | ||
} | ||
}; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
const SecureStore = require('expo-secure-store'); | ||
|
||
const internals = {}; | ||
|
||
exports.get = async (key) => { | ||
|
||
const { secureStoreConf } = internals; | ||
|
||
const token = await SecureStore.getItemAsync(key, secureStoreConf.options); | ||
|
||
if (key === 'refreshToken') { | ||
return JSON.parse(token); | ||
} | ||
|
||
return token; | ||
}; | ||
|
||
exports.store = ({ accessToken, refreshToken } = {}) => { | ||
|
||
const { secureStoreConf: { keys, options } } = internals; | ||
|
||
return Promise.all([ | ||
SecureStore.setItemAsync(keys.accessToken, accessToken, options), | ||
SecureStore.setItemAsync(keys.refreshToken, JSON.stringify(refreshToken), options) | ||
]); | ||
}; | ||
|
||
exports.clear = () => { | ||
|
||
const { secureStoreConf: { keys, options } } = internals; | ||
|
||
return Promise.all([ | ||
SecureStore.deleteItemAsync(keys.accessToken, options), | ||
SecureStore.deleteItemAsync(keys.refreshToken, options) | ||
]); | ||
}; | ||
|
||
internals.secureStoreConf = { | ||
keys: { | ||
accessToken: 'accessToken', | ||
refreshToken: 'refreshToken' | ||
}, | ||
options: { | ||
keyChainAccessible: SecureStore.WHEN_UNLOCKED | ||
} | ||
}; |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.