feat(usermanager): implement User update and detail views

This commit is contained in:
Julian Lobbes 2022-11-18 00:17:54 +01:00
parent cd7233f566
commit b111490bab
4 changed files with 218 additions and 105 deletions

View File

@ -1,38 +1,39 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ config.SITE_TITLE }}</title>
<meta name="description" content="{{ config.SITE_DESCRIPTION }}">
<meta name="author" content="{{ config.SITE_AUTHOR }}">
<title>{{ config.SITE_TITLE }}</title>
<meta name="description" content="{{ config.SITE_DESCRIPTION }}">
<meta name="author" content="{{ config.SITE_AUTHOR }}">
<meta property="og:title" content="{{ config.SITE_TITLE }}">
<meta property="og:type" content="website">
<meta property="og:url" content="{{ config.SITE_URL }}">
<meta property="og:description" content="{{ config.SITE_DESCRIPTION }}">
<meta property="og:image" content="{{ url_for('static', filename='images/base/og.png') }}">
<meta property="og:title" content="{{ config.SITE_TITLE }}">
<meta property="og:type" content="website">
<meta property="og:url" content="{{ config.SITE_URL }}">
<meta property="og:description" content="{{ config.SITE_DESCRIPTION }}">
<meta property="og:image" content="{{ url_for('static', filename='images/base/og.png') }}">
<link rel="icon" href="{{ url_for('static', filename='images/base/favicon.ico') }}">
<link rel="icon" href="{{ url_for('static', filename='images/base/favicon.svg') }}" type="image/svg+xml">
<link rel="apple-touch-icon" href="{{ url_for('static', filename='images/base/apple-touch-icon.png') }}">
<link rel="icon" href="{{ url_for('static', filename='images/base/favicon.ico') }}">
<link rel="icon" href="{{ url_for('static', filename='images/base/favicon.svg') }}" type="image/svg+xml">
<link rel="apple-touch-icon" href="{{ url_for('static', filename='images/base/apple-touch-icon.png') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<!--<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">-->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
</head>
<body>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flash-message>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
{% block content %}
{% endblock content %}
</body>
<body>
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<div class="alert alert-primary m-3">{{ message }}</div>
{% endfor %}
{% endif %}
{% endwith %}
<div class="container border rounded">
{% block content %}
{% endblock content %}
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
</body>
</html>

View File

