Commit fa8205b1 authored by Matija Obreza's avatar Matija Obreza
Browse files

Fix: copied missing backend API configuration

parent 51a9d92c
Pipeline #6868 passed with stages
in 5 minutes and 47 seconds
......@@ -18,6 +18,7 @@ import getDir from '../server/middleware/detectDirection';
// JSS & MUI
import { MuiThemeProvider } from '@material-ui/core/styles';
import theme from 'ui/theme';
import { configureBackendApi } from 'utilities/requestUtils';
declare const __PRELOADED_STATE__: any;
......@@ -33,6 +34,9 @@ const detectedLang = initialLanguage ? initialLanguage : detectLocaleFromPath(vi
const historyOptions = { basename: detectedLang !== 'en' ? `${virtualPath}/${detectedLang}` : `${virtualPath}` };
const history = createHistory(historyOptions);
// Configure axios for client
configureBackendApi({ apiUrl: `${virtualPath}/proxy` });
const initialState = __PRELOADED_STATE__ === undefined ? {} : __PRELOADED_STATE__;
const store = composeEnhancers(applyMiddleware(thunk, routerMiddleware(history)))(createStore)(rootReducer, initialState);
......
import { configureBackendApi } from 'utilities/requestUtils';
/**
* Start the frontend server
*/
let server = require('./server').default;
const server = require('./server').default;
const PORT = process.env.PORT || 3000;
// Configure axios for server
configureBackendApi({ apiUrl: `http://localhost:${PORT}/proxy` });
// start server on PORT
server.listen(PORT, () => {
console.log('HTTP server listening on: ' + PORT);
......
......@@ -11,7 +11,7 @@ const httpProxy = proxy(config.apiUrl, {
return true;
}
if (req.url.startsWith('/uploads')) {
req.url = req.url.replace(/^\/uploads/, '/api/v0/repository/download');
req.url = req.url.replace(/^\/uploads/, '/api/v1/repository/download');
}
if (req.url.startsWith('/api')) {
// If authorization header is not provided, use access_token from cookie
......
......@@ -17,7 +17,7 @@ import createGenerateClassName from '@material-ui/core/styles/createGenerateClas
import MuiThemeProvider from '@material-ui/core/styles/MuiThemeProvider';
import theme from 'ui/theme';
import checkAuthToken from './checkAuthToken';
// import checkAuthToken from './checkAuthToken';
import routes from 'ui/routes';
import matchRoutes from 'ui/matchRoutes';
import renderRoutes from 'ui/renderRoutes';
......@@ -25,7 +25,8 @@ import fetchComponentData from './fetchComponentData';
import detectLocaleFromPath from './detectLocaleFromPath';
import getDir from './detectDirection';
import config from '../config';
import {configure} from 'actions/applicationConfig';
import checkAuthToken from './checkAuthToken';
import { configure } from 'actions/applicationConfig';
const prerenderer = (html) => (req, res) => {
console.log('Init prerenderer, request url:', req.url);
......@@ -51,13 +52,14 @@ const prerenderer = (html) => (req, res) => {
const generateClassName = createGenerateClassName();
const initialLanguage = req.i18n.language;
const initialI18nStore = {};
const defaultLanguage = 'en';
initialI18nStore[initialLanguage] = req.i18n.services.resourceStore.data[initialLanguage];
if (initialLanguage !== 'en') {
if (initialLanguage !== defaultLanguage) {
// So that we have missing translations
initialI18nStore['en'] = req.i18n.services.resourceStore.data['en'];
initialI18nStore[defaultLanguage] = req.i18n.services.resourceStore.data[defaultLanguage];
}
const basename = initialLanguage !== 'en' ? `${config.frontendPath}/${initialLanguage}` : `${config.frontendPath}`;
const pathWithoutLang = req.url.substr(initialLanguage !== 'en' ? 3 : 0, req.url.length);
const basename = initialLanguage !== defaultLanguage ? `${config.frontendPath}/${initialLanguage}` : `${config.frontendPath}`;
const pathWithoutLang = req.url.substr(initialLanguage !== defaultLanguage ? 3 : 0, req.url.length);
console.log(`<StaticRouter location="${pathWithoutLang}" basename="${basename}"`);
......@@ -105,6 +107,7 @@ const prerenderer = (html) => (req, res) => {
checkAuthToken(req, res, store.dispatch).then(() => {
const language = req.i18n.language;
const pathWithoutLang = pathname.substr(language !== 'en' ? 3 : 0, pathname.length);
console.log(`Rendering ${pathWithoutLang} for ${pathname}`);
const branch = matchRoutes(routes, pathWithoutLang);
fetchComponentData(store.dispatch, branch, search)
......
......@@ -3,127 +3,123 @@ import * as Constants from 'constants/login';
import * as cookies from 'es-cookie';
import { clearCookies, saveCookies } from 'utilities';
import { ROLE_CLIENT } from 'constants/userRoles';
import {log} from 'utilities/debug';
import { log } from 'utilities/debug';
import { configureBackendApi } from 'utilities/requestUtils';
export function checkAccessTokens(dispatch) {
const cookieToken: string = typeof window !== 'undefined' && cookies.get('access_token');
const applicationLogin = () =>
LoginService.loginApp()
.then((data) => {
saveCookies({access_token: data.access_token, authorities: [ROLE_CLIENT]});
dispatch(loginApp(data));
})
.catch((error) => {
log('Something went wrong', error);
});
if (cookieToken) {
return LoginService.checkToken(cookieToken)
.then((data) => {
dispatch(loginUser({ access_token: cookieToken, ...data }));
return true;
})
.catch((error) => {
const cookieToken: string = typeof window !== 'undefined' && cookies.get('access_token');
const applicationLogin = () =>
LoginService.loginApp()
.then((data) => {
saveCookies({access_token: data.access_token, authorities: [ROLE_CLIENT]});
dispatch(loginApp(data));
})
.catch((error) => {
log('Something went wrong', error);
});
if (cookieToken) {
return LoginService.checkToken(cookieToken)
.then((data) => {
dispatch(loginUser({ access_token: cookieToken, ...data }));
return true;
})
.catch((error) => {
clearCookies();
return applicationLogin();
});
} else {
clearCookies();
return applicationLogin();
});
} else {
clearCookies();
return applicationLogin();
}
}
}
function loginRequest(username, password) {
return (dispatch) => {
return LoginService.login(username, password)
.then((data) => {
saveCookies(data);
return dispatch(loginUser(data));
});
};
export function loginAppRequest() {
return (dispatch) => {
return LoginService.loginApp()
.then((data) => {
return dispatch(loginApp(data));
});
};
}
function loginAppRequest() {
return (dispatch) => {
return LoginService.loginApp()
.then((data) => {
return dispatch(loginApp(data));
});
};
export function loginApp(d) {
// console.log('Login app', d);
configureBackendApi({ accessToken: d.access_token });
return {
type: Constants.LOGIN_APP,
authorities: [ROLE_CLIENT],
...d,
};
}
function logoutRequest() {
return (dispatch, getState) => {
const token = getState().login.access_token;
return LoginService.logout(token)
.then(() => {
clearCookies();
return dispatch(logout());
});
// Login
export const loginUser = (payload) => {
// console.log('loginUser', payload);
configureBackendApi({ accessToken: payload.access_token });
return {
type: Constants.LOGIN_USER,
...payload,
};
}
};
function checkTokenRequest(token) {
return (dispatch) => {
log('checkTokenRequest verifying ', token);
return LoginService.checkToken(token)
.then((data) => {
log('checkTokenRequest got', data);
return dispatch(checkToken({ access_token: token, ...data }));
});
const checkToken = (payload) => {
return {
type: Constants.CHECK_TOKEN,
...payload,
};
}
};
function verifyGoogleTokenRequest(accessToken, googleClientId) {
return (dispatch, getState) => {
const token = getState().login.access_token;
export const loginRequest = (username, password) => (dispatch) => {
return LoginService.verifyGoogleToken(token, accessToken, googleClientId)
.then((data) => {
saveCookies(data);
return dispatch(loginApp(data));
});
};
}
return LoginService.login(username, password)
.then((data) => {
saveCookies(data);
return dispatch(loginUser(data));
});
};
function loginUser(d) {
return {
type: Constants.LOGIN_USER,
...d,
};
}
export const checkTokenRequest = (token) => (dispatch) => {
log('checkTokenRequest verifying ', token);
return LoginService.checkToken(token)
.then((data) => {
log('checkTokenRequest got', data);
return dispatch(checkToken({access_token: token, ...data}));
});
};
function loginApp(d) {
// Google login
// TODO find usage
export const verifyGoogleToken = (payload) => {
return {
type: Constants.LOGIN_APP,
authorities: [ROLE_CLIENT],
...d,
type: Constants.VERIFY_GOOGLE_TOKEN,
...payload,
};
}
};
function logout() {
return {
type: Constants.LOGOUT,
};
}
export const verifyGoogleTokenRequest = (accessToken) => (dispatch, getState) => {
const token = getState().login.access_token;
function checkToken(d) {
return {
type: Constants.CHECK_TOKEN,
...d,
};
}
return LoginService.verifyGoogleToken(token, accessToken)
.then((data) => {
saveCookies(data);
return dispatch(loginApp(data));
});
};
function verifyGoogleToken(d) {
// Logout
const logout = () => {
return {
type: Constants.VERIFY_GOOGLE_TOKEN,
...d,
type: Constants.LOGOUT,
};
}
};
export {
loginRequest, loginUser, loginAppRequest, loginApp, logoutRequest, logout,
checkTokenRequest, checkToken, verifyGoogleTokenRequest, verifyGoogleToken,
export const logoutRequest = () => (dispatch, getState) => {
const token = getState().login.access_token;
return LoginService.logout(token)
.then(() => {
clearCookies();
return dispatch(logout());
});
};
class ApiError {
public status: number;
public statusText: string;
public data: any;
public static axiosError(err): ApiError {
const ae = new ApiError();
if (err.response) {
ae.status = err.response.status;
ae.statusText = err.response.statusText;
ae.data = err.response.data;
} else {
ae.status = -1;
ae.data = 'Unknown error';
}
return ae;
}
}
export default ApiError;
import axios from 'axios';
// import FormData from 'form-data'; // it's in the browser
import { axiosBackend } from 'utilities/requestUtils';
// import FormData from 'form-data'; // it's in the browser
import { LOGIN_URL, LOGOUT_URL, CHECK_TOKEN_URL, VERIFY_GOOGLE_TOKEN_URL } from 'constants/apiURLS';
const LOGIN_URL = `/oauth/token`;
const URL_LOGOUT = `/api/v0/me/logout`;
// const LOGOUT_URL = `${API_BASE_URL}/me/logout`;
export const CHECK_TOKEN_URL = `/oauth/check_token`;
export const VERIFY_GOOGLE_TOKEN_URL = `/google/verify-token`;
export class LoginService {
public static loginApp() {
return axios.post(LOGIN_URL, null, {
return axiosBackend.post(LOGIN_URL, null, {
params: {
grant_type: 'client_credentials',
},
......@@ -21,7 +22,7 @@ export class LoginService {
const form = new FormData();
form.append('username', username);
form.append('password', password);
return axios.post(LOGIN_URL, form, {
return axiosBackend.post(LOGIN_URL, form, {
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded',
// },
......@@ -32,15 +33,26 @@ export class LoginService {
.then(({ data }) => data);
}
public static logout(token: string) {
/**
* logout at /api/v0/me/logout
*
* @param authToken Authorization token
*/
public static logout(authToken: string): Promise<any> {
const apiUrl = URL_LOGOUT;
// console.log(`Fetching from ${apiUrl}`);
const content = { /* No content in request body */ };
return axiosBackend.request({
url: LOGOUT_URL,
url: apiUrl,
method: 'POST',
});
...content,
}).then(({ data }) => data as any);
}
public static checkToken(token: string) {
return axios.get(CHECK_TOKEN_URL, {
return axiosBackend.get(CHECK_TOKEN_URL, {
params: {
token,
},
......@@ -50,13 +62,12 @@ export class LoginService {
});
}
public static verifyGoogleToken(token: string, accessToken, googleClientId) {
public static verifyGoogleToken(token: string, accessToken) {
return axiosBackend.request({
url: VERIFY_GOOGLE_TOKEN_URL,
method: 'GET',
params: {
accessToken,
googleClientId,
},
})
.then(({ data }) => data);
......
import axios from 'axios';
import ApiError from 'model/ApiError';
axios.interceptors.response.use((response) => {
return response;
}, (error) => {
if (error.response.status < 500) {
return Promise.reject(error.response.data);
} else {
return Promise.reject(error);
}
return Promise.reject(ApiError.axiosError(error));
});
......@@ -4,21 +4,21 @@ import axios from 'axios';
* Default Axios configuration for accessing the backend API
*/
export const axiosBackend = axios.create({
baseURL: 'http://localhost:3000/proxy', // use embedded proxy
timeout: 0,
headers: {
'X-Custom-Header': 'Genesys Frontend',
'Content-Type': 'application/json',
},
baseURL: 'http://localhost:3000/proxy', // use embedded proxy
timeout: 0,
headers: {
'X-Custom-Header': 'Genesys Frontend',
'Content-Type': 'application/json',
},
});
axiosBackend.interceptors.request.use((config) => {
// Do something before request is sent
console.log('Backend API request to ', config.url);
return config;
// Do something before request is sent
console.log('Backend API request to ', config.url);
return config;
}, (error) => {
// Do something with request error
return Promise.reject(error);
// Do something with request error
return Promise.reject(error);
});
/**
......@@ -26,15 +26,15 @@ axiosBackend.interceptors.request.use((config) => {
* @param apiUrl baseURL to the backend API (http://localhost:3000/proxy)
* @param authToken OAuth authorization token
*/
export const configureBackendApi = ({ apiUrl, accessToken, timeout = 0 }: { apiUrl?: string, accessToken?: string, timeout?: number }) => {
if (apiUrl) {
console.log(`Using backend API baseURL ${apiUrl}`);
axiosBackend.defaults.baseURL = apiUrl;
}
if (accessToken) {
console.log(`Using backend API accessToken ..snip..`);
axiosBackend.defaults.headers.common.Authorization = `Bearer ${accessToken}`;
}
console.log(`Using backend API timeout ${timeout}`);
axiosBackend.defaults.timeout = timeout;
export const configureBackendApi = ({apiUrl, accessToken, timeout = 0}: {apiUrl?: string, accessToken?: string, timeout?: number}) => {
if (apiUrl) {
console.log(`Using backend API baseURL ${apiUrl}`);
axiosBackend.defaults.baseURL = apiUrl;
}
if (accessToken) {
console.log(`Using backend API accessToken ..snip..`);
axiosBackend.defaults.headers.common.Authorization = `Bearer ${accessToken}`;
}
console.log(`Using backend API timeout ${timeout}`);
axiosBackend.defaults.timeout = timeout;
};
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment