Skip to content

Commit

Permalink
feat: auto update token when a new token is received
Browse files Browse the repository at this point in the history
  • Loading branch information
mbetancurt committed Jun 30, 2020
1 parent 39145ad commit b53a9bc
Show file tree
Hide file tree
Showing 6 changed files with 74 additions and 61 deletions.
13 changes: 4 additions & 9 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src/Ades.css

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

32 changes: 29 additions & 3 deletions src/Ades.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@ import {
} from '@blueprintjs/core';
import S from 'sanctuary';
import { useTranslation } from 'react-i18next';
import './css/animate.css';
import jwtDecode from 'jwt-decode';
import io from 'socket.io-client';

/*
* CSS Styling
*/
import './Ades.css';

import './css/animate.css';
/*
* Components
*/
Expand Down Expand Up @@ -57,6 +57,7 @@ import VehiclesList from './dashboard/vehicle/VehiclesList';
import NewVehicle from './dashboard/vehicle/NewVehicle';
import HomeScreen from './dashboard/main_screen/HomeScreen';
import VerificationScreen from './VerificationScreen';
import {API} from './consts';

/*function alertIsImportant(alertUtmMessage) {
return (
Expand Down Expand Up @@ -135,6 +136,7 @@ function Ades() {
const [isLoggedIn, setLoggedIn] = useState(true);
const [role, setRole] = useState('none');
const [timeoutUnlogin, setTimeoutUnlogin] = useState(0);
const [mbSocket, setSocket] = useState(S.Nothing);

useEffect(() => {
if (S.isJust(state.auth.token)) {
Expand All @@ -145,7 +147,6 @@ function Ades() {
setRole(decoded.role);
/* Get user full information if not yet fetched */
const username = decoded.username;
console.log('User is', username);
if (S.isNothing(state.auth.user)) {
actions.auth.info(username, () => {
actions.operations.fetch();
Expand All @@ -157,6 +158,31 @@ function Ades() {
actions.auth.logout();
});
}
if (S.isJust(mbSocket)) {
const socket = fM(mbSocket);
const token = fM(state.auth.token);
if (socket.connected)
socket.close();
socket.io.opts.query = { token };
socket.connect();
} else {
const newSocket = io(API, {
query: {
token: fM(state.auth.token)
},
transports: ['websocket']
});
/* Initialize sockets */
newSocket.on('new-position', function (info) {
const info2 = {...info};
//console.log('DroneState: new-position: ', info2);
actions.drones.post(info2);
});
newSocket.on('operation-state-change', function (info) {
actions.operations.updateOne(info.gufi, info.state);
});
setSocket(S.Just(newSocket));
}
setTimeoutUnlogin(setTimeout(() => {
actions.auth.logout();
setRole('none');
Expand Down
11 changes: 1 addition & 10 deletions src/dashboard/user/UsersList.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,15 @@ import React, {useEffect, useState} from 'react';
import {API} from '../../consts';
import {fM, maybeValues} from '../../libs/SaferSanctuary';
import S from 'sanctuary';
import A from 'axios';
import '../../Ades.css';
import {Button, Intent, Tab, Tabs} from '@blueprintjs/core';
import {useHistory} from 'react-router-dom';
import useAdesState, {print} from '../../state/AdesState';
import useAdesState, {Axios, print} from '../../state/AdesState';
import {useTranslation} from 'react-i18next';
import { useParams } from 'react-router-dom';

import Pilot from './Pilot';

const Axios = A.create({
baseURL: API,
timeout: 15000,
headers: {
'Content-Type': 'application/json',
}
});

const USERS_ONE_PAGE_NUMBER = 8;

function useUsersState() {
Expand Down
4 changes: 2 additions & 2 deletions src/map/hooks/useSimulatorLogic.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,10 @@ function UseSimulatorLogic(refMapOnClick, map, token) {
});

if (ratio < 1) {
const newTimer = setTimeout(() => fly(ratio + 0.02), 100);
const newTimer = setTimeout(() => fly(ratio + 0.02), 1000);
setTimer(newTimer);
} else {
const newTimer = setTimeout(() => fly(0.02), 100);
const newTimer = setTimeout(() => fly(0.02), 1000);
setTimer(newTimer);
}
};
Expand Down
73 changes: 37 additions & 36 deletions src/state/AdesState.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,17 @@
import React from 'react';
import globalHook from '../libs/useGlobalHook';
import A from 'axios';
import S from 'sanctuary';

import A from 'axios';
import {API, DEBUG} from '../consts';
import {Mutex} from 'async-mutex';
import {fM, maybeValues} from '../libs/SaferSanctuary';
import io from 'socket.io-client';

/**
* Global state of Ades
* @type {{operations: {list: Maybe, updated: number}, auth: {user: Maybe, username: string, token: Maybe}}}
* @type {AxiosInstance}
*/

const Axios = A.create({
baseURL: API,
timeout: 15000,
headers: {
'Content-Type': 'application/json',
}
});
let Axios;

const quickFlyLocations = [
{
Expand Down Expand Up @@ -236,6 +228,21 @@ function addQuickFly(store, data) {
const actions = {
auth: {
login: (store, username, password, callback, errorCallback) => {
Axios = A.create({
baseURL: API,
timeout: 15000,
headers: {
'Content-Type': 'application/json',
}
});
Axios.interceptors.response.use(function (response) {
if (response.headers.token) {
store.actions.auth.updateToken(response.headers.token);
}
return response;
}, function (error) {
return Promise.reject(error);
});
const authInfo = JSON.stringify({
username: username,
password: password
Expand All @@ -251,27 +258,11 @@ const actions = {
errorCallback && error.response && errorCallback(error.response.data);
});
},

info: (store, username, okCallback, errorCallback) => {
Axios.get('user/' + username, {headers: {auth: fM(store.state.auth.token)}})
.then(result => {
print(store.state, false, 'InfoState', result.data);
store.setState({auth: {...store.state.auth, user: S.Just(result.data)}});
const socket = io(API, {
query: {
token: fM(store.state.auth.token)
},
transports: ['websocket']
});
/* Initialize sockets */
socket.on('new-position', function (info) {
const info2 = {...info};
//console.log('DroneState: new-position: ', info2);
store.actions.drones.post(info2);
});
socket.on('operation-state-change', function (info) {
updateOperationState(store, info.gufi, info.state);
});
okCallback && okCallback(result.data);
})
.catch(error => {
Expand All @@ -280,6 +271,12 @@ const actions = {
errorCallback && errorCallback();
});
},
updateToken: (store, newToken) => {
if (fM(store.state.auth.token) !== newToken) {
print(store.state, false, 'Token', newToken);
store.setState({auth: {...store.state.auth, token: S.Just(newToken)}});
}
},
logout: (store) => {
store.setState(initialState);
}
Expand All @@ -296,7 +293,7 @@ const actions = {
},*/
vehicles: {
fetch: (store) => {
Axios.get(API + 'vehicle', {headers: {auth: fM(store.state.auth.token)}})
Axios.get('vehicle', {headers: {auth: fM(store.state.auth.token)}})
.then(result => addVehicles(store, result.data))
.catch(error => {
print(store.state, true, 'VehicleState', error);
Expand All @@ -309,7 +306,7 @@ const actions = {
}
},
post: (store, vehicle, callback, errorCallback) => {
A.post(API + 'vehicle', vehicle, {headers: {auth: fM(store.state.auth.token)}})
Axios.post('vehicle', vehicle, {headers: {auth: fM(store.state.auth.token)}})
.then(result => {
addVehicle(store, result.data);
callback && callback();
Expand All @@ -326,13 +323,13 @@ const actions = {
},
operations: {
fetch: (store) => {
A.get(API + 'operation', {headers: {auth: fM(store.state.auth.token)}})
Axios.get('operation', {headers: {auth: fM(store.state.auth.token)}})
.then(result => addOperations(store, result.data.ops)) // TODO: Contract
.catch(error => print(store.state, true, 'OperationState', error));
},
post: (store, operation, callback, errorCallback) => {
const operationCleaned = prepareOperation(operation);
A.post(API + 'operation', operationCleaned, {headers: {auth: fM(store.state.auth.token)}})
Axios.post('operation', operationCleaned, {headers: {auth: fM(store.state.auth.token)}})
.then(result => {
//addOperations(store, result.data);
// TODO: Don't ask the server for the operations...
Expand All @@ -346,7 +343,7 @@ const actions = {
},
pendingacceptation: (store, gufi, comments, isApproved) => {
const data = {comments: comments, approved: isApproved};
A.post(API + 'operation/' + gufi + '/pendingtoaccept', data, {headers: {auth: fM(store.state.auth.token)}})
Axios.post('operation/' + gufi + '/pendingtoaccept', data, {headers: {auth: fM(store.state.auth.token)}})
.then(() => {
// TODO:
// updateOperationState(store, gufi, isApproved ? 'ACCEPTED' : 'NOT_ACCEPTED');
Expand All @@ -355,6 +352,9 @@ const actions = {
print(store.state, true, 'OperationState', error);
//errorCallback && error.response && errorCallback(error.response.data);
});
},
updateOne: (store, gufi, info) => {
updateOperationState(store, gufi, info);
}
},
drones: {
Expand Down Expand Up @@ -429,14 +429,14 @@ const actions = {
},
rfv: {
fetch: (store) => {
A.get(API + 'restrictedflightvolume', {headers: {auth: fM(store.state.auth.token)}})
Axios.get('restrictedflightvolume', {headers: {auth: fM(store.state.auth.token)}})
.then(result => addRFV(store, result.data))
.catch(error => print(store.state, true, 'RFVState', error));
}
},
quickFly: {
fetch: (store) => {
A.get(API + 'quickfly', {headers: { auth: fM(store.state.auth.token) }})
Axios.get('quickfly', {headers: { auth: fM(store.state.auth.token) }})
.then(result => addQuickFly(store, result.data))
.catch(error => {
addQuickFly(store, quickFlyLocations);
Expand All @@ -450,7 +450,7 @@ const actions = {
olds.push(data);
addQuickFly(store, olds);
callback && callback();
/*A.post(API + 'quickfly', data, {headers: { auth: fM(store.state.auth.token) }})
/*Axios.post('quickfly', data, {headers: { auth: fM(store.state.auth.token) }})
.then(result => {
addQuickFly(result.data);
callback && callback();
Expand Down Expand Up @@ -504,7 +504,8 @@ export {
extractOperationsFromState,
filterOperationsByState,
filterOperationsByIds,
print
print,
Axios
};


Expand Down

0 comments on commit b53a9bc

Please sign in to comment.