示例#1
0
    def post(self, request, key, *args, **kwargs):
        try:
            key = force_text(urlsafe_base64_decode(key))
            if key != request.session.session_key:
                raise TypeError
        except (TypeError, ValueError, OverflowError):
            messages.error(request, u"会话已过期或无效链接")
            return HttpResponseRedirect("/login")

        email = request.session.get("register_email", "")
        account = ConsoleAccountModel.get_instance_by_email(email)
        if account is None:
            messages.error(request, u"用户邮箱未注册")
            return HttpResponseRedirect("")

        send_activate_email = SendActivateEmail(
            request=request,
            account=account,
            redis_conn=account_redis_api,
            expire_time=settings.REGISTER_ID_EXPIRE)
        result, error = send_activate_email.send_email()
        logger.info("Send Register Email: %s" % (error or "succ"))

        request.session[
            "register_email_next_send_datetime"] = get_expire_timestamp(
                settings.EMAIL_SEND_INTERVAL)
        return HttpResponseRedirect("")
示例#2
0
 def post(self, request, uidb64, token, *args, **kwargs):
     UserModel = get_user_model()
     uid = force_text(urlsafe_base64_decode(uidb64))
     user = UserModel.objects.get(pk=uid)
     set_password_form = SetPasswordForm(user, request.POST)
     if set_password_form.is_valid():
         set_password_form.save()
         return HttpResponseRedirect("/password/reset/complete")
     messages.error(request, get_form_error(set_password_form.errors))
     return HttpResponseRedirect("")
示例#3
0
 def get(self, request, key, *args, **kwargs):
     try:
         key = force_text(urlsafe_base64_decode(key))
         if key != request.session.session_key:
             raise TypeError
     except (TypeError, ValueError, OverflowError):
         messages.error(request, u"会话已过期或无效链接")
         return HttpResponseRedirect("/login")
     cell_phone = request.session.get("password_reset_phone", "")
     return render_to_response("password/password_reset_phone.html",
                               context_instance=RequestContext(
                                   request, locals()))
示例#4
0
def activate_user(request, uidb64, token):
    """Validate link and mark user as active else return error and redirect response."""
    if uidb64 is not None and token is not None:
        uid = force_text(urlsafe_base64_decode(uidb64))
        user = CustomUser.objects.get(pk=uid)
        if default_token_generator.check_token(user, token) and not user.is_active:
            user.is_active = True
            user.save()
            messages.success(request, 'Email verified! Proceed to login.')
            return HttpResponseRedirect(reverse('accounts:login_user'))

    messages.error(request, 'Invalid link.')
    return HttpResponseRedirect(reverse('home_page'))
示例#5
0
 def get(self, request, key, *args, **kwargs):
     try:
         key = force_text(urlsafe_base64_decode(key))
         if key != request.session.session_key:
             raise TypeError
     except (TypeError, ValueError, OverflowError):
         messages.error(request, u"会话已过期或无效链接")
         return HttpResponseRedirect("/login")
     email = request.session.get("register_email", "")
     email_link = get_email_link(email)
     return render_to_response("activate/activate_account_done.html",
                               context_instance=RequestContext(
                                   request, locals()))
