Completed
Push — master ( a00ccb...2c6ba4 )
by Andrew
53s
created

ProfileView.send_email_if_needed()   B

Complexity

Conditions 5

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
c 1
b 0
f 0
dl 0
loc 16
rs 8.5454
1
# -*- encoding: utf-8 -*-
2
import datetime
3
import json
4
import logging
5
import os
6
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
from django.contrib.auth.hashers import make_password
11
from django.core.mail import mail_admins
12
13
from chat.templatetags.md5url import md5url
14
from chat.tornado.message_creator import MessagesCreator
15
16
try:
17
	from django.template.context_processors import csrf
18
except ImportError:
19
	from django.core.context_processors import csrf
20
from django.core.exceptions import ObjectDoesNotExist, ValidationError, PermissionDenied
21
from django.db import transaction
22
from django.db.models import Count, Q
23
from django.http import Http404
24
from django.http import HttpResponse
25
from django.shortcuts import render_to_response
26
from django.template import RequestContext
27
from django.views.decorators.http import require_http_methods
28
from django.views.generic import View
29
from chat import utils
30
from chat.decorators import login_required_no_redirect, validation
31
from chat.forms import UserProfileForm, UserProfileReadOnlyForm
32
from chat.models import Issue, IssueDetails, IpAddress, UserProfile, Verification, Message, Subscription, \
33
	SubscriptionMessages, RoomUsers, Room, UserJoinedInfo, UploadedFile
34
from django.conf import settings
35
from chat.utils import hide_fields, check_user, check_password, check_email, extract_photo, send_sign_up_email, \
36
	create_user_model, check_captcha, send_reset_password_email, get_client_ip, get_or_create_ip, \
37
	send_password_changed, send_email_change, send_new_email_ver, get_message_images_videos
38
39
logger = logging.getLogger(__name__)
40
RECAPTCHA_PUBLIC_KEY = getattr(settings, "RECAPTCHA_PUBLIC_KEY", None)
41
RECAPTHCA_SITE_URL = getattr(settings, "RECAPTHCA_SITE_URL", None)
42
GOOGLE_OAUTH_2_CLIENT_ID = getattr(settings, "GOOGLE_OAUTH_2_CLIENT_ID", None)
43
GOOGLE_OAUTH_2_JS_URL = getattr(settings, "GOOGLE_OAUTH_2_JS_URL", None)
44
FACEBOOK_APP_ID = getattr(settings, "FACEBOOK_APP_ID", None)
45
FACEBOOK_JS_URL = getattr(settings, "FACEBOOK_JS_URL", None)
46
47
# TODO doesn't work
48
def handler404(request):
49
	return HttpResponse("Page not found", content_type='text/plain')
50
51
52
@require_http_methods(['POST'])
53
@validation
54
def validate_email(request):
55
	"""
56
	POST only, validates email during registration
57
	"""
58
	utils.check_email(request.POST.get('email'))
59
	return HttpResponse(settings.VALIDATION_IS_OK, content_type='text/plain')
60
61
62
@require_http_methods(['POST'])
63
@login_required_no_redirect(False)
64
@transaction.atomic
65
def upload_file(request):
66
	"""
67
	POST only, validates email during registration
68
	"""
69
	logger.debug('Uploading file %s', request.POST)
70
	res = []
71
	for file in request.FILES:
72
		uf = UploadedFile(symbol=file[1], user=request.user, file=request.FILES[file], type_enum=UploadedFile.UploadedFileChoices(file[0]))
73
		uf.save()
74
		res.append(uf.id)
75
	return HttpResponse(json.dumps(res), content_type='application/json')
76
77
78
@require_http_methods(['POST'])
79
@login_required_no_redirect(False)
80
@transaction.atomic
81
def save_room_settings(request):
82
	"""
83
	POST only, validates email during registration
84
	"""
85
	logger.debug('save_room_settings request,  %s', request.POST)
86
	room_id = request.POST['roomId']
87
	room_name = request.POST.get('roomName')
88
	updated = RoomUsers.objects.filter(room_id=room_id, user_id=request.user.id).update(
89
		volume=request.POST['volume'],
90
		notifications=request.POST['notifications'] == 'true',
91
	)
92
	if updated != 1:
93
		raise PermissionDenied
94
	if room_name is not None:
95
		room_name = room_name.strip()
96
		if room_name and int(room_id) != settings.ALL_ROOM_ID:
97
			Room.objects.filter(id=room_id).update(name = room_name)
