Automatically refresh jwt token periodically

Signed-off-by: Thomas Citharel <tcit@tcit.fr>
This commit is contained in:
Thomas Citharel 2021-05-27 18:24:11 +02:00
parent fb94c64c63
commit fd28b4d410
No known key found for this signature in database
GPG Key ID: A061B9DDE0CA0773
3 changed files with 28 additions and 0 deletions

View File

@ -37,6 +37,7 @@
"graphql": "^15.0.0",
"graphql-tag": "^2.10.3",
"intersection-observer": "^0.12.0",
"jwt-decode": "^3.1.2",
"leaflet": "^1.4.0",
"leaflet.locatecontrol": "^0.73.0",
"lodash": "^4.17.11",

View File

@ -50,6 +50,8 @@ import { initializeCurrentActor } from "./utils/auth";
import { CONFIG } from "./graphql/config";
import { IConfig } from "./types/config.model";
import { ICurrentUser } from "./types/current-user.model";
import jwt_decode, { JwtPayload } from "jwt-decode";
import { refreshAccessToken } from "./apollo/utils";
@Component({
apollo: {
@ -78,6 +80,8 @@ export default class App extends Vue {
online = true;
interval: number | undefined = undefined;
async created(): Promise<void> {
if (await this.initializeCurrentUser()) {
await initializeCurrentActor(this.$apollo.provider.defaultClient);
@ -119,11 +123,29 @@ export default class App extends Vue {
this.online = true;
console.log("online");
});
this.interval = setInterval(async () => {
const accessToken = localStorage.getItem(AUTH_ACCESS_TOKEN);
if (accessToken) {
const token = jwt_decode<JwtPayload>(accessToken);
if (
token?.exp !== undefined &&
new Date(token.exp * 1000 - 60000) < new Date()
) {
refreshAccessToken(this.$apollo.getClient());
}
}
}, 60000);
}
showOfflineNetworkWarning(): void {
this.$notifier.error(this.$t("You are offline") as string);
}
unmounted(): void {
clearInterval(this.interval);
this.interval = undefined;
}
}
</script>

View File

@ -7509,6 +7509,11 @@ jsprim@^1.2.2:
json-schema "0.2.3"
verror "1.10.0"
jwt-decode@^3.1.2:
version "3.1.2"
resolved "https://registry.yarnpkg.com/jwt-decode/-/jwt-decode-3.1.2.tgz#3fb319f3675a2df0c2895c8f5e9fa4b67b04ed59"
integrity sha512-UfpWE/VZn0iP50d8cz9NrZLM9lSWhcJ+0Gt/nm4by88UL+J1SiKN8/5dkjMmbEzwL2CAe+67GsegCbIKtbp75A==
killable@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/killable/-/killable-1.0.1.tgz#4c8ce441187a061c7474fb87ca08e2a638194892"