@ -1,32 +1,81 @@
{% extends 'base.html' %}
{% block content %}
<h1>User: {{ user.username }}</h1>
<img src="{{ url_for('static', filename='images/users/' + user.username + '/full.jpg') }}" alt="profile picture for user {{ user.username }}">
<div class="row">
<div class="col">
<h1>Edit user: {{ username }}</h1>
</div>
</div>
<form method="post" enctype="multipart/form-data">
{{ form.csrf_token }}
{{ form.email.label }}
{{ form.email }}
{{ form.first_name.label }}
{{ form.first_name }}
{{ form.last_name.label }}
{{ form.last_name }}
{{ form.display_name.label }}
{{ form.display_name }}
{{ form.password.label }}
{{ form.password }}
{{ form.password_confirmation.label }}
{{ form.password_confirmation }}
{{ form.picture.label }}
{{ form.picture }}
{{ form.submit }}
<div class="mb-3">
{{ form.email.label(class="form-label") }}
{{ form.email(class="form-control" + (" is-invalid" if form.email.errors else "")) }}
{% if form.email.errors %}
{% for error in form.email.errors %}
<div class="invalid-feedback">{{ error }}</div>
{% endfor %}
{% endif %}
</div>
<div class="mb-3">
{{ form.first_name.label(class="form-label") }}
{{ form.first_name(class="form-control" + (" is-invalid" if form.first_name.errors else "")) }}
{% if form.first_name.errors %}
{% for error in form.first_name.errors %}
<div class="invalid-feedback">{{ error }}</div>
{% endfor %}
{% endif %}
</div>
<div class="mb-3">
{{ form.last_name.label(class="form-label") }}
{{ form.last_name(class="form-control" + (" is-invalid" if form.last_name.errors else "")) }}
{% if form.last_name.errors %}
{% for error in form.last_name.errors %}
<div class="invalid-feedback">{{ error }}</div>
{% endfor %}
{% endif %}
</div>
<div class="mb-3">
{{ form.display_name.label(class="form-label") }}
{{ form.display_name(class="form-control" + (" is-invalid" if form.display_name.errors else "")) }}
{% if form.display_name.errors %}
{% for error in form.display_name.errors %}
<div class="invalid-feedback">{{ error }}</div>
{% endfor %}
{% endif %}
</div>
<div class="mb-3">
{{ form.password.label(class="form-label") }}
{{ form.password(class="form-control" + (" is-invalid" if form.password.errors else "")) }}
{% if form.password.errors %}
{% for error in form.password.errors %}
<div class="invalid-feedback">{{ error }}</div>
{% endfor %}
{% endif %}
</div>
<div class="mb-3">
{{ form.password_confirmation.label(class="form-label") }}
{{ form.password_confirmation(class="form-control" + (" is-invalid" if form.password_confirmation.errors else "")) }}
{% if form.password_confirmation.errors %}
{% for error in form.password_confirmation.errors %}
<div class="invalid-feedback">{{ error }}</div>
{% endfor %}
{% endif %}
</div>
<div class="mb-3">
{{ form.picture.label(class="form-label") }}
{{ form.picture(class="form-control" + (" is-invalid" if form.picture.errors else "")) }}
{% if form.picture.errors %}
{% for error in form.picture.errors %}
<div class="invalid-feedback">{{ error }}</div>
{% endfor %}
{% endif %}
</div>
<div class="mb-3">
<a class="btn btn-secondary"
href="{{ url_for('usermanager.user_view', username=username) }}"
role="button">Cancel</a>
{{ form.submit(class_="btn btn-primary") }}
</div>
</form>
{% endblock content %}

View File

@ -0,0 +1,44 @@
{% extends 'base.html' %}
{% block content %}
<div class="row text-center">
<div class="col">
<img src="{{ url_for('static', filename='images/users/' + user.username + '/full.jpg') }}"
alt="profile picture for user {{ user.username }}"
class="img-thumbnail"
>
</div>
</div>
<div class="row text-center">
<div class="col">
<h1>{{ user.username }}</h1>
</div>
</div>
<div class="row gx-1">
<div class="col text-end fw-bold">Username:</div>
<div class="col text-start">{{ user.username }}</div>
</div>
<div class="row gx-1">
<div class="col text-end fw-bold">Email:</div>
<div class="col text-start">{{ user.email }}</div>
</div>
<div class="row gx-1">
<div class="col text-end fw-bold">First Name:</div>
<div class="col text-start">{{ user.first_name }}</div>
</div>
<div class="row gx-1">
<div class="col text-end fw-bold">Last Name:</div>
<div class="col text-start">{{ user.last_name }}</div>
</div>
<div class="row gx-1">
<div class="col text-end fw-bold">Nickname:</div>
<div class="col text-start">{{ user.display_name }}</div>
</div>
<div class="row text-center">
<div class="col">
<a class="btn btn-primary"
href="{{ url_for('usermanager.user_update', username=user.username) }}"
role="button">Edit</a>
</div>
</div>
{% endblock content %}

View File

