next-auth 使用Credentials登录,并格式化session

in nodejs with 0 comment

1、配置
/api/auth/[...nextauth].js:

  
import NextAuth  from 'next-auth'
import CredentialsProvider from 'next-auth/providers/credentials'
import nookies from 'nookies'

export default NextAuth({
    // Configure one or more authentication providers
    providers: [
        CredentialsProvider({
            // 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.
            credentials: {
              username: { label: "Username", type: "text"},
              password: {  label: "Password", type: "password" }
            },
            async authorize(credentials, req) {
              // e.g. return { id: 1, name: 'J Smith', email: 'jsmith@example.com' }
              const res = await fetch("http://api.airwaybill.cn/auth", {
                method: 'POST',
                body: JSON.stringify(credentials),
                headers: { "Content-Type": "application/json" }
              })
              const user = await res.json()
              user.name = user.customer_name
            //   console.log(user)
              // If no error and we have user data, return it
              if (res.ok && user) {
           
                return user
              }else{ 
                    throw new Error('login fiald!') 
              } 
            },
            
        }),
        // ...add more providers here
    ],
    session: {
        maxAge: 1 * 24 * 60 * 60, // 24 hrs 
        updateAge: 24 * 60 * 60, // 24 hours
    },
    callbacks:{
        jwt: async (token, user) => {
            user && (token.user = user);  //
            return Promise.resolve(token)   // ...here
        },
        session: async (session, user) => {
            session.user = user.user;
            return Promise.resolve(session)
        }
    },
    pages: {
        signIn: '/auth/login',
    }
})

2、Layout.js:

import React from 'react' 
import { useSession } from 'next-auth/client'
import Head from 'next/head'
import Header from './header'
import Footer from './footer' 


export default function Layout ({title, children}) {
    const [ session, loading ] = useSession() 
    if(!session && loading){
        return <div></div>
    }
    if(!session){ 
        return <div>
            <div style={{padding:"400px"}}>禁止访问, <a href="/auth/login">请先登录</a></div>
        </div>
    }
    return (
        <div>
            <Head>
                <title>{title||'首页'}</title>
            </Head>
            <Header/>
            <main>
                {children}
            </main>
            <Footer/>
        </div>
    )
}
Comments are closed.