hanze/muizenval

server/routes.py in master
Repositories | Summary | Log | Files

routes.py (6888B) download


  1from flask import flash, redirect, render_template, request, url_for
  2from flask_login import current_user, login_required, login_user, logout_user
  3from PIL import Image
  4
  5from .app import app, bcrypt, db
  6from .forms import AdminForm, LoginForm, RegistrationForm, SearchForm, UpdateAccountForm, UpdateTrapForm
  7from .models import Trap, User
  8
  9import secrets
 10import os
 11
 12current_user: User
 13
 14
 15# index.html (home-page) route
 16@app.route("/")
 17def index():
 18    return render_template('index.html')
 19
 20# about.html route
 21
 22
 23@app.route("/about")
 24def about():
 25    return render_template('about.html')
 26
 27# register.html route
 28
 29
 30@app.route("/register", methods=['GET', 'POST'])
 31def register():
 32    if current_user.is_authenticated:
 33        flash('U bent al ingelogd', 'warning')
 34        return redirect('/')
 35
 36    form = RegistrationForm()
 37    if form.validate_on_submit():
 38        hashed_password = bcrypt.generate_password_hash(
 39            form.password.data).decode('utf-8')
 40        address = f"{form.street} {form.housenumber}\n{form.postcode} {form.place}"
 41        user = User(
 42            name=form.name.data,
 43            email=form.email.data,
 44            password=hashed_password,
 45            phone=form.phone.data,
 46            address=address
 47        )
 48        db.session.add(user)
 49        db.session.commit()
 50        flash('Uw profiel is toegevoegd! U kunt nu inloggen.', 'success')
 51        return redirect(url_for('login'))
 52    return render_template('register.html', title='Registeren', form=form)
 53
 54
 55# login.html route
 56@app.route("/login", methods=['GET', 'POST'])
 57def login():
 58    if current_user.is_authenticated:
 59        flash('U bent al ingelogd', 'warning')
 60        return redirect('/')
 61    form = LoginForm()
 62    if form.validate_on_submit():
 63        user = User.query.filter_by(email=form.email.data).first()
 64        if user and bcrypt.check_password_hash(user.password, form.password.data):
 65            login_user(user, remember=form.remember.data)
 66            if bcrypt.check_password_hash(user.password, form.email.data):
 67                flash(
 68                    'Wij raden u aan om uw wachtwoord te veranderen', 'warning')
 69            next_page = request.args.get('next')
 70            return redirect(next_page if next_page else '/')
 71        else:
 72            flash('Inloggen mislukt, is uw e-mail en/of wachtwoord juist?', 'danger')
 73    return render_template('login.html', title='Inloggen', form=form)
 74
 75
 76# logout route
 77@app.route("/logout")
 78def logout():
 79    logout_user()
 80    return redirect('/')
 81
 82
 83# save-picture function for account.html
 84def save_picture(form_picture):
 85    random_hex = secrets.token_hex(8)
 86    _, f_ext = os.path.splitext(form_picture.filename)
 87    picture_fn = random_hex + f_ext
 88    picturepath = os.path.join(
 89        app.root_path, 'static/profile_pics', picture_fn)
 90
 91    output_size = (125, 125)
 92    i = Image.open(form_picture)
 93    i.thumbnail(output_size)
 94    i.save(picturepath)
 95
 96    return picture_fn
 97
 98
 99""" account.html route """
100
101
102@app.route("/user/self", methods=['GET', 'POST'])
103@login_required
104def account():
105    form = UpdateAccountForm()
106    if form.validate_on_submit():
107        current_user.name = form.name.data
108        current_user.email = form.email.data
109        if form.picture.data:
110            picture_file = save_picture(form.picture.data)
111            current_user.image_file = picture_file
112        if form.password.data:
113            current_user.password = bcrypt.generate_password_hash(
114                form.password.data).decode('utf-8')
115        db.session.commit()
116        flash('Uw profiel is bewerkt!', 'success')
117        return redirect(url_for('account'))
118
119    elif request.method == 'GET':
120        form.name.data = current_user.name
121        form.email.data = current_user.email
122    image_file = url_for(
123        'static', filename='profile_pics/' + current_user.image_file)
124    return render_template('account.html',  title='Profiel', image_file=image_file, form=form)
125
126
127@app.route('/traps')
128@login_required
129def traps():
130    return render_template('trap.html')
131
132
133@app.route('/contact')
134@login_required
135def contact():
136    return render_template('contact.html', contact=current_user.contact_class())
137
138
139""" admin.html route """
140
141
142@app.route("/users", methods=['GET', 'POST'])
143@login_required
144def admin():
145    if not current_user.admin:
146        flash('U mag deze website niet bereiken', 'error')
147        return redirect('/')
148    form = SearchForm()
149    if form.validate_on_submit():
150        user = User.query.filter_by(name=form.username.data).first()
151        if user == None:
152            flash(
153                f'Geen gebrukers gevonden met de gebruikersnaam: {form.username.data}!', 'danger')
154        else:
155            flash(
156                f'Gebruiker gevonden met gebruikersnaam: {form.username.data}!', 'success')
157            return redirect(url_for('admin_user', user_id=user.id))
158    return render_template('admin.html', form=form)
159
160
161""" account-admin route """
162
163
164@app.route("/user/<int:user_id>", methods=['GET', 'POST'])
165@login_required
166def admin_user(user_id):
167    if not current_user.admin:
168        flash('U mag deze website niet bereiken', 'error')
169        return redirect('/')
170    form = AdminForm()
171    user = User.query.filter_by(id=user_id).first()
172    image_file = url_for('static', filename='profile_pics/' + user.image_file)
173    if form.validate_on_submit():
174        user.admin = form.type.data == 'admin'
175        db.session.commit()
176        flash(f'De gebruiker {user.username} is nu een {user.type}', 'success')
177        return redirect(url_for('admin'))
178    elif request.method == 'GET':
179        form.type.data = 'admin' if user.admin else 'client'
180    return render_template('admin_user.html', form=form, user=user, image_file=image_file)
181
182
183""" delete-user route """
184
185
186@app.route("/user/<int:user_id>/delete", methods=['GET', 'POST'])
187@login_required
188def delete_user(user_id):
189    if not current_user.admin:
190        flash('U mag deze website niet bereiken', 'danger')
191        return redirect('/')
192    user = User.query.get_or_404(user_id)
193    db.session.delete(user)
194    db.session.commit()
195    flash(f'De gebruiker {user.username} is verwijderd', 'success')
196    return redirect(url_for('admin'))
197
198
199""" reset user's password route """
200
201
202@app.route("/user/<int:user_id>/reset", methods=['GET', 'POST'])
203@login_required
204def reset_user(user_id):
205    if not current_user.admin:
206        flash('U mag deze website niet bereiken', 'danger')
207        return redirect('/')
208    user = User.query.get_or_404(user_id)
209    user.password = bcrypt.generate_password_hash(user.email).decode('utf-8')
210    db.session.commit()
211    flash(f'{user.name}\'s wachtwoord is nu zijn/haar e-mail', 'success')
212    return redirect(url_for('admin'))
213
214
215""" 404 not found handler """
216
217
218@app.errorhandler(404)
219def not_found(error):
220    flash(f"De pagina is niet gevonden", 'danger')
221    return index()  # geen redirect om de '/bla' te houden