-1

after i log in and check the session on the same page I do get the session an the user object on the console

Object { user: {…}, expires: "2022-10-11T01:12:26.311Z" }
​
expires: "2022-10-11T01:12:26.311Z"
​
user: Object { name: "admin@admin.com", email: "admin@admin.com", id: 1, … }
​
<prototype>: Object { … }
 authenticated
but if I redirect to another page I get null unauthenticated on the other page console using the useSession() hook

I'm using apollo to get the credentials from a database, my [...nextauth] file is like so:

import NextAuth from "next-auth"
import { ApolloClient, InMemoryCache } from "@apollo/client";
import CredentialsProvider from "next-auth/providers/credentials";
import { GET_ADMIN_LOGIN } from "../../../components/fam.querys";

export default NextAuth({

    providers: [
        CredentialsProvider({
            session: {
                strategy: 'jwt',
                maxAge: 30 * 24 * 60 * 60, //30 days
                updateAge: 24 * 60 * 60, // 24 hours
            },
            // The name to display on the sign in form (e.g. "Sign in with...")
            name: "Credentials",
            // e.g. domain, username, password, 2FA token, etc.
            credentials: {
                email: { label: "email", type: "email", placeholder: "correo" },
                password: { label: "Password", type: "password", placeholder: 'clave' }
            },
            async authorize(credentials, req) {
                // Add logic here to look up the user from the credentials supplied

                const client = new ApolloClient({
                    uri: "my uri",
                    cache: new InMemoryCache(),
                    headers: {
                        'content-type': 'application/json',
                        'x-hasura-admin-secret': '******'
                    }
                })

                //buscar en la base de datos si existe el usuario

                try {
                    await client.resetStore();
                    const { data } = await client.query({
                        query: GET_ADMIN_LOGIN,
                        variables: {
                            _eq1: credentials.email,
                            _eq: credentials.password
                        }
                    });

                    const adminPass = data?.control_admin[0]?.clave
                    const adminId = data?.control_admin[0]?.id
                    const adminCorr = data?.control_admin[0]?.correoadmin
                    const adminName = data?.control_admin[0]?.correoadmin
                    const userName = data?.control_usuarios[0]?.user
                    const userPassword = data?.control_usuarios[0]?.clave_user
                    const userId = data?.control_usuarios[0]?.iduser

                    if (credentials.email !== adminCorr || credentials.password !== adminPass) {
                        if (credentials.email !== userName || credentials.password !== userPassword) {
                            return null;
                        }
                        // si todo esta bien
                        return { id: userId, name: userName, email: userName, tipo: 'user' };
                    }
                    // si todo esta bien
                    return { id: adminId, name: adminName, email: adminCorr, tipo: 'admin' };
                    
                } catch (error) {
                    console.log(error)
                }
            }
        })
    ],

    callbacks: {
        session: async ({ session, token }) => {
            if (session?.user) {
                session.user.id = token.uid;
                session.user.tipo = token.tipo;
            }
            console.log('sesion: ', session)

            return session;
        },
        jwt: async ({ user, token }) => {
            if (user) {
                token.uid = user.id;
                token.tipo = user.tipo;
            }
            console.log('token: ', token)
            console.log('user: ', user)
            return token;
        },
    },
    pages: {
        signIn: '/',
    },
});

and I'm calling the sessionProvider like this on my _app file:

import { GetServerSidePropsContext } from 'next';
import { useState } from 'react';
import { AppProps } from 'next/app';
import { getCookie, setCookie } from 'cookies-next';
import Head from 'next/head';
import { MantineProvider, ColorScheme, ColorSchemeProvider } from '@mantine/core';
import { NotificationsProvider } from '@mantine/notifications';
import { SessionProvider } from 'next-auth/react';
import { ApolloProvider } from '@apollo/client';
import client from '../apollo-client';

export default function App(props: AppProps & { colorScheme: ColorScheme }) {
  const { Component, session, ...pageProps } = props;
  const [colorScheme, setColorScheme] = useState<ColorScheme>(props.colorScheme);

  const toggleColorScheme = (value?: ColorScheme) => {
    const nextColorScheme = value || (colorScheme === 'dark' ? 'light' : 'dark');
    setColorScheme(nextColorScheme);
    setCookie('mantine-color-scheme', nextColorScheme, { maxAge: 60 * 60 * 24 * 30 });
  };

  return (
    <>
      <Head>
        <title>Family 5 Dashboard</title>
        <meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width" />
        <link rel="shortcut icon" href="/icono.png" />
      </Head>

      <SessionProvider session={session}>
        <ColorSchemeProvider colorScheme={colorScheme} toggleColorScheme={toggleColorScheme}>
          <MantineProvider theme={{ colorScheme }} withGlobalStyles withNormalizeCSS>
            <NotificationsProvider>
              <ApolloProvider client={client}>
                <Component {...pageProps} session={session} />
              </ApolloProvider>
            </NotificationsProvider>
          </MantineProvider>
        </ColorSchemeProvider>
      </SessionProvider>
    </>
  );
}

