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

home2 게시판 Next.js 게시판 로그인 기능 구현 중에 실패한 사유를 전달하고 싶습니다.

로그인 기능 구현 중에 실패한 사유를 전달하고 싶습니다.

2 글 보임 - 1 에서 2 까지 (총 2 중에서)
  • 글쓴이
  • #128616

    이돈형
    참가자
    signIn("credentials", {}) 함수 .then의 콜백함수로 확인할 수 있는 건 ok가 true인지 false인지 밖에 알 수가 없는데....
    
    [...nextauth].js에서 실패한 사유 중 계정이 잠겼을 때 if (myAccount[0].LOCK_YN == 'Y')  잠겼다고는 알려줘야할 것 같은데
    
    사용자 client에서 alert창에 그 걸 알려줄 방법을 못찾겠습니다 ㅜ
    
    
    
    [...nextauth].js
    
    import { sendReq } from "@/util/dbcMaria";
    import bcrypt from "bcrypt";
    import NextAuth from "next-auth";
    import CredentialsProvider from "next-auth/providers/credentials";
    export const authOptions = {
    providers: [
    CredentialsProvider({
    name: "credentials",
    credentials: {
    USER_ID: { label: "USER ID", type: "text" },
    PWD: { label: "PASSWORD", type: "text" },
    LANG: { label: "LANG", type: "text" },
    ORG: { label: "ORG", type: "text" }
     },
    async authorize(credentials) {
    let prm = {
    pInput: [
     {
    name: 'P_USER_ACCOUNT',
    value: `${credentials.USER_ID}`
     },
     ],
    pOutput: [
     {
    name: 'P_RESULT'
     },
     {
    name: 'P_VALUE'
     }
     ],
    procedure: 'account_sp_find_my_auth'
     }
    let rs = await sendReq(prm)
    if (!rs.errno) {
    if (rs.output.P_RESULT == "SUCCESS") {
    let myAccount = rs.recordsets[0]
    let myMenu = []
    rs.recordsets[1].map((v, i) => {
    myMenu.push(v.MENU_CODE)
     })
    if (myAccount.length == 1) {
    if (bcrypt.compareSync(credentials.PWD, myAccount[0].PWD)) {
    if (myAccount[0].LOCK_YN == 'Y') {
    return null;
     } else if (myAccount[0].USE_YN == 'Y') {
    return {
    USER_ACCOUNT: myAccount[0].USER_ACCOUNT,
    AUTH_CODE : myAccount[0].AUTH_CODE,
    MY_ORG : credentials.ORG,
    MY_LANG : credentials.LANG,
    myMenu: myMenu
     };
     }
     } else {
    return null;
     }
     } else {
    return null;
     }
     } else if (rs.output.P_RESULT == "ERROR") {
    return null;
     }
     } else {
    return null;
     }
     }
     })
     ],
    session: {
    strategy: 'jwt',
    maxAge: 600 // [second]
     },
    callbacks: {
    jwt: async ({ token, user }) => {
    if (user) {
    token.user = {};
    token.user.USER_ACCOUNT = user.USER_ACCOUNT
    token.user.AUTH_CODE = user.AUTH_CODE
    token.user.MY_ORG = user.MY_ORG
    token.user.MY_LANG = user.MY_LANG
    token.user.MY_MENU = user.myMenu
    token.user.EXPIRY_ALERT = 30 // [second]
     }
    return token;
     },
    session: async ({ session, token }) => {
    session.user = token.user;
    return session;
     },
     },
    debug: true, // 디버그 모드 활성화
    cookies: {
    sessionToken: {
    name: `next-auth-${process.env.NEXTAUTH_COOKIE_IDENTIFIER}.session-token`,
    options: {
    httpOnly: true,
    sameSite: 'lax',
    path: '/',
    secure: false, //https 이어야 true로 설정 가능
     },
     },
    callbackUrl: {
    name: `next-auth-${process.env.NEXTAUTH_COOKIE_IDENTIFIER}.callback-url`,
    options: {
    httpOnly: true,
    sameSite: 'lax',
    path: '/',
    secure: false, //https 이어야 true로 설정 가능
     },
     },
    csrfToken: {
    name: `next-auth-${process.env.NEXTAUTH_COOKIE_IDENTIFIER}.csrf-token`,
    options: {
    httpOnly: true,
    sameSite: 'lax',
    path: '/',
    secure: false, //https 이어야 true로 설정 가능
     },
     }
     },
    secret: process.env.NEXTAUTH_SECRET,
    pages: {
    signIn: '/',
     },
    };
    export default NextAuth(authOptions); 
    
    
    
    
    
    page.js (로그인화면)
    'use client'
    import PassKeyIcon from "@/public/PassKeyIcon"
    import { signIn } from 'next-auth/react'
    import { useState } from 'react'
    import { setCookie, getCookie } from 'cookies-next';
    export default function LoginPage() {
    const [userId, setUserId] = useState('')
    const [password, setPassword] = useState('')
    const [organization, setOrganization] = useState('')
    const [language, setLanguage] = useState('')
    const handleSignIn = async () => {
     
    let userLang= language
    let userLangCookie = getCookie('site-lang')
    if(!userLang && !userLangCookie){
    userLang = 'ENG'
    setCookie('site-lang', 'ENG');
     } else if (!userLang ){
    userLang = getCookie('site-lang')
     } else {
    setCookie('site-lang', userLang);
     }
    await signIn("credentials", {
    USER_ID: userId,
    PWD: password,
    ORG: organization,
    LANG: userLang,
    redirect: false,
     }).then((res)=>{
    if(res.ok) {
    console.log(res)
     } else {
    console.log(res)
     }
     })
     }
    const langList = [
     {
    code: 'KOR',
    label: 'Korea'
     },
     {
    code: 'ENG',
    label: 'English'
     }
     ]
    return (
    <div className="login-page">
    <PassKeyIcon />
    <div>Basic Framework for business web tool</div>
    <form className="login-box" action={handleSignIn}>
    <input
    name="USER_ID"
    type="text"
    placeholder="User ID"
    value={userId}
    onChange={(e) => setUserId(e.target.value)}
    />
    <input
    name="PWD"
    type="password"
    placeholder="Password"
    value={password}
    onChange={(e) => setPassword(e.target.value)}
    />
    <input
    name="ORG"
    type="text"
    placeholder="Organization"
    value={organization}
    onChange={(e) => setOrganization(e.target.value)}
    />
    <select
    id="LANG"
    name="LANG"
    value={language}
    onChange={(e) => setLanguage(e.target.value)}>
    <option value="">-----</option>
    {
    langList.map((v, i) => {
    return <option key={i} value={v.code}>{v.label}</option>
     })
    }
    </select>
    <button className="confirm-button" type="submit">LOGIN</button>
    </form>
    </div>
     )
    }
     
    #128626

    codingapple
    키 마스터
    https://stackoverflow.com/questions/70897330/return-error-information-from-api-when-using-next-auth
    throw new Error() 하면 클라이언트에서 뭔가 보이는거같습니다
2 글 보임 - 1 에서 2 까지 (총 2 중에서)
  • 답변은 로그인 후 가능합니다.

About

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

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

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