@ -1,10 +1,10 @@
"""Views for lumi2."""
from pathlib import Path
from tempfile import TemporaryDirectory
from tempfile import TemporaryFile
from flask import (
Blueprint, render_template, abort, request, flash, redirect
Blueprint, render_template, abort, request, flash, redirect, url_for
)
from PIL import Image, UnidentifiedImageError
from flask_wtf import FlaskForm
@ -27,31 +27,55 @@ def index():
return render_template('usermanager/index.html')
@bp.route("/user/view/<string:username>")
def user_view(username: str):
"""Detail view for a specific User.
Shows the user's information.
"""
try:
conn = ldap.get_connection()
except Exception:
abort(500)
try:
user = ldap.get_user(conn, username)
except ldap.EntryNotFoundException:
conn.unbind()
abort(404)
user._generate_static_images()
conn.unbind()
return render_template('usermanager/user_view.html',user=user)
class UserUpdateForm(FlaskForm):
@staticmethod
def validate_name(form, field) -> None:
try:
User.assert_is_valid_name(field.data)
except InvalidStringFormatException as e:
raise ValidationError from e
raise ValidationError(str(e))
@staticmethod
def validate_password(form, field) -> None:
try:
User.assert_is_valid_password(field.data)
except InvalidStringFormatException as e:
raise ValidationError from e
if field.data:
try:
User.assert_is_valid_password(field.data)
except InvalidStringFormatException as e:
raise ValidationError(str(e))
@staticmethod
def validate_picture(form, field) -> None:
if field.data:
if field.data and field.data.filename:
try:
with TemporaryDirectory() as temp_dir:
temp_file = Path(temp_dir) / "upload.jpg"
field.data.save(temp_file)
Image.open(temp_file, formats=['JPEG'])
Image.open(field.data, formats=['JPEG'])
field.data.seek(0)
except UnidentifiedImageError as e:
raise ValidationError from e
raise ValidationError(
"Invalid JPEG file. It may be corrupted."
)
email = StringField(
'Email',
@ -70,7 +94,7 @@ class UserUpdateForm(FlaskForm):
[InputRequired(), validate_name]
)
password = PasswordField(
'Password',
'Password (leave empty to keep the same)',
[
EqualTo('password_confirmation', message='Passwords must match'),
validate_password,
@ -90,7 +114,10 @@ class UserUpdateForm(FlaskForm):
@bp.route("/user/update/<string:username>", methods=("GET", "POST"))
def user_update(username: str):
"""Update view for a specific User."""
"""Update view for a specific User.
Provides a form which can be used to edit that user's details.
"""
try:
conn = ldap.get_connection()
@ -105,41 +132,33 @@ def user_update(username: str):
user._generate_static_images()
if request.method == 'GET':
form = UserUpdateForm(obj=user)
else:
form = UserUpdateForm(request.form)
if form.validate():
if form.email.data:
user.email = form.email.data
print("Email updated.")
if form.first_name.data:
user.first_name = form.first_name.data
print("First Name updated.")
if form.last_name.data:
user.last_name = form.last_name.data
print("Last Name updated.")
if form.display_name.data:
user.display_name = form.display_name.data
print("Display Name updated.")
if form.password.data:
user.password_hash = User.generate_password_hash(form.password.data)
print("Password updated.")
picture_updated = False
if form.picture.data:
with TemporaryDirectory() as temp_dir:
temp_file = Path(temp_dir) / "upload.jpg"
form.picture.data.save(temp_file)
user.picture = Image.open(temp_file, formats=['JPEG'])
picture_updated = True
print("Picture updated.")
form = UserUpdateForm(obj=user)
if form.validate_on_submit():
if form.email.data:
user.email = form.email.data
if form.first_name.data:
user.first_name = form.first_name.data
if form.last_name.data:
user.last_name = form.last_name.data
if form.display_name.data:
user.display_name = form.display_name.data
if form.password.data:
user.password_hash = User.generate_password_hash(form.password.data)
picture_updated = False
if form.picture.data and form.picture.data.filename:
user.picture = Image.open(form.picture.data, formats=['JPEG'])
picture_updated = True
ldap.update_user(conn, user)
if picture_updated:
user._generate_static_images(force=True)
conn.unbind()
# TODO redirect to user detail view
return redirect(request.url)
ldap.update_user(conn, user)
if picture_updated:
user._generate_static_images(force=True)
conn.unbind()
flash(f"Information for user '{user.username}' was updated.")
return redirect(url_for('usermanager.user_view', username=user.username))
conn.unbind()
return render_template('usermanager/user_update.html', form=form, user=user)
return render_template(
'usermanager/user_update.html',
form=form,
username=user.username
)