#anyone familiar with nextauth ive been

1 messages · Page 1 of 1 (latest)

dim holly
#

Show me your code and tell me what it is your trinyf to do

ember scaffold
#
import NextAuth, { type NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import prisma from "@/lib/prisma";
import { compare } from "bcrypt";
import { sendDiscordMessage } from "utils/logger";

export const authOptions: NextAuthOptions = {
  providers: [
    CredentialsProvider({
      credentials: {
        username: { label: "Username", type: "text" },
        password: { label: "Password", type: "password" },
      },
      // @ts-ignore
      async authorize(credentials) {
        const { username, password } = credentials ?? {};
        if (!username || !password) {
          console.log(1);
          sendDiscordMessage(
            "**" + username + "** failed to login on the panel",
            false
          );
          throw new Error("Missing username or password");
        }
        const user = await prisma.user.findUnique({
          where: {
            username,
          },
        });
        // if user doesn't exist or password doesn't match
        if (!user || !(await compare(password, user.password))) {
          console.log(2);
          sendDiscordMessage(
            "**" + username + "** failed to login on the panel",
            false
          );
          throw new Error("Invalid username or password");
        }

        sendDiscordMessage("**" + username + "** logged in on the panel", true);
        //console.log(user.role); //first time
        return user;
        console.log(3);
      },
    }),
  ],

  callbacks: {
    async session({ session, token, user }) {
      console.log("session working");

      if(session && session.user){
        session.user.role = token.role;
      }
      return session;
    },
    async jwt(params) {
      console.log("jwt working");
     //console.log(params);
      params.token.role = params.user.role;
      console.log(params.token.role);
      return params.token;
    },
  },
};

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };

#

im trying to save things like the users role in session

#

it logs jwt working but not session working

dim holly
#

Heres mine @ember scaffold

export default NextAuth({
  // Custom pages
  pages: {
    signIn: '/auth/signin',
  },

  // Configure one or more authentication providers
  providers: [
    // Discord provider
    DiscordProvider({
      clientId: process.env.DISCORD_CLIENT_ID,
      clientSecret: process.env.DISCORD_SECRET,
      // authorization: { params: { scope: 'identify guilds' } }, // Scopes for later
    }),

    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_SECRET,
    }),

    PatreonProvider({
      clientId: process.env.PATREON_ID,
      clientSecret: process.env.PATREON_SECRET,
      authorization: { params: { scope: 'identity identity[email] identity.memberships' } },
    }),

  ],

  callbacks: {
    async jwt({ token, account }) {

      if (account) { // Create/Update Account

        // Connect to database
        const { db } = await connectToDatabase();

        let query = { email: token.email };
        let user = await db.collection('users').findOne(query);

        if (user) return token = {
          ...token, 
          id: user.id,
          email: user.email,
          picture: user.avatar,
          name: user.name,
          bio: user.settings.profile.bio,
          links: user.settings.profile.links,
          quota: user.quota,
          elevation: user.elevation
        }

        user = new dataModel(id(), token.name, token.email).user;
        user.avatar = token.picture;

        query = { _id: user.id };

        const update = { $set: user };
        const options = { upsert: true };
  
        await db.collection('users').updateOne(query, update, options);

        return token = {
          ...token, 
          id: user.id,
          email: user.email,
          picture: user.avatar,
          name: user.name,
          bio: user.settings.profile.bio,
          links: user.settings.profile.links,
          quota: user.quota,
          elevation: user.elevation
        }
      
      } else {
        // Connect to database
        const { db } = await connectToDatabase();
        
        let query = { email: token.email };
        let user = await db.collection('users').findOne(query);

        if (user) return token = {
          ...token, 
          id: user.id,
          email: user.email,
          picture: user.avatar,                                    
          name: user.name,
          banner: user?.banner,
          bio: user.settings.profile.bio,
          links: user.settings.profile.links,
          quota: user.quota,
          elevation: user.elevation
        }
        return token;
      }

    },
    
    async session({ session, token, user }) {
      session.user.id = token.id;
      session.user.image = token.picture;
      session.user.name = token.name;
      session.user.banner = token.banner;
      session.user.bio = token.bio;
      session.user.links = token.links;
      session.user.quota = token.quota;
      session.user.elevation = token.elevation;

      return session;
    }
  },

  // Secret for encryption
  secret: process.env.SECRET,
})```
ember scaffold
#

hmm

dim holly
#

Follow how I worked mine

#

I pass account elevation from my db

#

To tell if someones an admin

#

same for their user profile and etc...

#

ensure to return the object tho

ember scaffold
#

my jwt callback is working

#

i logged the params and role and stuff and it logs the user

dim holly
#

so

#

think of it this way

#

You need to do your JWT first, then your session after

ember scaffold
#

yea

dim holly
#

Because your token is made then passed to the session

ember scaffold
#

yeah

dim holly
#

but jwt will also appear every update.

ember scaffold
#

im not sure what im domig wrogn tho

#

it doesnt log anything not even 123 in the sessiom callback

dim holly
#

I'm reading ur stuff a minute

#

@ember scaffold

#

This is where you done goofed

#

The session object will always be present if its successful...

#

The JWT token that you made in JWT function is inserted into your session object.

#

Sometimes the session user object is empty, so you need to define them.

#

So this is why your session isnt carry/sending over.

ember scaffold
#

im back

dim holly
#

kk

ember scaffold
#

if i dont put that if

#

i get this

#

also

#

the log i put before that

#

shouldnt this be logged at least?

dim holly
ember scaffold
dim holly
#

at the top level

#
if (!session) return console.log(`No session provided`)```
ember scaffold
#

