a
This commit is contained in:
58
src/services/authService.js
Normal file
58
src/services/authService.js
Normal file
@@ -0,0 +1,58 @@
|
||||
import useApiFetch from "@/composables/useApiFetch";
|
||||
|
||||
class AuthService {
|
||||
detectPlatform() {
|
||||
const ua = navigator.userAgent.toLowerCase();
|
||||
if (/micromessenger/.test(ua)) return "wxh5";
|
||||
return "h5";
|
||||
}
|
||||
|
||||
async authenticate() {
|
||||
const platform = this.detectPlatform();
|
||||
return await this.authByPlatform(platform);
|
||||
}
|
||||
|
||||
async authByPlatform(platform) {
|
||||
switch (platform) {
|
||||
case "h5":
|
||||
return await this.authBrowser();
|
||||
case "wxh5":
|
||||
return await this.authWechatH5();
|
||||
default:
|
||||
return await this.authBrowser();
|
||||
}
|
||||
}
|
||||
|
||||
async authBrowser() {
|
||||
let token = localStorage.getItem("token");
|
||||
if (!token) {
|
||||
const { data } = await useApiFetch("/user/auth")
|
||||
.post({ platform: "h5" })
|
||||
.json();
|
||||
token = data.accessToken;
|
||||
localStorage.setItem("token", token);
|
||||
localStorage.setItem("refreshAfter", data.refreshAfter);
|
||||
localStorage.setItem("accessExpire", data.accessExpire);
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
async authWechatH5() {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const code = params.get("code");
|
||||
if (code) {
|
||||
const { data } = await useApiFetch("/user/auth")
|
||||
.post({ platform: "wxh5", code })
|
||||
.json();
|
||||
window.history.replaceState({}, "", window.location.pathname);
|
||||
localStorage.setItem("token", data.accessToken);
|
||||
localStorage.setItem("refreshAfter", data.refreshAfter);
|
||||
localStorage.setItem("accessExpire", data.accessExpire);
|
||||
return data.accessToken;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const authService = new AuthService();
|
||||
Reference in New Issue
Block a user