Ejemplo n.º 1
0
def add(request, list_id, item_id):
    item_id = base36_to_int(item_id)
    item = get_object_or_404(Item, pk=item_id)

    if list_id == '!ignored':
        try:
            name = "{user}'s ignore list".format(user=request.user)
        except AttributeError:
            # python 2.5 compatibility 
            name = "%s's ignore list" % (request.user,)
        list, created = List.objects.get_or_create(owner=request.user, ignored=True, defaults={'category_id': 8, 'name': name, 'options': {}})
        list_id = list.id
    elif list_id == '!queue':
        try:
            name = "{user}'s queue".format(user=request.user)
        except AttributeError:
            # python 2.5 compatibility 
            name = "%s's queue" % (request.user,)
        list, created = List.objects.get_or_create(owner=request.user, queue=True, defaults={'category_id': 8, 'name': name, 'options': {}})
        list_id = list.id
    else:
        list_id = base36_to_int(list_id)
        list = get_object_or_404(List, pk=list_id, owner=request.user)

    order_max = list.entries.aggregate(Max('order'))['order__max']
    if order_max is None:
        order = 0
    else:
        order = order_max + 1

    list.entries.create(type=Entry.types['item'], item_id=item_id, order=order)
    
    data = {'success': True}
    json = simplejson.dumps(data)
    return HttpResponse(json, mimetype='application/json')
Ejemplo n.º 2
0
    def reverse_access_token(cls, access_token):
        if not access_token:
            raise InvalidAccessToken()
        part = access_token.split('.')
        if len(part) != 3:
            raise InvalidAccessToken()

        expire, info, check = part
        expire_timestamp = int(base36_to_int(expire))
        if CurrentTimestamp()() > expire_timestamp:
            raise AccessTokenExpired()

        part = decrypt_cbc(info, OAUTH2_SETTINGS.ACCESS_TOKEN_SECRET_KEY).split('.')

        if len(part) != 6:
            raise InvalidAccessToken()

        client_pk, user_pk, expire2, scope, is_refreshable, checksum = base36_to_int(part[0]), base36_to_int(part[1]), \
                                                                       part[2], part[3], part[4], part[5]
        if expire2 != expire:
            raise InvalidAccessToken()

        user_secret_key = UserClientSecretKey.objects.get_cached(user_id=user_pk,
                                                                 client=Client(pk=client_pk)).secret_key.encode('utf-8')
        if checksum != decrypt_cbc(check, user_secret_key):
            raise InvalidAccessToken()

        return client_pk, user_pk, scope, is_refreshable, expire_timestamp, user_secret_key
Ejemplo n.º 3
0
def unsubscribe(request, uidb36, token, step):
	if step == '1':
		return render_to_response('response.html', {'next_url': '/unsubscribe/' + uidb36 + '/' + token + '/2/', 'msg': 'Are you sure you want to unsubscribe?'}, context_instance=RequestContext(request))
	elif step == '2':
		try:
			uid_int = base36_to_int(uidb36)
		except ValueError:
			raise Http404

		user = get_object_or_404(User, id=uid_int)
		try:
			ts_b36, hash = token.split("-")
			ts = base36_to_int(ts_b36)
		except ValueError:
			return render_to_response('response.html', {'msg': 'The link is invalid!'}, context_instance=RequestContext(request))

		from django.utils.hashcompat import sha_constructor
		hash2 = sha_constructor(unicode(user.id) + unicode(ts)).hexdigest()[::2]

		if (hash2 != hash) or (((date.today() - date(2001,1,1)).days - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS):
			return render_to_response('response.html', {'msg': 'The link is invalid!'}, context_instance=RequestContext(request))

		user.email_chapter_optin = False
		user.save()
		return render_to_response('response.html', {'msg': 'Unsubscribe succeeded!'}, context_instance=RequestContext(request))
	else:
		return render_to_response('response.html', {'msg': 'The link is invalid!'}, context_instance=RequestContext(request))
Ejemplo n.º 4
0
 def authenticate(self, user_token, key_token):
     logger.debug("Attempting auth: user token is (%s, %d) " % (user_token, base36_to_int(user_token)))
     try:
         token_generator=PasswordResetTokenGenerator()
         user = get_object_or_404(User, pk=base36_to_int(user_token))
         logger.debug("User: %s checking login token" % user.username)
         if token_generator.check_token( user, key_token) and user.is_active:
             logger.debug("User: %s authenticated via token" % user.username)
             return user
     except User.DoesNotExist:
         return None
Ejemplo n.º 5
0
    def test_base36(self):
        # reciprocity works
        for n in [0, 1, 1000, 1000000]:
            self.assertEqual(n, http.base36_to_int(http.int_to_base36(n)))

        # bad input
        with self.assertRaises(ValueError):
            http.int_to_base36(-1)
        for n in ['1', 'foo', {1: 2}, (1, 2, 3), 3.141]:
            with self.assertRaises(TypeError):
                http.int_to_base36(n)

        for n in ['#', ' ']:
            with self.assertRaises(ValueError):
                http.base36_to_int(n)
        with self.assertRaises(ValueError) as cm:
            http.base36_to_int('1' * 14)
        self.assertEqual('Base36 input too large', str(cm.exception))
        for n in [123, {1: 2}, (1, 2, 3), 3.141]:
            with self.assertRaises(TypeError):
                http.base36_to_int(n)

        # more explicit output testing
        for n, b36 in [(0, '0'), (1, '1'), (42, '16'), (818469960, 'django')]:
            self.assertEqual(http.int_to_base36(n), b36)
            self.assertEqual(http.base36_to_int(b36), n)
Ejemplo n.º 6
0
    def get(self, request, *args, **kwargs):
        """
        Check whether the activation link is valid, for this both the user id and the token should
        be valid. Messages are shown when user belonging to the user id is already active
        and when the account is successfully activated. In all other cases the activation failed
        template is shown.
        Finally if the user is successfully activated, log user in and redirect to their dashboard.
        """
        try:
            user_id = base36_to_int(kwargs['uidb36'])
            user = LilyUser.objects.get(id=user_id)
            token = kwargs['token']
        except (ValueError, LilyUser.DoesNotExist):
            # Show template as per normal TemplateView behaviour
            return TemplateView.get(self, request, *args, **kwargs)

        if self.token_generator.check_token(user, token):
            # Show activation message
            messages.info(request, _('I\'ve activated your account, please login.'))
        else:
            # Show template as per normal TemplateView behaviour
            return TemplateView.get(self, request, *args, **kwargs)

        # Set is_active to True and save the user
        user.is_active = True
        user.save()

        # Redirect to dashboard
        return redirect(reverse_lazy('login'))
Ejemplo n.º 7
0
def password_reset_confirm(request, uidb36=None, token=None):
    """View that checks the hash in a password reset link and presents a
    form for entering a new password.

    Based on django.contrib.auth.views.

    """
    try:
        uid_int = base36_to_int(uidb36)
    except ValueError:
        raise Http404

    user = get_object_or_404(User, id=uid_int)
    context = {}

    if default_token_generator.check_token(user, token):
        context['validlink'] = True
        if request.method == 'POST':
            form = SetPasswordForm(user, request.POST)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect(reverse('users.pw_reset_complete'))
        else:
            form = SetPasswordForm(None)
    else:
        context['validlink'] = False
        form = None
    context['form'] = form
    return jingo.render(request, 'users/pw_reset_confirm.html', context)
Ejemplo n.º 8
0
 def authenticate(self, *args, **kwargs):
     if kwargs:
         username = kwargs.pop("username", None)
         if username:
             username_or_email = Q(username__iexact=username) | Q(email__iexact=username)
             password = kwargs.pop("password", None)
             try:
                 user = User.objects.get(username_or_email, **kwargs)
             except User.DoesNotExist:
                 pass
             else:
                 if user.check_password(password):
                     return user
         else:
             if 'uidb36' not in kwargs:
                 return
             kwargs["id"] = base36_to_int(kwargs.pop("uidb36"))
             token = kwargs.pop("token")
             try:
                 user = User.objects.get(**kwargs)
             except User.DoesNotExist:
                 pass
             else:
                 if default_token_generator.check_token(user, token):
                     return user
Ejemplo n.º 9
0
def email_reset_complete(request, uidb36=None, token=None):
    # Check that the link is valid and the base36 corresponds to a user id
    assert uidb36 is not None and token is not None  # checked by URLconf
    try:
        uid_int = base36_to_int(uidb36)
        user = User.objects.get(id=uid_int)
    except (ValueError, User.DoesNotExist):
        raise Http404

    # Retreive the new mail from the DB
    try:
        rer = ResetEmailRequest.objects.get(user=user)
    except ResetEmailRequest.DoesNotExist:
        raise Http404

    # Change the mail in the DB
    old_email = user.email
    user.email = rer.email
    user.save()

    # Remove temporal mail change information ftom the DB
    ResetEmailRequest.objects.get(user=user).delete()

    tvars = {'old_email': old_email, 'user': user}
    return render(request, 'accounts/email_reset_complete.html', tvars)
Ejemplo n.º 10
0
    def check_token(self, user, token):
        """
        Check that the token is correct for a given user
        """

        # Parse the token
        try:
            ts_b36, hash = token.split("-")
        except ValueError:
            return False

        try:
            ts = base36_to_int(ts_b36)
        except ValueError:
            return False

        # Check that the timestamp/uid have not been tampered
        if self._make_token_with_timestamp(user, ts) != token:
            return False

        # Check that the timestamp is within limits
        if (self._num_days(self._today()) - ts) > self.timeout:
            return False

        return True
Ejemplo n.º 11
0
def decode_uid(pk):
    try:
        from django.utils.http import urlsafe_base64_decode
        return urlsafe_base64_decode(pk)
    except ImportError:
        from django.utils.http import base36_to_int
        return base36_to_int(pk)
Ejemplo n.º 12
0
def auto_login(request, uidb36, token, template="autologin/failed.html", redirect_to="/"):
    redirect = request.GET.get('next', None)
    args = request.GET.copy()
    if 'next' in args:
        del args['next']
    args = args.urlencode()
    if redirect is None:
        redirect = redirect_to
    if args != "":
        if '?' in redirect:
            redirect += '&'
        else:
            redirect += '?'
        redirect += args
    User = get_user_model()
    try:
        user = User.objects.get(pk=base36_to_int(uidb36))
    except (ValueError, User.DoesNotExist):
        user = None

    if request.user.is_authenticated():
        if request.user == user:
            update_last_login(None, user)
            return HttpResponseRedirect(redirect)
        else:
            user = None

    if user is None or not default_token_generator.check_token(user, token):
        return TemplateResponse(request, template, {}, status=400)
    else:
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        login(request, user)
        return HttpResponseRedirect(redirect)
Ejemplo n.º 13
0
def resolve_cpq_code(cpq_code, cpq_type=CPQType.INVOICE):
    """Returns the CPQ object (Quote or Invoice) for this `cpq_code`
    """
    check_hash = cpq_code[:CPQ_CHECK_HASH_LENGTH]
    cpq_code = cpq_code[CPQ_CHECK_HASH_LENGTH:]
    if is_valid_cpq_code_check_hash(cpq_code, check_hash):
        if cpq_type == CPQType.INVOICE:
            CPQModel = resolve_model_dynamically(settings.HTK_CPQ_INVOICE_MODEL)
        elif cpq_type == CPQType.QUOTE:
            CPQModel = resolve_model_dynamically(settings.HTK_CPQ_QUOTE_MODEL)
        else:
            raise Exception('Bad value for cpq_type')
        try:
            padded = base36_to_int(cpq_code)
            if is_luhn_valid(padded):
                xored = padded / 10
                cpq_id = xored ^ CPQ_XOR_KEY
                cpq = CPQModel.objects.get(id=cpq_id)
            else:
                cpq = None
        except ValueError:
            cpq = None
        except CPQModel.DoesNotExist:
            cpq = None
    else:
        cpq = None
    return cpq
Ejemplo n.º 14
0
    def check_token(self, newsletter_recipient, token):
        """
        Check that a newsletter unsubscribe token is correct
        for a given recipient.

        """
        # Parse the token
        try:
            ts_b36, hash = token.split("-")
        except ValueError:
            return False

        try:
            ts = base36_to_int(ts_b36)
        except ValueError:
            return False

        # Check that the timestamp/uid has not been tampered with
        if not constant_time_compare(
                self._make_token_with_timestamp(
                    newsletter_recipient, ts
                ), token
        ):
            return False

        return True
Ejemplo n.º 15
0
    def check_token(self, user, token):
        """Check that a registration token is correct for a given user."""
        # If the user is active, the hash can't be valid.
        if user.is_active:
            return False

            # Parse the token
        try:
            ts_b36, hash = token.split("-")
        except ValueError:
            return False

        try:
            ts = base36_to_int(ts_b36)
        except ValueError:
            return False

            # Check that the timestamp and uid have not been tampered with.
        if self._make_token_with_timestamp(user, ts) != token:
            return False

            # Check that the timestamp is within limit
        if (self._num_days(self._today()) - ts) > REGISTRATION_TIMEOUT_DAYS:
            return False

        return True
Ejemplo n.º 16
0
    def check_token(self, user, token):
        """
        @parameter{user,User} instance of the User whose Token should be
        checked.
        @parameter{token,string} Token to check

        @returns{bool} @val{true} for right Token, @val{false} for wrong Token
        """
        try:
            ts_b36 = token.split("-")[0]
        except ValueError:
            return False

        try:
            uid = base36_to_int(ts_b36)
        except ValueError:
            return False

        # Check that the uid has not been tampered with
        if uid != user.id:
            return False

        if self.make_token(user) != token:
            return False

        return True
Ejemplo n.º 17
0
def password_reset_confirm(request, uidb36=None, token=None, template_name='registration/password_reset_confirm.html',
                           token_generator=default_token_generator, set_password_form=SetPasswordForm,
                           post_reset_redirect=None):
    """
    View that checks the hash in a password reset link and presents a
    form for entering a new password.
    """
    assert uidb36 is not None and token is not None # checked by URLconf
    if post_reset_redirect is None:
        post_reset_redirect = reverse('django.contrib.auth.views.password_reset_complete')
    try:
        uid_int = base36_to_int(uidb36)
    except ValueError:
        raise Http404

    user = get_object_or_404(User, id=uid_int)
    context_instance = RequestContext(request)

    if token_generator.check_token(user, token):
        context_instance['validlink'] = True
        if request.method == 'POST':
            form = set_password_form(user, request.POST)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect(post_reset_redirect)
        else:
            form = set_password_form(None)
    else:
        context_instance['validlink'] = False
        form = None
    context_instance['form'] = form
    return render_to_response(template_name, context_instance=context_instance)
Ejemplo n.º 18
0
def password_reset_confirm(request, uidb36=None, token=None):
    """
    Pulled from django contrib so that we can add user into the form
    so then we can show relevant messages about the user.
    """
    assert uidb36 is not None and token is not None
    user = None
    try:
        uid_int = base36_to_int(uidb36)
        user = UserProfile.objects.get(id=uid_int)
    except (ValueError, UserProfile.DoesNotExist):
        pass

    if user is not None and default_token_generator.check_token(user, token):
        validlink = True
        if request.method == 'POST':
            form = forms.SetPasswordForm(user, request.POST)
            if form.is_valid():
                form.save()
                log_cef('Password Changed', 5, request,
                        username=user.username,
                        signature='PASSWORDCHANGED',
                        msg='User changed password')
                return redirect(reverse('django.contrib.auth.'
                                        'views.password_reset_complete'))
        else:
            form = forms.SetPasswordForm(user)
    else:
        validlink = False
        form = None

    return jingo.render(request, 'users/pwreset_confirm.html',
                        {'form': form, 'validlink': validlink})
Ejemplo n.º 19
0
def password_reset_from_key(request, uidb36, key, **kwargs):
    
    form_class = kwargs.get("form_class", ResetPasswordKeyForm)
    template_name = kwargs.get("template_name", "account/password_reset_from_key.html")
    token_generator = kwargs.get("token_generator", default_token_generator)
    
    group, bridge = group_and_bridge(kwargs)
    ctx = group_context(group, bridge)
    
    # pull out user
    try:
        uid_int = base36_to_int(uidb36)
    except ValueError:
        raise Http404
    
    user = get_object_or_404(User, id=uid_int)
    
    if token_generator.check_token(user, key):
        if request.method == "POST":
            password_reset_key_form = form_class(request.POST, user=user, temp_key=key)
            if password_reset_key_form.is_valid():
                password_reset_key_form.save()
                password_reset_key_form = None
        else:
            password_reset_key_form = form_class()
        ctx.update({
            "form": password_reset_key_form,
        })
    else:
        ctx.update({
            "token_fail": True,
        })
    
    return render_to_response(template_name, RequestContext(request, ctx))
Ejemplo n.º 20
0
def verify_email_view(request, uidb36, token):
    user = Hacker.objects.get(pk=base36_to_int(uidb36))
    if default_token_generator.check_token(user, token):
        user.email_verified = True
        user.save()
        return HttpResponseRedirect(reverse_lazy('profile'))
    raise Http404
Ejemplo n.º 21
0
 def get_user(self):
     try:
         uid_int = base36_to_int(self.kwargs["uid"])
     except ValueError:
         raise Http404()
     self.user = get_object_or_404(get_user_model(), id=uid_int)
     return self.user
Ejemplo n.º 22
0
 def _get_user(self, uidb36):
     # pull out user
     try:
         uid_int = base36_to_int(uidb36)
     except ValueError:
         raise Http404
     return get_object_or_404(User, id=uid_int)
Ejemplo n.º 23
0
    def check_token(self, user, token):
        """
        Check that a password reset token is correct for a given user.
        """
        # Parse the token
        try:
            ts_b36, hash = token.split("-")
        except ValueError:
            return False

        try:
            ts = base36_to_int(ts_b36)
        except ValueError:
            return False

        # Check that the timestamp/uid has not been tampered with
        if not constant_time_compare(self._make_token_with_timestamp(user, ts), token):
            # Fallback to Django 1.2 method for compatibility.
            # PendingDeprecationWarning <- here to remind us to remove this in
            # Django 1.5
            if not constant_time_compare(self._make_token_with_timestamp_old(user, ts), token):
                return False

        # Check the timestamp is within limit
        if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS:
            return False

        return True
Ejemplo n.º 24
0
def unsubscribe_notifications(request, uidb36=None, token=None):

	assert uidb36 is not None and token is not None # checked by URLconf
	
	# ensure working uid
	try:
		uid_int = base36_to_int(uidb36)
	except ValueError:
		raise Http404
	
	# ensure user with uid exists
	try:
		user = User.objects.get(id=uid_int)
	except User.DoesNotExist:
		raise Http404
	
	# check email hash matches   
	hasher = ""#hashlib.md5() TODO
	hasher.update(user.email)
	if(token != hasher.hexdigest()):
		raise Http404
   
	# add unsubscribe row if there isn't one in UserData   
	user_data_cache = UserData.objects.filter(user=user, key = 'unsubscribe_notification_updates')
	if user_data_cache.count() == 0:
		user_data_cache = UserData(user=user, key = 'unsubscribe_notification_updates', value='')
		user_data_cache.save()
	
	return render_to_response("unsubscribe.html", context_instance=None)
Ejemplo n.º 25
0
def reset_confirm(request, uidb36=None, token=None):
    assert uidb36 is not None and token is not None
    validlink = False
    form = UserSetPasswordForm(None)

    try:
        uid_int = base36_to_int(uidb36)
        user = User.objects.get(id=uid_int)
    except (ValueError, User.DoesNotExist):
        user = None

    if user is not None and default_token_generator.check_token(user, token):
        validlink = True

        if request.method == 'POST':
            form = UserSetPasswordForm(user, request.POST)
            if form.is_valid():
                form.save()
                messages.success(request, _(u'You have successfully reseted password, please sign in.')) 
                return redirect('app_auth_sign_in')

    if not validlink:
        raise Http404

    return direct_to_template(request, 'auth/reset_confirm.html', {'form': form})
Ejemplo n.º 26
0
 def save(self, uidb36, token):
     password = self.cleaned_data.get('password')
     user = Hacker.objects.get(pk=base36_to_int(uidb36))
     if default_token_generator.check_token(user, token):
         user.set_password(password)
         user.save()
     return user
Ejemplo n.º 27
0
def activate_account(request, uidb36=None, token=None,
                           token_generator=default_token_generator,
                           post_reset_redirect=None,
                           current_app=None, extra_context=None):
    """
    View that checks the hash in an activate account link. Modified from
    password reset link checker.
    """
    assert uidb36 is not None and token is not None  # checked by URLconf
    if post_reset_redirect is None:
        post_reset_redirect = reverse(home)
    try:
        uid_int = base36_to_int(uidb36)
        user = User.objects.get(pk=uid_int)
    except (ValueError, OverflowError, User.DoesNotExist):
        user = None
    if user is not None and token_generator.check_token(user, token):
        person = Person.objects.get(email=user.email)
        if person.account_status != 'unregistered':
            return HttpResponseRedirect(post_reset_redirect)
        os.system('sh fetchresults.sh --newcompetitor '
            '{0} &'.format(str(person.eventor_id)))
        person.user = user
        person.account_status = 'new'
        person.save()
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        login(request, user)
        welcome = """Hallå, välkommen till Orientalyst! Till vänster ser du
        länkar till graferna från dina senaste tävlingar. Under 'Dina
        tävlingar' högst upp kan du se alla tävlingar som finns registrerade på
        eventor."""
        return home(request, welcome)
    else:
        # TODO make nice error message page here w 404
        return HttpResponseRedirect(post_reset_redirect)
Ejemplo n.º 28
0
	def email_change_confirm(self, request, extra_context=None, uidb36=None, token=None, email=None, token_generator=email_token_generator):
		"""
		Checks that ``token`` is valid, and if so, changes the user's email.
		
		:param token_generator: The token generator used to check the ``token``.
		
		"""
		assert uidb36 is not None and token is not None and email is not None
		
		try:
			uid_int = base36_to_int(uidb36)
		except:
			raise Http404
		
		user = get_object_or_404(User, id=uid_int)
		
		email = '@'.join(email.rsplit('+', 1))
		
		if email == user.email:
			# Then short-circuit.
			raise Http404
		
		if token_generator.check_token(user, email, token):
			self.account_form.set_email(user, email)
			messages.add_message(request, messages.SUCCESS, 'Email changed successfully.')
			if self.manage_account_page:
				redirect = self.reverse('account', node=request.node)
			else:
				redirect = request.node.get_absolute_url()
			return HttpResponseRedirect(redirect)
		
		raise Http404
Ejemplo n.º 29
0
    def get_queryset(self):
        """
        Overriding super().get_queryset to limit the queryset based on a kwarg when provided.
        """
        if self.queryset is not None:
            queryset = self.queryset
            if hasattr(queryset, '_clone'):
                queryset = queryset._clone()
        elif self.model is not None:
            # If kwarg is provided, try reducing the queryset
            if self.kwargs.get('b36_pks', None):
                try:
                    # Convert base36 to int
                    b36_pks = self.kwargs.get('b36_pks').split(';')
                    int_pks = []
                    for pk in b36_pks:
                        int_pks.append(base36_to_int(pk))
                    # Filter queryset
                    queryset = self.model._default_manager.filter(pk__in=int_pks)
                except:
                    queryset = self.model._default_manager.all()
            else:
                queryset = self.model._default_manager.all()
        else:
            raise ImproperlyConfigured(u"'%s' must define 'queryset' or 'model'"
                                       % self.__class__.__name__)

        if hasattr(self, 'select_related'):
            queryset = queryset.select_related(*self.select_related)

        if hasattr(self, 'prefetch_related'):
            queryset = queryset.prefetch_related(*self.prefetch_related)

        return queryset
Ejemplo n.º 30
0
def password_reset_from_key(request, uidb36, key, **kwargs):

    form_class = kwargs.get("form_class", ResetPasswordKeyForm)
    template_name = kwargs.get("template_name", "account/password_reset_from_key.html")
    token_generator = kwargs.get("token_generator", default_token_generator)

    # pull out user
    try:
        uid_int = base36_to_int(uidb36)
    except ValueError:
        raise Http404

    user = get_object_or_404(User, id=uid_int)

    if token_generator.check_token(user, key):
        if request.method == "POST":
            password_reset_key_form = form_class(request.POST, user=user, temp_key=key)
            if password_reset_key_form.is_valid():
                password_reset_key_form.save()
                messages.add_message(request, messages.SUCCESS,
                    ugettext(u"Password successfully changed.")
                )
                signals.password_reset.send(sender=request.user.__class__,
                        request=request, user=request.user)
                password_reset_key_form = None
        else:
            password_reset_key_form = form_class()
        ctx = { "form": password_reset_key_form, }
    else:
        ctx = { "token_fail": True, }

    return render_to_response(template_name, RequestContext(request, ctx))
Ejemplo n.º 31
0
 def _set_user(self, request):
     try:
         self.uid_int = base36_to_int(self.uidb36)
         if request.user.is_authenticated and request.user.id != self.uid_int:
             raise Http404
         self.user = User.objects.get(id=self.uid_int)
     except (ValueError, User.DoesNotExist):
         # if there's any error getting a user, just let django's
         # password_reset_confirm function handle it.
         return super(PasswordResetConfirmWrapper,
                      self).dispatch(request,
                                     uidb64=self.uidb64,
                                     token=self.token,
                                     extra_context=self.platform_name)
Ejemplo n.º 32
0
def uidb36_to_uidb64(uidb36):
    """
    Needed to support old password reset URLs that use base36-encoded user IDs
    https://github.com/django/django/commit/1184d077893ff1bc947e45b00a4d565f3df81776#diff-c571286052438b2e3190f8db8331a92bR231
    Args:
        uidb36: base36-encoded user ID

    Returns: base64-encoded user ID. Otherwise returns a dummy, invalid ID
    """
    try:
        uidb64 = force_text(urlsafe_base64_encode(force_bytes(base36_to_int(uidb36))))
    except ValueError:
        uidb64 = '1'  # dummy invalid ID (incorrect padding for base64)
    return uidb64
Ejemplo n.º 33
0
    def check_link(self, uidb36, token):
        """
        Check if the link that the person is accessing the page from is a
        valid one
        """
        try:
            uid_int = base36_to_int(uidb36)
            self.user = CustomUser.objects.get(id=uid_int)
        except (ValueError, OverflowError, CustomUser.DoesNotExist):
            self.user = None

        check_token = default_token_generator.check_token(self.user, token)
        self.valid_link = bool(self.user is not None and check_token)
        return self.valid_link
Ejemplo n.º 34
0
    def _check_token_has_required_values(self, uidb36, token):
        """
        Helper function to test that token
        string passed has the required kwargs needed
        to process token validation.
        """

        if not uidb36 or not token:
            return False, None
        try:
            uid_int = base36_to_int(uidb36)
        except ValueError:
            return False, None
        return True, uid_int
Ejemplo n.º 35
0
def activate_user(request, uidb36=None, token=None):
    assert uidb36 is not None and token is not None
    try:
        uid_int = base36_to_int(uidb36)
        usr = get_object_or_404(Participant, id=uid_int)
    except Exception:
        return render_to_response('reactivation.html', {})
    if token_generator.check_token(usr, token):
        usr.is_active = True
        usr.save()
    else:
        return render_to_response('reactivation.html', {})
    return HttpResponseRedirect(
        '/login/?next=/change_preferences/')  # yeah, right...
Ejemplo n.º 36
0
def email_verify(request, uidb36, token):
    """Verification for the user's email address."""

    try:
        uid_int = base36_to_int(uidb36)
        user = User.objects.get(pk=uid_int)
    except (ValueError, OverflowError, User.DoesNotExist):
        return HttpResponseNotFound()
    valid = user.find_valid_email(token)
    if valid:
        valid.extra_data['verified'] = True
        valid.save()
    return render(
        request, 'registration/email_verified.html', {'valid': valid})
Ejemplo n.º 37
0
def activate(request, uidb64, token):
    try:
        uid = base36_to_int(uidb64)
        user = User.objects.get(pk=uid)
    except(TypeError, ValueError, OverflowError, User.DoesNotExist):
        user = None
    if user is not None and account_activation_token.check_token(user, token):
        user.is_active = True
        user.save()
        login(request, user)
        messages.success(request, ' Your Account has been successfully verified.')
        return redirect('index')
    else:
        return render(request, 'home/error.html', {'errors': 'Activation link is invalid!'})
Ejemplo n.º 38
0
    def test_base36(self):
        # reciprocity works
        for n in [0, 1, 1000, 1000000]:
            self.assertEqual(n, http.base36_to_int(http.int_to_base36(n)))
        if six.PY2:
            self.assertEqual(sys.maxint, http.base36_to_int(http.int_to_base36(sys.maxint)))

        # bad input
        self.assertRaises(ValueError, http.int_to_base36, -1)
        if six.PY2:
            self.assertRaises(ValueError, http.int_to_base36, sys.maxint + 1)
        for n in ['1', 'foo', {1: 2}, (1, 2, 3), 3.141]:
            self.assertRaises(TypeError, http.int_to_base36, n)

        for n in ['#', ' ']:
            self.assertRaises(ValueError, http.base36_to_int, n)
        for n in [123, {1: 2}, (1, 2, 3), 3.141]:
            self.assertRaises(TypeError, http.base36_to_int, n)

        # more explicit output testing
        for n, b36 in [(0, '0'), (1, '1'), (42, '16'), (818469960, 'django')]:
            self.assertEqual(http.int_to_base36(n), b36)
            self.assertEqual(http.base36_to_int(b36), n)
Ejemplo n.º 39
0
def password_reset_confirm(
        request,
        uidb36=None,
        token=None,
        template_name='registration/password_reset_confirm.html',
        token_generator=default_token_generator,
        set_password_form=SetPasswordForm,
        post_reset_redirect=None,
        current_app=None,
        extra_context=None):
    '''View that checks the hash in a password reset link and presents a form
    for entering a new password. Doesn't need ``csrf_protect`` since no-one can
    guess the URL.
    '''
    assert uidb36 is not None and token is not None  # checked by URLconf
    if post_reset_redirect is None:
        post_reset_redirect = reverse('baph_password_change_complete')
    else:
        post_reset_redirect = resolve_url(post_reset_redirect)
    try:
        uid = base36_to_int(uidb36)
        user = get_object_or_404(User, id=uid)
    except (TypeError, ValueError, OverflowError):
        user = None

    if user is not None and token_generator.check_token(user, token):
        validlink = True
        title = _('Enter new password')
        if request.method == 'POST':
            form = set_password_form(user, request.POST)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect(post_reset_redirect)
        else:
            form = set_password_form(user)
    else:
        validlink = False
        form = None
        title = _('Password reset unsuccessful')
    context = {
        'form': form,
        'title': title,
        'validlink': validlink,
    }
    if extra_context is not None:
        context.update(extra_context)

    return render_to_response(template_name,
                              context,
                              context_instance=RequestContext(request))
Ejemplo n.º 40
0
def password_reset_confirm(
        request,
        uidb36=None,
        token=None,
        template_name='registration/password_reset_confirm.html',
        token_generator=default_token_generator,
        set_password_form=SetPasswordForm,
        post_reset_redirect=None,
        current_app=None,
        extra_context=None):
    """
    View that checks the hash in a password reset link and presents a
    form for entering a new password.
    """
    UserModel = get_user_model()
    assert uidb36 is not None and token is not None  # checked by URLconf
    if post_reset_redirect is None:
        post_reset_redirect = reverse(
            'django.contrib.auth.views.password_reset_complete')
    else:
        post_reset_redirect = resolve_url(post_reset_redirect)
    try:
        uid_int = base36_to_int(uidb36)
        user = UserModel._default_manager.get(pk=uid_int)
    except (ValueError, OverflowError, UserModel.DoesNotExist):
        user = None

    if user is not None and token_generator.check_token(user, token):
        validlink = True
        if request.method == 'POST':
            form = set_password_form(user, request.POST)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect(post_reset_redirect)
        else:
            form = set_password_form(None)
    else:
        validlink = False
        form = None
    context = {
        'form': form,
        'validlink': validlink,
    }
    if extra_context is not None:
        context.update(extra_context)
    return TemplateResponse(request,
                            template_name,
                            context,
                            current_app=current_app)
Ejemplo n.º 41
0
 def get_user(self):
     # django 1.5 uses uidb36, django 1.6 uses uidb64
     uidb36 = self.kwargs.get('uidb36')
     uidb64 = self.kwargs.get('uidb64')
     assert bool(uidb36) ^ bool(uidb64)
     try:
         if uidb36:
             uid = base36_to_int(uidb36)
         else:
             # urlsafe_base64_decode is not available in django 1.5
             from django.utils.http import urlsafe_base64_decode
             uid = urlsafe_base64_decode(uidb64)
         return self.get_queryset().get(pk=uid)
     except (TypeError, ValueError, OverflowError, User.DoesNotExist):
         return None
Ejemplo n.º 42
0
    def get_instance(self, request, uidb36, ts_b36, token):
        def create_token(instance):
            key_salt = "cadastro.forms.AtualizarCadastroLinkForm"
            value = u'%s%s' % (
                instance.pk,
                instance.email,
            )
            return salted_hmac(key_salt, value).hexdigest()[::2]

        try:
            uid_int = base36_to_int(uidb36)

            # Link só funciona 3 dia
            ts_int = base36_to_int(ts_b36)
            if ts_int + 3 < (date.today() - date(2001, 1, 1)).days:
                return None

            instance = Membro.objects.get(id=uid_int)
        except (ValueError, Membro.DoesNotExist):
            return None
        if not constant_time_compare(create_token(instance), token):
            return None

        return instance
Ejemplo n.º 43
0
def reset_psw_confirm(request, uid, token):
    from django.utils.http import base36_to_int
    user = User.objects.get(pk=base36_to_int(uid))

    if request.method == 'POST':
        form = ResetPasswordForm(user, request.POST)
        if form.is_valid():
            form.save()
            return render_to_response('users/reset_psw_done.html', {})
        else:
            return TemplateResponse(request, 'users/reset_psw_confirm.html',
                                    {'form': form})
    form = ResetPasswordForm(user)
    return TemplateResponse(request, 'users/reset_psw_confirm.html',
                            {'form': form})
Ejemplo n.º 44
0
    def get(self, request, *args, **kwargs):
        """
        Check whether the activation link is valid, for this both the user id and the token should
        be valid. Messages are shown when user belonging to the user id is already active
        and when the account is successfully activated. In all other cases the activation failed
        template is shown.
        Finally if the user is successfully activated, log user in and redirect to their dashboard.
        """
        try:
            user_id = base36_to_int(kwargs['uidb36'])
            user = LilyUser.objects.get(id=user_id)
            token = kwargs['token']
        except (ValueError, LilyUser.DoesNotExist):
            # Show template as per normal TemplateView behaviour.
            return TemplateView.get(self, request, *args, **kwargs)

        if not self.token_generator.check_token(user, token):
            # Show template as per normal TemplateView behaviour.
            return TemplateView.get(self, request, *args, **kwargs)

        call_command('create_tenant', tenant=user.tenant.id)

        # Set is_active to True and save the user.
        user.is_active = True
        user.save()

        if settings.BILLING_ENABLED:
            tenant = user.tenant

            result = chargebee.Subscription.create({
                'plan_id': tenant.billing.plan.name,
                'customer': {
                    'first_name': user.first_name,
                    'last_name': user.last_name,
                    'email': user.email,
                    'company': tenant.name,
                },
            })

            tenant.billing.customer_id = result.customer.id
            tenant.billing.subscription_id = result.subscription.id
            tenant.billing.save()

        # Programmatically login the user.
        user.backend = settings.AUTHENTICATION_BACKENDS[0]
        auth.login(request, user)

        return redirect(reverse_lazy('base_view'))
Ejemplo n.º 45
0
 def invite_user_confirm(self, request, uidb36, token):
     """Performs confirmation of the invite user email."""
     form = None
     admin_form = None
     # Get the user.
     try:
         uid_int = base36_to_int(uidb36)
         user = User.objects.get(id=uid_int)
     except (ValueError, User.DoesNotExist):
         valid_link = False
         user = None
     else:
         # Check the token.
         valid_link = default_token_generator.check_token(user, token)
         # Activate the account.
         if valid_link:
             # Process the form.
             if request.method == "POST":
                 form = self.invite_confirm_form(user, request.POST)
                 if form.is_valid():
                     user = form.save(commit=False)
                     # Activate the user.
                     user.is_active = True
                     user.save()
                     # Login the user.
                     user = auth.authenticate(username=user.username, password=form.cleaned_data["password1"])
                     auth.login(request, user)
                     # Message and redirect.
                     self.message_user(request, "Thanks for signing up! We've saved your password and logged you in.")
                     return redirect("{admin_site}:index".format(
                         admin_site = self.admin_site.name,
                     ))
             else:
                 form = self.invite_confirm_form(user)
             admin_form = admin.helpers.AdminForm(form, self.invite_confirm_fieldsets, {})
     # Render the template.
     if valid_link:
         title = "Welcome to the site!"
     else:
         title = "This link has expired"
     return render(request, self.invite_confirm_form_template, {
         "title": title,
         "opts": self.model._meta,
         "valid_link": valid_link,
         "form": form,
         "adminform": admin_form,
         "user": user,
     })
Ejemplo n.º 46
0
def custom_password_reset_confirm(request, uidb36=None, token=None, set_password_form=SetPasswordForm,
                                  template_name='registration/datasender_activate.html'):
    response = password_reset_confirm(request, uidb36=uidb36, token=token, set_password_form=set_password_form,
                                      template_name=template_name)
    if request.method == 'POST' and type(response) == HttpResponseRedirect:
        try:
            uid_int = base36_to_int(uidb36)
            user = User.objects.get(id=uid_int)
        except (ValueError, User.DoesNotExist):
            return response
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        sign_in(request, user)
        redirect_url = django_settings.DATASENDER_DASHBOARD + '?activation=1' \
            if user.get_profile().reporter else django_settings.HOME_PAGE
        return HttpResponseRedirect(redirect_url)
    return response
Ejemplo n.º 47
0
    def check_token(self):
        uidb36 = self.kwargs.get('uidb36')
        token = self.kwargs.get('token')
        assert uidb36 is not None and token is not None
        user_id = base36_to_int(uidb36)
        user = User._default_manager.get(pk=user_id)

        valid = activation_token_generator.check_token(user, token)
        if not valid:
            raise PermissionDenied

        user.is_active = True
        user.save()
        # backend attribute needed to log user in
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        login(self.request, user)
Ejemplo n.º 48
0
    def is_expired(self, token):
        # Parse the token
        try:
            ts_b36, hash = token.split("-")
            ts = base36_to_int(ts_b36)
        except ValueError:
            return False

        if ts < 7228:
            ts = ts * 24 * 60 * 60

        # Check the timestamp is within limit
        if (self._num_seconds(self._now()) - ts) > self.validity:
            return True

        return False
Ejemplo n.º 49
0
    def check_token(self, user, token):
        """
        Check that a password reset token is correct for a given user.
        """
        # Parse the token
        try:
            ts_b36, hash = token.split("-")
        except ValueError:
            return False

        try:
            ts = base36_to_int(ts_b36)
        except ValueError:
            return False

        return True
Ejemplo n.º 50
0
def activate_email(request, uid, token):
    try:
        uid = base36_to_int(uid)
        user = User.objects.get(pk=uid)
    except User.DoesNotExist:
        user = None

    if user is not None and confirm_email_token_generator.check_token(
            user, token):
        user.is_active = True
        user.save()

        # Login automatically?
        return redirect('login')
    else:
        return HttpResponseBadRequest('Bad Token')
Ejemplo n.º 51
0
def url_str_to_user_pk(s):
    User = get_user_model()
    # TODO: Ugh, isn't there a cleaner way to determine whether or not
    # the PK is a str-like field?
    if getattr(User._meta.pk, 'remote_field', None):
        pk_field = User._meta.pk.remote_field.to._meta.pk
    else:
        pk_field = User._meta.pk
    if issubclass(type(pk_field), models.UUIDField):
        return pk_field.to_python(s)
    try:
        pk_field.to_python('a')
        pk = s
    except ValidationError:
        pk = base36_to_int(s)
    return pk
Ejemplo n.º 52
0
def active_account(request, uidb36, token):
    try:
        uid_int = base36_to_int(uidb36)
    except ValueError:
        raise Http404

    user = get_object_or_404(User, id=uid_int)
    if user and default_token_generator.check_token(user, token):
        user.is_active = True
        user.save(update_fields=['is_active'])
        login(request, user, backend='django.contrib.auth.backends.ModelBackend')
        messages.success(request, 'Selamat, akun Anda sudah aktif')
    else:
        messages.warning(request, 'Maaf, ada masalah dengan aktivasi akun')

    return redirect("website:accounts:index")
Ejemplo n.º 53
0
def password_reset_confirm(request, uidb36=None, token=None,
                           template_name='registration/password_reset_confirm.html',
                           token_generator=default_token_generator,
                           set_password_form=SetPasswordForm,
                           post_reset_redirect=None,
                           current_app=None, extra_context=None):
    """
    View that checks the hash in a password reset link and presents a
    form for entering a new password.

    NOTE: we adapt this because we want to automatically log them in
    once they've set their new password. Because this is correct behaviour.
    And it's IMPOSSIBLE to do this in a form, because forms don't get a
    Request object as context. Sigh.
    """
    UserModel = get_user_model()
    assert uidb36 is not None and token is not None  # checked by URLconf
    if post_reset_redirect is None:
        post_reset_redirect = reverse('django.contrib.auth.views.password_reset_complete')
    try:
        uid_int = base36_to_int(uidb36)
        user = UserModel.objects.get(pk=uid_int)
    except (ValueError, OverflowError, UserModel.DoesNotExist):
        user = None

    if user is not None and token_generator.check_token(user, token):
        validlink = True
        if request.method == 'POST':
            form = set_password_form(user, request.POST)
            if form.is_valid():
                user = form.save()
                user.backend = 'django.contrib.auth.backends.ModelBackend'
                login(request, user)
                return HttpResponseRedirect(post_reset_redirect)
        else:
            form = set_password_form(None)
    else:
        validlink = False
        form = None
    context = {
        'form': form,
        'validlink': validlink,
    }
    if extra_context is not None:
        context.update(extra_context)
    return TemplateResponse(request, template_name, context,
                            current_app=current_app)
Ejemplo n.º 54
0
    def check_token(self, user, token):
        """
        Check that a password reset token is correct for a given user.
        """
        if not (user and token):
            return False
        # Parse the token
        try:
            ts_b36, _ = token.split("-")
        except ValueError:
            return False

        try:
            ts = base36_to_int(ts_b36)
            new_ts = int(str(ts)[:12])
            print(new_ts, "this is the new ts")
        except ValueError:
            return False

        # Check that the timestamp/uid has not been tampered with
        if not constant_time_compare(
                self._make_token_with_timestamp_fixed(user, ts), token):
            # RemovedInDjango40Warning: when the deprecation ends, replace
            # with:
            #   return False
            if not constant_time_compare(
                    self._make_token_with_timestamp_fixed(
                        user, ts, legacy=True),
                    token,
            ):

                #print(token, self._make_token_with_timestamp(user, ts, legacy=True))
                return False
        print("pass through")
        # Check the timestamp is within limit.
        from django.conf import settings
        print(self._num_seconds(self._now()))
        print(ts, "this is the new timestamp")
        if (self._num_seconds(self._now()) -
                ts) > settings.PASSWORD_RESET_TIMEOUT:
            print(self._num_seconds(self._now()))
            #print(ts)
            print("timeout")
            return False

        return True
Ejemplo n.º 55
0
    def validate(self, data):
        uid = data['uid']
        key = data['key']

        if data['new_password1'] != data['new_password2']:
            raise serializers.ValidationError(
                _('The two password fields did not match.'))

        try:
            pk = base36_to_int(uid)
            self.user = User.objects.get(pk=pk)
            if not password_reset_token_generator.check_token(self.user, key):
                raise serializers.ValidationError(_('bad token'))

            return data
        except EmailAddress.DoesNotExist:
            raise serializers.ValidationError(_('bad token'))
Ejemplo n.º 56
0
def password_reset_confirm(request, uidb36=None, token=None):
    response = django_password_reset_confirm(request, uidb36=uidb36, token=token,
            template_name='account/password_reset_confirm.html',
            post_reset_redirect=reverse('account-show'))
    # TODO: this is not the smartest of ideas
    # if django view returns 302, it is assumed that everything was fine
    # currently this seems safe to assume.
    if response.status_code == 302:
        uid_int = base36_to_int(uidb36)
        user = auth.models.User.objects.get(id=uid_int)
        login_user(request, user)
        messages.add_message(request, messages.SUCCESS,
                _('Your password has been set and you are now logged in.'))
        if 'next' in request.session:
            response['Location'] = request.session['next']
            del request.session['next']
    return response
Ejemplo n.º 57
0
def token_valid(timed_token):
    """Validate a timed token.

    Return the user id for which the token is valid, if the token is
    valid.  Return -1 if the token is not (either because it is
    malformed or because it has expired).

    """
    the_rand_value, the_user_id, the_soon, the_hmac = timed_token.split('|')
    computed_hmac = salted_hmac(the_soon, the_rand_value +
                                str(the_user_id)).hexdigest()[:20]
    if computed_hmac != the_hmac:
        return -1
    now = datetime.datetime.now().timestamp()
    if now > base36_to_int(the_soon):
        return -1
    return int(the_user_id)
Ejemplo n.º 58
0
    def test_cannot_change_mail_if_time_expired(self):
        regex_token = r"token=(([0-9a-z]*)-([0-9a-f]*))"
        new_mail = "*****@*****.**"

        send_confirmation_change_email(new_mail, str(self.person.pk))
        match = re.search(regex_token, mail.outbox[0].body)
        ts = match.group(2)
        signature = match.group(3)
        token_expired = int_to_base36((base36_to_int(ts) - 8)) + "-" + signature
        params = {
            "new_email": new_mail,
            "user": str(self.person.pk),
            "token": token_expired,
        }
        ulr_expired = reverse("confirm_change_mail") + "?" + urlencode(params)
        res = self.client.get(ulr_expired)
        self.assertContains(res, "Il semble que celui-ci est expiré.")
Ejemplo n.º 59
0
 def activate(self, request, uidb36, token):
     try:
         # uid = int(uidb64)
         uid = base36_to_int(uidb36)
         user = User.objects.get(pk=uid)
     except (TypeError, ValueError, OverflowError, User.DoesNotExist):
         user = None
     if user is not None and account_activation_token.check_token(
             user, token):
         user.email_verified = True
         user.save()
         # return user.email_verified
         return True
         # return HttpResponse('Thank you for confirming your Email.')
     else:
         # return user.email_verified
         return False
Ejemplo n.º 60
0
def password_reset_view(request, uidb36, token):
    try:
        user = User.objects.get(id=base36_to_int(uidb36))
    except (ValueError, User.DoesNotExist):
        pass
    else:
        if default_token_generator.check_token(user, token):
            if request.method == 'GET':
                return render_to_response('reset.html')
            else:
                user.set_password(request.POST['new'])
                user.save()
                user.backend = AUTHENTICATION_BACKENDS[0]
                auth.login(request, user)
                return HttpResponseRedirect('/ide/')
    return HttpResponse(get_template('bad_reset.html').render(Context()),
                        status=NOT_FOUND)