98
	return HttpResponse(settings.VALIDATION_IS_OK, content_type='text/plain')
99
100
101
@require_http_methods('GET')
102
@transaction.atomic
103
def get_firebase_playback(request):
104
	registration_id = request.META['HTTP_AUTH']
105
	logger.debug('Firebase playback, id %s', registration_id)
106
	query_sub_message = SubscriptionMessages.objects.filter(subscription__registration_id=registration_id, received=False).order_by('-message__time')[:1]
107
	sub_message = query_sub_message[0]
108
	SubscriptionMessages.objects.filter(id=sub_message.id).update(received=True)
109
	message = Message.objects.select_related("sender__username", "room__name").get(id=sub_message.message_id)
110
	data = {
111
		'title': message.sender.username,
112
		'options': {
113
			'body': message.content,
114
			'icon': md5url('images/favicon.ico'),
115
			'data': {
116
				'id': sub_message.message_id,
117
				'sender': message.sender.username,
118
				'room': message.room.name,
119
				'roomId': message.room_id
120
			},
121
			'requireInteraction': True
122
		},
123
	}
124
	return HttpResponse(json.dumps(data), content_type='application/json')
125
126
127
def test(request):
128
	return HttpResponse(settings.VALIDATION_IS_OK, content_type='text/plain')
129
130
131
@require_http_methods('POST')
132
@login_required_no_redirect(False)
133
@validation
134
def search_messages(request):
135
	data = request.POST['data']
136
	room_id = request.POST['room']
137
	offset = int(request.POST['offset'])
138
	if not RoomUsers.objects.filter(room_id=room_id, user_id=request.user.id).exists():
139
		raise ValidationError("You can't access this room")
140
	messages = Message.objects.filter(content__icontains=data, room_id=room_id).order_by('-id')[offset:offset+settings.MESSAGES_PER_SEARCH]
141
	imv = get_message_images_videos(messages)
142
	result = []
143
	for message in messages:
144
		files = MessagesCreator.prepare_img_video(imv, message.id)
145
		prep_m = MessagesCreator.create_message(message, files)
146
		result.append(prep_m)
147
	response = json.dumps(result)
148
	return HttpResponse(response, content_type='application/json')
149
150
151
@require_http_methods('POST')
152
def register_subscription(request):
153
	logger.debug('Subscription request,  %s', request)
154
	registration_id = request.POST['registration_id']
155
	agent = request.POST['agent']
156
	is_mobile = request.POST['is_mobile']
157
	ip = get_or_create_ip(get_client_ip(request), logger)
158
	Subscription.objects.update_or_create(
159
		registration_id=registration_id,
160
		defaults={
161
			'user': request.user,
162
			'inactive': False,
163
			'updated': datetime.datetime.now(),
164
			'agent': agent,
165
			'is_mobile': is_mobile == 'true',
166
			'ip': ip
167
		}
168
	)
169
	return HttpResponse(settings.VALIDATION_IS_OK, content_type='text/plain')
170
171
@require_http_methods('POST')
172
@validation
173
def validate_user(request):
174
	"""
175
	Validates user during registration
176
	"""
177
	utils.check_user(request.POST.get('username'))
178
	# hardcoded ok check in register.js
179
	return HttpResponse(settings.VALIDATION_IS_OK, content_type='text/plain')
180
181
182
def get_service_worker(request):  # this stub is only for development, this is replaced in nginx for prod
183
	worker = open(os.path.join(settings.STATIC_ROOT, 'js', 'sw.js'), 'rb')
184
	response = HttpResponse(content=worker)
185
	response['Content-Type'] = 'application/javascript'
186
	return response
187
188
@require_http_methods('GET')
189
@login_required_no_redirect(False)
190
def home(request):
191
	"""
192
	Login or logout navbar is creates by means of create_nav_page
193
	@return:  the x intercept of the line M{y=m*x+b}.
194
	"""
195
	context = csrf(request)
196
	ip = get_client_ip(request)
197
	if not UserJoinedInfo.objects.filter(Q(ip__ip=ip) & Q(user=request.user)).exists():
198
		ip_obj = get_or_create_ip(ip, logger)
199
		UserJoinedInfo.objects.create(ip=ip_obj, user=request.user)
200
	up = UserProfile.objects.defer('suggestions', 'highlight_code', 'embedded_youtube', 'online_change_sound', 'incoming_file_call_sound', 'message_sound', 'theme').get(id=request.user.id)
201
	context['suggestions'] = up.suggestions
202
	context['highlight_code'] = up.highlight_code
203
	context['message_sound'] = up.message_sound
204
	context['incoming_file_call_sound'] = up.incoming_file_call_sound
205
	context['online_change_sound'] = up.online_change_sound
206
	context['theme'] = up.theme
207
	context['embedded_youtube'] = up.embedded_youtube
208
	context['extensionId'] = settings.EXTENSION_ID
209
	context['extensionUrl'] = settings.EXTENSION_INSTALL_URL
210
	context['defaultRoomId'] = settings.ALL_ROOM_ID
211
	context['pingCloseDelay'] = settings.PING_CLOSE_JS_DELAY
212
	context['pingServerCloseDelay'] = settings.CLIENT_NO_SERVER_PING_CLOSE_TIMEOUT
213
	context['MESSAGES_PER_SEARCH'] = settings.MESSAGES_PER_SEARCH
214
	context['manifest'] = hasattr(settings, 'FIREBASE_API_KEY')
215
	return render_to_response('chat.html', context, context_instance=RequestContext(request))
216
217
218
@login_required_no_redirect(True)
219
def logout(request):
220
	"""
221
	POST. Logs out into system.
222
	"""
223
	registration_id = request.POST.get('registration_id')
224
	if registration_id is not None:
225
		Subscription.objects.filter(registration_id=registration_id).delete()
226
	djangologout(request)
227
	return HttpResponse(settings.VALIDATION_IS_OK, content_type='text/plain')
228
229
230
@require_http_methods(['POST'])
231
def auth(request):
232
	"""
233
	Logs in into system.
234
	"""
235
	username = request.POST.get('username')
236
	password = request.POST.get('password')
237
	user = authenticate(username=username, password=password)
238
	if user is not None:
239
		djangologin(request, user)
240
		message = settings.VALIDATION_IS_OK
241
	else:
242
		message = 'Login or password is wrong'
243
	logger.debug('Auth request %s ; Response: %s', hide_fields(request.POST, ('password',)), message)
244
	return HttpResponse(message, content_type='text/plain')
245
246
247
def send_restore_password(request):
248
	"""
249
	Sends email verification code
250
	"""
251
	logger.debug('Recover password request %s', request)
252
	try:
253
		username_or_password = request.POST.get('username_or_password')
254
		check_captcha(request)
255
		user_profile = UserProfile.objects.get(Q(username=username_or_password) | Q(email=username_or_password))
256
		if not user_profile.email:
257
			raise ValidationError("You didn't specify email address for this user")
258
		verification = Verification(type_enum=Verification.TypeChoices.password, user_id=user_profile.id)
259
		verification.save()
260
		send_reset_password_email(request, user_profile, verification)
261
		message = settings.VALIDATION_IS_OK
262
		logger.debug('Verification email has been send for token %s to user %s(id=%d)',
263
				verification.token, user_profile.username, user_profile.id)
264
	except UserProfile.DoesNotExist:
265
		message = "User with this email or username doesn't exist"
266
		logger.debug("Skipping password recovery request for nonexisting user")
267
	except (UserProfile.DoesNotExist, ValidationError) as e:
268
		logger.debug('Not sending verification email because %s', e)
269
		message = 'Unfortunately we were not able to send you restore password email because {}'.format(e)
270
	return HttpResponse(message, content_type='text/plain')
271
272
273
@require_http_methods(['GET'])
274
def proceed_email_changed(request):
275
	try:
276
		with transaction.atomic():
277
			token = request.GET['token']
278
			logger.debug('Proceed change email with token %s', token)
279
			user, verification = utils.get_user_by_code(token, Verification.TypeChoices.email)
280
			new_ver = send_new_email_ver(request, user, verification.email)
281
			user.email = verification.email
282
			user.email_verification = new_ver
283
			user.save(update_fields=('email', 'email_verification'))
284
			verification.verified = True
285
			verification.save(update_fields=('verified',))
286
			logger.info('Email has been change for token %s user %s(id=%d)', token, user.username, user.id)
287
			return render_to_response(
288
				'email_changed.html',
289
				{'text': 'Your email has been changed to {}.'.format(verification.email)},
290
				context_instance=RequestContext(request)
291
			)
292
	except Exception as e:
293
		return render_to_response(
294
			'email_changed.html',
295
			{'text': 'Unable to change your email because {}'.format(e.message)}
296
			, context_instance=RequestContext(request)
297
		)
298
299
300
class RestorePassword(View):
301
302
	@transaction.atomic
303
	@validation
