@2ltech/nextjs-app-passport
v1.1.16
Published
[](https://sonarcloud.io/summary/new_code?id=2LTech_nextjs-app-passport)
Readme
nextjs-app-passport
NextJS authentication using local passport
Demo
You can see an example in nextjs-app-passport-demo
Environment variables
NEXTJS_APP_PASSPORT_TOKEN (mandatory)
Used to encrypt the cookie, minimum 32 characters length.
NEXTJS_APP_PASSPORT_UNSECURE (optional)
If defined, allow usage of cookie over HTTP connexion.
setLocalStrategy
You have to define your own findUser and validatePassword function to set passport strategy.
Type:
type setLocaLStrategy = async (
findUser: FindUser,
validatePassword: ValidatePassword
) => voidUsage:
setLocaLStrategy(findUser, validatePassword)Typically used in the API login route to initialize passport.
findUser
Type:
type FindUser = (body: any) => Promise<{ user?: any }>This function should find an user from request body content (see APILoginRoute) and return it, or nothing if no user is found.
validatePassord
Type:
type ValidatePassword = (user: any, body: any) => booleanThis function should validate the password using the user data (for example hash, salt, ...).
APILoginRoute
Type:
type APILoginRoute = async (req: NextRequest) => ResponseUsage in app/api/[loginRouteName]/route.[js|ts]:
export const POST = APILoginRoute
APILoginRouteget the body content directly from your fetch request in the client side.
APILogoutRoute
Type:
type APILogoutRoute = async () => ResponseUsage in app/api/[logoutRouteName]/route.[js|ts]:
export const GET = APILogoutRouteAPIRefreshSessionRoute
Type:
type APIRefreshSessionRoute = async () => ResponseUsage in app/api/[refreshSessionRouteName]/route.[js|ts]:
export const GET = APIRefreshSessionRoutegetSession
Type:
type getSession = async () => SessionUsage in app/api/[getSessionRouteName]/route.[js|ts]:
export const GET = async () => {
try {
const session = await getSession()
// Be carfeul! The entire user object is returned
// Filter session to not send hash, salt, ...
return Response.json({
ok: true,
data: {
id: session.id,
username: session.username
}
})
} catch (err) {
console.error(err)
return Response.json({ ok: false, err: err.message })
}
}:warning: Be careful that
getSessionreturn the entireuserobject that can contain some sensitive informations as hash or salt for example.
