Example #1
0
 def _activate_user(self, activation_key):
     """
     Given an an activation key, look up and activate the user
     account corresponding to that key. If the key is not in a valid
     format or does not have a corresponding RegistrationProfile, then
     the function returns false. Otherwise, the function returns the
     activated User
     """
     # Make sure the key we're trying conforms to the pattern of a
     # SHA1 hash; if it doesn't, no point trying to look it up in
     # the database.
     if SHA1_RE.search(activation_key):
         try:
             profile = RegistrationProfile.objects.get(activation_key=activation_key)
         except RegistrationProfile.objects.model.DoesNotExist:
             return False
         if not profile.activation_key_expired():
             user = profile.user
             user.is_active = True
             user.save_base()
             profile.activation_key = RegistrationProfile.objects.model.ACTIVATED
             profile.save()
             return user
     else:
         return False
Example #2
0
    def activate(self, request, **kwargs):
        try:
            self.validate_request(request.GET, ['token'])
            token = request.GET.get("token", None)
            # Make sure the key we're trying conforms to the pattern of a
            # SHA1 hash; if it doesn't, no point trying to look it up in
            # the database.
            if SHA1_RE.search(token):
                profile = RegistrationProfile.objects.get(activation_key=token)
                if not profile.activation_key_expired():
                    user = profile.user
                    user.is_active = True
                    user.save()
                    profile.activation_key = RegistrationProfile.ACTIVATED
                    profile.save()
                    return self.create_response(request, {
                            "success": True
                        })
                else:
                    return http.HttpForbidden('Your activation token is no longer active or valid')
            else:
                return http.HttpForbidden('Your activation token  is no longer active or valid')

        except RegistrationProfile.DoesNotExist:
            return http.HttpNotFound('Your activation token is no longer active or valid')

        except MalformedRequestError as e:
            return http.HttpBadRequest("%s as request GET parameters" % e)
Example #3
0
    def activate(self, request, **kwargs):
        try:
            self.validate_request(request.GET, ['token'])
            token = request.GET.get("token", None)
            # Make sure the key we're trying conforms to the pattern of a
            # SHA1 hash; if it doesn't, no point trying to look it up in
            # the database.
            if SHA1_RE.search(token):
                profile = RegistrationProfile.objects.get(activation_key=token)
                if not profile.activation_key_expired():
                    user = profile.user
                    user.is_active = True
                    user.save()
                    profile.activation_key = RegistrationProfile.ACTIVATED
                    profile.save()
                    return self.create_response(request, {
                            "success": True
                        })
                else:
                    return http.HttpForbidden('Your activation token is no longer active or valid')
            else:
                return http.HttpForbidden('Your activation token  is no longer active or valid')

        except RegistrationProfile.DoesNotExist:
            return http.HttpNotFound('Your activation token is no longer active or valid')

        except MalformedRequestError as e:
            return http.HttpBadRequest("%s as request GET parameters" % e)
Example #4
0
    def establish_user_profile(self, invitation_key, username, password):
        """
        Validate an activation key and activate the corresponding
        ``User`` if valid.
        
        If the key is valid and has not expired, return the ``User``
        after activating.
        
        If the key is not valid or has expired, return ``False``.
        
        If the key is valid but the ``User`` is already active,
        return ``False``.
        
        To prevent reactivation of an account which has been
        deactivated by site administrators, the activation key is
        reset to the string constant ``RegistrationProfile.ACTIVATED``
        after successful activation.

        """
        # Make sure the key we're trying conforms to the pattern of a
        # SHA1 hash; if it doesn't, no point trying to look it up in
        # the database.
        if SHA1_RE.search(invitation_key):
            try:
                profile = self.get(key=invitation_key)
            except self.model.DoesNotExist:
                return False
            new_user = User.objects.create_user(username=username, email=profile.to_email, password=password)
            new_group, user_created = GridGroup.objects.get_or_create(founder=new_user, name='My first grid')
            new_user_profile, profile_created = UserProfile.objects.get_or_create(user=new_user, default_grid=new_group)
            profile.gridgroup.members.add(new_user.pk)
            profile.key = self.model.ACTIVATED
            profile.save()
            return (new_user, profile.gridgroup)
        return False
Example #5
0
    def activate_user(self, activation_key):
        """
        Validate an activation key and activate the corresponding
        ``User`` if valid.

        If the key is valid and has not expired, return the ``User``
        after activating.

        If the key is not valid or has expired, return ``False``.

        If the key is valid but the ``User`` is already active,
        return ``False``.

        To prevent reactivation of an account which has been
        deactivated by site administrators, the activation key is
        reset to the string constant ``RegistrationProfile.ACTIVATED``
        after successful activation.

        """
        # Make sure the key we're trying conforms to the pattern of a
        # SHA1 hash; if it doesn't, no point trying to look it up in
        # the database.
        if SHA1_RE.search(activation_key):
            profile = self.objects.filter(activation_key=activation_key)
            if not profile:
                return False
            profile = profile[0]
            if not profile.activation_key_expired():
                user = profile.user
                user.is_active = True
                user.save()
                profile.activation_key = self.ACTIVATED
                profile.save()
                return user
        return False
Example #6
0
def _get_user(**kwargs):
    try:
        activation_key = kwargs.get('activation_key')
        if SHA1_RE.search(activation_key):
            return RegistrationProfile.objects.get(
                activation_key=activation_key).user
    except RegistrationProfile.DoesNotExist:
        pass
Example #7
0
 def can_activate(self, activation_key):
     if SHA1_RE.search(activation_key):
         try:
             profile = RegistrationProfile.objects.get(activation_key=activation_key)
         except RegistrationProfile.DoesNotExist:
             return False
         if not profile.activation_key_expired():
             return True
     return False
Example #8
0
def registration_password_confirm(request, activation_key, token=None,
        template_name='registration/password_reset_confirm.html',
        token_generator=default_token_generator,
        set_password_form=SetPasswordForm,
        post_reset_redirect=None,
        extra_context=None,
        redirect_field_name=REDIRECT_FIELD_NAME):
    """
    View that checks the hash in a password activation link and presents a
    form for entering a new password. We can activate the account for real
    once we know the email is valid and a password has been set.
    """
    user = None
    profile = None
    redirect_to = request.REQUEST.get(redirect_field_name, None)
    if SHA1_RE.search(activation_key):
        profile = RegistrationProfile.objects.get(activation_key=activation_key)
        if not profile.activation_key_expired():
            user = profile.user

    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()
                activated = RegistrationProfile.objects.activate_user(activation_key)
                if activated:
                    signals.user_activated.send(
                        sender=profile, user=activated, request=request)

                # Okay, security check complete. Log the user in.
                user_with_backend = authenticate(
                    username=user.username,
                    password=form.cleaned_data.get('new_password1'))
                auth_login(request, user_with_backend)
                if request.session.test_cookie_worked():
                    request.session.delete_test_cookie()

                if redirect_to is None:
                    redirect_to = reverse('accounts_profile')
                return redirect(redirect_to)
        else:
            form = set_password_form(None)
    else:
        validlink = False
        form = None
    context = {
        'form': form,
        'validlink': validlink,
    }
    if redirect_to:
        context.update({redirect_field_name: redirect_to})
    if extra_context is not None:
        context.update(extra_context)
    return render(request, template_name, context)
Example #9
0
 def return_email(self, invitation_key):
     """
     Get the grid from which the invitation was extended
     """
     if SHA1_RE.search(invitation_key):
         try:
             invitation_key = self.get(key=invitation_key)
         except self.model.DoesNotExist:
             return None
         return invitation_key.to_email
Example #10
0
 def is_valid(self, user, invite_key):
     """
     TODO: documentation
     """
     if SHA1_RE.search(invite_key):
         try:
             invite = self.get(invite_key=invite_key)
         except self.model.DoesNotExist:
             return False
         return not invite.invite_key_expired() and user.email == invite.email
     return False
Example #11
0
 def is_valid(self, user, invite_key):
     """
     TODO: documentation
     """
     if SHA1_RE.search(invite_key):
         try:
             invite = self.get(invite_key=invite_key)
         except self.model.DoesNotExist:
             return False
         return not invite.invite_key_expired(
         ) and user.email == invite.email
     return False
