From f6212cf81bd08ac97242771751de3a7878710f2f Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 29 Apr 2020 19:38:24 -0500 Subject: [PATCH] Refresh user token on pageload --- app/gabsocial/actions/auth.js | 23 +++++++++++++++++++++-- app/gabsocial/actions/me.js | 10 ++++++---- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/app/gabsocial/actions/auth.js b/app/gabsocial/actions/auth.js index 1ea47c985..6d80e337a 100644 --- a/app/gabsocial/actions/auth.js +++ b/app/gabsocial/actions/auth.js @@ -75,6 +75,27 @@ function createUserToken(username, password) { grant_type: 'password', username: username, password: password, + }).then(response => { + dispatch(authLoggedIn(response.data)); + }); + }; +} + +export function refreshUserToken() { + return (dispatch, getState) => { + const refreshToken = getState().getIn(['auth', 'user', 'refresh_token']); + const app = getState().getIn(['auth', 'app']); + + if (!refreshToken) return dispatch(noOp()); + + return api(getState, 'app').post('/oauth/token', { + client_id: app.get('client_id'), + client_secret: app.get('client_secret'), + refresh_token: refreshToken, + redirect_uri: 'urn:ietf:wg:oauth:2.0:oob', + grant_type: 'refresh_token', + }).then(response => { + dispatch(authLoggedIn(response.data)); }); }; } @@ -83,8 +104,6 @@ export function logIn(username, password) { return (dispatch, getState) => { return dispatch(initAuthApp()).then(() => { return dispatch(createUserToken(username, password)); - }).then(response => { - return dispatch(authLoggedIn(response.data)); }).catch(error => { dispatch(showAlert('Login failed.', 'Invalid username or password.')); throw error; diff --git a/app/gabsocial/actions/me.js b/app/gabsocial/actions/me.js index 27fdc3337..7586aab90 100644 --- a/app/gabsocial/actions/me.js +++ b/app/gabsocial/actions/me.js @@ -1,5 +1,6 @@ import api from '../api'; import { importFetchedAccount } from './importer'; +import { refreshUserToken } from './auth'; export const ME_FETCH_REQUEST = 'ME_FETCH_REQUEST'; export const ME_FETCH_SUCCESS = 'ME_FETCH_SUCCESS'; @@ -18,10 +19,11 @@ export function fetchMe() { dispatch({ type: ME_FETCH_SKIP }); return; }; - dispatch(fetchMeRequest()); - - api(getState).get('/api/v1/accounts/verify_credentials').then(response => { - dispatch(fetchMeSuccess(response.data)); + dispatch(refreshUserToken()).then(() => { + dispatch(fetchMeRequest()); + return api(getState).get('/api/v1/accounts/verify_credentials').then(response => { + dispatch(fetchMeSuccess(response.data)); + }); }).catch(error => { dispatch(fetchMeFail(error)); });