Created
June 12, 2012 06:46
-
-
Save atkinson/2915665 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LoginForm(forms.Form): | |
password = PasswordField( | |
label = _("Password")) | |
remember = forms.BooleanField( | |
label = _("Remember Me"), | |
# help_text = _("If checked you will stay logged in for 3 weeks"), | |
required = False | |
) | |
user = None | |
def __init__(self, *args, **kwargs): | |
super(LoginForm, self).__init__(*args, **kwargs) | |
ordering = [] | |
if app_settings.EMAIL_AUTHENTICATION: | |
self.fields["email"] = forms.EmailField( | |
label = ugettext("E-mail"), | |
) | |
ordering.append("email") | |
else: | |
self.fields["username"] = forms.CharField( | |
label = ugettext("Username"), | |
max_length = 30, | |
) | |
ordering.append("username") | |
ordering.extend(["password", "remember"]) | |
self.fields.keyOrder = ordering | |
def user_credentials(self): | |
""" | |
Provides the credentials required to authenticate the user for | |
login. | |
""" | |
credentials = {} | |
if app_settings.EMAIL_AUTHENTICATION: | |
credentials["email"] = self.cleaned_data["email"] | |
else: | |
credentials["username"] = self.cleaned_data["username"] | |
credentials["password"] = self.cleaned_data["password"] | |
return credentials | |
def clean(self): | |
if self._errors: | |
return | |
user = authenticate(**self.user_credentials()) | |
if user: | |
if user.is_active: | |
self.user = user | |
else: | |
raise forms.ValidationError(_("This account is currently inactive.")) | |
else: | |
if app_settings.EMAIL_AUTHENTICATION: | |
error = _("The e-mail address and/or password you specified are not correct.") | |
else: | |
error = _("The username and/or password you specified are not correct.") | |
raise forms.ValidationError(error) | |
return self.cleaned_data | |
def login(self, request, redirect_url=None): | |
ret = perform_login(request, self.user, redirect_url=redirect_url) | |
if self.cleaned_data["remember"]: | |
request.session.set_expiry(60 * 60 * 24 * 7 * 3) | |
else: | |
request.session.set_expiry(0) | |
return ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment