feature login

This commit is contained in:
chiayin
2023-01-31 15:38:14 +08:00
parent cd074c3c04
commit 76463f084c
25 changed files with 569 additions and 69 deletions

87
src/stores/login.js Normal file
View File

@@ -0,0 +1,87 @@
import { defineStore } from "pinia";
import axios from 'axios';
export default defineStore('loginStore', {
// data, methods, computed
// state, actions, getters
state: () => ({
auth: {
username: '',
password: '',
},
isInvalid: false,
userData: {},
}),
// 讓元件取用相關的資料狀態
getters: {
},
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);
if(response.status === 200){
// 將 token 儲存在 cookie
const token = response.data.access_token;
document.cookie = `luciaToken=${token}`;
this.$router.push('/files')
}
} catch(error) {
this.isInvalid = true;
};
},
/**
* log out, tooken expired
*/
logOut() {
let isCookie = document.cookie.split(';').some(c => c.trim().startsWith('luciaToken='));
let expires = new Date();
expires.setTime(expires.getTime() - 60000);
if(isCookie){
document.cookie = `luciaToken=; expires=${expires.toGMTString()}`;
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) {
};
},
/**
* check login for 'my-account' api
*/
async checkLogin() {
const api = 'api/my-account';
try {
const response = await axios.get(api);
if(response.status !== 200) this.$router.push('/login');
} catch(error) {
this.$router.push('/login');
};
},
}
})