赞
踩
安装略
其中secret可以使用openssl命令生成
openssl rand -base64 32
获得client id和client secrets,并配置到环境变量中的GITHUB_ID和GITHUB_SECRET
创建登录登出端点,可以在lib下创建并在对应的api router中暴露,也可以直接在api router中创建
- export const {
- handlers: { GET, POST },
- auth,
- signIn,
- signOut,
- } = NextAuth({
- ...authConfig,
- providers: [
- GitHub({
- clientId: process.env.GITHUB_ID,
- clientSecret: process.env.GITHUB_SECRET,
- }
- ...
在provider后面增加callback
npm i bcryptjs
- const login = async (credentials) => {
- try {
- connectToDb();
- const user = await User.findOne({ username: credentials.username });
-
- if (!user) throw new Error("Wrong credentials!");
-
- const isPasswordCorrect = await bcrypt.compare(
- credentials.password,
- user.password
- );
-
- if (!isPasswordCorrect) throw new Error("Wrong credentials!");
-
- return user;
- } catch (err) {
- console.log(err);
- throw new Error("Failed to login!");
- }
- };
-
- export const {
- handlers: { GET, POST },
- auth,
- signIn,
- signOut,
- } = NextAuth({
- ...authConfig,
- providers: [
- GitHub({
- clientId: process.env.GITHUB_ID,
- clientSecret: process.env.GITHUB_SECRET,
- }),
- CredentialsProvider({
- async authorize(credentials) {
- try {
- const user = await login(credentials);
- return user;
- } catch (err) {
- return null;
- }
- },
- }),
- ],
- callbacks: {
- async signIn({ user, account, profile }) {
- if (account.provider === "github") {
- connectToDb();
- try {
- const user = await User.findOne({ email: profile.email });
-
- if (!user) {
- const newUser = new User({
- username: profile.login,
- email: profile.email,
- image: profile.avatar_url,
- });
-
- await newUser.save();
- }
- } catch (err) {
- console.log(err);
- return false;
- }
- }
- return true;
- },
- ...authConfig.callbacks,
- },
- });
当使用await signIn("credentials", { username, password });进行登录的时候会触发重定向错误,这是nextjs redirect的一个问题,可以通过抛出这个错误而非return来规避。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。