diff --git a/src/router/index.js b/src/router/index.js index 310a541..f6521a6 100644 --- a/src/router/index.js +++ b/src/router/index.js @@ -52,8 +52,12 @@ const router = createRouter({ router.beforeEach(async(to, from, next) => { const auth = useAuthStore(); - if (!auth.isLoggedIn) { - // auth.restoreSession(); + if (!auth.user) { + const restored = auth.restoreSession(); + if(restored){ + await auth.fetchUser(); + } + try { await auth.fetchUser(); } catch (e) { @@ -67,13 +71,13 @@ router.beforeEach(async(to, from, next) => { // if(to.meta.requiresAuth && !isLoggedIn) { // return next('/login'); // } - // if (to.path === '/login' && isLoggedIn) { - // return next('/') - // } + if (to.path === '/login' && isLoggedIn) { + return next('/') + } - // if (to.meta.requiresAuth && !isLoggedIn) { - // return next("/login"); - // } + if (to.meta.requiresAuth && !isLoggedIn) { + return next("/login"); + } return next(); }); diff --git a/src/stores/auth.js b/src/stores/auth.js index c4b5073..331e24e 100644 --- a/src/stores/auth.js +++ b/src/stores/auth.js @@ -1,5 +1,6 @@ import {defineStore} from "pinia"; import axios from "axios"; +import api from '@/util/api' export const useAuthStore = defineStore('auth', { state: () => ({ @@ -11,8 +12,7 @@ export const useAuthStore = defineStore('auth', { user: null }), getters: { - isLoggedIn: (state) => !!state.user, - // isLoggedIn: (state) => !!state.token && !!state.user, + isLoggedIn: (state) => !!state.token && !!state.user, }, actions: { async register(username, password, re_password) { @@ -38,41 +38,47 @@ export const useAuthStore = defineStore('auth', { }) const { access_token, refresh_token } = response.data; - const user = await axios.get(this.baseUrl + '/auth/users/me', { - headers: { - Authorization: `Bearer ${access_token}` - } - }).then(res => res.data) + // const user = await axios.get(this.baseUrl + '/auth/users/me', { + // headers: { + // Authorization: `Bearer ${access_token}` + // } + // }).then(res => res.data) this.refresh_token = refresh_token this.token = access_token - this.user = user - await this.fetchUser(); + // this.user = user + const user = await this.fetchUser(); + console.log(user) // localStorage.setItem('token', this.token) // localStorage.setItem('user', JSON.stringify(user)) }, async fetchUser() { + console.log("Token :", this.token) + if (!this.token) return false; try { - const res = await axios.get(`${this.baseUrl}/auth/users/me`, { - headers: { - Authorization: `Bearer ${this.token}`, - }, - withCredentials: true, + const res = await api.get(`/auth/users/me`, { + withCredentials: true, + headers: { + Authorization: `Bearer ${this.token}` + } }); this.user = res.data; + return true; } catch (err) { - console.error("❌ fetch user failed", err); + console.error("Fetch user failed", err); this.user = null; } }, async logout() { if(this.token){ - await axios.post(this.baseUrl + '/oauth/revoke_token/', { - token: this.token, - client_id: this.clientId, - client_secret: this.clientSecret - }, + const body = new URLSearchParams(); + body.append("token", this.token); + body.append("client_id", this.clientId); + body.append("client_secret", this.clientSecret); + + await axios.post(this.baseUrl + '/oauth/revoke_token/', + body.toString(), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, withCredentials:true @@ -83,15 +89,48 @@ export const useAuthStore = defineStore('auth', { this.token = null; this.user = null; + this.refresh_token = null; // localStorage.removeItem('token') // localStorage.removeItem('user') }, async restoreSession() { try { + if (!this.token && this.refresh_token) { + await this.refreshToken(); + } await this.fetchUser(); } catch { - console.log("No active session found."); + console.log("No active session."); + } + }, + + async refreshToken() { + try { + const form = new URLSearchParams(); + form.append("grant_type", "refresh_token"); + form.append("refresh_token", this.refresh_token); + form.append("client_id", this.clientId); + form.append("client_secret", this.clientSecret); + + const response = await axios.post( + `${this.baseUrl}/oauth/token/`, + form.toString(), + { + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + withCredentials: true, + } + ); + + this.token = response.data.access_token; + this.refresh_token = response.data.refresh_token; + return true; + } catch (e) { + this.token = null; + this.user = null; + return false; } } + + } }) \ No newline at end of file diff --git a/src/util/api.js b/src/util/api.js index 062be9f..63b72e2 100644 --- a/src/util/api.js +++ b/src/util/api.js @@ -12,36 +12,46 @@ const api = axios.create({ api.interceptors.request.use( config =>{ - const token = localStorage.getItem('token') - if(token){ - config.headers.Authorization = `Bearer ${token}` + const auth = useAuthStore() + if(auth.token){ + config.headers.Authorization = `Bearer ${auth.token}` } return config - } + }, + error => Promise.reject(error) ) api.interceptors.response.use( response => response, async error => { - const originalRequest = error.config; const auth = useAuthStore(); + const originalRequest = error.config; if(error.response && error.response.status === 401 && !originalRequest._retry){ originalRequest._retry =true; - try { - const res = await axios.post(`${this.baseURL}` + "/oauth/token/refresh/", {},{withCredentials:true}); - - auth.token = res.data.access_token; + const success = await auth.refreshToken(); + if(success){ originalRequest.headers.Authorization = `Bearer ${auth.token}`; + return api(originalRequest); + } + + await auth.logout(); + window.location = "/login"; + + // try { + // const res = await axios.post(`${this.baseURL}` + "/oauth/token/refresh/", {},{withCredentials:true}); + + // auth.token = res.data.access_token; + // originalRequest.headers.Authorization = `Bearer ${auth.token}`; // error.config.headers.Authorization = `Bearer ${res.data.access}`; // return api.request(error.config); - return api(originalRequest) - } catch (refreshError) { + // return api(originalRequest) + // } catch (refreshError) { // jika refresh juga gagal, logout - window.location = "/login"; - auth.logout(); - return Promise.reject(refreshError) - } + // window.location = "/login"; + // auth.logout(); + // return Promise.reject(refreshError) + // } } return Promise.reject(error) }