Example #12
0
	def get_key(self, invitation_key):
		"""
		Return InvitationKey, or None if it doesn't (or shouldn't) exist.
		"""
		if not SHA1_RE.search(invitation_key):
			return None

		try:
			key = self.get(key=invitation_key)
		except self.model.DoesNotExist:
			return None

		return key
Example #13
0
def verify(verification_key):
    if SHA1_RE.search(verification_key):
        try:
            profile = RegistrationProfile.objects.get(activation_key=verification_key)
        except RegistrationProfile.DoesNotExist:
            return False
        if not profile.activation_key_expired():
            user = profile.user
            user.save()
            profile.activation_key = 'EMAIL_VERIFIED'
            profile.save()
            return user
    return False
Example #14
0
def verify(verification_key):
    if SHA1_RE.search(verification_key):
        try:
            profile = RegistrationProfile.objects.get(activation_key=verification_key)
        except RegistrationProfile.DoesNotExist:
            return False
        if not profile.activation_key_expired():
            user = profile.user
            user.save()
            profile.activation_key = 'EMAIL_VERIFIED'
            profile.save()
            return user
    return False
Example #15
0
    def get_key(self, invitation_key):
        """
		Return InvitationKey, or None if it doesn't (or shouldn't) exist.
		"""
        if not SHA1_RE.search(invitation_key):
            return None

        try:
            key = self.get(key=invitation_key)
        except self.model.DoesNotExist:
            return None

        return key
Example #16
0
	def get_key(self, invitation_key):
		
		## Return InvitationKey
		
	   
		if not SHA1_RE.search(invitation_key):
			return None
		
		try:
			key = self.get(key=invitation_key)
		except self.model.DoesNotExist:
			return None
		
		return key
Example #17
0
    def get_key(self, invitation_key):
        """
        Return InvitationKey, or None if it doesn't (or shouldn't) exist.
        """
        # Don't bother hitting database if invitation_key doesn't match pattern.
        if not SHA1_RE.search(invitation_key):
            return None

        try:
            key = self.get(key=invitation_key)
        except self.model.DoesNotExist:
            return None

        return key
Example #18
0
    def get_key(self, invitation_key):
        """
        Return InvitationKey, or None if it doesn't (or shouldn't) exist.
        """
        # Don't bother hitting database if invitation_key doesn't match pattern.
        if not SHA1_RE.search(invitation_key):
            return None

        try:
            key = self.get(key=invitation_key)
        except self.model.DoesNotExist:
            return None

        return key
Example #19
0
    def activate_user(self, activation_key):
        """
        Validate an activation key and activate the corresponding
        ``User`` if valid.

        This overrides the method in the base class. The user does NOT get
        activated when the profile is activated.

        If the key is valid and has not expired, return the ``User``
        after activating.

        If the key is not valid or has expired, return ``False``.

        If the key is valid but the ``User`` is already active,
        return ``User``.

        If the key is valid but the ``User`` is inactive, return ``False``.

        To prevent reactivation of an account which has been
        deactivated by site administrators, ``RegistrationProfile.activated``
        is set to ``True`` after successful activation.

        """
        # Make sure the key we're trying conforms to the pattern of a
        # SHA1 hash; if it doesn't, no point trying to look it up in
        # the database.
        if SHA1_RE.search(activation_key):
            try:
                profile = self.get(activation_key=activation_key)
            except self.model.DoesNotExist:
                # This is an actual activation failure as the activation
                # key does not exist. It is *not* the scenario where an
                # already activated User reuses an activation key.
                return False

            if profile.activated:
                # The User has already activated and is trying to activate
                # again. If the User is active, return the User. Else,
                # return False as the User has been deactivated by a site
                # administrator.
                if profile.user.is_active:
                    return profile.user
                else:
                    return False

            if not profile.activation_key_expired():
                profile.activated = True
                profile.save()
                return profile.user
        return False
