I am using sidebase nuxt auth for my application. I am trying to connect to my database via axios. This code works, i get no error from database but not through sidebase auth. The result returns true, but at the same time I am thrown to a page with an authorization error. And in index.vue i got status from useSession() = not authorized. Can you help me?
this is file index.vue where is form define
<template>
<section >
{{status}}
<div >
<div >
<div >
<SectionTitle
title="Партнерам"
subtitle="Приглашаем агентов к сотрудничеству по продаже автобусных билетов"
description="Описание о том, что это и как это работает"
/>
<!-- <img v-if="!isMobile()" alt="Агенты" src="/img/agents/agents.svg"> -->
</div>
<div >
<div >
<div >
<h3 >
Вход для агентов
</h3>
<form @submit.prevent="signIn('credentials', { username: userStore.username, password: userStore.password })">
<!-- TODO добавить is-ok-bordered или is-error-bordered для валидации-->
<div >
<label for="login" >Эл. почта</label>
<div >
<input v-model="userStore.username" id="mail" type="text" name="mail" placeholder="Введите email">
<div >
<IconsMail color="#B5BDDB" />
</div>
<div >
<IconsMail color="#fff" />
</div>
</div>
<div >
Неверная почта
</div>
</div>
<div >
<label for="passwordInputForm" >Пароль</label>
<div >
<input v-model="userStore.password" id="passwordInputForm" type="password" name="password" placeholder="Введите пароль">
<div >
<IconsPassword color="#B5BDDB" />
</div>
<div >
<IconsPassword color="#fff" />
</div>
</div>
<div >
Неверный пароль
</div>
</div>
<div >
<button : type="submit" >
Войти
</button>
</div>
</form>
<ForgotPasswordLink />
</div>
</div>
</div>
</div>
</div>
</section>
<ForgotPasswordModal />
</template>
<script setup>
import {useUserStore} from "~/stores/userStore";
const userStore = useUserStore()
const { status, data, signIn, signOut } = useSession()
</script>
<script>
export default {
name: "index",
}
</script>
<style scoped>
</style>
and this is auth file, when is logic need to be done. My path is server/api/auth/[...].ts
// file: ~/server/api/auth/[...].ts
import { NuxtAuthHandler } from '#auth'
import CredentialsProvider from "next-auth/providers/credentials";
import axios from "axios";
export default NuxtAuthHandler({
secret: 'your-secret-here',
session: {
strategy: 'jwt'
},
jwt: {
// The maximum age of the NextAuth.js issued JWT in seconds.
// Defaults to `session.maxAge`.
maxAge: 60 * 60 * 24 * 30,
},
providers: [
// @ts-expect-error You need to use .default here for it to work during SSR. May be fixed via Vite at some point
CredentialsProvider.default({
// The name to display on the sign in form (e.g. 'Sign in with...')
name: 'Credentials',
// The credentials is used to generate a suitable form on the sign in page.
// You can specify whatever fields you are expecting to be submitted.
// e.g. domain, username, password, 2FA token, etc.
// You can pass any HTML attribute to the <input> tag through the object.
credentials: {
username: { label: 'Username', type: 'text'},
password: { label: 'Password', type: 'password'}
},
async authorize (credentials: any) {
try {
// You need to provide your own logic here that takes the credentials
// submitted and returns either a object representing a user or value
// that is false/null if the credentials are invalid.
const usernameForm = credentials?.username
const passwordForm = credentials?.password
const config = {
url: 'https://api3.evrotrans.net/auth/login',
credentials: 'include',
method: 'post',
headers: {
"Content-type": "application/json; charset=UTF-8"
},
data: '{\"login\":\"' usernameForm '\",\"password\":\"' passwordForm '\"}',
}
await axios.request(config).then((response) => {
const user = {username: usernameForm, password: passwordForm, token: response.data.token}
console.log(response.data.message)
if (response.data.error == 0) {
// Any object returned will be saved in `user` property of the JWT
console.log('авторизован')
return true
}
if (response.data.password == 'Incorrect login or password.') {
console.error('неправильный логин или пароль')
return null
}
})
}
catch (e) {
console.log(e)
return e
}
}
})
],
})
CodePudding user response:
The problem was in axios.
My solution for this:
let response = await axios.post('https://api3.evrotrans.net/auth/login', {
credentials: 'include',
headers: {
"Content-type": "application/json; charset=UTF-8"
},
login: usernameForm,
password: passwordForm
})
if (response.data.error == 0) {
response.data.username = usernameForm
const user = response.data
console.log(user)
return user
}