auth.js 2.03 KB
/*
 * @Date: 2025-03-20 21:11:31
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2025-03-22 10:08:20
 * @FilePath: /mlaj/src/contexts/auth.js
 * @Description: 文件描述
 */
import { ref, provide, inject, onMounted } from 'vue'

// 创建认证上下文的key
const authKey = Symbol('auth')

/**
 * 提供认证功能的组合式函数
 */
export function provideAuth() {
  const currentUser = ref(null)
  const loading = ref(true)

  // 检查token是否过期(24小时)
  const checkTokenExpiration = () => {
    const loginTimestamp = localStorage.getItem('loginTimestamp')
    if (loginTimestamp) {
      const now = Date.now()
      const diff = now - parseInt(loginTimestamp)
      if (diff > 24 * 60 * 60 * 1000) { // 24小时
        // 清理登录状态并返回false表示token已过期
        logout()
        return false
      }
    }
    return true
  }

  // 初始化时检查本地存储的用户信息
  onMounted(() => {
    const savedUser = localStorage.getItem('currentUser')
    if (savedUser) {
      // 只有在token未过期的情况下才恢复用户信息
      if (checkTokenExpiration()) {
        currentUser.value = JSON.parse(savedUser)
      }
    }
    loading.value = false
  })

  // 登录函数
  const login = (userData) => {
    currentUser.value = userData
    localStorage.setItem('currentUser', JSON.stringify(userData))
    localStorage.setItem('loginTimestamp', Date.now().toString())
    return true
  }

  // 登出函数
  const logout = () => {
    currentUser.value = null
    localStorage.removeItem('currentUser')
    localStorage.removeItem('loginTimestamp')
  }

  // 提供认证上下文
  provide(authKey, {
    currentUser,
    loading,
    login,
    logout
  })

  return {
    currentUser,
    loading,
    login,
    logout
  }
}

/**
 * 使用认证功能的组合式函数
 * @returns {Object} 认证上下文值
 */
export function useAuth() {
  const auth = inject(authKey)
  if (!auth) {
    throw new Error('useAuth 必须在 provideAuth 的范围内使用')
  }
  return auth
}