summaryrefslogtreecommitdiff
path: root/app/views/user.py
blob: cb97136124c814c16760b2ff0d8af032268dd297 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# -*- encoding: utf-8 -*-
from . import Blueprint, flash, db, \
        current_user, login_required, \
        templated, redirect, request, url_for

from .. import forms as F
from ..login import login_user, logout_user, login_manager, User

import flask

mod = Blueprint('user', __name__)

#
# Forms
#
class LoginForm(F.Form):
    username = F.StringField(u'Username', F.req)
    pwd = F.PasswordField(u'Passwort', F.req)
    remember = F.BooleanField(u'Eingeloggt bleiben?')

    def __init__(self, *args, **kwargs):
        super(LoginForm, self).__init__(*args, **kwargs)
        self.user = None

    def validate(self):
        rv = super(LoginForm, self).validate()
        if not rv:
            return False

        user = User.get_by(name = self.username.data)
        if user is None or not user.check_password(self.pwd.data):
            return False

        self.user = user
        return True


class ChangePwdForm(F.Form):
    old = F.PasswordField(u'Passwort', F.req)
    new = F.PasswordField(u'Neues Passwort', F.req + [F.validators.EqualTo('confirm', u'Passwörter stimmen nicht überein')])
    confirm = F.PasswordField(u'Wdh. neues Passwort', F.req)

    def validate_old(self, field):
        if not current_user.check_password(field.data):
            raise F.ValidationError(u"Falsches Passwort")

    @property
    def newpwd(self):
        return self.new.data

#
# Views
#
@mod.route('/login', methods=('GET', 'POST'))
@templated
def login():
    """Log the user in."""
    form = LoginForm(flash=u"Login fehlgeschlagen!")
    if form.validate_on_submit():
        login_user(form.user, remember=form.remember.data)
        # we explicitly need flask's variant as we redirect to a URI
        return flask.redirect(request.args.get('next') or url_for('index'))
    return { 'form': form }


@mod.route('/logout')
def logout():
    """Log the user out."""
    logout_user()
    return redirect('.login')


@mod.route('/cpw', methods=('GET', 'POST'))
@login_required
@templated
def cpw():
    """Change the password of the user."""
    form = ChangePwdForm()

    if form.validate_on_submit():
        current_user.set_password(form.newpwd)
        db.session.commit()
        flash(u"Passwort geändert.")
        return redirect('index')

    return { 'form': form }

# set this, so the user is redirected to the correct view, when not logged in
login_manager.login_view = 'user.login'