Login is the process of verifying or authenticating certain registered users for them to get into some forbidden pages. As the result, first of all, we need to register those special users in the database so that when they try to log into the dashboard or some other forbidden pages, we can check in the database if they are registered or not. If they are registered, we can write code to let them get into those forbidden areas, otherwise, we will not.
Before achieving this goal, we need to create a user collection in MongoDB database to register a superuser or manager for him/her to register other special users and control the dashboard.
On the other hand, for the security of user's password, we can use bcrypt package to hash user's passwords so that nobody can read and understand those passwords even the administrator(s) of the website. Here is an example of a hashed password: $2a$08$zuHtXr2ITSIHYfLL/kaj9uo7XTZiL/rNJV0jdJB/7HIHFmuSGWb7C.
// controllers/users/login.js
import login from "../../views/users/login.jsx";
import userdb from "../../models/user.ts";
class Login{
async getForm(req){
const config = req.mysetting();
config.page_title = "Login Page";
config.route = '/users/login';
userdb.createRootUser(req);
return await login(config);
}
}
export default new Login();
// models/users.ts
import { bcrypt } from '../deps.ts';
interface UserSchema {
_id: ObjectId;
id: string;
title: string;
content: string;
thumb: string;
date: string;
role: string;
email: string;
password: string;
}
class User{
async createRootUser(req){
const id = Date.now() + Math.round(Math.random() * 1E9).toString();
const salt = await bcrypt.genSalt(8);
const hashPassword = bcrypt.hashSync('xxxxxxxxxx', salt);
let newUser = {
id: id,
title: 'Sokhavuth',
content: '',
thumb: '',
date: '',
role: 'Admin',
email: 'vuthdevelop@gmail.app',
password: hashPassword,
}
const users = req.mydb.collection<UserSchema>("users");
await users.insertOne(newUser);
}
}
export default new User();
GitHub: https://github.com/Sokhavuth/opine-job
Deno Deploy: https://khmerweb-job.deno.dev/users