Commit b50e4b6a authored by berumuron's avatar berumuron
Browse files

Add workflow to login and logout as a user

parent d5015c26
......@@ -113,3 +113,6 @@ Cela exécute Flask (le framework utilisé pour le backend) en lui précisant qu
l'application se trouve dans le répertoire `src` et de se lancer en mode
`development` pour qu'il détecte automatiquement les changements faits dans le
code.
Vous pouvez désormais vous connecter en allant sur [127.0.0.1:5000](http://127.0.0.1:5000/)
et en saisissant les identifiants donnés plus haut.
......@@ -2,7 +2,7 @@ import os
from flask import Flask, render_template
from . import cli, db
from . import cli, db, auth
__version__ = "0.1.0"
......@@ -10,7 +10,9 @@ __version__ = "0.1.0"
def create_app():
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(DATABASE=os.path.join(app.instance_path, "db.sqlite"))
app.config.from_mapping(
SECRET_KEY="a-dev-secret", DATABASE=os.path.join(app.instance_path, "db.sqlite")
)
try:
os.makedirs(app.instance_path)
......@@ -21,6 +23,9 @@ def create_app():
cli.init_app(app)
db.init_app(app)
# Register blueprints (collection of views)
app.register_blueprint(auth.bp)
# Define a default basic route (it will be improved later).
@app.route("/")
def index():
......
from flask import (
Blueprint,
request,
session,
redirect,
url_for,
flash,
render_template,
g,
)
from .models import User
bp = Blueprint("auth", __name__, url_prefix="/auth")
@bp.before_app_request
def load_logged_in_user():
"""Set the global current_user if logged in."""
user_id = session.get("user_id")
g.current_user = User.find_by_id(user_id)
@bp.route("/login", methods=("GET", "POST"))
def login():
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
user = User.find_by_username(username)
if user is not None and user.check_password(password):
session.clear()
session["user_id"] = user.id
return redirect(url_for("index"))
else:
flash("Les identifiants sont incorrects.")
return render_template("auth/login.html")
@bp.route("/logout")
def logout():
session.clear()
return redirect(url_for("index"))
......@@ -9,6 +9,9 @@ class User:
self.username = username
self.password = password
def check_password(self, password):
return security.check_password_hash(self.password, password)
@classmethod
def find_by_id(cls, user_id):
database = db.get_db()
......@@ -21,6 +24,18 @@ class User:
return cls(user["id"], user["username"], user["password"])
@classmethod
def find_by_username(cls, username):
database = db.get_db()
user = database.execute(
"SELECT * FROM users WHERE username = ?", (username,)
).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()
......
{% extends 'layout.html' %}
{% block content %}
<div class="container">
<h1>Connexion</h1>
<form method="post">
<div class="alert alert-error">
{% for message in get_flashed_messages() %}
<p>{{ message }}</p>
{% endfor %}
</div>
<div class="form-group">
<label for="username">Nom d’utilisateur</label>
<input type="text" name="username" id="username" required autofocus />
</div>
<div class="form-group">
<label for="password">Mot de passe</label>
<input type="password" name="password" id="password" required />
</div>
<div class="form-group form-group-actions">
<button type="submit" class="button-primary">
Se connecter
</button>
<a href="{{ url_for('index') }}">
Retour à l'accueil
</a>
</div>
</form>
</div>
{% endblock %}
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0" />
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='app.css') }}">
<title>Reflets</title>
</head>
{% extends 'layout.html' %}
<body>
<div class="container">
{% block content %}
<div class="container">
{% if g.current_user %}
<h1>Bonjour {{ g.current_user.username }}&nbsp;!</h1>
{% else %}
<h1>Bonjour Monde&nbsp;!</h1>
{% endif %}
<p>Bienvenue sur Reflets.</p>
</div>
</body>
</html>
<p>Bienvenue sur Reflets.</p>
</div>
{% endblock %}
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0" />
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='app.css') }}">
<title>Reflets</title>
</head>
<body class="app">
<header>
<nav class="app-navigation">
<ul class="container">
<li class="app-navigation-title">
<a href="{{ url_for('index') }}">Reflets</a>
</li>
<li class="app-navigation-auth">
{% if g.current_user %}
{{ g.current_user.username }}
(<a href="{{ url_for('auth.logout') }}">Se déconnecter</a>)
{% else %}
<a href="{{ url_for('auth.login') }}">Connexion</a>
{% endif %}
</li>
</ul>
</nav>
</header>
<main class="app-page">
{% block content %}{% endblock %}
</main>
</body>
</html>
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