PageRenderTime 43ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/kitsune/users/utils.py

https://github.com/rlr/kitsune
Python | 136 lines | 98 code | 30 blank | 8 comment | 17 complexity | b16d4b3ddf987308e75e45075e9ae3d6 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. import bisect
  2. import logging
  3. from smtplib import SMTPException
  4. from django.conf import settings
  5. from django.contrib import auth
  6. from django.contrib.auth.models import User
  7. from statsd import statsd
  8. from tower import ugettext as _
  9. from kitsune.sumo import email_utils
  10. from kitsune.users import ERROR_SEND_EMAIL
  11. from kitsune.users.forms import RegisterForm, AuthenticationForm
  12. from kitsune.users.models import (RegistrationProfile, Group,
  13. CONTRIBUTOR_GROUP, Deactivation)
  14. log = logging.getLogger('k.users')
  15. def handle_login(request, only_active=True):
  16. auth.logout(request)
  17. if request.method == 'POST':
  18. form = AuthenticationForm(data=request.POST, only_active=only_active)
  19. if form.is_valid():
  20. auth.login(request, form.get_user())
  21. statsd.incr('user.login')
  22. if request.session.test_cookie_worked():
  23. request.session.delete_test_cookie()
  24. return form
  25. request.session.set_test_cookie()
  26. return AuthenticationForm()
  27. def handle_register(request, text_template=None, html_template=None,
  28. subject=None, email_data=None, *args, **kwargs):
  29. """Handle to help registration."""
  30. if request.method == 'POST':
  31. form = RegisterForm(request.POST)
  32. if form.is_valid():
  33. form = try_send_email_with_form(
  34. RegistrationProfile.objects.create_inactive_user,
  35. form, 'email',
  36. form.cleaned_data['username'],
  37. form.cleaned_data['password'],
  38. form.cleaned_data['email'],
  39. locale=request.LANGUAGE_CODE,
  40. text_template=text_template,
  41. html_template=html_template,
  42. subject=subject,
  43. email_data=email_data,
  44. volunteer_interest=form.cleaned_data['interested'],
  45. *args, **kwargs)
  46. if not form.is_valid():
  47. # Delete user if form is not valid, i.e. email was not sent.
  48. # This is in a POST request and so always pinned to master,
  49. # so there is no race condition.
  50. User.objects.filter(email=form.instance.email).delete()
  51. else:
  52. statsd.incr('user.register')
  53. return form
  54. return RegisterForm()
  55. def try_send_email_with_form(func, form, field_name, *args, **kwargs):
  56. """Send an email by calling func, catch SMTPException and place errors in
  57. form."""
  58. try:
  59. func(*args, **kwargs)
  60. except SMTPException as e:
  61. log.warning(u'Failed to send email: %s' % e)
  62. if 'email' not in form.errors:
  63. form.errors[field_name] = []
  64. form.errors[field_name].append(unicode(ERROR_SEND_EMAIL))
  65. return form
  66. def add_to_contributors(request, user):
  67. group = Group.objects.get(name=CONTRIBUTOR_GROUP)
  68. user.groups.add(group)
  69. user.save()
  70. @email_utils.safe_translation
  71. def _make_mail(locale):
  72. mail = email_utils.make_mail(
  73. subject=_('Welcome to SUMO!'),
  74. text_template='users/email/contributor.ltxt',
  75. html_template='users/email/contributor.html',
  76. context_vars={'contributor': user},
  77. from_email=settings.DEFAULT_FROM_EMAIL,
  78. to_email=user.email)
  79. return mail
  80. email_utils.send_messages([_make_mail(request.LANGUAGE_CODE)])
  81. def suggest_username(email):
  82. username = email.split('@', 1)[0]
  83. username_regex = r'^{0}[0-9]*$'.format(username)
  84. users = User.objects.filter(username__iregex=username_regex)
  85. if users.count() > 0:
  86. ids = []
  87. for u in users:
  88. # get the number at the end
  89. i = u.username[len(username):]
  90. # incase there's no number in the case where just the base is taken
  91. if i:
  92. i = int(i)
  93. bisect.insort(ids, i)
  94. else:
  95. ids.insert(0, 0)
  96. for index, i in enumerate(ids):
  97. if index + 1 < len(ids):
  98. if i + 1 != ids[index + 1]:
  99. break
  100. username = '{0}{1}'.format(username, i + 1)
  101. return username
  102. def deactivate_user(user, moderator):
  103. user.is_active = False
  104. user.save()
  105. deactivation = Deactivation(user=user, moderator=moderator)
  106. deactivation.save()