Skip to content

Get Current User Information

Interface Information

  • Endpoint: /api/auth/me
  • Method: GET
  • Authentication Required: Yes

Request Parameters

No parameters.

Request Example

bash
curl -X GET http://localhost:3000/api/auth/me \
  -H "Content-Type: application/json" \
  -b "auth_token=your_token_here"

Response Examples

Success Response

json
{
  "success": true,
  "data": {
    "userId": 1,
    "username": "admin",
    "email": "admin@demo.com",
    "nickname": "Demo Administrator",
    "avatar": null,
    "bio": null,
    "role": "admin",
    "status": "active",
    "created_at": "2025-01-01T00:00:00.000Z",
    "updated_at": "2025-01-01T00:00:00.000Z"
  }
}

Unauthenticated

json
{
  "success": false,
  "message": "Not logged in or session expired"
}

User Status Exception

json
{
  "success": false,
  "message": "User status exception"
}

Response Field Descriptions

Field NameTypeDescription
userIdnumberUser ID
usernamestringUsername
emailstringEmail
nicknamestringNickname
avatarstring | nullAvatar URL
biostring | nullBiography
rolestringUser role (admin/user)
statusstringUser status (active/inactive)
created_atstringCreation time (ISO 8601)
updated_atstringUpdate time (ISO 8601)

Frontend Integration Example

javascript
// Get current user information
async function getCurrentUser() {
  const response = await fetch('/api/auth/me', {
    method: 'GET',
    credentials: 'include'
  })
  
  if (!response.ok) {
    // Token expired, redirect to login page
    if (response.status === 401) {
      window.location.href = '/admin/login'
    }
    throw new Error('Failed to get user information')
  }
  
  const result = await response.json()
  
  if (result.success) {
    return result.data
  }
  
  throw new Error(result.message)
}

// Using composable function
const useAuth = () => {
  const user = ref(null)
  const loading = ref(false)
  const error = ref(null)

  const fetchUser = async () => {
    loading.value = true
    error.value = null
    
    try {
      user.value = await getCurrentUser()
    } catch (err) {
      error.value = err.message
    } finally {
      loading.value = false
    }
  }

  return {
    user,
    loading,
    error,
    fetchUser
  }
}

Usage Scenarios

1. Page Permission Check

javascript
// Middleware or route guard
export default defineNuxtRouteMiddleware(async (to, from) => {
  const { user } = await getCurrentUser()
  
  if (!user || user.role !== 'admin') {
    return navigateTo('/admin/login')
  }
})

2. Display User Information

vue
<template>
  <div class="user-info">
    <img :src="user.avatar || '/default-avatar.png'" alt="Avatar" />
    <div class="user-details">
      <p class="name">{{ user.nickname || user.username }}</p>
      <p class="email">{{ user.email }}</p>
      <p class="role">{{ user.role === 'admin' ? 'Administrator' : 'Regular User' }}</p>
    </div>
  </div>
</template>

<script setup>
const { data: user } = await useFetch('/api/auth/me')
</script>

3. Auto Refresh User Information

javascript
// Regularly refresh user information
setInterval(async () => {
  try {
    const user = await getCurrentUser()
    // Update local user information
    updateUserInfo(user)
  } catch (error) {
    console.error('Failed to refresh user information:', error)
  }
}, 5 * 60 * 1000) // Refresh every 5 minutes

Notes

  1. Token Verification: The interface verifies the validity of JWT tokens
  2. User Status Check: User status must be active to retrieve information
  3. Caching Strategy: Frontend can cache user information but should refresh regularly
  4. Error Handling: Automatically redirect to login page when token expires