示例#6
0
    def get(self, request, user_id='', token='', stage=''):

        # Check if user has been authenticated before - if so, redirect him/her to the main site
        if request.user is not None and request.user.is_authenticated():

            ActionLog.objects.log_account(
                'User redirected since already logged in',
                user=request.user,
                status=302)
            return redirect(reverse_lazy('index'))

        # This view is based on recovery stage. There are two stages: "recover" and "reset".
        # In "recover", the user account is identified and a next steps mail is sent to the user's email address
        # In "reset", the user is prompted to set a new password
        # The GET method processes both stages' form rendering. Care is taken to make this as legible as possible, and
        # as commented as possible
        if stage == 'recover':

            # We are in "recover" stage: we must ask the user for the account he/she wishes to recover
            # Add the recovery form, in "recover" mode, and render the stuff
            form = RecoveryForm(stage=stage)
            return render_to_response('accounts/recover.html',
                                      context=RequestContext(
                                          request, locals()))

        elif stage == 'reset':

            # We are in "reset" stage: we must validate the token and, if valid, prompt the user to reset his/her password
            # Identify the user - if the user is invalid, we may have an in-progress security breach
            try:
                user = User.objects.get(
                    id=int(force_text(base64_decode(user_id))))
            except User.DoesNotExist:
                user = None

            if user is None or not tokens.check_token(user, token):

                # The URL has been tampered with - abort right now
                ActionLog.objects.log_account(
                    'URL tampering attempt detected: aborting recovery process',
                    status=403,
                    user=user)
                return HttpResponseForbidden()

            form = RecoveryForm(stage=stage, user=user)
            return render_to_response('accounts/reset.html',
                                      context=RequestContext(
                                          request, locals()))

        return HttpResponseForbidden()
示例#7
0
    def post(self, request, key, *args, **kwargs):
        try:
            key = force_text(urlsafe_base64_decode(key))
            if key != request.session.session_key:
                raise TypeError
        except (TypeError, ValueError, OverflowError):
            messages.error(request, u"会话已过期或无效链接")
            return HttpResponseRedirect("/login")
        if not is_time_up(
                request.session.get("password_reset_email_next_send_datetime",
                                    0)):
            remain_seconds = get_remain_seconds(
                request.session.get("password_reset_email_next_send_datetime",
                                    0))
            messages.error(request, u"发送太频繁,请稍等%s秒再试" % remain_seconds)
            return HttpResponseRedirect("")
        email = request.session.get("reset_password_email", "")
        user = get_user_model().objects.get(accounts__email__iexact=email,
                                            accounts__is_active=True)
        host_name = settings.HOST_NAME
        token_generator = PasswordResetTokenGenerator()
        use_https = request.is_secure()
        context = {
            'email': email,
            'host_name': host_name,
            'uid': urlsafe_base64_encode(force_bytes(user.pk)),
            'token': token_generator.make_token(user),
            'protocol': 'https' if use_https else 'http',
        }
        reset_password_link = "{protocol}://{host_name}/password/reset/confirm/" \
                              "{uid}/{token}".format(**context)
        context_data = {"reset_password_link": reset_password_link}
        email_string = render_to_string("password/password_reset_email.html",
                                        context_instance=RequestContext(
                                            request, context_data))
        request.session["reset_password_email"] = email

        send_auth_email(email_type="password_reset",
                        email=email,
                        html_msg=email_string)

        request.session[
            "password_reset_email_next_send_datetime"] = get_expire_timestamp(
                settings.EMAIL_SEND_INTERVAL)

        return HttpResponseRedirect("")
示例#8
0
def password_confirm(request, uidb64, token):
    user_id = urlsafe_base64_decode(force_text(uidb64))
    user = get_object_or_404(get_user_model(), pk=user_id)

    validlink = False
    if user is not None and account_token_generator.check_token(user, token):
        validlink = True
        form = PasswordResetConfirm(request.POST or None)

        if request.method == 'POST':
            if form.is_valid():
                password = form.cleaned_data['new_password1']
                user.set_password(password)
                user.save()

                return redirect('account:reset_password_complete')

    context = {'validlink': validlink, 'form': form}
    return render(request, 'password_reset_confirm.html', context)
示例#9
0
 def get(self, request, uidb64, token, *args, **kwargs):
     UserModel = get_user_model()
     token_generator = PasswordResetTokenGenerator()
     try:
         uid = force_text(urlsafe_base64_decode(uidb64))
         user = UserModel.objects.get(pk=uid)
     except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist):
         user = None
     if user is not None and token_generator.check_token(user=user,
                                                         token=token):
         valid_link = True
         title = _(u"重置密码成功")
         msg = _(u"重置链接校验成功")
     else:
         valid_link = False
         title = _(u"重置密码失败")
         msg = _(u"重置链接校验失败,请确认重置密码链接是否正确")
     return render_to_response("password/password_reset_confirm.html",
                               context_instance=RequestContext(
                                   request, locals()))
示例#10
0
 def email_token(self, user):
     """Generate activation email and to user else write to file."""
     token = default_token_generator.make_token(user)
     uid = urlsafe_base64_encode(force_bytes(user.pk))
     subject = 'Account Activation - Enstitute'
     text_content = 'You have registered for an account with Enstitute.'
     activation_link = 'http://{0}/accounts/user/validate/{1}/{2}'.format(
         self.host, force_text(uid), token)
     html_content = '<p>Click --><a href="%s" rel="nofollow">here</a><-- to activate your account.</p>' % activation_link
     from_email = getattr(settings, 'EMAIL_HOST_USER', None)
     to_email = user.email
     message = EmailMultiAlternatives(
         subject, text_content, from_email, [to_email])
     message.attach_alternative(html_content, 'text/html')
     try:
         message.send()
     except socket.error as socket_err:
         filename = user.username + '_activation_fail'
         with open(os.path.join(os.getcwd(), filename), 'w+') as fn:
             fn.write('email: \t\t\t\t' + str(user.email) + '\nactivation link: \t' +
                      str(activation_link) + '\nerror: \t\t\t\t' + str(socket_err))
             fn.close()
示例#11
0
    def post(self, request, user_id='', token='', stage=''):

        # Check if user has been authenticated before - if so, redirect him/her to the main site
        if request.user is not None and request.user.is_authenticated():

            ActionLog.objects.log_account(
                'User redirected since already logged in',
                user=request.user,
                status=302)
            return redirect(reverse_lazy('index'))

        if stage == 'recover':

            # Create the form in "recover" mode and attempt to validate it
            form = RecoveryForm(request.POST, stage=stage)
            if form.is_valid():

                # The form was submitted correctly, thus we send the email and notify the user on further steps
                user = form.user
                ActionLog.objects.log_account(
                    'Initiated account recovery for user (current permissions: %s)'
                    % user.groups,
                    user=user,
                    status=200)
                form.send_recovery_email(request, user,
                                         tokens.make_token(user))

                return render_to_response('accounts/recovering.html',
                                          context=RequestContext(
                                              request, locals()))

            # The account is invalid: notify this error to the user and log it
            email = form.cleaned_data['email_address']
            ActionLog.objects.log_account(
                'Attempted to recover password of invalid account (email address: %s)'
                % email,
                status=401)

            return render_to_response('accounts/recover.html',
                                      context=RequestContext(
                                          request, locals()),
                                      status=401)
        elif stage == 'reset':

            # Identify the user - if the user is invalid, we may have an in-progress security breach
            try:
                user = User.objects.get(
                    id=int(force_text(base64_decode(user_id))))
            except User.DoesNotExist:
                user = None

            if user is None or not tokens.check_token(user, token):

                # The URL has been tampered with - abort right now
                ActionLog.objects.log_account(
                    'URL tampering attempt detected: aborting recovery process',
                    status=403,
                    user=user)
                return HttpResponseForbidden()

            # Validate the user data using the form in "complete" mode
            form = RecoveryForm(request.POST, stage=stage, user=user)
            if form.is_valid():

                # Reset the user password
                ActionLog.objects.log_account(
                    'Resetting password for user account',
                    status=200,
                    user=user)
                password = form.cleaned_data['password']
                user.set_password(password)
                user.save()

                # Invalidate all sessions since they are no longer valid
                update_session(request, user)
                return redirect(reverse_lazy('accounts:login'),
                                context=RequestContext(request, locals()))

            # The form could not be validated due to incompatible passwords
            ActionLog.objects.log_account(
                'Attempted to change password for user', status=401, user=user)
            return render_to_response('accounts/reset.html',
                                      context=RequestContext(
                                          request, locals()),
                                      status=401)

        return HttpResponseForbidden()