nothing is being logged at all no matter what i put in it

#

session callback not being used at all or something?

dim holly
#

Give me 15 mins

#

I'm in a work meeting right now.

#

Can you get on a discord call, and I help you debug?

ember scaffold
#

np you dont have to help only if you want to

dim holly
#

I'll help, it just in the middle of a meeting rn

ember scaffold
ember scaffold
dim holly
#

You still there @ember scaffold

ember scaffold
#

yep

dim holly
#

Pushed a change, check it out

ember scaffold
#

thanks i look

#

i added console.logs to test

#

only thing being logged is the jwt

#

idk why

dim holly
ember scaffold
#

yea

#

i just logged out and logged back in to see if the log

dim holly
#

Welp

#

@ember scaffold

ember scaffold
#

session: {
// Set to jwt in order to CredentialsProvider works properly
strategy: 'jwt'
}

dim holly
#

You need to add this

ember scaffold
#

i had it

dim holly
#

you dont have it @ember scaffold

ember scaffold
#

still only jwt

dim holly
#

you need to reboot the server

#

if you make changes like that

#

i pushed the JWT

ember scaffold
#

i stopped it and

dim holly
#

to it

ember scaffold
#

did npm run dev

#

still only jwt test

#

logs

dim holly
#

pull my changes

ember scaffold
#

done

#

still only jwt test 😭

dim holly
#

Heck

ember scaffold
#

can you try opening it in a codespace?

#

maybe i did something wrong with exentding the session or something idk

#

in nextauth.d.ts

dim holly
#

your extending the session?

ember scaffold
#

im probably using the wrong terminology

dim holly
#

Any luck @ember scaffold

ember scaffold
#

callback was never used

ember scaffold
dim holly
ember scaffold
#

i only used this

#

const session = await getServerSession();

#

const session = await getServerSession(authOptions);

dim holly
#

o

ember scaffold
#

i had to add that to actually use it, otherwise the session callback was never used

#
  callbacks: {
    async signIn({ user, account }) {
      if (account) account.access_token = user.role;
      return true;
    },
    async jwt({ token, account }) {
      if (account) token.accessToken = account.access_token;

      return token;
    },
    async session({ session, token, user }) {
      //@ts-ignore
      session.user.role = token.accessToken;
      return session;
    },
  },
dim holly
#

you don't happen to know how to type non-typescript modules do ya

ember scaffold
#

not rlly

dim holly
#

heck

ember scaffold
#

but i also had to add signIn callback, to pass the user from the authorize