login.py 1.83 KB
Newer Older
Cédric Bonhomme's avatar
Cédric Bonhomme committed
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
#! /usr/bin/env python
#-*- coding: utf-8 -*-

# ***** BEGIN LICENSE BLOCK *****
# This file is part of Shelter Database.
# Copyright (c) 2016
# All rights reserved.
#
#
#
# ***** END LICENSE BLOCK *****

__author__ = "Cedric Bonhomme"
__version__ = "$Revision: 0.1 $"
__date__ = "$Date: 2016/03/30$"
__revision__ = "$Date: 2016/03/30 $"
__copyright__ = "Copyright (c) "
__license__ = ""

from flask.ext.wtf import Form
from flask import url_for, redirect
from wtforms import validators, TextField, PasswordField, BooleanField, \
                    SubmitField, HiddenField

from web.models import User
from web.lib import utils

class RedirectForm(Form):
    """
    Secure back redirects with WTForms.
    """
    next = HiddenField()

    def __init__(self, *args, **kwargs):
        Form.__init__(self, *args, **kwargs)
        if not self.next.data:
            self.next.data = utils.get_redirect_target() or ''

    def redirect(self, endpoint='start', **values):
        if utils.is_safe_url(self.next.data):
            return redirect(self.next.data)
        target = utils.get_redirect_target()
        return redirect(target or url_for(endpoint, **values))

class LoginForm(RedirectForm):
    """
    Login form.
    """
    name = TextField("Name",
        [validators.Required("Please enter your name.")])
    password = PasswordField('Password',
        [validators.Required("Please enter a password.")])
    remember_me = BooleanField("Remember me", default=False)
    submit = SubmitField("Log In")

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

        user = User.query.filter(User.name==self.name.data).first()
        if user and user.check_password(self.password.data):
            return True
        else:
            self.name.errors.append("Invalid name or password")
            return False