DEV Community

Cover image for TV Channel Website: Creating Root User
Sokhavuth TIN
Sokhavuth TIN

Posted on

TV Channel Website: Creating Root User

GitHub: https://github.com/Sokhavuth/TV-Channel
Vercel: https://khmerweb-tv-channel.vercel.app/login

Before building a dashboard, we need to create a rootuser or an administrator (admin) for him/her to supervise the dashboard. We will register the rootuser in the "users" collection in MongoDB Atlas for later use.

To achieve this goal, we are going to create a "User" class in the user.py file inside models folder. This class will be imported into the "Login" class in login.py file inside controllers folder. Doing so, we can instantiate User class and call createRootUser() method in that class to create an administrator or a rootuser.

To make user's password confidential, we could use Python standard library "hashlib" to hash the password.

# models/user.py

import config, hashlib, uuid


class User:
    def __init__(self):
        self.db = config.db
        self.setup = config.settings()


    def createRootUser(self):
        raw_salt = uuid.uuid4().hex
        password = "xxxxxxxxxxxxxxxxxxx".encode('utf-8')
        salt = raw_salt.encode('utf-8')
        hashed_password = hashlib.sha512(password + salt).hexdigest()

        user = { 
            "id": uuid.uuid4().hex, 
            "title": 'Sokhavuth',
            "content": '',
            "thumb": '',
            "date": '',
            "role": 'Admin',
            "email": 'vuthdevelop@gmail.com',
            "salt": raw_salt,
            "password": hashed_password,
        }

        usercol = self.db["users"]
        usercol.insert_one(user)


Enter fullscreen mode Exit fullscreen mode
# controllers/frontend/login.py

import config, copy
from bottle import template
from models.user import User


class Login:
    def __init__(self):
        settings = copy.deepcopy(config.settings)
        self.setup = settings()


    def getPage(self):
        user = User()
        user.createRootUser()

        self.setup["pageTitle"] = "Log into Admin Page"
        self.setup["route"] = "/login"

        return template("base", data=self.setup)


Enter fullscreen mode Exit fullscreen mode

Top comments (0)