44 lines
No EOL
1.3 KiB
JavaScript
44 lines
No EOL
1.3 KiB
JavaScript
// from an old project: https://git.zenoverse.net/bigly-archive/auth-thing/raw/branch/main/src/routes/login/+page.server.js
|
|
import Route from "../route.js";
|
|
import initDb from "../db.js";
|
|
import { compare } from "bcrypt";
|
|
import { randomBytes } from 'node:crypto';
|
|
|
|
let db = await initDb();
|
|
|
|
function isValid(user) {
|
|
return user.search(/[^A-Za-z0-9\-\_]/g) == -1;
|
|
}
|
|
|
|
// TODO: rewrite
|
|
let main = new Route([], async function (req, res, input) {
|
|
let { user, pass } = req.body;
|
|
|
|
if (!pass || !user) return { 'success': false, 'message': 'Some fields are missing' };
|
|
|
|
if (!isValid(user)) return { 'success': false, 'message': 'Username is invalid' };
|
|
|
|
let isExist = await db.all('SELECT * FROM auth WHERE UPPER(username) LIKE UPPER(?)', [
|
|
user
|
|
]);
|
|
|
|
if (isExist.length < 1) return { 'success': false, 'message': 'Account does not exist' };
|
|
|
|
let passHash = await compare(pass,isExist[0].password);
|
|
|
|
if (!passHash)
|
|
return { 'success': false, 'message': 'Incorrect password' };
|
|
|
|
let token = randomBytes(32).toString('hex');
|
|
|
|
await db.run('INSERT INTO token (username, token) VALUES (?, ?)', [
|
|
user,
|
|
token
|
|
])
|
|
|
|
res.cookie('token',token);
|
|
|
|
return {'success': true, 'message': 'Log in succeeded', 'redirect': '/', 'data': token};
|
|
});
|
|
|
|
export default main; |