Senha

# Arquivo: app.py
from flask import Flask, jsonify, request
from repositories.user import UserRepository
from utils.passgen import passgen

app = Flask("testapp")


# Register new user with a secure auto-generated password.
@app.route("/users", methods=["POST"])
def create_user():
    request_data = request.json
    username = request_data["username"]
    email = request_data["email"]

    return jsonify(
        UserRepository.add_user(
            username,
            email,
            passgen(64),
        )
    )
# Arquivo: utils/passgen.py
import random
import time


pass_dict = (
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRST"
    "UVWXYZ0123456789-_!.,~`^+{}[]();:@#%&*'\" "
)


def passgen(size: int) -> bytes:
    passwd = bytes()
    random.seed(int(time.time()))

    for i in range(size):
        rindex = random.randint(0, len(pass_dict) - 1)
        passwd += pass_dict[rindex].encode()

    return passwd
# Arquivo: repositories/user.py
import time
import bcrypt


class UserRepository:
    @staticmethod
    def add_user(
        username: str,
        email: str,
        password: bytes
    ) -> dict:
        hash = bcrypt.hashpw(password, bcrypt.gensalt())

        # Finja que esse usuário está sendo cadastrado no banco
        # de dados
        return {
            "username": username,
            "email": email,
            # Finja que a hash não está sendo retornada para
            # o usuário
            "hash": hash.decode(),
            "registered_at": int(time.time()),
        }