mirror of
https://github.com/nagisa77/OpenIsle.git
synced 2026-02-22 22:21:09 +08:00
fix goToProfile and store user info
This commit is contained in:
@@ -2,12 +2,18 @@ import { API_BASE_URL } from '../main'
|
||||
import { reactive } from 'vue'
|
||||
|
||||
const TOKEN_KEY = 'token'
|
||||
const USER_ID_KEY = 'userId'
|
||||
const USERNAME_KEY = 'username'
|
||||
|
||||
export const authState = reactive({
|
||||
loggedIn: false
|
||||
loggedIn: false,
|
||||
userId: null,
|
||||
username: null
|
||||
})
|
||||
|
||||
authState.loggedIn = localStorage.getItem(TOKEN_KEY) !== null && localStorage.getItem(TOKEN_KEY) !== ''
|
||||
authState.userId = localStorage.getItem(USER_ID_KEY)
|
||||
authState.username = localStorage.getItem(USERNAME_KEY)
|
||||
|
||||
export function getToken() {
|
||||
return localStorage.getItem(TOKEN_KEY)
|
||||
@@ -20,9 +26,24 @@ export function setToken(token) {
|
||||
|
||||
export function clearToken() {
|
||||
localStorage.removeItem(TOKEN_KEY)
|
||||
clearUserInfo()
|
||||
authState.loggedIn = false
|
||||
}
|
||||
|
||||
export function setUserInfo({ id, username }) {
|
||||
authState.userId = id
|
||||
authState.username = username
|
||||
if (id !== undefined && id !== null) localStorage.setItem(USER_ID_KEY, id)
|
||||
if (username) localStorage.setItem(USERNAME_KEY, username)
|
||||
}
|
||||
|
||||
export function clearUserInfo() {
|
||||
localStorage.removeItem(USER_ID_KEY)
|
||||
localStorage.removeItem(USERNAME_KEY)
|
||||
authState.userId = null
|
||||
authState.username = null
|
||||
}
|
||||
|
||||
export async function fetchCurrentUser() {
|
||||
const token = getToken()
|
||||
if (!token) return null
|
||||
@@ -37,6 +58,14 @@ export async function fetchCurrentUser() {
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadCurrentUser() {
|
||||
const user = await fetchCurrentUser()
|
||||
if (user) {
|
||||
setUserInfo({ id: user.id, username: user.username })
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
export function isLogin() {
|
||||
return authState.loggedIn
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { API_BASE_URL, GOOGLE_CLIENT_ID, toast } from '../main'
|
||||
import { setToken } from './auth'
|
||||
import { setToken, loadCurrentUser } from './auth'
|
||||
|
||||
export function googleSignIn(redirect) {
|
||||
if (!window.google || !GOOGLE_CLIENT_ID) {
|
||||
@@ -18,6 +18,7 @@ export function googleSignIn(redirect) {
|
||||
const data = await res.json()
|
||||
if (res.ok && data.token) {
|
||||
setToken(data.token)
|
||||
await loadCurrentUser()
|
||||
toast.success('登录成功')
|
||||
if (redirect) redirect()
|
||||
} else {
|
||||
|
||||
Reference in New Issue
Block a user