App.getInitialProps = ({ ctx }: { ctx: GetServerSidePropsContext }) => ({
  colorScheme: getCookie('mantine-color-scheme', ctx) || 'dark',
});
----edit---- after returning Promises still doesn't maintain the session on refresh

[...nextauth]

import NextAuth from "next-auth"
import {
  ApolloClient,
  InMemoryCache
} from "@apollo/client";
import CredentialsProvider from "next-auth/providers/credentials";
import {
  GET_ADMIN_LOGIN
} from "../../../components/fam.querys";

export default NextAuth({

  providers: [
    CredentialsProvider({
      session: {
        strategy: 'jwt',
        maxAge: 30 * 24 * 60 * 60, //30 days
        updateAge: 24 * 60 * 60, // 24 hours
      },
      // The name to display on the sign in form (e.g. "Sign in with...")
      name: "Credentials",
      // e.g. domain, username, password, 2FA token, etc.
      credentials: {
        email: {
          label: "email",
          type: "email",
          placeholder: "correo"
        },
        password: {
          label: "Password",
          type: "password",
          placeholder: 'clave'
        }
      },
      async authorize(credentials, req) {
        // Add logic here to look up the user from the credentials supplied

        const client = new ApolloClient({
          uri: "my uri",
          cache: new InMemoryCache(),
          headers: {
            'content-type': 'application/json',
            'x-hasura-admin-secret': '******'
          }
        })

        //buscar en la base de datos si existe el usuario

        try {
          await client.resetStore();
          const {
            data
          } = await client.query({
            query: GET_ADMIN_LOGIN,
            variables: {
              _eq1: credentials.email,
              _eq: credentials.password
            }
          });

          const adminPass = data ? .control_admin[0] ? .clave
          const adminId = data ? .control_admin[0] ? .id
          const adminCorr = data ? .control_admin[0] ? .correoadmin
          const adminName = data ? .control_admin[0] ? .correoadmin
          const userName = data ? .control_usuarios[0] ? .user
          const userPassword = data ? .control_usuarios[0] ? .clave_user
          const userId = data ? .control_usuarios[0] ? .iduser

          if (credentials.email !== adminCorr || credentials.password !== adminPass) {
            if (credentials.email !== userName || credentials.password !== userPassword) {
              return null;
            }
            // si todo esta bien
            return Promise.resolve({
              id: userId,
              name: userName,
              email: userName,
              tipo: 'user'
            });
          }
          // si todo esta bien
          return Promise.resolve({
            id: adminId,
            name: adminName,
            email: adminCorr,
            tipo: 'admin'
          });
        } catch (error) {
          console.log(error)
        }

        /* if (credentials.email !== 'john@gmail.com' || credentials.password !== '1234') {
            return null;
        }
        // si todo esta bien
        return { id: '1234', name: 'john', email: 'john@gmail.com', tipo: 'extra' }; */
      }
    })
  ],

  callbacks: {
    session: async({
      session,
      token
    }) => {
      if (session ? .user) {
        session.user.id = token.uid;
        session.user.tipo = token.tipo;
      }
      console.log('sesion: ', session)

      return Promise.resolve(session);
    },
    jwt: async({
      user,
      token
    }) => {
      if (user) {
        token.uid = user.id;
        token.tipo = user.tipo;
      }
      console.log('token: ', token)
      console.log('user: ', user)
      return Promise.resolve(token)
    },
  },
  pages: {
    signIn: '/',
  },
});
alfonzo fong
  • 53
  • 2
  • 7

1 Answers1

0

You have to return Promises

in jwt

  return Promise.resolve(token);

in session

  return Promise.resolve(session);

in authorize:

  return Promise.resolve({ id: adminId, name: adminName, email: adminCorr, tipo: 'admin' });
Yilmaz
  • 35,338
  • 10
  • 157
  • 202
  • no friend, it still doesnt retain the session, if I do a router.push() it does but if I go to another tab it returns null – alfonzo fong Sep 11 '22 at 16:37
  • as I got tired of this thing I changed it to _app.jsx and now it keeps the session if I change tabs or refresh the page, sorry for wasting your time on the other post. – alfonzo fong Sep 11 '22 at 17:54