feature login
This commit is contained in:
@@ -1,19 +0,0 @@
|
||||
import { ref, computed } from "vue";
|
||||
import { defineStore } from "pinia";
|
||||
|
||||
const useCounterStore = defineStore("counter", () => {
|
||||
const count = ref(0);
|
||||
const doubleCount = computed(() => count.value * 2);
|
||||
|
||||
function increment() {
|
||||
count.value++;
|
||||
}
|
||||
|
||||
return {
|
||||
count,
|
||||
doubleCount,
|
||||
increment
|
||||
};
|
||||
})
|
||||
|
||||
export default useCounterStore;
|
||||
87
src/stores/login.js
Normal file
87
src/stores/login.js
Normal 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');
|
||||
};
|
||||
},
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user