def check_permissions(self): """ Checks that all permissions are set correctly for the users. :return: A set of users whose permissions was wrong. """ # Variable to supply some feedback changed_permissions = [] changed_users = [] warnings = [] # Check that all the permissions are available. for model, perms in ASSIGNED_PERMISSIONS.items(): if model == "profile": model_obj = get_profile_model() else: model_obj = get_user_model() model_content_type = ContentType.objects.get_for_model(model_obj) for perm in perms: try: Permission.objects.get( codename=perm[0], content_type=model_content_type ) except Permission.DoesNotExist: changed_permissions.append(perm[1]) Permission.objects.create( name=perm[1], codename=perm[0], content_type=model_content_type ) # it is safe to rely on settings.ANONYMOUS_USER_NAME since it is a # requirement of django-guardian for user in get_user_model().objects.exclude( username=settings.ANONYMOUS_USER_NAME ): try: user_profile = get_user_profile(user=user) except ObjectDoesNotExist: warnings.append( _("No profile found for %(username)s") % {"username": user.username} ) else: all_permissions = get_perms(user, user_profile) + get_perms(user, user) for model, perms in ASSIGNED_PERMISSIONS.items(): if model == "profile": perm_object = get_user_profile(user=user) else: perm_object = user for perm in perms: if perm[0] not in all_permissions: assign_perm(perm[0], user, perm_object) changed_users.append(user) return (changed_permissions, changed_users, warnings)
def create_profile(user=None, is_new=False, *args, **kwargs): """Create user profile if necessary.""" if is_new: UserenaSignup.objects.get_or_create(user=user) # Give permissions to view and change profile for perm in ASSIGNED_PERMISSIONS["profile"]: assign_perm(perm[0], user, get_user_profile(user=user)) # Give permissions to view and change itself for perm in ASSIGNED_PERMISSIONS["user"]: assign_perm(perm[0], user, user) return {"profile": get_user_profile(user=user)}
def check_permissions(self): """ Checks that all permissions are set correctly for the users. :return: A set of users whose permissions was wrong. """ # Variable to supply some feedback changed_permissions = [] changed_users = [] warnings = [] # Check that all the permissions are available. for model, perms in ASSIGNED_PERMISSIONS.items(): if model == 'profile': model_obj = get_profile_model() else: model_obj = get_user_model() model_content_type = ContentType.objects.get_for_model(model_obj) for perm in perms: try: Permission.objects.get(codename=perm[0], content_type=model_content_type) except Permission.DoesNotExist: changed_permissions.append(perm[1]) Permission.objects.create(name=perm[1], codename=perm[0], content_type=model_content_type) # it is safe to rely on settings.ANONYMOUS_USER_ID since it is a # requirement of django-guardian for user in get_user_model().objects.exclude(id=settings.ANONYMOUS_USER_ID): try: user_profile = get_user_profile(user=user) except ObjectDoesNotExist: warnings.append(_("No profile found for %(username)s") \ % {'username': user.username}) else: all_permissions = get_perms(user, user_profile) + get_perms(user, user) for model, perms in ASSIGNED_PERMISSIONS.items(): if model == 'profile': perm_object = get_user_profile(user=user) else: perm_object = user for perm in perms: if perm[0] not in all_permissions: assign_perm(perm[0], user, perm_object) changed_users.append(user) return (changed_permissions, changed_users, warnings)
def test_create_inactive_user(self): """ Test the creation of a new user. ``UserenaSignup.create_inactive_user`` should create a new user that is not active. The user should get an ``activation_key`` that is used to set the user as active. Every user also has a profile, so this method should create an empty profile. """ # Check that the fields are set. new_user = UserenaSignup.objects.create_user(**self.user_info) self.assertEqual(new_user.username, self.user_info['username']) self.assertEqual(new_user.email, self.user_info['email']) self.failUnless(new_user.check_password(self.user_info['password'])) # User should be inactive self.failIf(new_user.is_active) # User has a valid SHA1 activation key self.failUnless( re.match('^[a-f0-9]{40}$', new_user.userena_signup.activation_key)) # User now has an profile. self.failUnless(get_user_profile(user=new_user)) # User should be saved self.failUnlessEqual( User.objects.filter(email=self.user_info['email']).count(), 1)
def test_create_inactive_user(self): """ Test the creation of a new user. ``UserenaSignup.create_inactive_user`` should create a new user that is not active. The user should get an ``activation_key`` that is used to set the user as active. Every user also has a profile, so this method should create an empty profile. """ # Check that the fields are set. new_user = UserenaSignup.objects.create_user(**self.user_info) self.assertEqual(new_user.username, self.user_info["username"]) self.assertEqual(new_user.email, self.user_info["email"]) self.assertTrue(new_user.check_password(self.user_info["password"])) # User should be inactive self.assertFalse(new_user.is_active) # User has a valid activation key self.assertTrue( re.match(r"^[\w]{40}$", new_user.userena_signup.activation_key)) # User now has an profile. self.assertTrue(get_user_profile(user=new_user)) # User should be saved self.assertEqual( User.objects.filter(email=self.user_info["email"]).count(), 1)
def oauth(request): try: code = request.GET.get('code', '') token_str = _access_token(request, code) token_json = json.loads(token_str) user = authenticate(token=token_json['access_token'], uid=token_json['uid'], expire_in=(60 * 60 * 24)) if user: try: user_str = _show_user(token_json['access_token'], token_json['uid']) user_json = json.loads(user_str) user.username = user_json['screen_name'] user.save() except: pass auth_login(request, user) profile = get_user_profile(user) profile.source = UserSource.objects.get(flag=100) profile.save() return HttpResponseRedirect(signin_redirect(user=user)) except: return HttpResponse("很抱歉,使用新浪微博认证登录失败,请尝试从网站注册!")
def profile_detail(request, username): user = get_object_or_404(User, username=username) profile = get_user_profile(user) context = { 'profile': profile, } return render(request, 'accounts/detail.html', context)
def test_activation_valid(self): """ Valid activation of an user. Activation of an user with a valid ``activation_key`` should activate the user and set a new invalid ``activation_key`` that is defined in the setting ``USERENA_ACTIVATED``. """ user = UserenaSignup.objects.create_user(**self.user_info) active_user = UserenaSignup.objects.activate_user( user.userena_signup.activation_key) profile = get_user_profile(user=active_user) # The returned user should be the same as the one just created. self.assertEqual(user, active_user) # The user should now be active. self.assertTrue(active_user.is_active) # The user should have permission to view and change its profile self.assertTrue("view_profile" in get_perms(active_user, profile)) self.assertTrue("change_profile" in get_perms(active_user, profile)) # The activation key should be the same as in the settings self.assertEqual( active_user.userena_signup.activation_key, userena_settings.USERENA_ACTIVATED, )
def profile_detail( request, username, template_name=userena_settings.USERENA_PROFILE_DETAIL_TEMPLATE, extra_context=None, **kwargs): """ Detailed view of an user. :param username: String of the username of which the profile should be viewed. :param template_name: String representing the template name that should be used to display the profile. :param extra_context: Dictionary of variables which should be supplied to the template. The ``profile`` key is always the current profile. **Context** ``profile`` Instance of the currently viewed ``Profile``. """ user = get_object_or_404(get_user_model(), username__iexact=username) profile = get_user_profile(user=user) if not profile.can_view_profile(request.user): raise PermissionDenied if not extra_context: extra_context = dict() extra_context['profile'] = profile extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL return ExtraContextTemplateView.as_view( template_name=template_name, extra_context=extra_context)(request)
def profile_detail(request, username, template_name=userena_settings.USERENA_PROFILE_DETAIL_TEMPLATE, extra_context=None, **kwargs): """ Detailed view of an user. :param username: String of the username of which the profile should be viewed. :param template_name: String representing the template name that should be used to display the profile. :param extra_context: Dictionary of variables which should be supplied to the template. The ``profile`` key is always the current profile. **Context** ``profile`` Instance of the currently viewed ``Profile``. """ user = get_object_or_404(get_user_model(), username__iexact=username) profile = get_user_profile(user=user) if not profile.can_view_profile(request.user): raise PermissionDenied if not extra_context: extra_context = dict() extra_context['profile'] = profile extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL return ExtraContextTemplateView.as_view(template_name=template_name, extra_context=extra_context)(request)
def test_create_inactive_user(self): """ Test the creation of a new user. ``UserenaSignup.create_inactive_user`` should create a new user that is not active. The user should get an ``activation_key`` that is used to set the user as active. Every user also has a profile, so this method should create an empty profile. """ # Check that the fields are set. new_user = UserenaSignup.objects.create_user(**self.user_info) self.assertEqual(new_user.username, self.user_info['username']) self.assertEqual(new_user.email, self.user_info['email']) self.failUnless(new_user.check_password(self.user_info['password'])) # User should be inactive self.failIf(new_user.is_active) # User has a valid SHA1 activation key self.failUnless(re.match('^[a-f0-9]{40}$', new_user.userena_signup.activation_key)) # User now has an profile. self.failUnless(get_user_profile(user=new_user)) # User should be saved self.failUnlessEqual(User.objects.filter(email=self.user_info['email']).count(), 1)
def test_activation_valid(self): """ Valid activation of an user. Activation of an user with a valid ``activation_key`` should activate the user and set a new invalid ``activation_key`` that is defined in the setting ``USERENA_ACTIVATED``. """ user = UserenaSignup.objects.create_user(**self.user_info) active_user = UserenaSignup.objects.activate_user(user.userena_signup.activation_key) profile = get_user_profile(user=active_user) # The returned user should be the same as the one just created. self.failUnlessEqual(user, active_user) # The user should now be active. self.failUnless(active_user.is_active) # The user should have permission to view and change its profile self.failUnless('view_profile' in get_perms(active_user, profile)) self.failUnless('change_profile' in get_perms(active_user, profile)) # The activation key should be the same as in the settings self.assertEqual(active_user.userena_signup.activation_key, userena_settings.USERENA_ACTIVATED)
def disabled_account( request, username, template_name="userena/disabled.html", extra_context=None, ): """ Checks if the account is not active, if so, returns the disabled account template. The ``disabled_account`` view has a high bar: it should only be shown if the user has a completed activation. Otherwise, redirect to `userena_activate_pending``. If no ``UserenaSignup`` object can be found for the user, we will still assume that it was deleted after expiration but not that account was deliberately disabled. :param username: String defining the username of the user that made the action. :param template_name: String defining the name of the template to use. Defaults to ``userena/disabled.html``. **Keyword arguments** ``extra_context`` A dictionary containing extra variables that should be passed to the rendered template. The ``account`` key is always the ``User`` that completed the action. **Extra context** ``viewed_user`` The currently :class:`User` that is viewed. ``profile`` Profile of the viewed user. """ user = get_object_or_404( get_user_model(), username__iexact=username, is_active=False ) if not user.userena_signup.activation_completed: return redirect( reverse( "userena_activate_pending", kwargs={"username": user.username} ) ) if not extra_context: extra_context = dict() extra_context["viewed_user"] = user extra_context["profile"] = get_user_profile(user=user) return ExtraContextTemplateView.as_view( template_name=template_name, extra_context=extra_context )(request)
def profile_detail( request, username, template_name=userena_settings.USERENA_PROFILE_DETAIL_TEMPLATE, extra_context=None, **kwargs): """ Detailed view of an user. :param username: String of the username of which the profile should be viewed. :param template_name: String representing the template name that should be used to display the profile. :param extra_context: Dictionary of variables which should be supplied to the template. The ``profile`` key is always the current profile. **Context** ``profile`` Instance of the currently viewed ``Profile``. """ user = get_object_or_404(get_user_model(), username__iexact=username) profile = get_user_profile(user=user) if not profile.can_view_profile(request.user): raise PermissionDenied if not extra_context: extra_context = dict() if request.method == 'POST': p = UserReviewForm(request.POST) tester1 = User.objects.get(username=username) if p.is_valid(): reviewform = p.save(commit=False) reviewform.name = tester1 reviewform.author = request.user reviewform.save() staravg = UserReview.objects.filter( name__username__iexact=username).aggregate(Avg('stars')) h = MyProfile.objects.get(user__username__iexact=username) h.reviewavg = staravg['stars__avg'] h.save() return redirect('/accounts/{}'.format(tester1)) else: p = UserReviewForm() hotsellers = Entry.objects.filter(author__username=username)[:4] userreviews = UserReview.objects.filter(name__username=username) extra_context['profile'] = user.my_profile extra_context['hotsellers'] = hotsellers extra_context['userreviews'] = userreviews extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL extra_context['form'] = p return ExtraContextTemplateView.as_view( template_name=template_name, extra_context=extra_context)(request)
def profile_detail_extended(request, username, edit_profile_form=EditProfileForm, template_name='userena/profile_detail_extended.html', success_url=None,extra_context=None, **kwargs): user = get_object_or_404(get_user_model(), username__iexact=username) profile = get_user_profile(user=user) if not extra_context: extra_context = dict() extra_context['profile'] = profile extra_context['profExpData'] = Profile_Experience.objects.filter(profile = profile) extra_context['projExpData'] = Project_Experience.objects.filter(profile = profile) extra_context['awardsData'] = Awards.objects.filter(profile = profile) return ExtraContextTemplateView.as_view(template_name=template_name, extra_context=extra_context)(request)
def get_object(self, queryset=None): user = get_object_or_404(get_user_model(), username__iexact=self.kwargs['username']) self.profile = get_user_profile(user=user) if not self.profile.can_view_profile(self.request.user): raise PermissionDenied self.profile.increment_nb_views()
def favourite(request, username): user = get_object_or_404(User, username=username) profile = get_user_profile(user) presenter_list = user.my_profile.follows.order_by('-presenterdetail__showing', '-presenterdetail__audience_count'); context = { 'profile': profile, 'presenter_list': presenter_list, } return render(request, 'accounts/favourite.html', context)
def send_invitation_email(self): """ Sends a invitation email to the user. This email is send when the user wants to invite their newly created user. """ context = {'img_url' : get_user_profile(user=self.user).get_mugshot_url(), 'inviter': get_user_profile(self.user).invitedBy.user, 'without_usernames': userena_settings.USERENA_WITHOUT_USERNAMES, 'protocol': get_protocol(), 'activation_days': userena_settings.USERENA_ACTIVATION_DAYS, 'invitation_key': self.invitation_key, 'site': Site.objects.get_current()} mailer = UserenaConfirmationMail(context=context) mailer.generate_mail("invitation") mailer.send_mail(self.user.email)
def get_queryset(self): logging.error(get_user_profile(self.request.user).__dict__) profile_model = get_profile_model() logging.error(profile_model.__dict__) logging.error(profile_model.objects.all()) logging.error(profile_model.__doc__) ## logging.error(self.__dict__) ## logging.error(self.request.__dict__) queryset = profile_model.objects.get_visible_profiles(self.request.user).select_related() return queryset
def favourite(request, username): user = get_object_or_404(User, username=username) profile = get_user_profile(user) presenter_list = user.my_profile.follows.order_by( '-presenterdetail__showing', '-presenterdetail__audience_count') context = { 'profile': profile, 'presenter_list': presenter_list, } return render(request, 'accounts/favourite.html', context)
def custom_profile_edit(request, username, *args, **kwargs): form = UserProfileEditForm user = get_object_or_404(get_user_model(), username__iexact=username) profile = get_user_profile(user=user) extra_context = { 'allowed_archival_units': profile.allowed_archival_units.all() } return profile_edit(request, edit_profile_form=form, extra_context=extra_context, username=username, *args, **kwargs)
def create_user(self, username, email, password, active=False, send_email=True): """ A simple wrapper that creates a new :class:`User`. :param username: String containing the username of the new user. :param email: String containing the email address of the new user. :param password: String containing the password for the new user. :param active: Boolean that defines if the user requires activation by clicking on a link in an e-mail. Defaults to ``False``. :param send_email: Boolean that defines if the user should be sent an email. You could set this to ``False`` when you want to create a user in your own code, but don't want the user to activate through email. :return: :class:`User` instance representing the new user. """ new_user = get_user_model().objects.create_user( username, email, password) new_user.is_active = active new_user.save() # Give permissions to view and change profile for perm in ASSIGNED_PERMISSIONS['profile']: assign_perm(perm[0], new_user, get_user_profile(user=new_user)) # Give permissions to view and change itself for perm in ASSIGNED_PERMISSIONS['user']: assign_perm(perm[0], new_user, new_user) userena_profile = self.create_userena_profile(new_user) if send_email: userena_profile.send_activation_email() return new_user
def invite_user(self,inviter,invited_email): if inviter.get_remaining_invite_tickets_number()>0 : password=self.make_random_password()#et_random_string() invitedUser = get_user_model().objects.create_user( invited_email.replace('@','-'),invited_email,password ) invitedUser.is_active = False invitedUser.save() # Give permissions to view and change profile for perm in ASSIGNED_PERMISSIONS['profile']: assign_perm(perm[0], invitedUser, get_user_profile(user=invitedUser)) # Give permissions to view and change itself for perm in ASSIGNED_PERMISSIONS['user']: assign_perm(perm[0], invitedUser, invitedUser) invitedUserSignupInfo = self.create_userena_profile(invitedUser) invitedUserSignupInfo.invite_status='INV' # user is invited invitedProfile=get_user_profile(user=invitedUser) inviter.invited_users.add(invitedProfile) invitedUserSignupInfo.send_invitation_email() return True else: return False
def process_request(self, request): lang_cookie = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME) if not lang_cookie: if request.user.is_authenticated(): try: profile = get_user_profile(user=request.user) except (ObjectDoesNotExist, SiteProfileNotAvailable): profile = False if profile: try: lang = getattr(profile, userena_settings.USERENA_LANGUAGE_FIELD) translation.activate(lang) request.LANGUAGE_CODE = translation.get_language() except AttributeError: pass
def get_queryset(self): if self.request.session.get('usertype', None) != None: user_profile = get_user_profile(self.request.user) logging.error(user_profile.__dict__) self.request.session['usertype'] = user_profile.usertype logging.error(self.request.session.__dict__) """Return the last five published questions.""" ##return Question.objects.order_by('-pub_date')[:5] meallist = Meal.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5] ##logging.error(meallist.__dict__) return meallist
def test_preference_user(self): """ Test the language preference of two users """ users = ((1, 'nl'), (2, 'en')) for pk, lang in users: user = User.objects.get(pk=pk) profile = get_user_profile(user=user) req = self._get_request_with_user(user) # Check that the user has this preference self.failUnlessEqual(profile.language, lang) # Request should have a ``LANGUAGE_CODE`` with dutch UserenaLocaleMiddleware().process_request(req) self.failUnlessEqual(req.LANGUAGE_CODE, lang)
def process_request(self, request): lang_cookie = request.session.get(settings.LANGUAGE_COOKIE_NAME) if not lang_cookie: if request.user.is_authenticated(): try: profile = get_user_profile(user=request.user) except (ObjectDoesNotExist, SiteProfileNotAvailable): profile = False if profile: try: lang = getattr(profile, userena_settings.USERENA_LANGUAGE_FIELD) translation.activate(lang) request.LANGUAGE_CODE = translation.get_language() except AttributeError: pass
def test_profile_edit_view_success(self): """ A ``POST`` to the edit view """ self.client.login(username="******", password="******") new_about_me = "I hate it when people use my name for testing." response = self.client.post( reverse("userena_profile_edit", kwargs={"username": "******"}), data={"about_me": new_about_me, "privacy": "open", "language": "en"}, ) # A valid post should redirect to the detail page. self.assertRedirects( response, reverse("userena_profile_detail", kwargs={"username": "******"}) ) # Users hould be changed now. profile = get_user_profile(user=User.objects.get(username="******")) self.assertEqual(profile.about_me, new_about_me)
def test_profile_edit_view_success(self): """ A ``POST`` to the edit view """ self.client.login(username='******', password='******') new_about_me = 'I hate it when people use my name for testing.' response = self.client.post(reverse('userena_profile_edit', kwargs={'username': '******'}), data={'about_me': new_about_me, 'privacy': 'open', 'language': 'en'}) # A valid post should redirect to the detail page. self.assertRedirects(response, reverse('userena_profile_detail', kwargs={'username': '******'})) # Users hould be changed now. profile = get_user_profile(user=User.objects.get(username='******')) self.assertEqual(profile.about_me, new_about_me)
def test_preference_user(self): """ Test the language preference of two users """ users = ((1, 'nl'), (2, 'en')) for pk, lang in users: user = User.objects.get(pk=pk) profile = get_user_profile(user=user) req = self._get_request_with_user(user) # Check that the user has this preference self.assertEqual(profile.language, lang) # Request should have a ``LANGUAGE_CODE`` with dutch UserenaLocaleMiddleware().process_request(req) self.assertEqual(req.LANGUAGE_CODE, lang)
def test_upload_mugshot(self): """ Test the uploaded path of mugshots TODO: What if a image get's uploaded with no extension? """ user = User.objects.get(pk=1) filename = 'my_avatar.png' path = upload_to_mugshot(get_user_profile(user=user), filename) # Path should be changed from the original self.failIfEqual(filename, path) # Check if the correct path is returned MUGSHOT_RE = re.compile('^%(mugshot_path)s[a-f0-9]{10}.png$' % {'mugshot_path': userena_settings.USERENA_MUGSHOT_PATH}) self.failUnless(MUGSHOT_RE.search(path))
def profile_edit(request, username): user = get_object_or_404(User, username=username) profile = get_user_profile(user) if request.method == 'POST': print request.POST form = EditProfileForm(request.POST, request.FILES) if form.is_valid(): mugshot = form.cleaned_data['mugshot'] if mugshot: profile.mugshot = form.cleaned_data['mugshot'] profile.save() else: form = EditProfileForm() context = { 'profile': profile, 'form': form, } return render(request, 'accounts/edit.html', context)
def test_upload_mugshot(self): """ Test the uploaded path of mugshots TODO: What if a image get's uploaded with no extension? """ user = User.objects.get(pk=1) filename = 'my_avatar.png' path = upload_to_mugshot(get_user_profile(user=user), filename) # Path should be changed from the original self.failIfEqual(filename, path) # Check if the correct path is returned MUGSHOT_RE = re.compile( '^%(mugshot_path)s[a-f0-9]{10}.png$' % {'mugshot_path': userena_settings.USERENA_MUGSHOT_PATH}) self.failUnless(MUGSHOT_RE.search(path))
def http_notification(request): response = HttpResponse(status=404) if request.method == 'POST': line_notification_options = '%s&%s&%s&%s&%s&%s&%s&%s&%s' % ( request.POST['notification_type'], request.POST['operation_id'], request.POST['amount'], request.POST['currency'], request.POST['datetime'], request.POST['sender'], request.POST['codepro'], settings.YANDEX_MONEY_SECRET_WORD, request.POST['label']) print(line_notification_options) print(request.POST['sha1_hash']) print(hashlib.sha1(line_notification_options.encode()).hexdigest()) if request.POST['sha1_hash'] == hashlib.sha1( line_notification_options.encode()).hexdigest(): YadTransaction.objects.create( notification_type=request.POST['notification_type'], currency=int(request.POST['currency']), operation_id=request.POST['operation_id'], amount=request.POST['amount'], withdraw_amount=request.POST['withdraw_amount'] if 'withdraw_amount' in request.POST else 0, datetime_transfer=dateutil.parser.parse( request.POST['datetime']), sender=request.POST['sender'], codepro=False if request.POST['codepro'] == 'false' else True, label=request.POST['label'], test_notification=True if 'test_notification' in request.POST else False, ) print(request.POST['label']) if request.POST['label']: print(request.POST['label']) user = get_object_or_404( get_user_model(), username__iexact=request.POST['label']) profile = get_user_profile(user=user) profile.wallet += float(request.POST['amount']) profile.save() response = HttpResponse(status=200) return response
def test_upload_mugshot(self): """ Test the uploaded path of mugshots TODO: What if a image get's uploaded with no extension? """ user = User.objects.get(pk=1) filename = "my_avatar.png" path = upload_to_mugshot(get_user_profile(user=user), filename) # Path should be changed from the original self.assertNotEqual(filename, path) # Check if the correct path is returned mugshot_re = re.compile( r"^%(mugshot_path)s[\w]{10}.png$" % {"mugshot_path": userena_settings.USERENA_MUGSHOT_PATH} ) self.assertTrue(mugshot_re.search(path))
def test_get_full_name_or_username(self): """ Test if the full name or username are returned correcly """ user = User.objects.get(pk=1) profile = get_user_profile(user=user) # Profile #1 has a first and last name full_name = profile.get_full_name_or_username() self.assertEqual(full_name, "John Doe") # Let's empty out his name, now we should get his username user.first_name = "" user.last_name = "" user.save() self.assertEqual(profile.get_full_name_or_username(), "john") # Finally, userena doesn't use any usernames, so we should return the # e-mail address. userena_settings.USERENA_WITHOUT_USERNAMES = True self.assertEqual(profile.get_full_name_or_username(), "*****@*****.**") userena_settings.USERENA_WITHOUT_USERNAMES = False
def direct_to_user_template(request, username, template_name, extra_context=None): """ Simple wrapper for Django's :func:`direct_to_template` view. This view is used when you want to show a template to a specific user. A wrapper for :func:`direct_to_template` where the template also has access to the user that is found with ``username``. For ex. used after signup, activation and confirmation of a new e-mail. :param username: String defining the username of the user that made the action. :param template_name: String defining the name of the template to use. Defaults to ``userena/signup_complete.html``. **Keyword arguments** ``extra_context`` A dictionary containing extra variables that should be passed to the rendered template. The ``account`` key is always the ``User`` that completed the action. **Extra context** ``viewed_user`` The currently :class:`User` that is viewed. """ user = get_object_or_404(get_user_model(), username__iexact=username) if not extra_context: extra_context = dict() extra_context["viewed_user"] = user extra_context["profile"] = get_user_profile(user=user) return ExtraContextTemplateView.as_view( template_name=template_name, extra_context=extra_context)(request)
def direct_to_user_template(request, username, template_name, extra_context=None): """ Simple wrapper for Django's :func:`direct_to_template` view. This view is used when you want to show a template to a specific user. A wrapper for :func:`direct_to_template` where the template also has access to the user that is found with ``username``. For ex. used after signup, activation and confirmation of a new e-mail. :param username: String defining the username of the user that made the action. :param template_name: String defining the name of the template to use. Defaults to ``userena/signup_complete.html``. **Keyword arguments** ``extra_context`` A dictionary containing extra variables that should be passed to the rendered template. The ``account`` key is always the ``User`` that completed the action. **Extra context** ``viewed_user`` The currently :class:`User` that is viewed. """ user = get_object_or_404(get_user_model(), username__iexact=username) if not extra_context: extra_context = dict() extra_context['viewed_user'] = user extra_context['request'] = request extra_context['profile'] = get_user_profile(user=user) return ExtraContextTemplateView.as_view(template_name=template_name, extra_context=extra_context)(request)
def disabled_account(request, username, template_name, extra_context=None): """ Checks if the account is disabled, if so, returns the disabled account template. :param username: String defining the username of the user that made the action. :param template_name: String defining the name of the template to use. Defaults to ``userena/signup_complete.html``. **Keyword arguments** ``extra_context`` A dictionary containing extra variables that should be passed to the rendered template. The ``account`` key is always the ``User`` that completed the action. **Extra context** ``viewed_user`` The currently :class:`User` that is viewed. ``profile`` Profile of the viewed user. """ user = get_object_or_404(get_user_model(), username__iexact=username) if user.is_active: raise Http404 if not extra_context: extra_context = dict() extra_context["viewed_user"] = user extra_context["profile"] = get_user_profile(user=user) return ExtraContextTemplateView.as_view( template_name=template_name, extra_context=extra_context )(request)
def test_get_full_name_or_username(self): """ Test if the full name or username are returned correcly """ user = User.objects.get(pk=1) profile = get_user_profile(user=user) # Profile #1 has a first and last name full_name = profile.get_full_name_or_username() self.failUnlessEqual(full_name, "John Doe") # Let's empty out his name, now we should get his username user.first_name = '' user.last_name = '' user.save() self.failUnlessEqual(profile.get_full_name_or_username(), "john") # Finally, userena doesn't use any usernames, so we should return the # e-mail address. userena_settings.USERENA_WITHOUT_USERNAMES = True self.failUnlessEqual(profile.get_full_name_or_username(), "*****@*****.**") userena_settings.USERENA_WITHOUT_USERNAMES = False
def disabled_account(request, username, template_name, extra_context=None): """ Checks if the account is disabled, if so, returns the disabled account template. :param username: String defining the username of the user that made the action. :param template_name: String defining the name of the template to use. Defaults to ``userena/signup_complete.html``. **Keyword arguments** ``extra_context`` A dictionary containing extra variables that should be passed to the rendered template. The ``account`` key is always the ``User`` that completed the action. **Extra context** ``viewed_user`` The currently :class:`User` that is viewed. ``profile`` Profile of the viewed user. """ user = get_object_or_404(get_user_model(), username__iexact=username) if user.is_active: raise Http404 if not extra_context: extra_context = dict() extra_context['viewed_user'] = user extra_context['profile'] = get_user_profile(user=user) return ExtraContextTemplateView.as_view(template_name=template_name, extra_context=extra_context)(request)
def email_change(request, username, email_form=ChangeEmailForm, template_name='userena/email_form.html', success_url=None, extra_context=None): """ Change email address :param username: String of the username which specifies the current account. :param email_form: Form that will be used to change the email address. Defaults to :class:`ChangeEmailForm` supplied by userena. :param template_name: String containing the template to be used to display the email form. Defaults to ``userena/email_form.html``. :param success_url: Named URL where the user will get redirected to when successfully changing their email address. When not supplied will redirect to ``userena_email_complete`` URL. :param extra_context: Dictionary containing extra variables that can be used to render the template. The ``form`` key is always the form supplied by the keyword argument ``form`` and the ``user`` key by the user whose email address is being changed. **Context** ``form`` Form that is used to change the email address supplied by ``form``. ``account`` Instance of the ``Account`` whose email address is about to be changed. **Todo** Need to have per-object permissions, which enables users with the correct permissions to alter the email address of others. """ user = get_object_or_404(get_user_model(), username__iexact=username) prev_email = user.email form = email_form(user) if request.method == 'POST': form = email_form(user, request.POST, request.FILES) if form.is_valid(): form.save() if success_url: # Send a signal that the email has changed userena_signals.email_change.send(sender=None, user=user, prev_email=prev_email, new_email=user.email) redirect_to = success_url else: redirect_to = reverse('userena_email_change_complete', kwargs={'username': user.username}) return redirect(redirect_to) if not extra_context: extra_context = dict() extra_context['form'] = form extra_context['profile'] = get_user_profile(user=user) return ExtraContextTemplateView.as_view( template_name=template_name, extra_context=extra_context)(request)
def profile_edit_extended(request, username, edit_profile_form=EditProfileForm, template_name='userena/profile_form_extended.html', success_url=None,extra_context=None, **kwargs): """ Edit profile. Edits a profile selected by the supplied username. First checks permissions if the user is allowed to edit this profile, if denied will show a 404. When the profile is successfully edited will redirect to ``success_url``. :param username: Username of the user which profile should be edited. :param edit_profile_form: Form that is used to edit the profile. The :func:`EditProfileForm.save` method of this form will be called when the form :func:`EditProfileForm.is_valid`. Defaults to :class:`EditProfileForm` from userena. :param template_name: String of the template that is used to render this view. Defaults to ``userena/edit_profile_form.html``. :param success_url: Named URL which will be passed on to a django ``reverse`` function after the form is successfully saved. Defaults to the ``userena_detail`` url. :param extra_context: Dictionary containing variables that are passed on to the ``template_name`` template. ``form`` key will always be the form used to edit the profile, and the ``profile`` key is always the edited profile. **Context** ``form`` Form that is used to alter the profile. ``profile`` Instance of the ``Profile`` that is edited. """ user = get_object_or_404(get_user_model(), username__iexact=username) profile = get_user_profile(user=user) user_initial = {'first_name': user.first_name, 'last_name': user.last_name} form = edit_profile_form(instance=profile, initial=user_initial) #FormSetProfExp = formset_factory(ProfExpForm) #FormSetProjExp = formset_factory(ProjExpForm) #FormSetAwards = formset_factory(AwardsForm, can_delete = True) FormSetProfExp = modelformset_factory(Profile_Experience, exclude=('profile',), can_delete = True, widgets = {'jobstart':SelectDateWidget(),'jobend':SelectDateWidget() }) FormSetProjExp = modelformset_factory(Project_Experience, exclude=('profile',), can_delete = True,widgets = {'projectstart':SelectDateWidget(),'projectend':SelectDateWidget() }) FormSetAwards = modelformset_factory(Awards, exclude=('profile',), can_delete = True) if request.method == 'POST': formSetProfExp = FormSetProfExp(request.POST) formSetProjExp = FormSetProjExp(request.POST) formSetAwards = FormSetAwards(request.POST) ''' for form in formSetProfExp: if form.is_valid(): profExp = form.save(commit = False) profExp.profile = profile try: profExp.save() except IntegrityError: pass for form in formSetProjExp: if form.is_valid(): projExp = form.save(commit = False) projExp.profile = profile try: projExp.save() except IntegrityError: pass ''' if formSetProfExp.is_valid(): formSetProfExp.save(commit = False) for anobject in formSetProfExp.new_objects: anobject.profile = profile formSetProfExp.save(commit = True) if formSetProjExp.is_valid(): formSetProjExp.save(commit = False) for anobject in formSetProjExp.new_objects: anobject.profile = profile formSetProjExp.save(commit = True) if formSetAwards.is_valid(): formSetAwards.save(commit = False) for anobject in formSetAwards.new_objects: anobject.profile = profile formSetAwards.save(commit = True) form = edit_profile_form(request.POST, request.FILES, instance=profile, initial=user_initial) if form.is_valid(): profile = form.save() if userena_settings.USERENA_USE_MESSAGES: messages.success(request, _('Your profile has been updated.'),fail_silently=True) if success_url: # Send a signal that the profile has changed userena_signals.profile_change.send(sender=None, user=user) redirect_to = success_url else: redirect_to = reverse('userena_profile_detail', kwargs={'username': username}) return redirect(redirect_to) if not extra_context: extra_context = dict() extra_context['form'] = form extra_context['profile'] = profile # here additional arguments, such as "extra", may be passed formSetProfExp = FormSetProfExp(queryset = Profile_Experience.objects.filter(profile = profile)) formSetProjExp = FormSetProjExp(queryset = Project_Experience.objects.filter(profile = profile)) formSetAwards = FormSetAwards(queryset = Awards.objects.filter(profile = profile)) extra_context['formSetProfExp'] = formSetProfExp extra_context['formSetProjExp'] = formSetProjExp extra_context['formSetAwards'] = formSetAwards return ExtraContextTemplateView.as_view(template_name=template_name, extra_context=extra_context)(request)
def profile_edit(request, username, edit_profile_form=EditProfileForm, template_name='userena/profile_form.html', success_url=None, extra_context=None, **kwargs): """ Edit profile. Edits a profile selected by the supplied username. First checks permissions if the user is allowed to edit this profile, if denied will show a 404. When the profile is successfully edited will redirect to ``success_url``. :param username: Username of the user which profile should be edited. :param edit_profile_form: Form that is used to edit the profile. The :func:`EditProfileForm.save` method of this form will be called when the form :func:`EditProfileForm.is_valid`. Defaults to :class:`EditProfileForm` from userena. :param template_name: String of the template that is used to render this view. Defaults to ``userena/edit_profile_form.html``. :param success_url: Named URL which will be passed on to a django ``reverse`` function after the form is successfully saved. Defaults to the ``userena_detail`` url. :param extra_context: Dictionary containing variables that are passed on to the ``template_name`` template. ``form`` key will always be the form used to edit the profile, and the ``profile`` key is always the edited profile. **Context** ``form`` Form that is used to alter the profile. ``profile`` Instance of the ``Profile`` that is edited. """ user = get_object_or_404(get_user_model(), username__iexact=username) profile = get_user_profile(user=user) user_initial = {'first_name': user.first_name, 'last_name': user.last_name} form = edit_profile_form(instance=profile, initial=user_initial) if request.method == 'POST': form = edit_profile_form(request.POST, request.FILES, instance=profile, initial=user_initial) if form.is_valid(): profile = form.save() if userena_settings.USERENA_USE_MESSAGES: messages.success(request, _('Your profile has been updated.'), fail_silently=True) if success_url: # Send a signal that the profile has changed userena_signals.profile_change.send(sender=None, user=user) redirect_to = success_url else: redirect_to = reverse('userena_profile_detail', kwargs={'username': username}) return redirect(redirect_to) if not extra_context: extra_context = dict() extra_context['form'] = form extra_context['profile'] = profile return ExtraContextTemplateView.as_view(template_name=template_name, extra_context=extra_context)(request)
def password_change(request, username, template_name='userena/password_form.html', pass_form=PasswordChangeForm, success_url=None, extra_context=None): """ Change password of user. This view is almost a mirror of the view supplied in :func:`contrib.auth.views.password_change`, with the minor change that in this view we also use the username to change the password. This was needed to keep our URLs logical (and REST) across the entire application. And that in a later stadium administrators can also change the users password through the web application itself. :param username: String supplying the username of the user who's password is about to be changed. :param template_name: String of the name of the template that is used to display the password change form. Defaults to ``userena/password_form.html``. :param pass_form: Form used to change password. Default is the form supplied by Django itself named ``PasswordChangeForm``. :param success_url: Named URL that is passed onto a :func:`reverse` function with ``username`` of the active user. Defaults to the ``userena_password_complete`` URL. :param extra_context: Dictionary of extra variables that are passed on to the template. The ``form`` key is always used by the form supplied by ``pass_form``. **Context** ``form`` Form used to change the password. """ user = get_object_or_404(get_user_model(), username__iexact=username) form = pass_form(user=user) if request.method == "POST": form = pass_form(user=user, data=request.POST) if form.is_valid(): form.save() # Send a signal that the password has changed userena_signals.password_complete.send(sender=None, user=user) if success_url: redirect_to = success_url else: redirect_to = reverse('userena_password_change_complete', kwargs={'username': user.username}) return redirect(redirect_to) if not extra_context: extra_context = dict() extra_context['form'] = form extra_context['profile'] = get_user_profile(user=user) return ExtraContextTemplateView.as_view(template_name=template_name, extra_context=extra_context)(request)
def email_change(request, username, email_form=ChangeEmailForm, template_name='userena/email_form.html', success_url=None, extra_context=None): """ Change email address :param username: String of the username which specifies the current account. :param email_form: Form that will be used to change the email address. Defaults to :class:`ChangeEmailForm` supplied by userena. :param template_name: String containing the template to be used to display the email form. Defaults to ``userena/email_form.html``. :param success_url: Named URL where the user will get redirected to when successfully changing their email address. When not supplied will redirect to ``userena_email_complete`` URL. :param extra_context: Dictionary containing extra variables that can be used to render the template. The ``form`` key is always the form supplied by the keyword argument ``form`` and the ``user`` key by the user whose email address is being changed. **Context** ``form`` Form that is used to change the email address supplied by ``form``. ``account`` Instance of the ``Account`` whose email address is about to be changed. **Todo** Need to have per-object permissions, which enables users with the correct permissions to alter the email address of others. """ user = get_object_or_404(get_user_model(), username__iexact=username) prev_email = user.email form = email_form(user) if request.method == 'POST': form = email_form(user, request.POST, request.FILES) if form.is_valid(): form.save() if success_url: # Send a signal that the email has changed userena_signals.email_change.send(sender=None, user=user, prev_email=prev_email, new_email=user.email) redirect_to = success_url else: redirect_to = reverse('userena_email_change_complete', kwargs={'username': user.username}) return redirect(redirect_to) if not extra_context: extra_context = dict() extra_context['form'] = form extra_context['profile'] = get_user_profile(user=user) return ExtraContextTemplateView.as_view(template_name=template_name, extra_context=extra_context)(request)
def update_user_source(sender, user, *args, **kwargs): profile = get_user_profile(user) profile.source = UserSource.objects.get(flag=10) profile.save()
def create_user(self, username, email, password, active=False, send_email=True, pending_activation=False, first_name="", last_name="", organization = ""): """ A simple wrapper that creates a new :class:`User`. :param username: String containing the username of the new user. :param email: String containing the email address of the new user. :param password: String containing the password for the new user. :param active: Boolean that defines if the user requires activation by clicking on a link in an e-mail. Defaults to ``False``. :param send_email: Boolean that defines if the user should be sent an email. You could set this to ``False`` when you want to create a user in your own code, but don't want the user to activate through email. :return: :class:`User` instance representing the new user. """ new_user = get_user_model().objects.create_user( username, email, password) new_user.is_active = active new_user.first_name = first_name new_user.last_name = last_name new_user.save() userena_profile = self.create_userena_profile(new_user) # All users have an empty profile profile_model = get_profile_model() try: new_profile = new_user.emif_profile except profile_model.DoesNotExist: new_profile = profile_model(user=new_user) new_profile.save(using=self._db) # Give permissions to view and change profile for perm in ASSIGNED_PERMISSIONS['profile']: assign_perm(perm[0], new_user, get_user_profile(user=new_user)) # Give permissions to view and change itself for perm in ASSIGNED_PERMISSIONS['user']: assign_perm(perm[0], new_user, new_user) userena_profile = self.create_userena_profile(new_user) if send_email: if pending_activation: userena_profile.send_pending_activation_email(organization=organization) else: userena_profile.send_activation_email() return new_user
def profile_edit(request, username, edit_profile_form=EditProfileForm, template_name='userena/profile_form.html', success_url=None, extra_context=None, **kwargs): """ Edit profile. Edits a profile selected by the supplied username. First checks permissions if the user is allowed to edit this profile, if denied will show a 404. When the profile is successfully edited will redirect to ``success_url``. :param username: Username of the user which profile should be edited. :param edit_profile_form: Form that is used to edit the profile. The :func:`EditProfileForm.save` method of this form will be called when the form :func:`EditProfileForm.is_valid`. Defaults to :class:`EditProfileForm` from userena. :param template_name: String of the template that is used to render this view. Defaults to ``userena/edit_profile_form.html``. :param success_url: Named URL which will be passed on to a django ``reverse`` function after the form is successfully saved. Defaults to the ``userena_detail`` url. :param extra_context: Dictionary containing variables that are passed on to the ``template_name`` template. ``form`` key will always be the form used to edit the profile, and the ``profile`` key is always the edited profile. **Context** ``form`` Form that is used to alter the profile. ``profile`` Instance of the ``Profile`` that is edited. """ user = get_object_or_404(get_user_model(), username__iexact=username) profile = get_user_profile(user=user) user_initial = {'first_name': user.first_name, 'last_name': user.last_name} form = edit_profile_form(instance=profile, initial=user_initial) if request.method == 'POST': form = edit_profile_form(request.POST, request.FILES, instance=profile, initial=user_initial) if form.is_valid(): profile = form.save() if userena_settings.USERENA_USE_MESSAGES: messages.success(request, _('Your profile has been updated.'), fail_silently=True) if success_url: # Send a signal that the profile has changed userena_signals.profile_change.send(sender=None, user=user) redirect_to = success_url else: redirect_to = reverse('userena_profile_detail', kwargs={'username': username}) return redirect(redirect_to) if not extra_context: extra_context = dict() extra_context['form'] = form extra_context['profile'] = profile return ExtraContextTemplateView.as_view( template_name=template_name, extra_context=extra_context)(request)
def profile_edit(request, username, edit_profile_form=EditProfileForm, template_name='userena/profile_form.html', success_url=None, extra_context=None, **kwargs): """ Edit profile. Edits a profile selected by the supplied username. First checks permissions if the user is allowed to edit this profile, if denied will show a 404. When the profile is successfully edited will redirect to ``success_url``. :param username: Username of the user which profile should be edited. :param edit_profile_form: Form that is used to edit the profile. The :func:`EditProfileForm.save` method of this form will be called when the form :func:`EditProfileForm.is_valid`. Defaults to :class:`EditProfileForm` from userena. :param template_name: String of the template that is used to render this view. Defaults to ``userena/edit_profile_form.html``. :param success_url: Named URL which will be passed on to a django ``reverse`` function after the form is successfully saved. Defaults to the ``userena_detail`` url. :param extra_context: Dictionary containing variables that are passed on to the ``template_name`` template. ``form`` key will always be the form used to edit the profile, and the ``profile`` key is always the edited profile. **Context** ``form`` Form that is used to alter the profile. ``profile`` Instance of the ``Profile`` that is edited. """ user = get_object_or_404(get_user_model(), username__iexact=username) profile = get_user_profile(user=user) user_initial = {'first_name': user.first_name, 'last_name': user.last_name} form = edit_profile_form(instance=profile, initial=user_initial) if request.method == 'POST': form = edit_profile_form(request.POST, request.FILES, instance=profile, initial=user_initial) if form.is_valid(): profile = form.save() mail_subject = [user.username] mail_body = 'Dear customer. Your order has been confirmed. Please come on time. If you could not make it Please ring 845-783-8866 for reschedule or cancelation' mail_from = '*****@*****.**' mail_to = [user.email,'*****@*****.**' ] send_mail(mail_subject, mail_body, mail_from, mail_to) if success_url: redirect_to = success_url else: redirect_to = reverse('userena_order_complete', kwargs={'username': user.username}) return redirect(redirect_to) if not extra_context: extra_context = dict() extra_context['form'] = form extra_context['profile'] = get_user_profile(user=user) return ExtraContextTemplateView.as_view(template_name=template_name, extra_context=extra_context)(request)
def password_change(request, username, template_name='userena/password_form.html', pass_form=PasswordChangeForm, success_url=None, extra_context=None): """ Change password of user. This view is almost a mirror of the view supplied in :func:`contrib.auth.views.password_change`, with the minor change that in this view we also use the username to change the password. This was needed to keep our URLs logical (and REST) across the entire application. And that in a later stadium administrators can also change the users password through the web application itself. :param username: String supplying the username of the user who's password is about to be changed. :param template_name: String of the name of the template that is used to display the password change form. Defaults to ``userena/password_form.html``. :param pass_form: Form used to change password. Default is the form supplied by Django itself named ``PasswordChangeForm``. :param success_url: Named URL that is passed onto a :func:`reverse` function with ``username`` of the active user. Defaults to the ``userena_password_complete`` URL. :param extra_context: Dictionary of extra variables that are passed on to the template. The ``form`` key is always used by the form supplied by ``pass_form``. **Context** ``form`` Form used to change the password. """ user = get_object_or_404(get_user_model(), username__iexact=username) form = pass_form(user=user) if request.method == "POST": form = pass_form(user=user, data=request.POST) if form.is_valid(): form.save() # Send a signal that the password has changed userena_signals.password_complete.send(sender=None, user=user) if success_url: redirect_to = success_url else: redirect_to = reverse('userena_password_change_complete', kwargs={'username': user.username}) return redirect(redirect_to) if not extra_context: extra_context = dict() extra_context['form'] = form extra_context['profile'] = get_user_profile(user=user) return ExtraContextTemplateView.as_view( template_name=template_name, extra_context=extra_context)(request)