Skip to content

Commit a7a96f7

Browse files
committed
Writing new token to sessionstorage
1 parent ef138f9 commit a7a96f7

File tree

3 files changed

+54
-104
lines changed

3 files changed

+54
-104
lines changed

src/client/src/App.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import About from './pages/About';
1010
import Login from './components/Login/Login';
1111
import CDialog from './components/CDialog';
1212
import Check from './pages/Check/Check';
13-
13+
import Refresh from './components/Refresh';
1414

1515
import useToken from './components/Login/useToken';
1616
var jwt = require('jsonwebtoken');
@@ -71,6 +71,7 @@ function AuthenticatedApp() {
7171

7272
const { access_token, setToken } = useToken();
7373

74+
console.log("AA - token = " + String(access_token).slice(-8))
7475

7576
var decoded = jwt.decode(access_token, { complete: true });
7677

@@ -119,6 +120,11 @@ function AuthenticatedApp() {
119120
<Route path="/check">
120121
<Check />
121122
</Route>
123+
124+
<Route path="/ref">
125+
<Refresh />
126+
</Route>
127+
122128
</Switch>
123129
}
124130

src/client/src/components/CDialog.js

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,26 @@ import DialogContent from '@material-ui/core/DialogContent';
66
import DialogContentText from '@material-ui/core/DialogContentText';
77
import DialogTitle from '@material-ui/core/DialogTitle';
88

9-
export default function CDialog() {
9+
import useToken from '../components/Login/useToken';
10+
11+
import Refresh from './Refresh';
12+
13+
export default function CDialog() {
1014
const [open, setOpen] = React.useState(true);
15+
const { access_token, setToken } = useToken();
16+
1117

1218
const handleClickOpen = () => {
1319
setOpen(true);
1420
};
1521

16-
const handleClose = (shouldRefresh) => {
22+
const handleClose = async (shouldRefresh) => {
1723
setOpen(false);
1824
console.log("Refresh? " + String(shouldRefresh));
25+
if (shouldRefresh){
26+
const new_at = await Refresh(access_token);
27+
setToken(new_at);
28+
}
1929
};
2030

2131

@@ -27,7 +37,7 @@ export default function CDialog() {
2737
</Button> */}
2838
<Dialog
2939
open={open}
30-
onClose={handleClose}
40+
onClose={() => handleClose(false)}
3141
aria-labelledby="alert-dialog-title"
3242
aria-describedby="alert-dialog-description"
3343
>

src/client/src/components/Refresh.js

Lines changed: 34 additions & 100 deletions
Original file line numberDiff line numberDiff line change
@@ -1,118 +1,52 @@
11
import React from 'react';
2-
import { useHistory } from "react-router-dom";
32
import useToken from '../components/Login/useToken';
43
var jwt = require('jsonwebtoken');
54

65

6+
export default async function Refresh(old_token) {
77

8-
export default function Refresh() {
8+
9+
console.log("Top of Refresh, old_token = " + String(old_token).slice(-8) );
910

10-
const { access_token, setToken } = useToken();
11+
// get the decoded payload and header
12+
var decoded = jwt.decode(old_token, { complete: true });
13+
const expTime = decoded?.payload.exp
14+
// console.log('User: ' + userName + ' / Role:' + userRole + '->' + processStatus + ' @ ' + DateTime.local().toFormat('HH:mm:ss.SSS'))
1115

12-
const [processStatus, setProcessStatus] = React.useState('loading');
13-
const [error, setError] = React.useState('');
14-
const [data, setData] = React.useState('');
16+
1517

16-
let history = useHistory()
17-
18-
1918

20-
21-
22-
// get the decoded payload and header
23-
var decoded = jwt.decode(access_token, { complete: true });
24-
const userName = decoded?.payload.sub
25-
const userRole = decoded?.payload.role
26-
const expTime = decoded?.payload.exp
27-
// console.log('User: ' + userName + ' / Role:' + userRole + '->' + processStatus + ' @ ' + DateTime.local().toFormat('HH:mm:ss.SSS'))
28-
29-
30-
31-
React.useEffect(() => {
32-
33-
function doRefresh() {
34-
// console.log('authCheck startfetch @ ' + DateTime.local().toFormat('HH:mm:ss.SSS'))
35-
fetch('http://localhost:5000/api/user/refresh',
36-
{
37-
method: 'GET',
38-
headers: {
39-
'Content-Type': 'application/json',
40-
'Authorization': 'Bearer ' + access_token
41-
}
42-
})
43-
44-
.then((response) => {
45-
// console.log('authCheck handle response @ ' + DateTime.local().toFormat('HH:mm:ss.SSS'))
46-
if (!response.ok) {
47-
//throw (String(response.status + ':' + response.statusText))
48-
throw (response)
49-
}
50-
return response.json()
51-
} )
52-
.then((data) => {
53-
// console.log('authCheck data @ ' + DateTime.local().toFormat('HH:mm:ss.SSS'))
54-
setProcessStatus('complete');
55-
setData(data);
56-
})
57-
.catch((e) => {
58-
let errCode = e.status
59-
let errText = e.statusText
60-
61-
setToken(null) // Clear the token to force login again
62-
let errStr = String(e)
63-
setProcessStatus('error');
64-
setError(errStr);
65-
console.log(errCode + ':' + errText)
66-
history.push('/')
67-
return e
68-
});
69-
70-
} //
71-
72-
73-
const handleRefresh = async e => {
74-
const dr = await doRefresh();
75-
const at = dr.access_token;
76-
setToken(at);
77-
};
78-
79-
80-
handleRefresh();
81-
82-
},
83-
// eslint-disable-next-line
84-
[ processStatus, access_token, history ]);
85-
86-
// if (processStatus === 'loading') {
87-
// console.log('Check: if pc=l loading...')
88-
// return <p>loading..</p>;
89-
// }
90-
91-
if (processStatus === 'error') {
92-
console.log('error')
93-
return <p>ERROR: <i>{error}</i></p>;
94-
}
19+
// console.log('authCheck startfetch @ ' + DateTime.local().toFormat('HH:mm:ss.SSS'))
20+
const new_at = await fetch('http://localhost:5000/api/user/refresh',
21+
{
22+
method: 'GET',
23+
headers: {
24+
'Content-Type': 'application/json',
25+
'Authorization': 'Bearer ' + old_token
26+
}
27+
})
9528

29+
.then((response) => {
30+
// console.log('authCheck handle response @ ' + DateTime.local().toFormat('HH:mm:ss.SSS'))
31+
if (!response.ok) {
32+
//throw (String(response.status + ':' + response.statusText))
33+
throw (response)
34+
}
35+
return response.json()
36+
} )
9637

38+
.catch((e) => {
39+
// If it failed there's not much to do, probably got here after expiration
40+
console.log(String(e));
41+
return '{}'
42+
});
9743

98-
// console.log("About to return")
99-
return (
100-
<div>
101-
102-
<h2>Refresh</h2>
103-
<ul>
104-
105-
<li>JWT expires: {-(Date.now()/1000 - expTime).toFixed(1)} secs</li>
106-
<li>{data}</li>
44+
console.log("New AT " + String(new_at.access_token).slice(-8) );
45+
46+
return(new_at.access_token);
10747

108-
</ul>
109-
{userRole === 'admin' &&
110-
<h2>Welcome, admin!</h2>
111-
}
112-
</div>
113-
);
11448

11549

11650

117-
};
51+
}
11852

0 commit comments

Comments
 (0)