Skip to content
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

Refresh token #36

Merged
merged 8 commits into from
Mar 14, 2021
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions src/main/webapp/app/config/axios-interceptor.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import axios from 'axios';
import { getBasePath, Storage } from 'react-jhipster';

import { SERVER_API_URL, AUTH_TOKEN_KEY } from 'app/config/constants';
import { SERVER_API_URL, AUTH_TOKEN_KEY, REFRESH_TOKEN_KEY } from 'app/config/constants';

const TIMEOUT = 1 * 60 * 1000;
axios.defaults.timeout = TIMEOUT;
axios.defaults.baseURL = SERVER_API_URL;

function setupAxiosInterceptors(onUnauthenticated: () => void) {
function setupAxiosInterceptors(onUnauthenticated: () => Promise<void>) {
const onRequestSuccess = config => {
const token = Storage.local.get(AUTH_TOKEN_KEY) || Storage.session.get(AUTH_TOKEN_KEY);
if (token) {
Expand All @@ -16,12 +16,11 @@ function setupAxiosInterceptors(onUnauthenticated: () => void) {
return config;
};
const onResponseSuccess = response => response;
const onResponseError = err => {
const onResponseError = async err => {
const status = err.status || (err.response ? err.response.status : 0);
if (status === 401) {
onUnauthenticated();
await onUnauthenticated();
}
return Promise.reject(err);
};
axios.interceptors.request.use(onRequestSuccess);
axios.interceptors.response.use(onResponseSuccess, onResponseError);
Expand Down
1 change: 1 addition & 0 deletions src/main/webapp/app/config/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,5 @@ export const APP_TWO_DIGITS_AFTER_POINT_NUMBER_FORMAT = '0,0.[00]';

export const FIREBASE_AUTH_HEADER_NAME = 'X-Authorization-Firebase';
export const AUTH_TOKEN_KEY = 'authToken';
export const REFRESH_TOKEN_KEY = 'refreshToken';
export const FIREBASE_TOKEN_KEY = 'firebaseToken';
4 changes: 2 additions & 2 deletions src/main/webapp/app/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ import ErrorBoundary from './shared/error/error-boundary';
import AppComponent from './app';
import { loadIcons } from './config/icon-loader';
import { AUTH_TOKEN_KEY, FIREBASE_TOKEN_KEY } from 'app/config/constants';
import { logout } from './shared/services/auth.service';
import { handleUnauthenticated } from './shared/services/auth.service';

const devTools = process.env.NODE_ENV === 'development' ? <DevTools /> : null;

registerLocale(store);
setupAxiosInterceptors(logout);
setupAxiosInterceptors(handleUnauthenticated);
loadIcons();

const rootEl = document.getElementById('root');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Redirect, RouteComponentProps, Link } from 'react-router-dom';
import { IRootState } from 'app/shared/reducers';
import { CardImg, Container, Button, Row, Col } from 'reactstrap';
import { AvForm, AvField } from 'availity-reactstrap-validation';
import { emailLogin, fetchAccount, getAuthToken } from 'app/shared/services/auth.service';
import { emailLogin, getAuthToken } from 'app/shared/services/auth.service';
import { toast } from 'react-toastify';

export interface IAuthEmailLoginProps extends StateProps, RouteComponentProps<{}> {}
Expand All @@ -29,7 +29,6 @@ export class AuthEmailLogin extends React.Component<IAuthEmailLoginProps, IAuthE
});
emailLogin(values)
.then(firebaseToken => getAuthToken(firebaseToken))
.then(() => fetchAccount())
.then(() => {
toast.success('Login Successfully');
this.props.history.push('/');
Expand Down
4 changes: 1 addition & 3 deletions src/main/webapp/app/modules/auth/login/auth-login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { CardImg, Container, Button, Row, Col } from 'reactstrap';
import { IconProp } from '@fortawesome/fontawesome-svg-core';
import firebase from 'firebase';
import { toast } from 'react-toastify';
import { fetchAccount, getAuthToken, socialLogin } from 'app/shared/services/auth.service';
import { getAuthToken, socialLogin } from 'app/shared/services/auth.service';

export interface IAuthLoginProps extends StateProps, RouteComponentProps<{}> {}

Expand All @@ -35,7 +35,6 @@ export class AuthLogin extends React.Component<IAuthLoginProps> {
async handleGoogleLogin() {
socialLogin('google')
.then(firebaseToken => getAuthToken(firebaseToken))
.then(() => fetchAccount())
.then(() => toast.success('Login Successfully'))
.catch(error => {
const firebaseError = error as firebase.FirebaseError;
Expand All @@ -47,7 +46,6 @@ export class AuthLogin extends React.Component<IAuthLoginProps> {
handleFacebookLogin() {
socialLogin('facebook')
.then(firebaseToken => getAuthToken(firebaseToken))
.then(() => fetchAccount())
.then(() => toast.success('Login Successfully'))
.catch(error => {
const firebaseError = error as firebase.FirebaseError;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,10 @@ import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

import './floatButton.css';

const FloatButton = props => {
return (
<Button color="action" className="floatButton shadow" onClick={props.onClick}>
<FontAwesomeIcon icon="plus" size="lg" />
</Button>
);
};
const FloatButton = props => (
<Button color="action" className="floatButton shadow" onClick={props.onClick}>
<FontAwesomeIcon icon="plus" size="lg" />
</Button>
);

export default FloatButton;
6 changes: 0 additions & 6 deletions src/main/webapp/app/shared/reducers/authentication.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
export const ACTION_TYPES = {
LOGIN: 'authentication/LOGIN',
LOGOUT: 'authentication/LOGOUT',
FETCH_ACCOUNT: 'authentication/FETCH_ACCOUNT'
};
Expand Down Expand Up @@ -28,11 +27,6 @@ const initialState: IAuthenticationInitialState = {

export default (state: IAuthenticationInitialState = initialState, action): IAuthenticationInitialState => {
switch (action.type) {
case ACTION_TYPES.LOGIN:
return {
...state,
isAuthenticated: true
};
case ACTION_TYPES.LOGOUT:
return {
...state,
Expand Down
24 changes: 20 additions & 4 deletions src/main/webapp/app/shared/services/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import axios from 'axios';
import { Storage } from 'react-jhipster';
import { firebaseAuth, firebaseGoogleAuthProvider, firebaseFacebookAuthProvider } from 'app/config/firebase';
import { FIREBASE_AUTH_HEADER_NAME, AUTH_TOKEN_KEY, FIREBASE_TOKEN_KEY } from 'app/config/constants';
import { FIREBASE_AUTH_HEADER_NAME, AUTH_TOKEN_KEY, FIREBASE_TOKEN_KEY, REFRESH_TOKEN_KEY } from 'app/config/constants';
import store from 'app/config/store';
import { ACTION_TYPES } from '../reducers/authentication';
import { ILogin } from '../model/auth/login.model';
Expand All @@ -10,20 +10,36 @@ export async function getAuthToken(firebaseToken: string): Promise<void> {
const headers = {
[FIREBASE_AUTH_HEADER_NAME]: firebaseToken
};
const response = await axios.post('/api/firebase/authenticate', null, {
const response = await axios.post('/api/authenticate/firebase', null, {
headers
});
const jwtToken: string = response.data['id_token'];
const jwtToken: string = response.data['accessToken'];
const refreshToken: string = response.data['refreshToken'];
junzai97 marked this conversation as resolved.
Show resolved Hide resolved
Storage.local.set(AUTH_TOKEN_KEY, jwtToken);
kachun333 marked this conversation as resolved.
Show resolved Hide resolved
store.dispatch({ type: ACTION_TYPES.LOGIN });
Storage.local.set(REFRESH_TOKEN_KEY, refreshToken);
await fetchAccount();
}

export function logout(): void {
Storage.local.remove(FIREBASE_TOKEN_KEY);
Storage.local.remove(AUTH_TOKEN_KEY);
Storage.local.remove(REFRESH_TOKEN_KEY);
store.dispatch({ type: ACTION_TYPES.LOGOUT });
}

export async function handleUnauthenticated(): Promise<void> {
const token = Storage.local.get(AUTH_TOKEN_KEY) || Storage.session.get(AUTH_TOKEN_KEY);
const refreshToken = Storage.local.get(REFRESH_TOKEN_KEY) || Storage.session.get(REFRESH_TOKEN_KEY);
if (token && refreshToken) {
const response = await axios.post(`/api/authenticate/refresh?refreshToken=${refreshToken}`);
junzai97 marked this conversation as resolved.
Show resolved Hide resolved
const newJwtToken: string = response.data['accessToken'];
const newRefreshToken: string = response.data['refreshToken'];
junzai97 marked this conversation as resolved.
Show resolved Hide resolved
Storage.local.set(AUTH_TOKEN_KEY, newJwtToken);
Storage.local.set(REFRESH_TOKEN_KEY, newRefreshToken);
fetchAccount();
}
}

const SocialProvider = {
facebook: firebaseFacebookAuthProvider,
google: firebaseGoogleAuthProvider
Expand Down