Skip to content

Commit

Permalink
feat: develop authentication api
Browse files Browse the repository at this point in the history
  • Loading branch information
huanghanzhilian committed Nov 24, 2023
1 parent e0875fb commit b475d97
Show file tree
Hide file tree
Showing 12 changed files with 2,406 additions and 128 deletions.
40 changes: 40 additions & 0 deletions app/api/auth/login/route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { NextResponse } from 'next/server'

import db from "lib/db";
import Users from "models/User";
import bcrypt from "bcrypt";
import { createAccessToken, createRefreshToken } from "utils/generateToken";

export async function POST(req) {
try {
await db.connect();
const { email, password } = await req.json();

const user = await Users.findOne({ email });

if (!user) return NextResponse.json({ err: '找不到此电子邮件的应用程序' }, { status: 400 });

const isMatch = await bcrypt.compare(password, user.password);

if (!isMatch) return NextResponse.json({ err: '电子邮件地址或密码不正确' }, { status: 400 });

const access_token = createAccessToken({ id: user._id });
const refresh_token = createRefreshToken({ id: user._id });

return NextResponse.json({
msg: "登录成功",
refresh_token,
access_token,
user: {
name: user.name,
email: user.email,
role: user.role,
avatar: user.avatar,
root: user.root,
}
}, { status: 200 })
} catch (error) {
console.log('====error====', error.message)
return NextResponse.json({ err: error.message }, { status: 500 });
}
}
38 changes: 38 additions & 0 deletions app/api/auth/register/route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { NextResponse } from 'next/server'

import db from "lib/db";
import Users from "models/User";
import bcrypt from "bcrypt";

export async function POST (req, { params }) {
try {

await await db.connect();
const { name, email, password } = await req.json();

console.log(name, email, password)

const user = await Users.findOne({ email });

if (user) return NextResponse.json({ err: '该账户已存在' }, { status: 400});

const hashPassword = await bcrypt.hash(password, 12);

const newUser = new Users({ name, email, password: hashPassword });

await newUser.save();
await db.disconnect();

return NextResponse.json({
meg: "注册成功"
}, {
status: 201
});
} catch (error) {
return NextResponse.json({
err: error.message
}, {
status: 500
});
}
}
2 changes: 1 addition & 1 deletion app/layout.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Inter } from 'next/font/google'
import './globals.css'
// import './globals.css'

const inter = Inter({ subsets: ['latin'] })

Expand Down
92 changes: 1 addition & 91 deletions app/page.js
Original file line number Diff line number Diff line change
@@ -1,95 +1,5 @@
import Image from 'next/image'
import styles from './page.module.css'

export default function Home() {
return (
<main className={styles.main}>
<div className={styles.description}>
<p>
Get started by editing&nbsp;
<code className={styles.code}>app/page.js</code>
</p>
<div>
<a
href="https://vercel.com?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
By{' '}
<Image
src="/vercel.svg"
alt="Vercel Logo"
className={styles.vercelLogo}
width={100}
height={24}
priority
/>
</a>
</div>
</div>

<div className={styles.center}>
<Image
className={styles.logo}
src="/next.svg"
alt="Next.js Logo"
width={180}
height={37}
priority
/>
</div>

<div className={styles.grid}>
<a
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"
className={styles.card}
target="_blank"
rel="noopener noreferrer"
>
<h2>
Docs <span>-&gt;</span>
</h2>
<p>Find in-depth information about Next.js features and API.</p>
</a>

<a
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"
className={styles.card}
target="_blank"
rel="noopener noreferrer"
>
<h2>
Learn <span>-&gt;</span>
</h2>
<p>Learn about Next.js in an interactive course with&nbsp;quizzes!</p>
</a>

<a
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"
className={styles.card}
target="_blank"
rel="noopener noreferrer"
>
<h2>
Templates <span>-&gt;</span>
</h2>
<p>Explore starter templates for Next.js.</p>
</a>

<a
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"
className={styles.card}
target="_blank"
rel="noopener noreferrer"
>
<h2>
Deploy <span>-&gt;</span>
</h2>
<p>
Instantly deploy your Next.js site to a shareable URL with Vercel.
</p>
</a>
</div>
</main>
<div>hello</div>
)
}
42 changes: 42 additions & 0 deletions lib/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import mongoose from "mongoose";

const connection = {};

async function connect() {
if (connection.isConnected) {
console.log("already connected");
return;
}
if (mongoose.connections.length > 0) {
connection.isConnected = mongoose.connections[0].readyState;
if (connection.isConnected === 1) {
console.log("use previous connection");
return;
}
await mongoose.disconnect();
}

try {
console.log('process.env.MONGODB_URL', process.env.MONGODB_URL)
const db = await mongoose.connect(process.env.MONGODB_URL);
console.log("new connection");
connection.isConnected = db.connections[0].readyState;
} catch (error) {
console.log(error);
process.exit(1);
}
}

async function disconnect() {
if (connection.isConnected) {
if (process.env.NODE_ENV === "production") {
await mongoose.disconnect();
connection.isConnected = false;
} else {
console.log("not disconnected");
}
}
}

const db = { connect, disconnect };
export default db;
14 changes: 14 additions & 0 deletions models/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import mongoose from "mongoose";

const userSchema = new mongoose.Schema({
name: { type: String, require: true },
email: { type: String, require: true, unique: true },
password: { type: String, require: true },
role: { type: String, default: "user" },
root: { type: Boolean, default: false },
avatar:{ type:String, default:'/person.png' }
});

const User = mongoose.models.user || mongoose.model("user", userSchema);

export default User;
9 changes: 8 additions & 1 deletion next.config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
/** @type {import('next').NextConfig} */
const nextConfig = {}
const nextConfig = {
env: {
BASE_URL: "http://localhost:3000",
MONGODB_URL: "mongodb://huangblogTwo:[email protected]:27017/exercise-full-next",
ACCESS_TOKEN_SECRET: "h1n0U6LHJtCZuWitwjn3oLd5qCRIgUFtemnjTrpfZLzVZ3ff0f",
REFRESH_TOKEN_SECRET: "q5*a8Swj9u8e5Wf'Wv1fA!Pz8TQ#S2!mKAwuFz29HqLeOeJSA",
},
}

module.exports = nextConfig
Loading

0 comments on commit b475d97

Please sign in to comment.