37 lines
		
	
	
	
		
			1.2 KiB
		
	
	
	
		
			TypeScript
		
	
	
	
	
	
			
		
		
	
	
			37 lines
		
	
	
	
		
			1.2 KiB
		
	
	
	
		
			TypeScript
		
	
	
	
	
	
// Utilities
 | 
						|
import { defineStore } from 'pinia'
 | 
						|
import type { Auth, DetailedUser } from '@/types'
 | 
						|
import { fetchWrapper } from '@/helpers/fetch-wrapper'
 | 
						|
import { getApiUrl } from '@/helpers/config-loader';
 | 
						|
import { useAlertStore } from './alert';
 | 
						|
 | 
						|
export const useAuthStore = defineStore('auth', {
 | 
						|
  state: () => ({
 | 
						|
    auth: JSON.parse(localStorage.getItem('auth') || "{}") as Auth,
 | 
						|
    user: JSON.parse(localStorage.getItem('this_user') || "{}") as DetailedUser,
 | 
						|
  }),
 | 
						|
  actions: {
 | 
						|
    async login(username: string, password: string) {
 | 
						|
      try {
 | 
						|
        const data = await fetchWrapper.post(`${getApiUrl()}/account/signin`, { username, password})
 | 
						|
        const token: string = data.token || ""
 | 
						|
 | 
						|
        if (token == null) {
 | 
						|
          throw new Error("Could not sign in, didn't receive token");
 | 
						|
        }
 | 
						|
 | 
						|
        this.auth = {
 | 
						|
          token 
 | 
						|
        }
 | 
						|
 | 
						|
        const user: DetailedUser = await fetchWrapper.get(`${getApiUrl()}/users/self`);
 | 
						|
        this.user = user;
 | 
						|
 | 
						|
        localStorage.setItem('this_user', JSON.stringify(user));
 | 
						|
      } catch (error) {
 | 
						|
        const alertStore = useAlertStore();
 | 
						|
        alertStore.error((error as Error).message, 5000);
 | 
						|
      }
 | 
						|
    }
 | 
						|
  }
 | 
						|
})
 |