• 로그인
  • 장바구니에 상품이 없습니다.

home2 게시판 Next.js 게시판 회원가입 기능 만드는 중인데 잘 안됩니다

회원가입 기능 만드는 중인데 잘 안됩니다

10 글 보임 - 1 에서 10 까지 (총 13 중에서)
  • 글쓴이
  • #130430

    유성찬
    참가자
    이번에 타입스크립트 강의듣고 응용해서 만들어보려는데 잘 안되서 여쭤봅니다
    
    import NextAuth, { NextAuthOptions } from 'next-auth';
    import CredentialsProvider from 'next-auth/providers/credentials';
    import { connectDB } from '@/util/database';
    import bcrypt from 'bcrypt';
    import { DefaultSession } from "next-auth";
    declare module 'next-auth' {
      interface Session {
        user: {
          id: string;
          email: string; 
          role: string; 
          userID?: string;
        } & DefaultSession['user'];
      }
      interface User {
        id: string;
        role: string;
        userID?: string;
      }
    }
    export const authOptions: NextAuthOptions = {
      providers: [
        CredentialsProvider({
          name: "credentials",
          credentials: {
            id: { label: "id", type: "text" },
            password: { label: "password", type: "password" },
          },
          async authorize(credentials) {
            if (!credentials?.id || !credentials?.password) {
              return null;
            }
            
            const db = (await connectDB).db('User');
            const user = await db.collection('information').findOne({ userID: credentials.id });
            
            if (!user) {
              console.log('해당 아이디가 존재하지 않습니다');
              return null;
            }
          
            const salt = process.env.SALT;
            const salt2 = process.env.SALTTWO;
            const realpw = salt + credentials.password + salt2;
          
            const pwcheck = await bcrypt.compare(realpw, user.password);
            
            if (!pwcheck) {
              console.log('비번틀림');
              return null;
            }
          
             return { id: user.userID, email: user.email, role: user.role }; 
          }
        })
      ],
      session:{
        strategy:'jwt',
        maxAge :30 *24 *60*60,
      },
      callbacks:{
        jwt :async ({ token,user })=>{
          if(user){
            token.user={
              userID:user.id,
              email:user.email ?? '',
              role:user.role ?? ''
            };
          }
          return token; 
        },
        
        session :async ({session ,token})=>{
          if(token.user){
            session.user={
              ...session.user,
              userID:(token as any).user?.userID,
              email:(token as any).user?.email,
              role:(token as any).user?.role,
            };
          }
          return session; 
        }, 
      },
      secret :process.env.NEXTAUTH_SECRET
    };
    export default NextAuth(authOptions);
    이렇게 해서
      const session = await getServerSession(authOptions)
      console.log(session)
    같은 명령어로 페이지에서 출력하면
    {
    user: { name: undefined, email: 'scryu32@gmail.com', image: undefined }
    }
    같은 엉뚱한 대답이 출력됩니다. 전에 구글OAuth로 만들었던 프로젝트에서 저런형식으로 세션이 출력됐었는데 왜 여기서도 똑같이 출력되는지 도저히 이해가 안됩니다 도와주실수 있을까요
    db에 저장된건 userID, email, password, role 저장되있습니다.
     
    #130436

    codingapple
    키 마스터
    jwt, session 함수들 안에서 user, token같은거 잘 나오나 출력해봅시다
    #130466

    유성찬
    참가자
    import NextAuth, { NextAuthOptions } from 'next-auth';
    import CredentialsProvider from 'next-auth/providers/credentials';
    import { connectDB } from '@/util/database';
    import bcrypt from 'bcrypt';
    import { DefaultSession } from "next-auth";
    declare module 'next-auth' {
      interface Session {
        user: {
          id: string;
          email: string; 
          role: string; 
          userID?: string;
        } & DefaultSession['user'];
      }
      interface User {
        id: string;
        role: string;
        userID?: string;
      }
    }
    export const authOptions: NextAuthOptions = {
      providers: [
        CredentialsProvider({
          name: "credentials",
          credentials: {
            id: { label: "id", type: "text" },
            password: { label: "password", type: "password" },
          },
          async authorize(credentials) {
            if (!credentials?.id || !credentials?.password) {
              return null;
            }
            
            const db = (await connectDB).db('User');
            const user = await db.collection('information').findOne({ userID: credentials.id });
            
            if (!user) {
              console.log('해당 아이디가 존재하지 않습니다');
              return null;
            }
          
            const salt = process.env.SALT;
            const salt2 = process.env.SALTTWO;
            const realpw = salt + credentials.password + salt2;
          
            const pwcheck = await bcrypt.compare(realpw, user.password);
            
            if (!pwcheck) {
              console.log('비번틀림');
              return null;
            }
          
             return { id: user.userID, email: user.email, role: user.role }; 
          }
        })
      ],
      session:{
        strategy:'jwt',
        maxAge :30 *24 *60*60,
      },
      callbacks:{
        jwt :async ({ token,user })=>{
          console.log(token)
          if(user){
            console.log(token)
            token.user={
              userID:user.id,
              email:user.email ?? '',
              role:user.role ?? ''
            };
            console.log(token)
          }
          console.log(token)
          return token; 
        },
        
        session :async ({session ,token})=>{
          if(token.user){
            console.log(token)
            session.user={
              ...session.user,
              userID:(token as any).user?.userID,
              email:(token as any).user?.email,
              role:(token as any).user?.role,
            };
            console.log(token)
          }
          console.log(token)
          return session; 
        }, 
      },
      secret :process.env.NEXTAUTH_SECRET
    };
    export default NextAuth(authOptions);
    함수들 사이에 console.log 여러개 집어넣어도 출력이안됩니다 어떻게해야 확인할수있을까요?
    #130468

    유성찬
    참가자
    이 프로젝트 생성하고 단 한번도 세션에 name이랑 image라는 옵션을 집어넣은적이없는데 세션에 왜 저런 정보가 담기는지 도저히 이해가안됩니다..
    비슷한 사례 찾기도 너무 막막한데 어쩌면좋을까요
    #130475

    codingapple
    키 마스터
    로그인하고 컴포넌트안에서 getServerSession 코드 동작시켜도 출력안됩니까
    async authorize(credentials) { 안에도 console.log 써서 변수들 잘 있나 확인해봅시다
    #130496

    유성찬
    참가자
    선생님 말대로 async authorize(credentials)  안에 console.log 쓰니까 데이터베이스에 저장된 정보는 잘 나옵니다. 근데 밑에 jwt에서 주는 콘솔에서 자꾸 넣은적도 없는것들이 나옵니다
    {
      _id: new ObjectId('66deb78a814f6036da42f05c'),
      userID: 'scryu32',
      email: 'scryu32@gmail.com',
      password: '',
      role: 'user'
    }
    
    
    {
    name: undefined,
    email: 'scryu32@gmail.com',
    picture: undefined,
    sub: 'scryu32'
    }
    id, email, role을 넣었는데 왜 이런게 나올까요?
     
    #130498

    유성찬
    참가자
    { id: 'scryu32', email: 'scryu32@gmail.com', role: 'User' } 이거 출력하는것까진 성공했습니다. jwt에 토큰 비우고시작하면 되는거같네요.
    근데 서버에서 authOptions 가져와서 출력하면 { user: { name: undefined, email: undefined, image: undefined } } 요런식으로 뜹니다
    #130507

    codingapple
    키 마스터
    원래 jwt에 picture같은 항목이 기본적으로 들어갑니다 
    서버컴포넌트 안에서 getServerSession 써본거 맞나 authOptions import해온 경로 맞나 
    로그인후에 쿠키도 생겼나 확인해봅시다 
    안되면 useSession() 같은걸로 출력해봅시다
    #130512

    유성찬
    참가자
    callbacks:{
        jwt :async ({ token,user })=>{
          if(user){
            token = {};
            token.user={
              userID:user.id,
              email:user.email ?? '',
              role:user.role ?? ''
            };
            console.log(token)
          }
          return token; 
        },
        
        session :async ({session ,token})=>{
          if(token.user){
            session.user={
              ...session.user,
              userID: (token.user as any)?.userID,
              email: (token.user as any)?.email,
              role: (token.user as any)?.role,
            };
          }
          return session; 
        },
      },
    여기서 console.log 한 부분은 제가 원하는대로 데이터 잘 나오고 session 부분에는 console.log 출력 자체가 안되는것같습니다
    useSession도 해봤는데 
    const session = useSession()
    console.log(session)
    { data: undefined, status: 'loading', update: [Function: update] }
    이런식으로 데이터가 안들어있다는것같습니다
    로그인 하면 쿠키도 생기는데 무슨오류인지 모르겠습니다
    몇일째 이문제만 잡고있는데 어디서 잘못된건지 도저히 감이 안잡힙니다..
     
     
    
    
     
    #130522

    codingapple
    키 마스터
    useSession쓰기전에 <SessionProvider>로 상위컴포넌트 감쌌나 확인해봅시다 
    https://github.com/nextauthjs/next-auth/issues/7760#issuecomment-1770475384
    
    package.json파일에 next-auth 버전이 어떻게됩니까
10 글 보임 - 1 에서 10 까지 (총 13 중에서)
  • 답변은 로그인 후 가능합니다.

About

현재 월 700명 신규수강중입니다.

  (09:00~20:00) 빠른 상담은 카톡 플러스친구 코딩애플 (링크)
  admin@codingapple.com
  이용약관
ⓒ Codingapple, 강의 예제, 영상 복제 금지
top

© Codingapple, All rights reserved. 슈퍼로켓 에듀케이션 / 서울특별시 강동구 고덕로 19길 30 / 사업자등록번호 : 212-26-14752 온라인 교육학원업 / 통신판매업신고번호 : 제 2017-서울강동-0002 호 / 개인정보관리자 : 박종흠