1. Làm chức năng đăng ký signup
import { hash } from 'bcrypt';
import { NextApiRequest, NextApiResponse } from 'next';
import sqlite from 'sqlite';
export default async function signup( req: NextApiRequest, res: NextApiResponse ) {
const db = await sqlite.open('./mydb.sqlite');
if (req.method === 'POST') {
hash(req.body.password, 10, async function(err, hash) {
// Store hash in your password DB.
const statement = await db.prepare( 'INSERT INTO person (name, email, password) values (?, ?, ?)');
const result = await statement.run(req.body.name, req.body.email, hash);
result.finalize();
const person = await db.all('select * from person');
res.json(person);
});
} else {
res.status(405).json({ message: 'We only support POST' });
}
}
2 Làm chức năng đăng nhập
export const secret = '0e900be1-0ac5-4e6a-bf4b-38f8b21a189b';
import { compare } from 'bcrypt';
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.json({ authToken: jwt });
} else {
res.json({ message: 'Ups, something went wrong!' });
}
});
} else {
res.status(405).json({ message: 'We only support POST' });
}
}