Commit d5015c26 authored by berumuron's avatar berumuron
Browse files

Add a command to create a user in db

parent 6ed2088e
......@@ -5,8 +5,9 @@ dep: ## Install the dependencies
python3 -m pip install -r requirements.txt
.PHONY: db-setup
db-setup: ## Initialize the database
db-setup: ## Initialize the database and seed the database
FLASK_APP=src FLASK_ENV=development flask db-init
FLASK_APP=src FLASK_ENV=development flask user-create admin --password secret
.PHONY: run
run: ## Run the application binary
......
......@@ -90,10 +90,14 @@ données avec :
```console
reflets$ FLASK_APP=src FLASK_ENV=development flask db-init
reflets$ FLASK_APP=src FLASK_ENV=development flask create-user admin --password secret
reflets$ # ou avec la commande make
reflets$ make db-setup
```
Cela va créer les tables en base de données et créer un utilisateur avec les
identifiants `admin` / `secret`.
## Lancer l'application (développement)
Une fois les dépendances installées, pour lancer l'application, exécutez la
......
......@@ -2,6 +2,7 @@ import click
from flask.cli import with_appcontext
from . import db
from .models import User
@click.command("db-init")
......@@ -12,6 +13,17 @@ def db_init_command():
click.echo("Database initialized.")
@click.command("user-create")
@click.argument("username")
@click.password_option()
@with_appcontext
def user_create_command(username, password):
"""Create a user in database."""
user = User.create(username=username, password=password)
click.echo(f"User {user.username} initialized.")
def init_app(app):
"""Register CLI commands to the application."""
app.cli.add_command(db_init_command)
app.cli.add_command(user_create_command)
import werkzeug.security as security
from . import db
class User:
def __init__(self, id, username, password):
self.id = id
self.username = username
self.password = password
@classmethod
def find_by_id(cls, user_id):
database = db.get_db()
user = database.execute(
"SELECT * FROM users WHERE id = ?", (user_id,)
).fetchone()
if user is None:
return None
return cls(user["id"], user["username"], user["password"])
@classmethod
def create(cls, username, password):
database = db.get_db()
cursor = database.execute(
"INSERT INTO users (username, password) VALUES (?, ?)",
(username, security.generate_password_hash(password)),
)
database.commit()
return cls.find_by_id(cursor.lastrowid)
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment