def test_no_profile(self): """ Check for warning when there is no profile """ # TODO: Dirty! Currently we check for the warning by getting a 100% # test coverage, meaning that it dit output some warning. user = UserenaSignup.objects.create_user(**self.user_info) # remove the profile of this user get_profile_model().objects.get(user=user).delete() # run the command to check for the warning. call_command('check_permissions', test=True)
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 = user.get_profile() except get_profile_model().DoesNotExist: 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 = user.get_profile() else: perm_object = user for perm in perms: if perm[0] not in all_permissions: assign(perm[0], user, perm_object) changed_users.append(user) return (changed_permissions, changed_users, warnings)
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 = user.get_profile() except get_profile_model().DoesNotExist: 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 = user.get_profile() else: perm_object = user for perm in perms: if perm[0] not in all_permissions: assign(perm[0], user, perm_object) changed_users.append(user) return (changed_permissions, changed_users, warnings)
def create_inactive_user(self, username, email, password): """ A simple wrapper that creates a new ``User``. """ now = datetime.datetime.now() new_user = User.objects.create_user(username, email, password) new_user.is_active = False new_user.save() userena_profile = self.create_userena_profile(new_user) # All users have an empty profile profile_model = get_profile_model() new_profile = profile_model(user=new_user) new_profile.save(using=self._db) # Give permissions to view and change profile for perm in PERMISSIONS['profile']: assign(perm, new_user, new_profile) # Give permissinos to view and change itself for perm in PERMISSIONS['user']: assign(perm, new_user, new_user) userena_profile.send_activation_email() return new_user
class Meta: model = get_profile_model() exclude = ['user', 'privacy'] widgets = { 'deliveryoption': forms.RadioSelect(choices=[(True, ' Yes'), (False, ' No')]) }
def create_profile_and_userdetail(self, user): userDetail = UserDetail() userDetail.user = user userDetail.save() userena_profile = UserenaSignup.objects.create_userena_profile(user) # All users have an empty profile profile_model = get_profile_model() try: new_profile = user.get_profile() except profile_model.DoesNotExist: new_profile = profile_model(user=user) new_profile.save(using=self._db) # Give permissions to view and change profile for perm in ASSIGNED_PERMISSIONS['profile']: assign(perm[0], user, new_profile) # Give permissions to view and change itself for perm in ASSIGNED_PERMISSIONS['user']: assign(perm[0], user, user) if settings.USERENA_ACTIVATION_REQUIRED: userena_profile.send_activation_email() return user
def get_context_data(self, username, extra_context=None, *args, **kwargs): context = super(ProfileDetailView, self).get_context_data(*args, **kwargs) user = get_object_or_404(get_user_model(), username__iexact=username) # Get profile profile_model = get_profile_model() try: profile = user.get_profile() except profile_model.DoesNotExist: profile = profile_model.objects.create(user=user) # Lookup badges services = profile.services.all() services_detailed = profile.service_detailed.all() badges = ServiceBadge.objects.filter(services__in=services).distinct().order_by('category') for b in badges: b.user_services = [] for service_detailed in services_detailed: if service_detailed.service in b.services.all(): b.user_services.append(service_detailed) # Check perms if not profile.can_view_profile(self.request.user): return HttpResponseForbidden(_("You don't have permission to view this profile.")) # context context['profile'] = profile context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL context['badges'] = badges return context
def setUp(self): # Add the models to the db. # Call the original method that does the fixtures etc. super(UserenaSignupModelTests, self).setUp() call_command('syncdb', interactive=False, verbosity=0) for model, perms in ASSIGNED_PERMISSIONS.items(): for perm in perms: if model == 'profile': model_obj = get_profile_model() else: model_obj = get_user_model() model_content_type = ContentType.objects.get_for_model( model_obj) try: Permission.objects.get(codename=perm[0], content_type=model_content_type) except Permission.DoesNotExist: Permission.objects.create(name=perm[1], codename=perm[0], content_type=model_content_type)
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 = User 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) for user in User.objects.all(): if not user.username == "AnonymousUser": try: user_profile = user.get_profile() except get_profile_model().DoesNotExist: 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 = user.get_profile() else: perm_object = user for perm in perms: if perm[0] not in all_permissions: assign(perm[0], user, perm_object) changed_users.append(user) return (changed_permissions, changed_users, warnings)
def create_user(self, username, email, password, active=False, send_email=True, firstname=''): """ 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. Defauts to ``True``. :param send_email: Boolean that defines if the user should be send 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. """ now = timezone.now() new_user = User.objects.create_user(username, email, password) new_user.first_name = firstname new_user.is_active = active 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.get_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[0], new_user, new_profile) # Give permissions to view and change itself for perm in ASSIGNED_PERMISSIONS['user']: assign(perm[0], new_user, new_user) if send_email: userena_profile.send_activation_email() # Send the signup complete signal userena_signals.signup_complete.send(sender=None, user=new_user) return new_user
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. """ now = get_datetime_now() new_user = get_user_model().objects.create_user( username, email, password) new_user.is_active = active 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.get_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[0], new_user, new_profile) # Give permissions to view and change itself for perm in ASSIGNED_PERMISSIONS['user']: assign(perm[0], new_user, new_user) if send_email: userena_profile.send_activation_email() return new_user
class Meta: model = get_profile_model() exclude = ['user'] fields = ['levels', 'content_areas'] widgets = { 'levels': forms.CheckboxSelectMultiple(), 'content_areas': forms.CheckboxSelectMultiple(), }
class Meta: model = get_profile_model() exclude = [ 'user', 'editions', 'tasks', 'signed_up', 'language', 'privacy', 'private_staff_rating', 'private_staff_notes', 'categories' ] fields = [ 'first_name', 'last_name', 'mobile_nbr', 'about_me', 'mugshot' ]
class Meta: model = get_profile_model() exclude = ( 'user', 'privacy', 'mugshot', ) fields = ('first_name', 'last_name', 'location', 'languages', 'tags', 'blog', 'linked_in', 'twitter', 'about', 'looking_for_work')
def save(self, *args, **kwargs): profile_model = get_profile_model() try: current_profile = profile_model.objects.get(user=self.user) except profile_model.DoesNotExist: return False result = UserenaSignup.objects.invite_user( inviter=current_profile, invited_email=self.cleaned_data['email']) return result
def create_inactive_user(self, username, email, password, send_email=userena_settings.USERENA_AUTO_ACTIVATE, profile_context={}): """ 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 send_email: Boolean that defines if the user should be send 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. """ now = datetime.datetime.now() new_user = User.objects.create_user(username, email, password) new_user.is_active = False new_user.save() userena_profile = self.create_userena_profile(new_user) # All users have an empty profile profile_model = get_profile_model() new_profile = profile_model(user=new_user, **profile_context) new_profile.save(using=self._db) # Give permissions to view and change profile for perm in PERMISSIONS['profile']: assign(perm, new_user, new_profile) # Give permissinos to view and change itself for perm in PERMISSIONS['user']: assign(perm, new_user, new_user) if send_email: userena_profile.send_activation_email() # Send the signup complete signal userena_signals.signup_complete.send(sender=None, user=new_user) return new_user
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 create_user(self, form_data, 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. Defauts to ``True``. :param send_email: Boolean that defines if the user should be send 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. """ username, email, password = (form_data['username'], form_data['email'], form_data['password1']) now = datetime.datetime.now() new_user = User.objects.create_user(username, email, password) new_user.is_active = active 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.get_profile() except profile_model.DoesNotExist: profile_model.objects.create_profile(new_user=new_user, form_data=form_data) # Give permissions to view and change itself for perm in ASSIGNED_PERMISSIONS['user']: assign(perm[0], new_user, new_user) if send_email: userena_profile.send_activation_email() return new_user
def create_inactive_user(self, username, email, password=None, 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 send_email: Boolean that defines if the user should be send 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. """ now = datetime.datetime.now() if password: new_user = User.objects.create_user(username, email, password) else: new_user = User.objects.create_user(username, email) new_user.is_active = False new_user.save() userena_profile = self.create_userena_profile(new_user) # All users have an empty profile profile_model = get_profile_model() new_profile = profile_model(user=new_user) new_profile.save(using=self._db) # Give permissions to view and change profile for perm in PERMISSIONS['profile']: assign(perm, new_user, new_profile) # Give permissinos to view and change itself for perm in PERMISSIONS['user']: assign(perm, new_user, new_user) if send_email: userena_profile.send_activation_email() # Send the signup complete signal userena_signals.signup_complete.send(sender=None, user=new_user) return new_user
def has_profile(user): """Test utility function to check if user has profile""" profile_model = get_profile_model() try: profile = user.get_profile() except AttributeError: related_name = profile_model._meta.get_field("user").related_query_name() profile = getattr(user, related_name, None) except profile_model.DoesNotExist: profile = None return bool(profile)
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_model = get_profile_model() try: profile = user.get_profile() except profile_model.DoesNotExist: profile = profile_model.objects.create(user=user) if not profile.can_view_profile(request.user): return HttpResponseForbidden( _("You don't have permission to view this profile.")) if not extra_context: extra_context = dict() extra_context['profile'] = user.get_profile() extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL extra_context['location'] = request.user_location["user_location_lat_lon"] extra_context['is_admin'] = user.is_superuser extra_context['per_page'] = int(request.GET.get('per_page', 6)) tabs_page = "profile-detail" active_tab = request.session.get(tabs_page, "account-events") extra_context['active_tab'] = active_tab return ExtraContextTemplateView.as_view( template_name=template_name, extra_context=extra_context)(request)
class Meta: model = get_profile_model() exclude = [ 'user', 'notes', "membership_starts_on", 'membership_ends_on', 'membership_type', 'has_parking_pass', 'has_office_key', 'has_elevator_fob', 'privacy', ]
def has_profile(user): """Test utility function to check if user has profile""" profile_model = get_profile_model() try: profile = user.get_profile() except AttributeError: related_name = profile_model._meta.get_field('user')\ .related_query_name() profile = getattr(user, related_name, None) except profile_model.DoesNotExist: profile = None return bool(profile)
def profile_detail(request, username,extra_context=None, **kwargs): template_name = 'userena/profile_detail.html' user = get_object_or_404(get_user_model(), username__iexact=username) profile_model = get_profile_model() try: profile = user.get_profile() except profile_model.DoesNotExist: profile = profile_model.objects.create(user=user) if not profile.can_view_profile(request.user): raise PermissionDenied return render(request, template_name, {'profile': profile,'bulletins' : Post.objects.filter(tag1='announcement').order_by("-time")})
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_model = get_profile_model() try: profile = user.get_profile() except profile_model.DoesNotExist: profile = profile_model.objects.create(user=user) if not profile.can_view_profile(request.user): return HttpResponseForbidden(_("You don't have permission to view this profile.")) if not extra_context: extra_context = dict() extra_context['profile'] = user.get_profile() extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL extra_context['location'] = request.user_location["user_location_lat_lon"] extra_context['is_admin'] = user.is_superuser extra_context['per_page'] = int(request.GET.get('per_page', 6)) tabs_page = "profile-detail" active_tab = request.session.get(tabs_page, "account-events") extra_context['active_tab'] = active_tab 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) if Pago.objects.filter(user=user).exists(): last_pago = Pago.objects.filter(user=user).order_by('-fecha_expiracion').get() else: last_pago = None today = date.today() profile_model = get_profile_model() try: profile = user.get_profile() except profile_model.DoesNotExist: profile = profile_model.objects.create(user=user) if not profile.can_view_profile(request.user): return HttpResponseForbidden(_("You don't have permission to view this profile.")) if not extra_context: extra_context = dict() extra_context['profile'] = user.get_profile() extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL if last_pago is None or last_pago.fecha_expiracion < today: extra_context['suscripcion_status'] = "Inactiva" return ExtraContextTemplateView.as_view(template_name=template_name, extra_context=extra_context)(request)
def get_queryset(self): filter_kwargs = {'usertype': 'chef'} profile_model = get_profile_model() logging.error('all') logging.error(profile_model.objects.all()) ## logging.error(self.__dict__) ## logging.error(self.request.__dict__) ##queryset = profile_model.objects.get_visible_profiles(self.request.user).select_related() queryset = profile_model.objects.get_visible_profiles().filter(**filter_kwargs) logging.error('cook - queryset') logging.error(queryset) return queryset
def test_incomplete_permissions(self): # noqa:C901 # Delete the neccesary permissions profile_model_obj = get_profile_model() content_type_profile = ContentType.objects.get_for_model( profile_model_obj) content_type_user = ContentType.objects.get_for_model(User) for model, perms in ASSIGNED_PERMISSIONS.items(): if model == "profile": content_type = content_type_profile else: content_type = content_type_user for perm in perms: Permission.objects.get(name=perm[1], content_type=content_type).delete() # Check if they are they are back for model, perms in ASSIGNED_PERMISSIONS.items(): if model == "profile": content_type = content_type_profile else: content_type = content_type_user for perm in perms: try: perm = Permission.objects.get(name=perm[1], content_type=content_type) except Permission.DoesNotExist: pass else: self.fail("Found %s: " % perm) # Repair them call_command("check_permissions", test=True) # Check if they are they are back for model, perms in ASSIGNED_PERMISSIONS.items(): if model == "profile": content_type = content_type_profile else: content_type = content_type_user for perm in perms: try: perm = Permission.objects.get(name=perm[1], content_type=content_type) except Permission.DoesNotExist: self.fail()
def profile_detail(request, username, extra_context=None, **kwargs): template_name = 'userena/profile_detail.html' user = get_object_or_404(get_user_model(), username__iexact=username) profile_model = get_profile_model() try: profile = user.get_profile() except profile_model.DoesNotExist: profile = profile_model.objects.create(user=user) if not profile.can_view_profile(request.user): raise PermissionDenied return render( request, template_name, { 'profile': profile, 'bulletins': Post.objects.filter(tag1='announcement').order_by("-time") })
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. Defauts to ``True``. :param send_email: Boolean that defines if the user should be send 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 = User.objects.create_user(username, email, password) new_user.is_active = active 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.get_profile() except profile_model.DoesNotExist: new_profile = profile_model(user=new_user) new_profile.save(using=self._db) if send_email: userena_profile.send_activation_email() return new_user
def profile_listview( request, username, template_name=userena_settings.USERENA_PROFILE_DETAIL_TEMPLATE, extra_context=None, **kwargs): """ note: 'extra_context' is a dictionary of variables which should be supplied to the template. """ user = get_object_or_404(get_user_model(), username__iexact=username) fullsalelist = Entry.objects.filter( author__username__iexact=username).order_by('-pub_date') userreviews = UserReview.objects.filter( name__username__iexact=username).order_by('-pub_date') if request.is_ajax(): object_name = request.POST.get('entryname') targetobject = Entry.objects.get(headline=object_name) if request.user.username == targetobject.author.username: targetobject.delete() return HttpResponseRedirect('/storefront/') profile_model = get_profile_model() try: profile = user.my_profile except profile_model.DoesNotExist: profile = profile_model.objects.create(user=user) if not profile.can_view_profile(request.user): raise PermissionDenied if not extra_context: extra_context = dict() if username == request.user.username: pageowner = "True" extra_context['pageowner'] = pageowner extra_context['profile'] = user.my_profile extra_context['fullsalelist'] = fullsalelist extra_context['userreviews'] = userreviews extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL return ExtraContextTemplateView.as_view( template_name='profile_listview.html', 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) ganaderia = 'Sin asignar' if Ganaderia.objects.all(): if Ganaderia.objects.filter(perfil=user.id): ganaderia = Ganaderia.objects.get(perfil=user.id) profile_model = get_profile_model() try: profile = user.get_profile() except profile_model.DoesNotExist: profile = profile_model.objects.create(user=user) if not profile.can_view_profile(request.user): raise PermissionDenied if not extra_context: extra_context = dict() extra_context['profile'] = user.get_profile() extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL extra_context['ganaderia'] = ganaderia return ExtraContextTemplateView.as_view(template_name=template_name, extra_context=extra_context)(request)
def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super(InvitedUsersListView, self).get_context_data(**kwargs) try: page = int(self.request.GET.get('page', None)) except (TypeError, ValueError): page = self.page if not self.extra_context: self.extra_context = dict() context['page'] = page context['paginate_by'] = self.paginate_by context['extra_context'] = self.extra_context profile_model = get_profile_model() currentProfile = profile_model.objects.get(user=self.request.user) context[ 'numOfRemainingInvitationTicket'] = currentProfile.get_remaining_invite_tickets_number( ) return context
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 warnings = [] for user in User.objects.all(): if not user.username == 'AnonymousUser': try: user.get_profile() except get_profile_model().DoesNotExist: warnings.append(_("No profile found for %(username)s") \ % {'username': user.username}) return warnings
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(User, username__iexact=username) profile_model = get_profile_model() try: profile = user.get_profile() except profile_model.DoesNotExist: profile = profile_model.create(user=user) if not profile.can_view_profile(request.user): return HttpResponseForbidden( _("You don't have permission to view this profile.")) if not extra_context: extra_context = dict() extra_context['profile'] = user.get_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): """ Add extra context and returns userena_profile_detail view """ extra_context = {} user = get_object_or_404(get_user_model(), username__iexact=username) # Get profile profile_model = get_profile_model() profile = user.get_profile() # Check perms if not profile.can_view_profile(request.user): return HttpResponseForbidden(_("You don't have permission to view this profile.")) # context extra_context['profile'] = profile extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL return userena_profile_detail(request=request, username=username, extra_context=extra_context)
def profile_detail(request, username, template_name=userena_settings.USERENA_PROFILE_DETAIL_TEMPLATE, extra_context=None, **kwargs): user = get_object_or_404(get_user_model(), username__iexact=username) profile_model = get_profile_model() try: profile = user.get_profile() except profile_model.DoesNotExist: profile = profile_model.objects.create(user=user) if not extra_context: extra_context = dict() extra_context['profile'] = user.get_profile() extra_context['company'] = Company.objects.get(id=profile.company_id) extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL return ExtraContextTemplateView.as_view(template_name=template_name, extra_context=extra_context)(request)
def authenticate(self, token=None): facebook_session = models.FacebookSession.objects.get( access_token=token, ) profile = facebook_session.query('me') try: user = auth_models.User.objects.get(username=profile['id']) except auth_models.User.DoesNotExist, e: user = auth_models.User(username=profile['id']) user.set_unusable_password() user.email = profile['email'] user.first_name = profile['first_name'] user.last_name = profile['last_name'] password = self.password_generate() user.set_password(password) user.email_user("Registrado en libreta", 'your username:'******'\n'+'your password:'******'hometown']['name'] new_profile.facebook_url = profile['link'] new_profile.save(using=self._db) for perm in PERMISSIONS['profile']: assign(perm, user, new_profile) for perm in PERMISSIONS['user']: assign(perm, user, user) try: models.FacebookSession.objects.get(uid=profile['id']).delete() except models.FacebookSession.DoesNotExist, e: pass
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_model = get_profile_model() try: profile = user.get_profile() except profile_model.DoesNotExist: profile = profile_model.objects.create(user=user) request.breadcrumbs((('Home', reverse('index')), ('{}\'s profile'.format(user.username), ''))) if not profile.can_view_profile(request.user): return HttpResponseForbidden(_("You don't have permission to view this profile.")) if not extra_context: extra_context = dict() extra_context['profile'] = user.get_profile() extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL return ExtraContextTemplateView.as_view(template_name=template_name, extra_context=extra_context)(request)
def check_permissions(self): """ Checks that all permissions are set correctly for the users. :return: A set of users whose permissions was wrong. """ # Check that all the permissions are available. for model, perms in ASSIGNED_PERMISSIONS.items(): for perm in perms: try: Permission.objects.get(codename=perm[0]) except Permission.DoesNotExist: if model == 'profile': model_obj = get_profile_model() else: model_obj = User content_type = ContentType.objects.get_for_model(model_obj) Permission.objects.create(name=perm[1], codename=perm[0], content_type=content_type) # Check permission for every user. changed_users = set() for user in User.objects.all(): if not user.username == 'AnonymousUser': all_permissions = get_perms(user, user.get_profile()) + get_perms(user, user) for model, perms in ASSIGNED_PERMISSIONS.items(): if model == 'profile': perm_object = user.get_profile() else: perm_object = user for perm in perms: if perm[0] not in all_permissions: assign(perm[0], user, perm_object) changed_users.add(user) return changed_users
def socialauth_registered_handler(sender, user, response, details, **kwargs): """ Called when user registers for the first time using social auth """ # Create user profile profile_model = get_profile_model() new_profile = profile_model(user=user) new_profile.save() # Give permissions to view and change profile for perm in ASSIGNED_PERMISSIONS['profile']: assign(perm[0], user, new_profile) # Give permissions to view and change itself for perm in ASSIGNED_PERMISSIONS['user']: assign(perm[0], user, user) # Try to get profile details fetch_profile_data(sender, new_profile, response) return True
def signup_active_user(self, user, reset_password=True, send_email=True): """ A simple wrapper that adds a signup data for an already created :class:`User`. :param user: User object of an existing user. :param reset_password: Boolean that says if the password should be reset or not. A new password will be autogenerated. This will also automatically generate an email to the user with his user id and the newly generated password :param send_email: Boolean that says if and email should be sent to the user specifying that a new account was created. Along with the new autogenerated password. """ now = datetime.datetime.now() userena = self.create_userena_profile(user) # All users have an empty profile profile_model = get_profile_model() new_profile = profile_model(user=user) new_profile.save(using=self._db) # Give permissions to view and change profile for perm in PERMISSIONS['profile']: assign(perm, user, new_profile) # Give permissinos to view and change itself for perm in PERMISSIONS['user']: assign(perm, user, user) # Send the signup complete signal userena_signals.signup_complete.send(sender=None, user=user) self.activate_user(user.username, userena.activation_key) if send_email: userena.send_activated_email() return user
def profile_listview(request, username, template_name=userena_settings.USERENA_PROFILE_DETAIL_TEMPLATE, extra_context=None, **kwargs): """ note: 'extra_context' is a dictionary of variables which should be supplied to the template. """ user = get_object_or_404(get_user_model(), username__iexact=username) fullsalelist = Entry.objects.filter(author__username__iexact=username).order_by('-pub_date') userreviews = UserReview.objects.filter(name__username__iexact=username).order_by('-pub_date') if request.is_ajax(): object_name = request.POST.get('entryname') targetobject = Entry.objects.get(headline=object_name) if request.user.username == targetobject.author.username: targetobject.delete() return HttpResponseRedirect('/storefront/') profile_model = get_profile_model() try: profile = user.get_profile() except profile_model.DoesNotExist: profile = profile_model.objects.create(user=user) if not profile.can_view_profile(request.user): raise PermissionDenied if not extra_context: extra_context = dict() if username == request.user.username: pageowner="True" extra_context['pageowner'] = pageowner extra_context['profile'] = user.get_profile() extra_context['fullsalelist'] = fullsalelist extra_context['userreviews'] = userreviews extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL return ExtraContextTemplateView.as_view(template_name='profile_listview.html', extra_context=extra_context)(request)
def get_context_data(self, username, extra_context=None, *args, **kwargs): context = super(ProfileDetailView, self).get_context_data(*args, **kwargs) user = get_object_or_404(get_user_model(), username__iexact=username) # Get profile profile_model = get_profile_model() try: profile = user.get_profile() except profile_model.DoesNotExist: profile = profile_model.objects.create(user=user) # Check perms if not profile.can_view_profile(self.request.user): return HttpResponseForbidden(_("You don't have permission to view this profile.")) # context context['profile'] = profile context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL return context
def fix_profile_and_userdetail(self, user): userDetail = UserDetail() userDetail.user = user userDetail.save() # All users have an empty profile profile_model = get_profile_model() try: new_profile = user.get_profile() except profile_model.DoesNotExist: new_profile = profile_model(user=user) new_profile.save(using=self._db) # Give permissions to view and change profile for perm in ASSIGNED_PERMISSIONS['profile']: assign(perm[0], user, new_profile) # Give permissions to view and change itself for perm in ASSIGNED_PERMISSIONS['user']: assign(perm[0], user, user) return user
def test_incomplete_permissions(self): # Delete the neccesary permissions profile_model_obj = get_profile_model() content_type_profile = ContentType.objects.get_for_model(profile_model_obj) content_type_user = ContentType.objects.get_for_model(User) for model, perms in ASSIGNED_PERMISSIONS.items(): if model == "profile": content_type = content_type_profile else: content_type = content_type_user for perm in perms: Permission.objects.get(name=perm[1], content_type=content_type).delete() # Check if they are they are back for model, perms in ASSIGNED_PERMISSIONS.items(): if model == "profile": content_type = content_type_profile else: content_type = content_type_user for perm in perms: try: perm = Permission.objects.get(name=perm[1], content_type=content_type) except Permission.DoesNotExist: pass else: self.fail("Found %s: " % perm) # Repair them call_command('check_permissions', test=True) # Check if they are they are back for model, perms in ASSIGNED_PERMISSIONS.items(): if model == "profile": content_type = content_type_profile else: content_type = content_type_user for perm in perms: try: perm = Permission.objects.get(name=perm[1], content_type=content_type) except Permission.DoesNotExist: self.fail()
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_model = get_profile_model() try: profile = user.get_profile() except profile_model.DoesNotExist: profile = profile_model.objects.create(user=user) if not profile.can_view_profile(request.user): return Response(_("You don't have permission to view this profile.")) serializer = ProfileSerializer(profile) return Response(serializer.data)
and not request.user.is_staff: raise Http404 profile_model = get_profile_model() queryset = profile_model.objects.get_visible_profiles(request.user) if not extra_context: extra_context = dict() return list_detail.object_list(request, queryset=queryset, paginate_by=paginate_by, page=page, template_name=template_name, extra_context=extra_context, template_object_name='profile', **kwargs) profile_edit_view = secure_required( permission_required_or_403( 'change_profile', (get_profile_model(), 'user__username', 'username'))(profile_edit)) password_change_view = secure_required( permission_required_or_403( 'change_user', (User, 'username', 'username'))(password_change)) email_change_view = secure_required( permission_required_or_403('change_user', (User, 'username', 'username'))(email_change)) signin_view = secure_required(signin) email_confirm_view = secure_required(email_confirm) signup_view = secure_required(signup) activate_view = secure_required(activate)
class Meta: model = get_profile_model() exclude = ['user', 'mugshot', 'privacy']
from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from guardian.admin import GuardedModelAdmin from userena.models import UserenaSignup from userena.utils import get_profile_model from news.crawlers.bbc_crawler import run from threading import Thread admin.site.unregister(get_user_model()) admin.site.unregister(get_profile_model()) def run_crawler_for_author(modeladmin, request, queryset): for object in queryset: if object.id == 1: Thread(target=run).start() run_crawler_for_author.short_description = "Run Crawler for author" class UserenaSignupInline(admin.StackedInline): model = UserenaSignup max_num = 1 class UserenaAdmin(UserAdmin, GuardedModelAdmin): inlines = [UserenaSignupInline]
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) @secure_required @permission_required_or_403('change_profile', (get_profile_model(), 'user__username', 'username') ) 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``.
def get_queryset(self): profile_model = get_profile_model() queryset = profile_model.objects.get_visible_profiles( self.request.user).select_related() return queryset
class Meta: model = get_profile_model() exclude = ['user', 'privacy', 'wallet']
from django.contrib import admin from django.contrib.auth.models import User from django.utils.importlib import import_module from userena.utils import get_profile_model from . import settings def get_class(path): if path: module_name, attr_name = path.rsplit('.', 1) module = import_module(module_name) return getattr(module, attr_name) else: return None UserenaUserAdmin = get_class(settings.USERENA_USERADMIN) if UserenaUserAdmin: admin.site.unregister(User) admin.site.register(User, UserenaUserAdmin) ProfileAdmin = get_class(settings.USERENA_PROFILEADMIN) if ProfileAdmin: profile_model = get_profile_model() admin.site.unregister(profile_model) admin.site.register(profile_model, ProfileAdmin)
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.utils.translation import ugettext as _ from guardian.admin import GuardedModelAdmin from userena.models import UserenaSignup from userena.utils import get_profile_model class UserenaSignupInline(admin.StackedInline): model = UserenaSignup max_num = 1 class UserenaAdmin(UserAdmin, GuardedModelAdmin): inlines = [ UserenaSignupInline, ] list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'date_joined') admin.site.register(get_profile_model())
class Meta: model = get_profile_model() exclude = ['user']
def profile_list(request, page=1, template_name='userena/profile_list.html', paginate_by=50, extra_context=None, **kwargs): """ Returns a list of all profiles that are public. It's possible to disable this by changing ``USERENA_DISABLE_PROFILE_LIST`` to ``True`` in your settings. :param page: Integer of the active page used for pagination. Defaults to the first page. :param template_name: String defining the name of the template that is used to render the list of all users. Defaults to ``userena/list.html``. :param paginate_by: Integer defining the amount of displayed profiles per page. Defaults to 50 profiles per page. :param extra_context: Dictionary of variables that are passed on to the ``template_name`` template. **Context** ``profile_list`` A list of profiles. ``is_paginated`` A boolean representing whether the results are paginated. If the result is paginated. It will also contain the following variables. ``paginator`` An instance of ``django.core.paginator.Paginator``. ``page_obj`` An instance of ``django.core.paginator.Page``. """ try: page = int(request.GET.get('page', None)) except (TypeError, ValueError): page = page if userena_settings.USERENA_DISABLE_PROFILE_LIST \ and not request.user.is_staff: raise Http404 profile_model = get_profile_model() queryset = profile_model.objects.get_visible_profiles(request.user) if not extra_context: extra_context = dict() return list_detail.object_list(request, queryset=queryset, paginate_by=paginate_by, page=page, template_name=template_name, extra_context=extra_context, template_object_name='profile', **kwargs)