You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
2.1 KiB
TypeScript

import { User } from "../models/User"
import { makeAutoObservable } from "mobx";
import AuthService from "../services/AuthService";
import axios from "axios";
import { AuthResponse } from "../models/response/AuthResponse";
import { API_URL } from "../http";
export default class Store {
user = {} as User;
isAuth = false;
isLoading = true;
constructor() {
makeAutoObservable(this);
}
setAuth(bool: boolean) {
this.isAuth = bool;
}
setUser(user: User) {
this.user = user;
}
setLoading(bool: boolean) {
this.isLoading = bool;
}
async registration (email: string, name: string, sname: string, password: string) {
try {
const response = await AuthService.registration(email, name, sname, password);
localStorage.setItem('token', response.data.accessToken);
this.setAuth(true);
this.setUser(response.data.user)
} catch (e) {
console.log(e)
}
}
async login (email: string, password: string) {
try {
const response = await AuthService.login(email, password);
localStorage.setItem('token', response.data.accessToken);
this.setAuth(true);
this.setUser(response.data.user)
} catch (e) {
console.log(e)
}
}
async logout () {
try {
await AuthService.logout();
localStorage.removeItem('token');
this.setAuth(false);
this.setUser({} as User);
} catch (e) {
console.log(e)
}
}
async checkAuth() {
this.setLoading(true);
try {
const response = await axios.get<AuthResponse>(`${API_URL}/auth/refresh`, {withCredentials: true});
localStorage.setItem('token', response.data.accessToken);
this.setAuth(true);
this.setUser(response.data.user)
} catch (e) {
console.log(e);
} finally {
this.setLoading(false);
}
}
storeLoad() {
this.setLoading(false);
}
}