Example #20
0
 def is_key_valid(self, invitation_key):
     """
     Check if an ``InvitationKey`` is valid or not, returning a boolean,
     ``True`` if the key is valid.
     """
     # Make sure the key we're trying conforms to the pattern of a
     # SHA1 hash; if it doesn't, no point trying to look it up in
     # the database.
     if SHA1_RE.search(invitation_key):
         try:
             invitation_key = self.get(key=invitation_key)
         except self.model.DoesNotExist:
             return False
         return not invitation_key.key_expired()
     return False
Example #21
0
 def is_key_valid(self, invitation_key):
     """
     Check if an ``InvitationKey`` is valid or not, returning a boolean,
     ``True`` if the key is valid.
     """
     # Make sure the key we're trying conforms to the pattern of a
     # SHA1 hash; if it doesn't, no point trying to look it up in
     # the database.
     if SHA1_RE.search(invitation_key):
         try:
             invitation_key = self.get(key=invitation_key)
         except self.model.DoesNotExist:
             return False
         return not invitation_key.key_expired()
     return False
Example #22
0
    def activate_user(self, activation_key):
        """
        Validate an activation key and activate the corresponding
        ``User`` if valid.

        If the key is valid and has not expired, return the ``User``
        after activating.

        If the key is not valid or has expired, return ``False``.

        If the key is valid but the ``User`` is already active,
        return ``False``.

        To prevent reactivation of an account which has been
        deactivated by site administrators, the activation key is
        reset to the string constant ``RegistrationProfile.ACTIVATED``
        after successful activation.

        """
        # Make sure the key we're trying conforms to the pattern of a
        # SHA1 hash; if it doesn't, no point trying to look it up in
        # the database.
        if SHA1_RE.search(activation_key):
            try:
                profile = self.get(activation_key=activation_key)
            except self.model.DoesNotExist:
                return False
            if not profile.activation_key_expired():
                #print "DEBUG: Envoit email a partir de AdminRegistrationManager"
                user = profile.user
                user.is_active = True
                user.save()
                profile.activation_key = self.model.ACTIVATED
                profile.save()
                # Send an email to the user
                #ctx_dict = {'activation_key': self.activation_key,
                #            'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
                #            'site': site}
                #subject = render_to_string('registration/activation_email_subject.txt',
                #                           ctx_dict)
                # Email subject *must not* contain newlines
                #subject = ''.join(subject.splitlines())
                #message = render_to_string('registration/activation_email.txt',
                #                           ctx_dict)
                #user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
                return user
        return False
Example #23
0
    def activate_user(self, activation_key):
        """
        Validate an activation key and activate the corresponding
        ``User`` if valid.

        If the key is valid and has not expired, return the ``User``
        after activating.

        If the key is not valid or has expired, return ``False``.

        If the key is valid but the ``User`` is already active,
        return ``False``.

        To prevent reactivation of an account which has been
        deactivated by site administrators, the activation key is
        reset to the string constant ``RegistrationProfile.ACTIVATED``
        after successful activation.

        """
        # Make sure the key we're trying conforms to the pattern of a
        # SHA1 hash; if it doesn't, no point trying to look it up in
        # the database.
        if SHA1_RE.search(activation_key):
            try:
                profile = self.get(activation_key=activation_key)
            except self.model.DoesNotExist:
                return False
            if not profile.activation_key_expired():
                #print "DEBUG: Envoit email a partir de AdminRegistrationManager"
                user = profile.user
                user.is_active = True
                user.save()
                profile.activation_key = self.model.ACTIVATED
                profile.save()
                # Send an email to the user
                #ctx_dict = {'activation_key': self.activation_key,
                #            'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
                #            'site': site}
                #subject = render_to_string('registration/activation_email_subject.txt',
                #                           ctx_dict)
                # Email subject *must not* contain newlines
                #subject = ''.join(subject.splitlines())
                #message = render_to_string('registration/activation_email.txt',
                #                           ctx_dict)
                #user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
                return user
        return False
Example #24
0
 def accept_invite(self, user, invite_key):
     """
     TODO: documentation
     """
     if SHA1_RE.search(invite_key):
         try:
             invite = self.get(invite_key=invite_key)
         except self.model.DoesNotExist:
             return False
         if not invite.invite_key_expired() and user.email == invite.email:
             profile = user.profile
             profile.house = invite.house
             profile.save()
             invite.invite_key = self.model.INVITE_ACCEPTED
             invite.save()
             return user
     return False
Example #25
0
 def accept_invite(self, user, invite_key):
     """
     TODO: documentation
     """
     if SHA1_RE.search(invite_key):
         try:
             invite = self.get(invite_key=invite_key)
         except self.model.DoesNotExist:
             return False
         if not invite.invite_key_expired() and user.email == invite.email:
             profile = user.profile
             profile.house = invite.house
             profile.save()
             invite.invite_key = self.model.INVITE_ACCEPTED
             invite.save()
             return user
     return False
Example #26
0
    def activate(self, request, activation_key):
        """
        Override default activation process. This will activate the user
        even if its passed its expiration date.
        """
        if SHA1_RE.search(activation_key):
            try:
                profile = RegistrationProfile.objects.get(activation_key=activation_key)
            except RegistrationProfile.DoesNotExist:
                return False

            user = profile.user
            user.is_active = True
            user.save()
            profile.activation_key = RegistrationProfile.ACTIVATED
            profile.save()
            return user
        return False
Example #27
0
    def activate(self, request, activation_key):
        """
        Override default activation process. This will activate the user
        even if its passed its expiration date.
        """
        if SHA1_RE.search(activation_key):
            try:
                profile = RegistrationProfile.objects.get(
                    activation_key=activation_key)
            except RegistrationProfile.DoesNotExist:
                return False

            user = profile.user
            user.is_active = True
            user.save()
            profile.activation_key = RegistrationProfile.ACTIVATED
            profile.save()
            return user
        return False
Example #28
0
 def activate_user(self, activation_key, enable=True):
     """
     Override default manager to have extra parameter 'enable'
     that allows adding an extra step to have a user active
     (as happens on RESTRICTED mode)
     """
     if SHA1_RE.search(activation_key):
         try:
             profile = self.get(activation_key=activation_key)
         except self.model.DoesNotExist:
             return False
         if not profile.activation_key_expired():
             user = profile.user
             if enable:
                 user.is_active = True
                 user.save()
             profile.activation_key = self.model.ACTIVATED
             profile.save()
             return user
     return False
Example #29
0
    def activate(self, request, **kwargs):
        token = request.GET.get("token", None)
        success = False
        # Make sure the key we're trying conforms to the pattern of a
        # SHA1 hash; if it doesn't, no point trying to look it up in
        # the database.
        if SHA1_RE.search(token):
            try:
                profile = RegistrationProfile.objects.get(activation_key=token)
                if not profile.activation_key_expired():
                    user = profile.user
                    user.is_active = True
                    user.save()
                    profile.activation_key = RegistrationProfile.ACTIVATED
                    profile.save()
                    success = True
            except RegistrationProfile.DoesNotExist:
                success = False

        return self.create_response(request, {
            "success": success
        })
Example #30
0
    def get_key(self, invitation_key):
        """
        Return InvitationKey, or None if it doesn't (or shouldn't) exist.
        """
        try:
            code = InvitationCode.objects.get(code=invitation_key)
            if self.filter(key=invitation_key).count() < code.redeem_limit:
                key = self.model(key=invitation_key, from_user=code.from_user)
                return key
        except InvitationCode.DoesNotExist:
            pass

        # Don't bother hitting database if invitation_key doesn't match pattern.
        if not SHA1_RE.search(invitation_key):
            return None
        
        try:
            key = self.get(key=invitation_key)
        except self.model.DoesNotExist:
            return None
        
        return key
Example #31
0
    def get_key(self, invitation_key):
        """
        Return InvitationKey, or None if it doesn't (or shouldn't) exist.
        """
        try:
            code = InvitationCode.objects.get(code=invitation_key)
            if self.filter(key=invitation_key).count() < code.redeem_limit:
                key = self.model(key=invitation_key, from_user=code.from_user)
                return key
        except InvitationCode.DoesNotExist:
            pass

        # Don't bother hitting database if invitation_key doesn't match pattern.
        if not SHA1_RE.search(invitation_key):
            return None

        try:
            key = self.get(key=invitation_key)
        except self.model.DoesNotExist:
            return None

        return key
