-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathviews.py
200 lines (163 loc) · 5.99 KB
/
views.py
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
from hashlib import sha1
from random import random
from datetime import datetime, timedelta
from django.views import generic
from django.shortcuts import HttpResponseRedirect
from django.core.mail import send_mail
from django.template.loader import get_template
from django.contrib import messages
from django.contrib.auth import login
from django.utils import timezone
from django.contrib.auth import (
models as auth_models,
views as auth_views
)
try:
from django.core.urlresolvers import reverse_lazy, reverse
except ImportError:
from django.urls import reverse_lazy, reverse
from . import (
models,
conf,
mixins,
forms
)
class Login(auth_views.LoginView):
template_name = "{}/log-in.html".format(conf.AUTH_TEMPLATE_FOLDER)
form_class = forms.CustomLogIn
def get_context_data(self, **kwargs):
context = super(Login, self).get_context_data(**kwargs)
context['password_reset_allowed'] = conf.AUTH_ALLOW_PASSWORD_RECOVERY
context['registration_allowed'] = conf.AUTH_ALLOW_SIGNUP
context['login_reversed_url'] = reverse_lazy(conf.LOGIN_URL)
context['password_reset_reversed_url'] = reverse_lazy(conf.RESET_PASSWORD_URL)
context['signup_reversed_url'] = reverse_lazy(conf.SIGNUP_URL)
context['logout_reversed_url'] = reverse_lazy(conf.LOGOUT_URL)
return context
class SignUp(
mixins.AlreadyAuthenticatedMixin,
generic.CreateView
):
"""
Custom Sign up view. Sends a mail for email verification
"""
template_name = '{}/sign-up.html'.format(conf.AUTH_TEMPLATE_FOLDER)
form_class = conf.AUTH_USER_SIGNUP_FORM
send_confirmation_mail = conf.AUTH_VERIFY_EMAIL
def get_context_data(self, **kwargs):
context = super(SignUp, self).get_context_data(**kwargs)
context['logout_reversed_url'] = reverse_lazy(conf.LOGOUT_URL)
return context
@staticmethod
def save_user(userform):
if userform.is_valid():
user = userform.save(commit=False)
user.set_password(userform.cleaned_data['password'])
user.save()
return user
return None
@staticmethod
def create_profile(user):
username = user.username
email = user.email
salt = sha1(str(random()).encode("UTF-8")).hexdigest()[:5]
activation_key = sha1((salt+email).encode("UTF-8")).hexdigest()
today = timezone.make_aware(datetime.today(), timezone.get_current_timezone())
key_expires = today + timedelta(2)
# Get user by username
user = auth_models.User.objects.get(username=username)
# Create and save user profile
user_profile = models.UserProfile(
user=user,
activation_token=activation_key,
expiration=key_expires
)
user_profile.save()
return user_profile
@staticmethod
def send_mail(user_profile):
activation_key = user_profile.activation_token
email = user_profile.user.email
# Send email with activation key
url = "%s%s" % (
conf.AUTH_DOMAIN,
reverse(
'sign_up_confirm',
kwargs={
'token': activation_key
})
)
context = {
'url': url
}
email_subject = conf.AUTH_EMAIL_SUBJECT
email_body = conf.AUTH_EMAIL_BODY + url
template = get_template('{}/email-signup-confirmation.html'.format(conf.AUTH_TEMPLATE_FOLDER))
send_mail(
email_subject,
email_body,
conf.AUTH_EMAIL_FROM,
[email],
fail_silently=False,
html_message=template.render(context))
def form_valid(self, form):
user = self.save_user(form)
if user is None:
return self.form_invalid(form)
user_profile = self.create_profile(user)
if self.send_confirmation_mail:
self.send_mail(user_profile)
messages.add_message(
self.request,
messages.INFO,
message=conf.AUTH_CONFIRM_ACCOUNT
)
return HttpResponseRedirect(reverse_lazy(conf.AUTH_INDEX_URL_NAME))
else:
user.is_active = True
user.save()
login(self.request, user)
return HttpResponseRedirect(self.get_next_page())
def form_invalid(self, form):
print("User is NONE")
messages.add_message(
self.request,
messages.ERROR,
message=conf.AUTH_USER_CANT_BE_CREATED
)
return self.render_to_response(
{
"form": form
}
)
def get_next_page(self):
if (conf.AUTH_REDIRECT_FIELD_NAME in self.request.POST or
conf.AUTH_REDIRECT_FIELD_NAME in self.request.GET):
next_page = self.request.POST.get(
conf.AUTH_REDIRECT_FIELD_NAME,
self.request.GET.get(conf.AUTH_REDIRECT_FIELD_NAME)
)
return next_page
return reverse_lazy(conf.AUTH_INDEX_URL_NAME)
class SignUpConfirm(
mixins.AlreadyAuthenticatedMixin,
generic.TemplateView
):
"""
Account verification view. Validates the token and activates the user for the platform
"""
template_name = '{}/sign-up-confirm.html'.format(conf.AUTH_TEMPLATE_FOLDER)
def get_context_data(self, **kwargs):
context = super(SignUpConfirm, self).get_context_data(**kwargs)
try:
activation_token = models.UserProfile.objects.get(activation_token=self.kwargs['token'])
if activation_token.expiration < timezone.now():
context['status'] = conf.EXPIRED_URL
else:
user = activation_token.user
user.is_active = True
user.save()
context['status'] = conf.AUTH_ACCOUNT_CONFIRMATION_SUCCESSFUL
except models.UserProfile.DoesNotExist:
context['status'] = conf.INVALID_URL
return context