304
	def post(self, request):
305
		"""
306
		Sends email verification token
307
		"""
308
		token = request.POST.get('token', False)
309
		logger.debug('Proceed Recover password with token %s', token)
310
		user, verification = utils.get_user_by_code(token, Verification.TypeChoices.password)
311
		password = request.POST.get('password')
312
		check_password(password)
313
		user.set_password(password)
314
		user.save(update_fields=('password',))
315
		verification.verified = True
316
		verification.save(update_fields=('verified',))
317
		logger.info('Password has been change for token %s user %s(id=%d)', token, user.username, user.id)
318
		return HttpResponse(settings.VALIDATION_IS_OK, content_type='text/plain')
319
320
	def get(self, request):
321
		token = request.GET.get('token', False)
322
		logger.debug('Rendering restore password page with token  %s', token)
323
		try:
324
			user = utils.get_user_by_code(token, Verification.TypeChoices.password)[0]
325
			response = {
326
				'message': settings.VALIDATION_IS_OK,
327
				'restore_user': user.username,
328
				'token': token
329
			}
330
		except ValidationError as e:
331
			logger.debug('Rejecting verification token %s because %s', token, e)
332
			response = {'message': "Unable to confirm email with token {} because {}".format(token, e)}
333
		return render_to_response('reset_password.html', response, context_instance=RequestContext(request))
334
335
336
@require_http_methods('GET')
337
def confirm_email(request):
338
	"""
339
	Accept the verification token sent to email
340
	"""
341
	token = request.GET.get('token', False)
342
	logger.debug('Processing email confirm with token  %s', token)
343
	try:
344
		try:
345
			v = Verification.objects.get(token=token)
346
		except Verification.DoesNotExist:
347
			raise ValidationError('Unknown verification token')
348
		if v.type_enum not in (Verification.TypeChoices.register, Verification.TypeChoices.confirm_email):
349
			raise ValidationError('This is not confirm email token')
350
		if v.verified:
351
			raise ValidationError('This verification token already accepted')
352
		user = UserProfile.objects.get(id=v.user_id)
353
		if user.email_verification_id != v.id:
354
			raise ValidationError('Verification token expired because you generated another one')
355
		v.verified = True
356
		v.save(update_fields=['verified'])
357
		message = settings.VALIDATION_IS_OK
358
		logger.info('Email verification token %s has been accepted for user %s(id=%d)', token, user.username, user.id)
359
	except Exception as e:
360
		logger.debug('Rejecting verification token %s because %s', token, e)
361
		message = ("Unable to confirm email with token {} because {}".format(token, e))
362
	response = {'message': message}
363
	return render_to_response('confirm_mail.html', response, context_instance=RequestContext(request))
364
365
366
@require_http_methods('GET')
367
def show_profile(request, profile_id):
368
	try:
369
		user_profile = UserProfile.objects.get(pk=profile_id)
370
		form = UserProfileReadOnlyForm(instance=user_profile)
371
		form.username = user_profile.username
372
		return render_to_response(
373
			'show_profile.html',
374
			{'form': form},
375
			context_instance=RequestContext(request)
376
		)
377
	except ObjectDoesNotExist:
378
		raise Http404
379
380
381
@require_http_methods('GET')
382
def statistics(request):
383
	pie_data = IpAddress.objects.values('country').filter(country__isnull=False).annotate(count=Count("country"))
384
	return HttpResponse(json.dumps(list(pie_data)), content_type='application/json')
385
386
387
@transaction.atomic
388
def report_issue(request):
389
	logger.info('Saving issue: %s', hide_fields(request.POST, ('log',), huge=True))
390
	issue_text = request.POST['issue']
391
	issue = Issue.objects.get_or_create(content=issue_text)[0]
392
	issue_details = IssueDetails(
393
		sender_id=request.user.id,
394
		browser=request.POST.get('browser'),
395
		issue=issue,
396
		log=request.POST.get('log')
397
	)
398
	try:
399
		mail_admins("{} reported issue".format(request.user.username), issue_text, fail_silently=True)
400
	except Exception as e:
401
		logging.error("Failed to send issue email because {}".format(e))
402
	issue_details.save()
403
	return HttpResponse(settings.VALIDATION_IS_OK, content_type='text/plain')
404
405
406
class ProfileView(View):
407
408
	@login_required_no_redirect()
409
	def get(self, request):
410
		user_profile = UserProfile.objects.get(pk=request.user.id)
411
		form = UserProfileForm(instance=user_profile)
