aboutsummaryrefslogtreecommitdiff
path: root/fietsboek/views/default.py
blob: 0170e02c4382ca46605830d0a39771dbf04cc5c1 (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
"""Home views."""
from pyramid.view import view_config
from pyramid.httpexceptions import HTTPFound
from pyramid.security import remember, forget
from pyramid.i18n import TranslationString as _

from sqlalchemy.exc import NoResultFound

from .. import models, summaries, util
from ..models.user import PasswordMismatch


@view_config(route_name='home', renderer='fietsboek:templates/home.jinja2')
def home(request):
    """Renders the home page.

    :param request: The Pyramid request.
    :type request: pyramid.request.Request
    :return: The HTTP response.
    :rtype: pyramid.response.Response
    """
    if not request.identity:
        return {}

    all_tracks = request.identity.all_tracks
    summary = summaries.Summary()

    for track in all_tracks:
        track.ensure_cache()
        request.dbsession.add(track.cache)
        summary.add(track)

    return {
        'summary': summary,
        'month_name': util.month_name,
    }


@view_config(route_name='login', renderer='fietsboek:templates/login.jinja2', request_method='GET')
def login(request):
    """Renders the login page.

    :param request: The Pyramid request.
    :type request: pyramid.request.Request
    :return: The HTTP response.
    :rtype: pyramid.response.Response
    """
    # pylint: disable=unused-argument
    return {}


@view_config(route_name='login', request_method='POST')
def do_login(request):
    """Endpoint for the login form.

    :param request: The Pyramid request.
    :type request: pyramid.request.Request
    :return: The HTTP response.
    :rtype: pyramid.response.Response
    """
    query = models.User.query_by_email(request.params['email'])
    try:
        user = request.dbsession.execute(query).scalar_one()
        user.check_password(request.params['password'])
    except (NoResultFound, PasswordMismatch):
        request.session.flash(request.localizer.translate(_('flash.invalid_credentials')))
        return HTTPFound(request.route_url('login'))

    request.session.flash(request.localizer.translate(_('flash.logged_in')))
    headers = remember(request, str(user.id))
    return HTTPFound('/', headers=headers)


@view_config(route_name='logout')
def logout(request):
    """Logs the user out.

    :param request: The Pyramid request.
    :type request: pyramid.request.Request
    :return: The HTTP response.
    :rtype: pyramid.response.Response
    """
    request.session.flash(request.localizer.translate(_('flash.logged_out')))
    headers = forget(request)
    return HTTPFound('/', headers=headers)