1 Làm chức năng login bằng cookie
C:\Users\Administrator\Desktop\abc\pages\api\login.ts
import { compare } from 'bcrypt';
import cookie from 'cookie';
import { sign } from 'jsonwebtoken';
import { NextApiRequest, NextApiResponse } from 'next';
import sqlite from 'sqlite';
import { secret } from '../../api/secret';
export default async function login(req: NextApiRequest, res: NextApiResponse) {
const db = await sqlite.open('./mydb.sqlite');
if (req.method === 'POST') {
const person = await db.get('select * from person where email = ?', [req.body.email]);
compare(req.body.password, person.password, function(err, result) {
if (!err && result) {
const claims = { sub: person.id, myPersonEmail: person.email };
const jwt = sign(claims, secret, { expiresIn: '1h' });
res.setHeader('Set-Cookie', cookie.serialize('auth', jwt, {
httpOnly: true,
secure: process.env.NODE_ENV !== 'development',
sameSite: 'strict',
maxAge: 3600,
path: '/'
}))
res.json({message: 'Welcome back to the app!'});
} else {
res.json({ message: 'Ups, something went wrong!' });
}
});
} else {
res.status(405).json({ message: 'We only support POST' });
}
}
C:\Users\Administrator\Desktop\abc\api\secret.ts
export const secret = '0e900be1-0ac5-4e6a-bf4b-38f8b21a189b';
2 Sử dụng cookie trên postman
C:\Users\Administrator\Desktop\abc\pages\api\people.ts
import { verify } from 'jsonwebtoken';
import { NextApiHandler, NextApiRequest, NextApiResponse } from 'next';
import sqlite from 'sqlite';
import { secret } from '../../api/secret';
export const authenticated = (fn: NextApiHandler) => async (req: NextApiRequest, res: NextApiResponse) => {
verify(req.cookies.auth!, secret, async function(err, decoded) {
if (!err && decoded) {
return await fn(req, res);
}
res.status(401).json({ message: 'Sorry you are not authenticated' });
});
};
export default authenticated(async function getPeople(req: NextApiRequest,res: NextApiResponse) {
const db = await sqlite.open('./mydb.sqlite');
const people = await db.all('select id, email, name from person');
res.json(people);
});
3 Làm form đăng nhập trên trình duyệt
C:\Users\Administrator\Desktop\abc\pages\login.tsx
import { useRef, useState } from 'react';
export default function Login() {
const emailRef = useRef<HTMLInputElement>(null);
const passRef = useRef<HTMLInputElement>(null);
const [message, setMessage] = useState<any>(null);
async function handleLogin() {
const resp = await fetch('http://localhost:3000/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: emailRef.current?.value,
password: passRef.current?.value
})
});
const json = await resp.json();
setMessage(json);
}
return (
<div>
{message && JSON.stringify(message)}
<input type="text" placeholder="email" ref={emailRef} />
<input type="password" placeholder="password" ref={passRef} />
<button onClick={handleLogin}>Login</button>
</div>
);
}
4 Làm form đăng ký trên trình duyệt
C:\Users\Administrator\Desktop\abc\pages\signup.tsx
import { useRef, useState } from 'react';
export default function Signup() {
const emailRef = useRef<HTMLInputElement>(null);
const passRef = useRef<HTMLInputElement>(null);
const [message, setMessage] = useState<any>(null);
async function handleLogin() {
const resp = await fetch('http://localhost:3000/api/signup', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: emailRef.current?.value,
password: passRef.current?.value
})
});
const json = await resp.json();
setMessage(json);
}
return (
<div>
<h1>Create a new user!!</h1>
{message && JSON.stringify(message)}
<input type="text" placeholder="email" ref={emailRef} />
<input type="password" placeholder="password" ref={passRef} />
<button onClick={handleLogin}>Login</button>
</div>
);
}
5 sử dụng cooke ngay trên trình duyệt
C:\Users\Administrator\Desktop\abc\pages\people.tsx
import { NextPageContext } from "next";
import { myGet } from "../api/myGet";
export default function People({ people }: any) {
return <div>Hello People {JSON.stringify(people)}</div>
}
People.getInitialProps = async (ctx: NextPageContext) => {
const json = await myGet('http://localhost:3000/api/people', ctx);
return { people: json };
}
C:\Users\Administrator\Desktop\abc\api\myGet.ts
import fetch from 'isomorphic-unfetch';
import { NextPageContext } from "next";
import Router from 'next/router';
export async function myGet(url: string, ctx: NextPageContext) {
const cookie = ctx.req?.headers.cookie;
const resp = await fetch(url, {
headers: {
cookie: cookie!
}
});
if(resp.status === 401 && !ctx.req) {
Router.replace('/login');
return {};
}
if(resp.status === 401 && ctx.req) {
ctx.res?.writeHead(302, {
Location: 'http://localhost:3000/login'
});
ctx.res?.end();
return;
}
const json = await resp.json();
return json;
}