57 lines
1.6 KiB
TypeScript
57 lines
1.6 KiB
TypeScript
"use client";
|
|
|
|
import CookieService from "@Front/Services/CookieService/CookieService";
|
|
import EventEmitter from "@Front/Services/EventEmitter";
|
|
import JwtService from "@Front/Services/JwtService/JwtService";
|
|
|
|
import User from "src/sdk/User";
|
|
|
|
export default class UserStore {
|
|
public static readonly instance = new this();
|
|
protected readonly event = new EventEmitter();
|
|
|
|
private constructor() { }
|
|
|
|
public isConnected(): boolean {
|
|
return !!CookieService.getInstance().getCookie("leCoffreAccessToken");
|
|
}
|
|
|
|
public async connect(user: any) {
|
|
try {
|
|
//Save tokens in cookies
|
|
CookieService.getInstance().setCookie("leCoffreAccessToken", JSON.stringify(user));
|
|
this.event.emit("connection", CookieService.getInstance().getCookie("leCoffreAccessToken"));
|
|
} catch (error) {
|
|
console.error(error);
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
public async disconnect() {
|
|
try {
|
|
User.getInstance().clear();
|
|
|
|
//Remove tokens from cookies
|
|
CookieService.getInstance().deleteCookie("leCoffreAccessToken");
|
|
this.event.emit("disconnection", CookieService.getInstance().getCookie("leCoffreAccessToken"));
|
|
} catch (error) {
|
|
console.error(error);
|
|
}
|
|
}
|
|
|
|
public onDisconnect(callback: (userAddress: string) => void): () => void {
|
|
this.event.on("disconnection", callback);
|
|
return () => this.event.off("disconnection", callback);
|
|
}
|
|
|
|
public onConnect(callback: (userAddress: string) => void): () => void {
|
|
this.event.on("connection", callback);
|
|
return () => this.event.off("connection", callback);
|
|
}
|
|
|
|
public getUser(): any {
|
|
return JSON.parse(CookieService.getInstance().getCookie("leCoffreAccessToken") || "");
|
|
}
|
|
}
|