feat: Implement authentication system with token refresh and initial instructor dashboard with course management.

This commit is contained in:
Missez 2026-01-23 09:53:39 +07:00
parent 0eb9b522f6
commit ab3124628c
11 changed files with 1053 additions and 93 deletions

View file

@ -70,10 +70,12 @@ export const useAuthStore = defineStore('auth', {
userCookie.value = null;
},
checkAuth() {
async checkAuth() {
const tokenCookie = useCookie('token');
const userCookie = useCookie('user');
const refreshTokenCookie = useCookie('refreshToken');
// Case 1: Have token and user - restore auth state
if (tokenCookie.value && userCookie.value) {
this.token = tokenCookie.value;
try {
@ -81,11 +83,45 @@ export const useAuthStore = defineStore('auth', {
? JSON.parse(userCookie.value)
: userCookie.value;
this.isAuthenticated = true;
return;
} catch (e) {
// Invalid user data
this.logout();
}
}
// Case 2: No token but have refresh token - try to refresh
if (!tokenCookie.value && refreshTokenCookie.value && userCookie.value) {
// Get cookie refs with options BEFORE await to maintain Nuxt context
const tokenCookieWithOptions = useCookie('token', {
maxAge: 60 * 60 * 24, // 24 hours
sameSite: 'strict'
});
const refreshTokenCookieWithOptions = useCookie('refreshToken', {
maxAge: 60 * 60 * 24 * 7, // 7 days
sameSite: 'strict'
});
const currentRefreshToken = refreshTokenCookie.value;
try {
console.log('Token missing, attempting refresh...');
const newTokens = await authService.refreshToken(currentRefreshToken);
// Update cookies with new tokens
tokenCookieWithOptions.value = newTokens.token;
refreshTokenCookieWithOptions.value = newTokens.refreshToken;
this.token = newTokens.token;
this.user = typeof userCookie.value === 'string'
? JSON.parse(userCookie.value)
: userCookie.value;
this.isAuthenticated = true;
console.log('Token refreshed successfully');
} catch (e) {
console.error('Token refresh failed');
this.logout();
}
}
}
}
});