Example #32
0
 def activate(self, request, activation_key):
     self.activation_key = activation_key
     if SHA1_RE.search(activation_key):
         try:
             profile = RegistrationProfile.objects.get(
                 activation_key=activation_key)
             if not profile.activation_key_expired():
                 user = profile.user
                 if user.password.startswith('!'):
                     messages.info(self.request,
                         _("Please set a password to protect your account."))
                 else:
                     activated = RegistrationProfile.objects.activate_user(
                         activation_key)
                     if activated:
                         signals.user_activated.send(
                             sender=profile, user=activated, request=request)
                     messages.info(self.request,
                         _("Thank you. Your account is now activate." \
                               " You can sign in at your convienience."))
                 return user
         except RegistrationProfile.DoesNotExist:
             return False
     return False
Example #33
0
def activate(request, activation_key,
             template_name='registration/activate.html',
             extra_context=None):
    # Activate, then add this account to any Racks that were created
    # anonymously with this user's email address.  I would prefer to
    # simply wrap the registration.views.activate function from
    # django-registration, but I can't really do that because I can't
    # get at the activated user - it just returns rendered HTML. So,
    # I'm copy-pasting its code.

    context_instance = RequestContext(request)

    from registration.models import RegistrationProfile
    # -- Begin copy-pasted code from django-registration.
    activation_key = activation_key.lower() # Normalize before trying anything with it.
    
    account = RegistrationProfile.objects.activate_user(activation_key)
    if extra_context is None:
        extra_context = {}
    for key, value in extra_context.items():
        context_instance[key] = callable(value) and value() or value
    # -- End copy-pasted code from django-registration.

    # Let the user know if activation failed, and why.
    context_instance['key_status'] = 'Activation failed. Double-check your URL'
    if account:
        context_instance['key_status'] = 'Activated'
    else:
        from registration.models import SHA1_RE
        if not SHA1_RE.search(activation_key):
            context_instance['key_status'] = ('Malformed activation key. '
                                              'Make sure you got the URL right!')
        else:
            reg_profile = RegistrationProfile.objects.filter(
                activation_key=activation_key)
            if reg_profile: 
                reg_profile = reg_profile[0]
                if reg_profile.activation_key_expired():
                    context_instance['key_status'] = 'Activation key expired'
            else:
                # Unfortunately it's impossible to be sure if the user already
                # activated, because activation causes the key to be reset.
                # We could do it if we knew who the user was at this point,
                # but we don't.
                context_instance['key_status'] = ('No such activation key.'
                                                  ' Maybe you already activated?')

    # Now see if we need to reset the password.
    token = request.REQUEST.get('token')
    context_instance['valid_reset_token'] = False
    if token:
        uidb36 = request.REQUEST['uidb36']
        # Copy-paste-and-hack code from django.contrib.auth.views, yay.
        try:
            uid_int = base36_to_int(uidb36)
        except ValueError:
            raise Http404
        user = get_object_or_404(User, id=uid_int)
        context_instance['token'] = token
        context_instance['uidb36'] = uidb36
        context_instance['username'] = user.username
        if token_generator.check_token(user, token):
            context_instance['valid_reset_token'] = True
            if request.method == 'POST':
                form = SetPasswordForm(user, request.POST)
                if form.is_valid():
                    form.save()
                    flash('Password changed.', request)
                    from django.contrib.auth import login, authenticate
                    user = authenticate(username=user.username,
                                        password=request.POST['new_password1'])
                    if user:
                        login(request, user)
                        return HttpResponseRedirect('/')

    # Post-activation: Modify anonymous racks.
    context_instance['activation_key'] = activation_key
    if account:
        for rack in Rack.objects.filter(email=account.email, user=u''):
            rack.user = account.username
            rack.save()

    return render_to_response(template_name,
                              { 'account': account,
                                'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS },
                              context_instance=context_instance)