import { defineStore } from "pinia"; import axios from 'axios'; import apiError from '@/module/apiError.js'; import { deleteCookie, setCookie } from "../utils/cookieUtil"; export default defineStore('loginStore', { // data, methods, computed // state, actions, getters state: () => ({ auth: { grant_type: 'password', // password | refresh_token username: '', password: '', refresh_token: '' }, isInvalid: false, userData: {}, isLoggedIn: false, rememberedReturnToUrl: "", // expired: new Date().setMonth(6), // 設定 Refresh Token 的到期日為半年後 }), actions: { /** * fetch Login For Access Token api */ async signIn() { const api = '/api/oauth/token'; const config = { headers: { // http post 預設的 url 編碼,非 json 格式 'Content-Type':'application/x-www-form-urlencoded', }, }; try { const response = await axios.post(api, this.auth, config); const accessToken = response.data.access_token; const refreshToken = response.data.refresh_token; // 將 token 儲存在 cookie document.cookie = `luciaToken=${accessToken}`; // document.cookie = `luciaRefreshToken=${refreshToken};expires=${new Date(this.expired)};`; this.isLoggedIn = true; setCookie("isLuciaLoggedIn", "true"); // 大部分的情況下,預設導向至 FILES 頁面 // 然而有一種情況是使用者在沒有登入的情況下貼上了某一個頁面的網址, // 則在此情況下時,我們會在使用者稍後登入後,把使用者帶到剛才記住的 return-to 網址 if(this.rememberedReturnToUrl !== "") { const decodedUrl = atob(this.rememberedReturnToUrl); window.location.href = decodedUrl; } else { this.$router.push('/files'); } } catch(error) { this.isInvalid = true; }; }, /** * Refresh Token (暫時沒做) */ async refreshTokenLogin() { const api = '/api/oauth/token'; const refreshToken = document.cookie.replace(/(?:(?:^|.*;\s*)luciaRefreshToken\s*\=\s*([^;]*).*$)|^.*$/, "$1"); this.auth.grant_type = 'refresh_token'; this.auth.refresh_token = refreshToken; // try { // const response = await axios.post(api, this.auth, config); // const newAccessToken = response.data.access_token; // const newRefreshToken = response.data.refresh_token; // document.cookie = `luciaToken=${newAccessToken}`; // document.cookie = `luciaRefreshToken=${newRefreshToken};expires=${this.expired}`; // defaults.headers.common['Authorization'] = `Bearer ${newAccessToken}`; // } catch(error) { // this.$router.push('/login'); // } }, /** * Logout, tooken expired */ logOut() { delete axios.defaults.headers.common["Authorization"]; document.cookie = 'luciaToken=; expires=Thu, 01 Jan 1970 00:00:00 UTC;'; this.isLoggedIn = false; deleteCookie("isLuciaLoggedIn"); this.$router.push('/login'); }, /** * get user detail for 'my-account' api */ async getUserData() { const api = '/api/my-account'; try { const response = await axios.get(api); this.userData = response.data; } catch(error) { apiError(error, 'Failed to load the Map.'); }; }, /** * check login for 'my-account' api */ async checkLogin() { const api = '/api/my-account'; try { const response = await axios.get(api); } catch(error) { this.$router.push('/login'); }; }, setRememberedReturnToUrl(returnToUrl){ this.rememberedReturnToUrl = returnToUrl } } });