2022-05-21 01:07:31 +02:00
|
|
|
import { defineStore } from "pinia";
|
2022-05-22 16:25:13 +02:00
|
|
|
import * as jose from "jose";
|
|
|
|
import axios from "axios";
|
2022-05-24 23:04:35 +02:00
|
|
|
import { cookiesStorage } from "./coockiesStorage";
|
2022-05-21 01:07:31 +02:00
|
|
|
|
2022-05-22 16:25:13 +02:00
|
|
|
export const useUserStore = defineStore("user", {
|
2022-05-21 01:07:31 +02:00
|
|
|
state: () => ({
|
2022-05-22 16:25:13 +02:00
|
|
|
userName: "",
|
|
|
|
discordId: "",
|
2022-05-24 23:04:35 +02:00
|
|
|
discriminator: "",
|
|
|
|
avatar: "",
|
2022-05-22 16:25:13 +02:00
|
|
|
token: "",
|
|
|
|
loginFail: false,
|
2022-05-21 01:07:31 +02:00
|
|
|
}),
|
|
|
|
getters: {
|
2022-05-22 16:25:13 +02:00
|
|
|
isLoggedIn(): boolean {
|
|
|
|
if (this.token) {
|
|
|
|
return !this.isExpired;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
},
|
|
|
|
isExpired(): boolean {
|
|
|
|
if (this.getTokenPayload?.exp) {
|
|
|
|
const exp = new Date(this.getTokenPayload.exp * 1000);
|
|
|
|
return exp < new Date();
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
},
|
|
|
|
getTokenPayload: (state) => {
|
2022-05-24 23:04:35 +02:00
|
|
|
const token = state.token;
|
2022-05-22 16:25:13 +02:00
|
|
|
return jose.decodeJwt(state.token);
|
|
|
|
},
|
|
|
|
},
|
|
|
|
actions: {
|
|
|
|
async login(code: string) {
|
|
|
|
const baseApi = import.meta.env.VITE_API_BASE_URL;
|
|
|
|
const baseUrl = window.location.origin;
|
|
|
|
try {
|
|
|
|
const response = await axios.post(baseApi + "auth/discord", {
|
|
|
|
redirectUri: baseUrl + "/oauth2/callback",
|
|
|
|
code: code,
|
|
|
|
});
|
|
|
|
|
|
|
|
this.token = response.data.token;
|
|
|
|
const payload = this.getTokenPayload;
|
2022-05-24 23:04:35 +02:00
|
|
|
|
|
|
|
this.userName = payload.sub as string;
|
|
|
|
this.discordId = payload.discord_id as string;
|
|
|
|
this.discriminator = payload.discriminator as string;
|
|
|
|
this.avatar = payload.avatar as string;
|
2022-05-22 16:25:13 +02:00
|
|
|
|
|
|
|
this.loginFail = false;
|
|
|
|
console.log("Loggin success !");
|
|
|
|
return true;
|
|
|
|
} catch (reason) {
|
|
|
|
console.log("Loggin fail !");
|
|
|
|
console.log(reason);
|
|
|
|
this.token = "";
|
|
|
|
this.userName = "";
|
|
|
|
this.discordId = "";
|
|
|
|
this.loginFail = true;
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
},
|
2022-05-21 01:07:31 +02:00
|
|
|
},
|
2022-05-24 23:04:35 +02:00
|
|
|
persist: {
|
|
|
|
storage: cookiesStorage,
|
|
|
|
},
|
2022-05-21 01:07:31 +02:00
|
|
|
});
|