import axios from 'axios'; import api from "../src/utils/axios.js"; import store from "../src/store/index.js"; import Cookies from 'js-cookie'; export default class AuthService { static async login(username, password) { let result = {} let isEmail = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(username); try { const data = { LOGIN_METHOD: isEmail ? "email" : "username", LOGIN_NAME: username, PASSWORD: password }; await api.post('/login', data).then(res => { result = res; }); Cookies.set('Token', result.token, {path: '/', expires: 1}) } catch (e) { result.code = 3; } return result; } static async sendMessage(username, email, password){ let result = {} const data = { USER_NAME: username, EMAIL: email, PASSWORD: password }; await api.post('/sendkey', data).then(res=>{ result = res; }) return result; } static logout() { Cookies.remove('Token'); store.commit('setToken', null) store.commit('setUserInfo', null) } static getToken() { return Cookies.get('Token'); } static async setSelfInfo() { let info = {}; if (!store.state.token) { store.commit('setToken', await this.getToken()); } try { await api.post('/selfinfo', { TOKEN: store.state.token }).then((res) => { info = res; }) if (info.code !== 0) { throw new Error('error') } if (store.state.token) { store.commit('setUserInfo', info.data) } } catch (e) { console.error(e) // this.logout(); } } static isTokenExpired() { const token = this.getToken(); if (!token) return true; // const payload = JSON.parse(atob(token.split('.')[1])); // 解码JWT的payload部分 // const exp = payload.exp * 1000; // 转换为毫秒 // return Date.now() >= exp; } // static async refreshToken() { // const refreshToken = localStorage.getItem('refreshToken'); // const response = await axios.post('/api/refresh-token', {refreshToken}); // localStorage.setItem('token', response.data.token); // return response.data.token; // } }