def test_username_uniqueness(self): data = { 'username': '******', 'password': '******', 'email': '*****@*****.**', } user = User(**data) user.save() user2 = User(**data) self.assertExcMsg(Exception, 'The username %s is already in use.' % data.get('username'), user2.save)
def test_email_uniqueness(self): data = { 'username': '******', 'password': '******', 'email': '*****@*****.**', } user = User(**data) user.save() data.update({ 'username': '******', }) user2 = User(**data) self.assertExcMsg(Exception, 'The email address %s is already in use.' % data.get('email'), user2.save)
def test_user_authentication(self): authdata = { 'username': '******', 'password': '******', 'email': '*****@*****.**', } data = authdata.copy() data.update({ 'email': '*****@*****.**', }) user = User(**data) user.set_password(data.get('password')) user.save() user = authenticate(username=authdata.get('username'), password=authdata.get('password')) self.assertIsNotNone(user)
def activate_user(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 not SHA1_RE.search(activation_key): return False user = User.get_by_key(activation_key) if not user.activation_key_expired(): del user.activation_key user.is_active = True user.save() return user
def test_user_registration(self): data = { 'username': '******', 'password': '******', 'email': '*****@*****.**', } user = User(**data) user.save() user = User.get_user(data['username']) self.assertIsNotNone(user) self.assertEqual(user.username, data['username']) user = User.get_user_by_email(data['email']) self.assertIsNotNone(user) self.assertEqual(user.username, data['username'])
def do_c(self, request, token = ''): if not token: # TODO: show a form where they can paste in their token? raise Http404 token = token.rstrip('/').encode('utf8') try: value = signed.unsign(token, key = ( self.confirm_link_secret or settings.SECRET_KEY ) + self.confirm_link_salt) except signed.BadSignature: return self.show_message( request, self.invalid_token_message, self.invalid_token_message + ': ' + token ) # Only line change compared with django-openid user_id = value user = self.lookup_user_by_id(user_id) if not user: # Maybe the user was deleted? return self.show_error(request, self.r_user_not_found_message) # Check user is NOT active but IS in the correct group if self.user_is_unconfirmed(user): # Confirm them try: user = User.view('%s/users_by_username' % User._meta.app_label, key=user.username, include_docs=True).first() except ResourceNotFound: user = None if user: self.mark_user_confirmed(user) self.log_in_user(request, user) return self.on_registration_complete(request) else: return self.show_error(request, self.c_already_confirmed_message)
def lookup_openid(self, request, identity_url): openid = UserOpenidAssociation.view('%s/openid_view' % UserOpenidAssociation._meta.app_label, key=identity_url, include_docs=True).first() if openid: return User.view('%s/users_by_username' % User._meta.app_label, reduce=False, key=openid['user_id'], include_docs=True).all()
def clean_email(self): email = self.cleaned_data.get('email', '') try: email_count = User.view('%s/users_by_email' % User._meta.app_label, key = email).count() except ResourceNotFound: email_count = 0 if self.no_duplicate_emails and email_count > 0: raise forms.ValidationError, self.duplicate_email_error return email
def user_is_unconfirmed(self, user): count = 0 try: count = User.view('%s/users_by_username' % User._meta.app_label, key=user.username, include_docs=True).count() except ResourceNotFound: return False if count: return True return False
def do_profile(self, request): if request.method == "GET": user_data = Person.view("world/by_user_id", key=request.user.id, include_docs=True).first() if user_data: form = PersonForm(data=user_data.to_json()) ctx_dict = {"form": form} if form.data.get("photo", None): photo = urlparse.urljoin(settings.MEDIA_URL, "site_media/%s" % form.data["photo"]) ctx_dict.update({"photo": photo}) else: ctx_dict = {"form": PersonForm(initial={"email": request.user.email})} return render(request, "person/edit_profile.html", ctx_dict) user_data = request.POST.copy() # Stuff the user id and full name # The full name is stored now to prevent HTTP requests later user_data["user_id"] = request.user.id user_data["email"] = request.user.email user = User.view( "%s/users_by_username" % User._meta.app_label, key=request.user.username, include_docs=True ).first() user_data["full_name"] = user.get_full_name() vf = PersonForm(user_data, request.FILES) if vf.is_valid(): # Let's handle the image first. if vf.cleaned_data.get("photo"): photo_name = request.FILES["photo"].name base_upload_path = os.path.basename(os.path.abspath(settings.PROFILE_PIC_UPLOAD_PATH)) upload_path = os.path.join(settings.PROFILE_PIC_UPLOAD_PATH, request.user.id) if not os.path.exists(upload_path): os.mkdir(upload_path) img_file = open(os.path.join(upload_path, photo_name), "w") img_file.write(request.FILES["photo"].read()) relative_dir = os.path.join(base_upload_path, os.path.basename(upload_path)) vf.cleaned_data.update({"photo": os.path.join(relative_dir, os.path.basename(img_file.name))}) img_file.close() data = Person.view("world/by_user_id", key=request.user.id, include_docs=True).first() if not data: data = Person() for (field, val) in vf.cleaned_data.items(): setattr(data, field, val) data.save() return render( request, "person/edit_profile.html", { "form": PersonForm(vf.cleaned_data), "photo": vf.cleaned_data.get("photo"), "message": ugettext("Successfully saved the data."), }, ) return render( request, "person/edit_profile.html", {"form": vf, "message": ugettext("Please correct the errors on the page")}, )
def test_user_profile(self): settings.AUTH_PROFILE_MODULE = 'auth.UserProfile' data = { 'username': '******', 'password': '******', 'email': '*****@*****.**', } user = User(**data) user.save() profiledata = { 'user_id': user.get_id, 'age': 7, } userprofile = UserProfile(**profiledata) userprofile.save() userprofile = UserProfile.get_userprofile(profiledata['user_id']) self.assertIsNotNone(userprofile) self.assertEqual(user.get_profile().age, profiledata['age'])
def test_user_change_email(self): data = { 'username': '******', 'password': '******', 'email': '*****@*****.**', } user = User(**data) user.save() user = User.get_user_by_email(data['email']) user.email = '*****@*****.**' user.save()
def create_inactive_user(username, email, password, site, send_email=True): """ Create a new, inactive ``User``, generate a ``RegistrationProfile`` and email its activation key to the ``User``, returning the new ``User``. By default, an activation email will be sent to the new user. To disable this, pass ``send_email=False``. """ new_user = User() new_user.username = username new_user.email = email new_user.set_password(password) new_user.is_active = False create_profile(new_user) new_user.save() if send_email: new_user.send_activation_email(site) return new_user
def migrate_users( get_user_data=lambda _: {}, get_profile_data=lambda p: p.__dict__, progress_callback= lambda: None): users = Dj_User.objects.all() ATTRIBS = ('username', 'first_name', 'last_name', 'email', 'password', 'is_staff', 'is_active', 'is_superuser', 'last_login', 'date_joined') total = users.count() for n, user in enumerate(users): data = user.__dict__ try: profile = user.get_profile() data.update(get_profile_data(profile)) except: pass data.update(get_user_data(user)) # filter private variables data = dict( (k, v) for (k, v) in data.items() if not k.startswith('_') and k != 'user_id') new_user = User.get_user(data['username']) or User() for attrib, val in data.items(): if attrib == 'id': continue setattr(new_user, attrib, val) new_user.save() progress_callback(n, total)
def delete_expired_users(): """ Remove expired instances of ``RegistrationProfile`` and their associated ``User``s. Accounts to be deleted are identified by searching for instances of ``RegistrationProfile`` with expired activation keys, and then checking to see if their associated ``User`` instances have the field ``is_active`` set to ``False``; any ``User`` who is both inactive and has an expired activation key will be deleted. It is recommended that this method be executed regularly as part of your routine site maintenance; this application provides a custom management command which will call this method, accessible as ``manage.py cleanupregistration``. Regularly clearing out accounts which have never been activated serves two useful purposes: 1. It alleviates the ocasional need to reset a ``RegistrationProfile`` and/or re-send an activation email when a user does not receive or does not act upon the initial activation email; since the account will be deleted, the user will be able to simply re-register and receive a new activation key. 2. It prevents the possibility of a malicious user registering one or more accounts and never activating them (thus denying the use of those usernames to anyone else); since those accounts will be deleted, the usernames will become available for use again. If you have a troublesome ``User`` and wish to disable their account while keeping it in the database, simply delete the associated ``RegistrationProfile``; an inactive ``User`` which does not have an associated ``RegistrationProfile`` will not be deleted. """ for user in User.all_users(): if user.activation_key_expired(): if not user.is_active: user.delete()
def migrate_users(get_user_data=lambda _: {}, get_profile_data=lambda p: p.__dict__, progress_callback=lambda: None): users = Dj_User.objects.all() ATTRIBS = ( "username", "first_name", "last_name", "email", "password", "is_staff", "is_active", "is_superuser", "last_login", "date_joined", ) total = users.count() for n, user in enumerate(users): data = user.__dict__ try: profile = user.get_profile() data.update(get_profile_data(profile)) except: pass data.update(get_user_data(user)) # filter private variables data = dict((k, v) for (k, v) in data.items() if not k.startswith("_") and k != "user_id") new_user = User.get_user(data["username"]) or User() for attrib, val in data.items(): if attrib == "id": continue setattr(new_user, attrib, val) new_user.save() progress_callback(n, total)
def suggest_nickname(self, nickname): "Return a suggested nickname that has not yet been taken" if not nickname: return '' original_nickname = nickname suffix = None username_exists = True while username_exists: try: username_exists = User.view('%s/users_by_username' % User._meta.app_label, key=nickname, include_docs=True).count() except ResourceNotFound: username_exists = False if not username_exists: break if suffix is None: suffix = 1 else: suffix += 1 nickname = original_nickname + str(suffix) return nickname
def create_user(self, request, data, openid=None): user = User( username = data['username'], first_name = data.get('first_name', ''), last_name = data.get('last_name', ''), email = data.get('email', ''), ) # Set OpenID, if one has been associated if openid: uoa = UserOpenidAssociation(user_id = user.username, openid = openid, created = datetime.now()) uoa.store() # Set password, if one has been specified password = data.get('password') if password: user.set_password(password) else: user.set_unusable_password() user.store() return user
def save(self): user = User(**self.cleaned_data) return user.store()
def lookup_users_by_email(self, email): return User.view('%s/users_by_email' % User._meta.app_label, key=email, include_docs=True).first()
def lookup_user_by_username(self, username): return User.view('%s/users_by_username' % User._meta.app_label, reduce=False, key=username, include_docs=True).first()