elearning/frontend_management/stores/auth.ts
2026-01-12 16:49:58 +07:00

77 lines
2.2 KiB
TypeScript

import { defineStore } from 'pinia';
interface User {
id: string;
email: string;
fullName: string;
role: 'INSTRUCTOR' | 'ADMIN' | 'STUDENT';
}
export const useAuthStore = defineStore('auth', {
state: () => ({
user: null as User | null,
token: null as string | null,
isAuthenticated: false
}),
getters: {
isInstructor: (state) => state.user?.role === 'INSTRUCTOR',
isAdmin: (state) => state.user?.role === 'ADMIN',
isStudent: (state) => state.user?.role === 'STUDENT'
},
actions: {
async login(email: string, password: string) {
// TODO: Replace with real API call
// const { $api } = useNuxtApp();
// const response = await $api('/auth/login', {
// method: 'POST',
// body: { email, password }
// });
// Mock login for development
const mockUser: User = {
id: '1',
email: email,
fullName: 'อาจารย์ทดสอบ',
role: 'INSTRUCTOR'
};
this.token = 'mock-jwt-token';
this.user = mockUser;
this.isAuthenticated = true;
// Save to localStorage
if (process.client) {
localStorage.setItem('token', this.token);
localStorage.setItem('user', JSON.stringify(this.user));
}
return { token: this.token, user: this.user };
},
logout() {
this.user = null;
this.token = null;
this.isAuthenticated = false;
if (process.client) {
localStorage.removeItem('token');
localStorage.removeItem('user');
}
},
checkAuth() {
if (process.client) {
const token = localStorage.getItem('token');
const user = localStorage.getItem('user');
if (token && user) {
this.token = token;
this.user = JSON.parse(user);
this.isAuthenticated = true;
}
}
}
}
});