|
1
|
|
|
# -*- encoding: utf-8 -*- |
|
2
|
|
|
import datetime |
|
3
|
|
|
import json |
|
4
|
|
|
|
|
5
|
|
|
import os |
|
6
|
|
|
from django.conf import settings |
|
7
|
|
|
from django.contrib.auth import authenticate |
|
8
|
|
|
from django.contrib.auth import login as djangologin |
|
9
|
|
|
from django.contrib.auth import logout as djangologout |
|
10
|
|
|
|
|
11
|
|
|
from chat.templatetags.md5url import md5url |
|
12
|
|
|
|
|
13
|
|
|
try: |
|
14
|
|
|
from django.template.context_processors import csrf |
|
15
|
|
|
except ImportError: |
|
16
|
|
|
from django.core.context_processors import csrf |
|
17
|
|
|
from django.core.exceptions import ObjectDoesNotExist, ValidationError |
|
18
|
|
|
from django.db import transaction |
|
19
|
|
|
from django.db.models import Count, Q, F |
|
20
|
|
|
from django.http import Http404 |
|
21
|
|
|
from django.utils.timezone import utc |
|
22
|
|
|
from django.http import HttpResponse |
|
23
|
|
|
from django.http import HttpResponseRedirect |
|
24
|
|
|
from django.shortcuts import render_to_response |
|
25
|
|
|
from django.template import RequestContext |
|
26
|
|
|
from django.views.decorators.http import require_http_methods |
|
27
|
|
|
from django.views.generic import View |
|
28
|
|
|
from chat import utils |
|
29
|
|
|
from chat.decorators import login_required_no_redirect |
|
30
|
|
|
from chat.forms import UserProfileForm, UserProfileReadOnlyForm |
|
31
|
|
|
from chat.models import Issue, IssueDetails, IpAddress, UserProfile, Verification, Message, Subscription |
|
32
|
|
|
from chat.settings import VALIDATION_IS_OK, DATE_INPUT_FORMATS_JS, logging, EXTENSION_ID, EXTENSION_INSTALL_URL, \ |
|
33
|
|
|
ALL_ROOM_ID, STATIC_ROOT |
|
34
|
|
|
from chat.utils import hide_fields, check_user, check_password, check_email, extract_photo, send_sign_up_email, \ |
|
35
|
|
|
create_user_model, check_captcha, send_reset_password_email |
|
36
|
|
|
|
|
37
|
|
|
logger = logging.getLogger(__name__) |
|
38
|
|
|
RECAPTCHA_SITE_KEY = getattr(settings, "RECAPTCHA_SITE_KEY", None) |
|
39
|
|
|
RECAPTHCA_SITE_URL = getattr(settings, "RECAPTHCA_SITE_URL", None) |
|
40
|
|
|
GOOGLE_OAUTH_2_CLIENT_ID = getattr(settings, "GOOGLE_OAUTH_2_CLIENT_ID", None) |
|
41
|
|
|
GOOGLE_OAUTH_2_JS_URL = getattr(settings, "GOOGLE_OAUTH_2_JS_URL", None) |
|
42
|
|
|
FACEBOOK_APP_ID = getattr(settings, "FACEBOOK_APP_ID", None) |
|
43
|
|
|
FACEBOOK_JS_URL = getattr(settings, "FACEBOOK_JS_URL", None) |
|
44
|
|
|
FIREBASE_API_KEY = getattr(settings, "FIREBASE_API_KEY", None) |
|
45
|
|
|
|
|
46
|
|
|
# TODO doesn't work |
|
47
|
|
|
def handler404(request): |
|
48
|
|
|
return HttpResponse("Page not found", content_type='text/plain') |
|
49
|
|
|
|
|
50
|
|
|
|
|
51
|
|
|
@require_http_methods(['POST']) |
|
52
|
|
|
def validate_email(request): |
|
53
|
|
|
""" |
|
54
|
|
|
POST only, validates email during registration |
|
55
|
|
|
""" |
|
56
|
|
|
email = request.POST.get('email') |
|
57
|
|
|
try: |
|
58
|
|
|
utils.check_email(email) |
|
59
|
|
|
response = VALIDATION_IS_OK |
|
60
|
|
|
except ValidationError as e: |
|
61
|
|
|
response = e.message |
|
62
|
|
|
return HttpResponse(response, content_type='text/plain') |
|
63
|
|
|
|
|
64
|
|
|
|
|
65
|
|
|
@require_http_methods('GET') |
|
66
|
|
|
def get_firebase_playback(request): |
|
67
|
|
|
registration_id = request.META['HTTP_AUTH'] |
|
68
|
|
|
user_id = Subscription.objects.values_list('user_id', flat=True).get(registration_id=registration_id) |
|
69
|
|
|
off_mess = Message.objects.filter( |
|
70
|
|
|
id__gt=F('room__roomusers__last_read_message_id'), |
|
71
|
|
|
deleted=False, |
|
72
|
|
|
room__roomusers__user_id=user_id |
|
73
|
|
|
) |
|
74
|
|
|
d = off_mess.select_related("sender__username").order_by("-time")[:1] |
|
75
|
|
|
message = list(d)[0] |
|
76
|
|
|
data = { |
|
77
|
|
|
'title': message.sender.username, |
|
78
|
|
|
'options': { |
|
79
|
|
|
'body': message.content, |
|
80
|
|
|
'icon': md5url('images/favicon.ico'), |
|
81
|
|
|
'data': { |
|
82
|
|
|
'url': '/#/chat/' + str(message.room_id) |
|
83
|
|
|
} |
|
84
|
|
|
}, |
|
85
|
|
|
} |
|
86
|
|
|
response = HttpResponse(json.dumps(data), content_type='application/json') |
|
87
|
|
|
return response |
|
88
|
|
|
|
|
89
|
|
|
|
|
90
|
|
|
@require_http_methods('POST') |
|
91
|
|
|
def register_subscription(request): |
|
92
|
|
|
registration_id = request.POST['registration_id'] |
|
93
|
|
|
Subscription.objects.update_or_create(registration_id=registration_id, user=request.user) |
|
94
|
|
|
return HttpResponse(VALIDATION_IS_OK, content_type='text/plain') |
|
95
|
|
|
|
|
96
|
|
|
@require_http_methods('POST') |
|
97
|
|
|
def validate_user(request): |
|
98
|
|
|
""" |
|
99
|
|
|
Validates user during registration |
|
100
|
|
|
""" |
|
101
|
|
|
try: |
|
102
|
|
|
username = request.POST.get('username') |
|
103
|
|
|
utils.check_user(username) |
|
104
|
|
|
# hardcoded ok check in register.js |
|
105
|
|
|
message = VALIDATION_IS_OK |
|
106
|
|
|
except ValidationError as e: |
|
107
|
|
|
message = e.message |
|
108
|
|
|
return HttpResponse(message, content_type='text/plain') |
|
109
|
|
|
|
|
110
|
|
|
|
|
111
|
|
|
def get_service_worker(request): # this stub is only for development, this is replaced in nginx for prod |
|
112
|
|
|
worker = open(os.path.join(STATIC_ROOT, 'js', 'sw.js'), 'rb') |
|
113
|
|
|
response = HttpResponse(content=worker) |
|
114
|
|
|
response['Content-Type'] = 'application/javascript' |
|
115
|
|
|
return response |
|
116
|
|
|
|
|
117
|
|
|
@require_http_methods('GET') |
|
118
|
|
|
@login_required_no_redirect(False) |
|
119
|
|
|
def home(request): |
|
120
|
|
|
""" |
|
121
|
|
|
Login or logout navbar is creates by means of create_nav_page |
|
122
|
|
|
@return: the x intercept of the line M{y=m*x+b}. |
|
123
|
|
|
""" |
|
124
|
|
|
context = csrf(request) |
|
125
|
|
|
up = UserProfile.objects.defer('suggestions', 'notifications', 'cache_messages', 'highlight_code', 'embedded_youtube').get(id=request.user.id) |
|
126
|
|
|
context['suggestions'] = up.suggestions |
|
127
|
|
|
context['notifications'] = up.notifications |
|
128
|
|
|
context['cache_messages'] = up.cache_messages |
|
129
|
|
|
context['highlight_code'] = up.highlight_code |
|
130
|
|
|
context['embedded_youtube'] = up.embedded_youtube |
|
131
|
|
|
context['extensionId'] = EXTENSION_ID |
|
132
|
|
|
context['extensionUrl'] = EXTENSION_INSTALL_URL |
|
133
|
|
|
context['defaultRoomId'] = ALL_ROOM_ID |
|
134
|
|
|
context['manifest'] = FIREBASE_API_KEY is not None |
|
135
|
|
|
return render_to_response('chat.html', context, context_instance=RequestContext(request)) |
|
136
|
|
|
|
|
137
|
|
|
|
|
138
|
|
|
@login_required_no_redirect(True) |
|
139
|
|
|
def logout(request): |
|
140
|
|
|
""" |
|
141
|
|
|
POST. Logs out into system. |
|
142
|
|
|
""" |
|
143
|
|
|
djangologout(request) |
|
144
|
|
|
return HttpResponseRedirect('/') |
|
145
|
|
|
|
|
146
|
|
|
@require_http_methods(['POST']) |
|
147
|
|
|
def auth(request): |
|
148
|
|
|
""" |
|
149
|
|
|
Logs in into system. |
|
150
|
|
|
""" |
|
151
|
|
|
username = request.POST.get('username') |
|
152
|
|
|
password = request.POST.get('password') |
|
153
|
|
|
user = authenticate(username=username, password=password) |
|
154
|
|
|
if user is not None: |
|
155
|
|
|
djangologin(request, user) |
|
156
|
|
|
message = VALIDATION_IS_OK |
|
157
|
|
|
else: |
|
158
|
|
|
message = 'Login or password is wrong' |
|
159
|
|
|
logger.debug('Auth request %s ; Response: %s', hide_fields(request.POST, ('password',)), message) |
|
160
|
|
|
return HttpResponse(message, content_type='text/plain') |
|
161
|
|
|
|
|
162
|
|
|
|
|
163
|
|
|
def send_restore_password(request): |
|
164
|
|
|
""" |
|
165
|
|
|
Sends email verification code |
|
166
|
|
|
""" |
|
167
|
|
|
logger.debug('Recover password request %s', request) |
|
168
|
|
|
try: |
|
169
|
|
|
username_or_password = request.POST.get('username_or_password') |
|
170
|
|
|
check_captcha(request) |
|
171
|
|
|
user_profile = UserProfile.objects.get(Q(username=username_or_password) | Q(email=username_or_password)) |
|
172
|
|
|
if not user_profile.email: |
|
173
|
|
|
raise ValidationError("You didn't specify email address for this user") |
|
174
|
|
|
verification = Verification(type_enum=Verification.TypeChoices.password, user_id=user_profile.id) |
|
175
|
|
|
verification.save() |
|
176
|
|
|
send_reset_password_email(request, user_profile, verification) |
|
177
|
|
|
message = VALIDATION_IS_OK |
|
178
|
|
|
logger.debug('Verification email has been send for token %s to user %s(id=%d)', |
|
179
|
|
|
verification.token, user_profile.username, user_profile.id) |
|
180
|
|
|
except UserProfile.DoesNotExist: |
|
181
|
|
|
message = "User with this email or username doesn't exist" |
|
182
|
|
|
logger.debug("Skipping password recovery request for nonexisting user") |
|
183
|
|
|
except (UserProfile.DoesNotExist, ValidationError) as e: |
|
184
|
|
|
logger.debug('Not sending verification email because %s', e) |
|
185
|
|
|
message = 'Unfortunately we were not able to send you restore password email because {}'.format(e) |
|
186
|
|
|
return HttpResponse(message, content_type='text/plain') |
|
187
|
|
|
|
|
188
|
|
|
|
|
189
|
|
|
def get_html_restore_pass(): |
|
190
|
|
|
"""""" |
|
191
|
|
|
|
|
192
|
|
|
class RestorePassword(View): |
|
193
|
|
|
|
|
194
|
|
|
def get_user_by_code(self, token): |
|
195
|
|
|
""" |
|
196
|
|
|
:param token: token code to verify |
|
197
|
|
|
:type token: str |
|
198
|
|
|
:raises ValidationError: if token is not usable |
|
199
|
|
|
:return: UserProfile, Verification: if token is usable |
|
200
|
|
|
""" |
|
201
|
|
|
try: |
|
202
|
|
|
v = Verification.objects.get(token=token) |
|
203
|
|
|
if v.type_enum != Verification.TypeChoices.password: |
|
204
|
|
|
raise ValidationError("it's not for this operation ") |
|
205
|
|
|
if v.verified: |
|
206
|
|
|
raise ValidationError("it's already used") |
|
207
|
|
|
# TODO move to sql query or leave here? |
|
208
|
|
|
if v.time < datetime.datetime.utcnow().replace(tzinfo=utc) - datetime.timedelta(days=1): |
|
209
|
|
|
raise ValidationError("it's expired") |
|
210
|
|
|
return UserProfile.objects.get(id=v.user_id), v |
|
211
|
|
|
except Verification.DoesNotExist: |
|
212
|
|
|
raise ValidationError('Unknown verification token') |
|
213
|
|
|
|
|
214
|
|
|
@transaction.atomic |
|
215
|
|
|
def post(self, request): |
|
216
|
|
|
""" |
|
217
|
|
|
Sends email verification token |
|
218
|
|
|
""" |
|
219
|
|
|
token = request.POST.get('token', False) |
|
220
|
|
|
try: |
|
221
|
|
|
logger.debug('Proceed Recover password with token %s', token) |
|
222
|
|
|
user, verification = self.get_user_by_code(token) |
|
223
|
|
|
password = request.POST.get('password') |
|
224
|
|
|
check_password(password) |
|
225
|
|
|
user.set_password(password) |
|
226
|
|
|
user.save(update_fields=('password',)) |
|
227
|
|
|
verification.verified = True |
|
228
|
|
|
verification.save(update_fields=('verified',)) |
|
229
|
|
|
logger.info('Password has been change for token %s user %s(id=%d)', token, user.username, user.id) |
|
230
|
|
|
response = VALIDATION_IS_OK |
|
231
|
|
|
except ValidationError as e: |
|
232
|
|
|
logger.debug('Rejecting verification token %s because %s', token, e) |
|
233
|
|
|
response = "".join(("You can't reset password with this token because ", str(e))) |
|
234
|
|
|
return HttpResponse(response, content_type='text/plain') |
|
235
|
|
|
|
|
236
|
|
|
def get(self, request): |
|
237
|
|
|
token = request.GET.get('token', False) |
|
238
|
|
|
logger.debug('Rendering restore password page with token %s', token) |
|
239
|
|
|
try: |
|
240
|
|
|
user = self.get_user_by_code(token)[0] |
|
241
|
|
|
response = { |
|
242
|
|
|
'message': VALIDATION_IS_OK, |
|
243
|
|
|
'restore_user': user.username, |
|
244
|
|
|
'token': token |
|
245
|
|
|
} |
|
246
|
|
|
except ValidationError as e: |
|
247
|
|
|
logger.debug('Rejecting verification token %s because %s', token, e) |
|
248
|
|
|
response = {'message': "Unable to confirm email with token {} because {}".format(token, e)} |
|
249
|
|
|
return render_to_response('reset_password.html', response, context_instance=RequestContext(request)) |
|
250
|
|
|
|
|
251
|
|
|
|
|
252
|
|
|
@require_http_methods('GET') |
|
253
|
|
|
def confirm_email(request): |
|
254
|
|
|
""" |
|
255
|
|
|
Accept the verification token sent to email |
|
256
|
|
|
""" |
|
257
|
|
|
token = request.GET.get('token', False) |
|
258
|
|
|
logger.debug('Processing email confirm with token %s', token) |
|
259
|
|
|
try: |
|
260
|
|
|
try: |
|
261
|
|
|
v = Verification.objects.get(token=token) |
|
262
|
|
|
except Verification.DoesNotExist: |
|
263
|
|
|
raise ValidationError('Unknown verification token') |
|
264
|
|
|
if v.type_enum != Verification.TypeChoices.register: |
|
265
|
|
|
raise ValidationError('This is not confirm email token') |
|
266
|
|
|
if v.verified: |
|
267
|
|
|
raise ValidationError('This verification token already accepted') |
|
268
|
|
|
user = UserProfile.objects.get(id=v.user_id) |
|
269
|
|
|
if user.email_verification_id != v.id: |
|
270
|
|
|
raise ValidationError('Verification token expired because you generated another one') |
|
271
|
|
|
v.verified = True |
|
272
|
|
|
v.save(update_fields=['verified']) |
|
273
|
|
|
message = VALIDATION_IS_OK |
|
274
|
|
|
logger.info('Email verification token %s has been accepted for user %s(id=%d)', token, user.username, user.id) |
|
275
|
|
|
except Exception as e: |
|
276
|
|
|
logger.debug('Rejecting verification token %s because %s', token, e) |
|
277
|
|
|
message = ("Unable to confirm email with token {} because {}".format(token, e)) |
|
278
|
|
|
response = {'message': message} |
|
279
|
|
|
return render_to_response('confirm_mail.html', response, context_instance=RequestContext(request)) |
|
280
|
|
|
|
|
281
|
|
|
|
|
282
|
|
|
@require_http_methods('GET') |
|
283
|
|
|
def show_profile(request, profile_id): |
|
284
|
|
|
try: |
|
285
|
|
|
user_profile = UserProfile.objects.get(pk=profile_id) |
|
286
|
|
|
form = UserProfileReadOnlyForm(instance=user_profile) |
|
287
|
|
|
form.username = user_profile.username |
|
288
|
|
|
return render_to_response( |
|
289
|
|
|
'show_profile.html', |
|
290
|
|
|
{'form': form}, |
|
291
|
|
|
context_instance=RequestContext(request) |
|
292
|
|
|
) |
|
293
|
|
|
except ObjectDoesNotExist: |
|
294
|
|
|
raise Http404 |
|
295
|
|
|
|
|
296
|
|
|
|
|
297
|
|
|
@require_http_methods('GET') |
|
298
|
|
|
def statistics(request): |
|
299
|
|
|
pie_data = IpAddress.objects.values('country').filter(country__isnull=False).annotate(count=Count("country")) |
|
300
|
|
|
return HttpResponse(json.dumps(list(pie_data)), content_type='application/json') |
|
301
|
|
|
|
|
302
|
|
|
|
|
303
|
|
|
@login_required_no_redirect() |
|
304
|
|
|
@transaction.atomic |
|
305
|
|
|
def report_issue(request): |
|
306
|
|
|
logger.info('Saving issue: %s', hide_fields(request.POST, ('log',), huge=True)) |
|
307
|
|
|
issue = Issue.objects.get_or_create(content=request.POST['issue'])[0] |
|
308
|
|
|
issue_details = IssueDetails( |
|
309
|
|
|
sender_id=request.user.id, |
|
310
|
|
|
browser=request.POST.get('browser'), |
|
311
|
|
|
issue=issue, |
|
312
|
|
|
log=request.POST.get('log') |
|
313
|
|
|
) |
|
314
|
|
|
issue_details.save() |
|
315
|
|
|
return HttpResponse(VALIDATION_IS_OK, content_type='text/plain') |
|
316
|
|
|
|
|
317
|
|
|
|
|
318
|
|
|
class ProfileView(View): |
|
319
|
|
|
|
|
320
|
|
|
@login_required_no_redirect() |
|
321
|
|
|
def get(self, request): |
|
322
|
|
|
user_profile = UserProfile.objects.get(pk=request.user.id) |
|
323
|
|
|
form = UserProfileForm(instance=user_profile) |
|
324
|
|
|
c = csrf(request) |
|
325
|
|
|
c['form'] = form |
|
326
|
|
|
c['date_format'] = DATE_INPUT_FORMATS_JS |
|
327
|
|
|
return render_to_response('change_profile.html', c, context_instance=RequestContext(request)) |
|
328
|
|
|
|
|
329
|
|
|
@login_required_no_redirect() |
|
330
|
|
|
def post(self, request): |
|
331
|
|
|
logger.info('Saving profile: %s', hide_fields(request.POST, ("base64_image", ), huge=True)) |
|
332
|
|
|
user_profile = UserProfile.objects.get(pk=request.user.id) |
|
333
|
|
|
image_base64 = request.POST.get('base64_image') |
|
334
|
|
|
|
|
335
|
|
|
if image_base64 is not None: |
|
336
|
|
|
image = extract_photo(image_base64) |
|
337
|
|
|
request.FILES['photo'] = image |
|
338
|
|
|
|
|
339
|
|
|
form = UserProfileForm(request.POST, request.FILES, instance=user_profile) |
|
340
|
|
|
if form.is_valid(): |
|
341
|
|
|
profile = form.save() |
|
342
|
|
|
response = profile. photo.url if 'photo' in request.FILES else VALIDATION_IS_OK |
|
343
|
|
|
else: |
|
344
|
|
|
response = form.errors |
|
345
|
|
|
return HttpResponse(response, content_type='text/plain') |
|
346
|
|
|
|
|
347
|
|
|
|
|
348
|
|
|
class RegisterView(View): |
|
349
|
|
|
|
|
350
|
|
|
def get(self, request): |
|
351
|
|
|
logger.debug( |
|
352
|
|
|
'Rendering register page with captcha site key %s and oauth key %s', |
|
353
|
|
|
RECAPTCHA_SITE_KEY, GOOGLE_OAUTH_2_CLIENT_ID |
|
354
|
|
|
) |
|
355
|
|
|
c = csrf(request) |
|
356
|
|
|
c['captcha_key'] = RECAPTCHA_SITE_KEY |
|
357
|
|
|
c['captcha_url'] = RECAPTHCA_SITE_URL |
|
358
|
|
|
c['oauth_url'] = GOOGLE_OAUTH_2_JS_URL |
|
359
|
|
|
c['oauth_token'] = GOOGLE_OAUTH_2_CLIENT_ID |
|
360
|
|
|
c['fb_app_id'] = FACEBOOK_APP_ID |
|
361
|
|
|
c['fb_js_url'] = FACEBOOK_JS_URL |
|
362
|
|
|
return render_to_response("register.html", c, context_instance=RequestContext(request)) |
|
363
|
|
|
|
|
364
|
|
|
@transaction.atomic |
|
365
|
|
|
def post(self, request): |
|
366
|
|
|
try: |
|
367
|
|
|
rp = request.POST |
|
368
|
|
|
logger.info('Got register request %s', hide_fields(rp, ('password', 'repeatpassword'))) |
|
369
|
|
|
(username, password, email) = (rp.get('username'), rp.get('password'), rp.get('email')) |
|
370
|
|
|
check_user(username) |
|
371
|
|
|
check_password(password) |
|
372
|
|
|
check_email(email) |
|
373
|
|
|
user_profile = UserProfile(username=username, email=email, sex_str=rp.get('sex')) |
|
374
|
|
|
user_profile.set_password(password) |
|
375
|
|
|
create_user_model(user_profile) |
|
376
|
|
|
# You must call authenticate before you can call login |
|
377
|
|
|
auth_user = authenticate(username=username, password=password) |
|
378
|
|
|
message = VALIDATION_IS_OK # redirect |
|
379
|
|
|
if email: |
|
380
|
|
|
send_sign_up_email(user_profile, request.get_host(), request) |
|
381
|
|
|
djangologin(request, auth_user) |
|
382
|
|
|
except ValidationError as e: |
|
383
|
|
|
message = e.message |
|
384
|
|
|
logger.debug('Rejecting request because "%s"', message) |
|
385
|
|
|
return HttpResponse(message, content_type='text/plain') |
|
386
|
|
|
|