atinux / nuxt-auth-utils

Add Authentication to Nuxt applications with secured & sealed cookies sessions.
MIT License
962 stars 90 forks source link

GET /api/_auth/session is 200. but loggedIn.value is false #208

Closed dalbodeule closed 1 month ago

dalbodeule commented 1 month ago

server/routes/api/auth/login.post.ts

export default defineEventHandler(async (event) => {
    // login logic is included

    // set session
    await setUserSession(event, {
        username: user.username,
        email: user.email,
        nickname: user.nickname,
        id: user.id
    });

    const response: LoginResponseDTO = {
        id: user.id,
        username: user.username,
        email: user.email,
        nickname: user.nickname
    }

    return response
})

pages/login.vue

const { fetch } = useUserSession()
const router = useRouter()

const username = ref('');
const password = ref('');

const error = ref<string | null>(null);

const login = async () => {
  const requestData = {
    username: username.value,
    password: password.value,
  };

  try {
    await $fetch('/api/auth/login', {
      method: 'POST',
      body: requestData,
      credentials: 'include',
    });

    console.log('Login successful:');
    await fetch() // fetch() is here
    await navigateTo('/') // move to main page
  } catch (err) {
    console.log(err)
    error.value = 'An unexpected error occurred.';
  }
};

But, loggedIn ref is still false. Help me!

(nuxt 3.12.4, @vite-pwa/nuxt used.)

dalbodeule commented 1 month ago

Hmm... is my fault.

if you make manual login, must follow this.

await setUserSession(event, {
        user: {
            username: user.username,
            email: user.email,
            nickname: user.nickname,
            id: user.id
        },
        secure: {

        },
        loggedInAt: new Date(),
    });