412
		c = csrf(request)
413
		c['form'] = form
414
		c['date_format'] = settings.DATE_INPUT_FORMATS_JS
415
		return render_to_response('change_profile.html', c, context_instance=RequestContext(request))
416
417
418
	@transaction.atomic
419
	@login_required_no_redirect()
420
	@validation # should follow after transaciton.atomic, thus ValidationError doesn't rollback
421
	def post(self, request):
422
		logger.info('Saving profile: %s', hide_fields(request.POST, ("base64_image", ), huge=True))
423
		image_base64 = request.POST.get('base64_image')
424
		new_email = request.POST['email']
425
		passwd = request.POST['password']
426
		username = request.POST['username']
427
		user_profile = UserProfile.objects.get(pk=request.user.id)
428
		if new_email:
429
			utils.validate_email(new_email)
430
		utils.validate_user(username)
431
		if image_base64:
432
			image = extract_photo(image_base64)
433
			request.FILES['photo'] = image
434
		if passwd:
435
			self.change_password(passwd, request)
436
		form = UserProfileForm(request.POST, request.FILES, instance=user_profile)
437
		if form.is_valid():
438
			if not passwd:
439
				form.instance.password = form.initial['password']
440
			if new_email != form.initial['email']:
441
				self.send_email_if_needed(form, new_email, request, user_profile)
442
			profile = form.save()
443
			if passwd and form.initial['email']:
444
				send_password_changed(request, form.initial['email'])
445
			response = profile. photo.url if 'photo' in  request.FILES else settings.VALIDATION_IS_OK
446
		else:
447
			response = form.errors
448
		return HttpResponse(response, content_type='text/plain')
449
450
	@staticmethod
451
	def change_password(passwd, request):
452
		if request.user.password:
453
			is_valid = authenticate(username=request.user.username, password=request.POST['old_password'])
454
			if not is_valid:
455
				raise ValidationError("Invalid old password")
456
		utils.check_password(passwd)
457
		request.POST['password'] = make_password(passwd)
458
459
	@staticmethod
460
	def send_email_if_needed(form, new_email, request, user_profile):
461
		if form.initial['email'] and form.instance.email_verification and form.instance.email_verification.verified:
462
			verification = Verification(
463
				type_enum=Verification.TypeChoices.email,
464
				user_id=user_profile.id,
465
				email=new_email
466
			)
467
			verification.save()
468
			send_email_change(request, request.user.username, form.initial['email'], verification, new_email)
469
			raise ValidationError(
470
				"In order to change an email please confirm it from you current address. We send you an verification email to {}.".format(
471
					form.initial['email']))
472
		if new_email:
473
			new_ver = send_new_email_ver(request, request.user, new_email)
474
			form.instance.email_verification = new_ver
475
476
477
class RegisterView(View):
478
479
	def get(self, request):
480
		logger.debug(
481
			'Rendering register page with captcha site key %s and oauth key %s',
482
			RECAPTCHA_PUBLIC_KEY, GOOGLE_OAUTH_2_CLIENT_ID
483
		)
484
		c = csrf(request)
485
		c['captcha_key'] = RECAPTCHA_PUBLIC_KEY
486
		c['captcha_url'] = RECAPTHCA_SITE_URL
487
		c['oauth_url'] = GOOGLE_OAUTH_2_JS_URL
488
		c['oauth_token'] = GOOGLE_OAUTH_2_CLIENT_ID
489
		c['fb_app_id'] = FACEBOOK_APP_ID
490
		c['fb_js_url'] = FACEBOOK_JS_URL
491
		return render_to_response("register.html", c, context_instance=RequestContext(request))
492
493
	@transaction.atomic
494
	@validation
495
	def post(self, request):
496
		rp = request.POST
497
		logger.info('Got register request %s', hide_fields(rp, ('password', 'repeatpassword')))
498
		(username, password, email) = (rp.get('username'), rp.get('password'), rp.get('email'))
499
		check_user(username)
500
		check_password(password)
501
		check_email(email)
502
		user_profile = UserProfile(username=username, email=email, sex_str=rp.get('sex'))
503
		user_profile.set_password(password)
504
		create_user_model(user_profile)
505
		# You must call authenticate before you can call login
506
		auth_user = authenticate(username=username, password=password)
507
		if email:
508
			send_sign_up_email(user_profile, request.get_host(), request)
509
		djangologin(request, auth_user)
510
		return HttpResponse(settings.VALIDATION_IS_OK, content_type='text/plain')
511