Ejemplo n.º 1
0
def edit_product(request, id=None):
	stuff = request.user
	if not has_permission(stuff, 'edit_product') and not has_permission(stuff, 'change_status'):
		messages.warning(request, 'You have no permission to edit product')
		return HttpResponseRedirect(reverse("products:about", kwargs={'id':id}))

	product = get_object_or_404(Product, id=id)
	
	role = get_user_role(stuff)
	if role.title == 'zavsklad':
		form = ProductForm(request.POST or None, request.FILES or None, instance=product)
	elif product.status == 'out of stock':
		form = ProductFormStatus(request.POST or None, instance=product)
	else:
		messages.warning(request, 'You can change product status only if it is "out of stock"')
		return HttpResponseRedirect(reverse("products:about", kwargs={'id':id}))
	
	context = {
		"form": form,
	}

	if form.is_valid():
		status = form.cleaned_data.get('status')
		if role.title == 'postavshik' and status != 'comming soon' and status != 'out of stock':
			messages.warning(request, 'You can change only to comming soon')
			return render(request, 'add_product.html', context)
			

		old_product = product
		product = form.save(commit=False)
		log = ProductHistory(
			changed_by=request.user,
			product_id=product.id,
			product_title = product.title,

			old_title = old_product.title,
			old_content = old_product.content,
			old_image = old_product.image,
			old_quantity = old_product.quantity,
			old_price = old_product.price,
			old_status = old_product.status,

			new_title = product.title,
			new_content = product.content,
			new_image = product.image,
			new_quantity = product.quantity,
			new_price = product.price,
			new_status = product.status,)

		product.save()
		log.save()
		# print log.product_changes
		messages.info(request, "Successfully changed!")
		# return HttpResponseRedirect(product.get_absolute_url())
		return redirect(reverse("products:about", kwargs={"id":product.id}))


	return render(request, 'add_product.html', context)
Ejemplo n.º 2
0
Archivo: roles.py Proyecto: defivelo/db
def user_cantons(user):
    if user.pk in _user_cantons:
        return _user_cantons[user.pk]

    if has_permission(user, 'cantons_all'):
        _user_cantons[user.pk] = DV_STATES
        return _user_cantons[user.pk]
    if has_permission(user, 'cantons_mine'):
        _user_cantons[user.pk] = [
            m.canton for m in user.managedstates.all()
        ]
        return _user_cantons[user.pk]
    raise LookupError("No user cantons")
Ejemplo n.º 3
0
def create_user(request):
	stuff = request.user
	if not has_permission(stuff, 'create_user'):
		messages.warning(request, 'You have no permission to create user')
		return HttpResponseRedirect(reverse("hr:list"))
	form = CreateUserForm(request.POST or None)
	print request.POST
	print 'pass', request.POST.get('password')
	print 'pass2', request.POST.get('verification')
	
	if form.is_valid():
		username = form.cleaned_data.get('username')
		password = form.cleaned_data.get('password')
		verification = form.cleaned_data.get('verification')
		image = request.FILES.get('image')
		role = form.cleaned_data.get('role')
		print username, password, verification
		print 'here is ', image
		user = User.objects.create_user(username=username, password=password)
		
		profile = UserProfile(
			user=user,
			role=role,
			image=image,
			)
		profile.save()

		if role == 'zavsklad':
			Zavsklad.assign_role_to_user(user)
		if role == 'postavshik':
			Postavshik.assign_role_to_user(user)
		if role == 'sotrudnik':
			Sotrudnik.assign_role_to_user(user)
		
		role = get_user_role(user)
		user.role = role.title

		print has_permission(user, 'create_product')
		print form.cleaned_data.get('role')
		print role.title
		print 'user.role', user.role
		return HttpResponseRedirect(reverse("hr:about", kwargs={'id': user.id}))

	context = {
		'form': form,
	}
	
	return render(request, 'create_user.html', context)		
        def wrapper(request, *args, **kwargs):
            user = request.user
            if user.is_authenticated():
                if has_permission(user, permission_name):
                    return dispatch(request, *args, **kwargs)

            raise PermissionDenied
Ejemplo n.º 5
0
    def wrapper(request, *args, **kwargs):

        if get_state().current == 1:
            if not (has_role(request.user, ['staff', 'dev', 'selection'])
                    or has_permission(request.user, 'edit_applicants')):
                raise Http404('App not available until later.')
        return f(request, *args, **kwargs)
Ejemplo n.º 6
0
def edit_info(request, name):
  user_info = McUser.objects.get(norm_name=normalize_name(name))
  if not user_info.user.id == request.user.id and not has_permission(request.user, 'edit_all_info'):
    return redirect('edit_info', request.user.mcuser.get_link_name())
  if request.method == 'POST':
    if has_role(request.user, 'staff'):
      form = McUserStaffForm(request.POST, request.FILES, instance=user_info, prefix='base')
    else:
      form = McUserForm(request.POST, request.FILES, instance=user_info, prefix='base')
    if (form.is_valid()):
      mcuser = form.save(commit=False)
      hidden_fields = [key.replace('checkbox_', '') for key in request.POST if key.startswith('checkbox_')]
      mcuser.hidden_fields = hidden_fields
      mcuser.save()
      messages.add_message(
        request, messages.SUCCESS,
        'Changes saved! Click <a href="%s">here</a> to view profile.' % reverse('profile', args=[mcuser.get_link_name()]))
      update_last_updated(user_info, request.user)
      return redirect('edit_info', user_info.norm_name)
  else:
    if has_role(request.user, 'staff'):
      form = McUserStaffForm(instance=user_info, prefix='base')
    else:
      form = McUserForm(instance=user_info, prefix='base')
  context = {
      'form': form,
      'mcuser': user_info
      }
  template = 'core/edit_info.html'
  if has_role(user_info.user, 'staff'):
    template = 'core/edit_info_staff.html'
  return render(request, template, context)
Ejemplo n.º 7
0
        def wrapper(request, *args, **kwargs):
            user = request.user
            if user.is_authenticated():
                if has_permission(user, permission_name):
                    return dispatch(request, *args, **kwargs)

            raise PermissionDenied
Ejemplo n.º 8
0
def edit_honor(request, name):
    user_info = McUser.objects.get(norm_name=normalize_name(name))
    if not user_info.user.id == request.user.id and not has_permission(
            request.user, 'edit_all_info'):
        return redirect('edit_honor', request.user.mcuser.norm_name)
    honor = Honor.objects.filter(user_id=user_info.id)
    if request.method == 'POST':
        honor_formset = HonorFormSet(request.POST,
                                     queryset=honor,
                                     initial=[{
                                         'user': user_info.id
                                     }])
        if (honor_formset.is_valid()):
            honor_formset.save()
            messages.add_message(
                request, messages.SUCCESS,
                'Changes saved! Click <a href="%s">here</a> to view profile.' %
                reverse('profile', args=[user_info.get_link_name()]))
            update_last_updated(user_info, request.user)
            return redirect('edit_honor', user_info.norm_name)
    else:
        honor_formset = HonorFormSet(queryset=honor,
                                     initial=[{
                                         'user': user_info.id
                                     }])
    context = {'honor_formset': honor_formset, 'mcuser': user_info}
    return render(request, 'core/edit_honor.html', context)
Ejemplo n.º 9
0
def add_product(request):
	stuff = request.user
	if not has_permission(stuff, 'create_product'):
		messages.warning(request, 'You have no permission to add product')
		return HttpResponseRedirect(reverse("products:list"))

	form = ProductForm(request.POST or None, request.FILES or None)

	context = {
		'form': form
	}

	if form.is_valid():
		product = form.save(commit=False)
		product.save()
		log = ProductHistory(
			changed_by=request.user,
			product_id=product.id,
			product_title=product.title,
			create_action=True)
		log.save()
		print log.product_changes()
		# return reverse("products:list")
		messages.success(request, "Successfully created!")
		return HttpResponseRedirect(reverse("products:about", kwargs={"id":product.id}))

	return render(request, 'add_product.html', context)
Ejemplo n.º 10
0
def can_advance_search(role, user, program):
    """
    Determines whether a user can perform an advanced search on a specific program.
    """
    return (has_permission(user, Permissions.CAN_ADVANCE_SEARCH)
            and Role.objects.filter(
                user=user, role=role.ROLE_ID, program=program).exists())
Ejemplo n.º 11
0
def sell_product(request, id=None):
	stuff = request.user
	if not has_permission(stuff, 'sell_product'):
		messages.warning(request, 'You have no permission to sell product')
		return HttpResponseRedirect(reverse("products:about", kwargs={'id':id}))
	
	product = get_object_or_404(Product, id=id)
	quantity = int(request.POST.get('quantity'))
	
	if quantity > product.quantity:
		messages.warning(request, 'Can not sell more than %s' % product.quantity)
		# return redirect(reverse("products:sell", kwargs={"id":product.id}))
		return redirect(reverse("products:about", kwargs={"id":product.id}))
	
	
	product.quantity -= quantity
	if product.quantity == 0:
		product.status = 'out of stock'
	product.save()
	messages.success(request, "Successfully sold!")
	
	log = ProductHistory(
		product_id = id,
		changed_by = request.user,
		sell_action=True,
		sold=quantity,)
	log.save()

	return redirect(reverse("products:about", kwargs={"id":product.id}))
Ejemplo n.º 12
0
def can_message_learners(role, user, program):
    """
    Determines whether a user can send a message to learners of a specific program.
    """
    return (has_permission(user, Permissions.CAN_MESSAGE_LEARNERS)
            and Role.objects.filter(
                user=user, role=role.ROLE_ID, program=program).exists())
Ejemplo n.º 13
0
 def wrapper(request, *args, **kwargs):
     user = request.user
     if user.is_authenticated():
         if has_permission(user, permission_name):
             return dispatch(request, *args, **kwargs)
     if hasattr(settings, 'ROLEPERMISSIONS_REDIRECT_TO_LOGIN'):
         return redirect_to_login(request.get_full_path())
     raise PermissionDenied
Ejemplo n.º 14
0
 def assert_standard_role_permissions(self, expected_bool, program=None):
     """
     Helper function to assert role and permissions assignment
     """
     assert isinstance(expected_bool, bool)
     assert has_role(self.user, 'staff') is expected_bool
     assert has_permission(self.user, 'can_advance_search') is expected_bool
     assert has_object_permission('can_advance_search', self.user, program or self.program) is expected_bool
 def wrapper(request, *args, **kwargs):
     user = request.user
     if user.is_authenticated():
         if has_permission(user, permission_name):
             return dispatch(request, *args, **kwargs)
     if hasattr(settings, 'ROLEPERMISSIONS_REDIRECT_TO_LOGIN'):
         return redirect_to_login(request.get_full_path())
     raise PermissionDenied
Ejemplo n.º 16
0
def delete_product(request, id=None):
	stuff = request.user
	if not has_permission(stuff, 'delete_product'):
		messages.warning(request, 'You have no permission to delete product')
		return HttpResponseRedirect(reverse("products:about", kwargs={'id':id}))
	product = get_object_or_404(Product, id=id)
	product.delete()
	messages.warning(request, "Successfully deleted!")
	return HttpResponseRedirect(reverse("products:list"))
Ejemplo n.º 17
0
 def get_form_kwargs(self):
     kwargs = super(UserSelfAccessMixin, self).get_form_kwargs()
     if has_permission(self.request.user, self.required_permission):
         kwargs['allow_email'] = True
     try:
         kwargs['cantons'] = user_cantons(self.request.user)
     except LookupError:
         pass
     return kwargs
Ejemplo n.º 18
0
def delete_user(request, id=None):
	stuff = request.user
	if not has_permission(stuff, 'delete_user'):
		messages.warning(request, 'You have no permission to delete user')
		return HttpResponseRedirect(reverse("hr:list"))
	user = get_object_or_404(User, id=id)
	messages.success(request, "%s succesfully deleted" % user.username)
	user.delete()
	return HttpResponseRedirect(reverse('hr:list'))
Ejemplo n.º 19
0
Archivo: views.py Proyecto: defivelo/db
 def get_context_data(self, **kwargs):
     context = super(HomeView, self).get_context_data(**kwargs)
     articles_qs = Article.objects
     if not has_permission(self.request.user, 'home_article_crud'):
         articles_qs = articles_qs.filter(published=True)
     context['articles'] = articles_qs.order_by('-modified')[:5]
     # Add our menu_category context
     context['menu_category'] = 'home'
     return context
Ejemplo n.º 20
0
 def get_success_url(self):
     if has_permission(self.request.user, 'challenge_season_crud'):
         return reverse_lazy('season-availabilities',
                             kwargs={'pk': self.season.pk})
     else:
         return reverse_lazy('season-availabilities-update',
                             kwargs={
                                 'pk': self.season.pk,
                                 'helperpk': self.request.user.pk,
                             })
Ejemplo n.º 21
0
 def dispatch(self, request, bypassperm=False, *args, **kwargs):
     if (
         bypassperm or
         # Soit j'ai le droit
         has_permission(request.user, self.required_permission)
     ):
         return (
             super(SeasonUpdateView, self)
             .dispatch(request, *args, **kwargs)
         )
     else:
         raise PermissionDenied
Ejemplo n.º 22
0
def available_perm_status(user):
    from rolepermissions.verifications import has_permission

    role = get_user_role(user)
    permission_names = role.permission_names_list()

    permission_hash = {}

    for permission_name in permission_names:
        permission_hash[permission_name] = has_permission(user, permission_name)

    return permission_hash
def available_perm_status(user):
    from rolepermissions.verifications import has_permission

    role = get_user_role(user)
    permission_names = role.permission_names_list()

    permission_hash = {}

    for permission_name in permission_names:
        permission_hash[permission_name] = has_permission(user, permission_name)

    return permission_hash
Ejemplo n.º 24
0
    def dispatch(self, request, *args, **kwargs):
        edit = kwargs.pop('edit', False)
        try:
            usercantons = user_cantons(request.user)
        except LookupError:
            usercantons = False

        user = self.get_object()
        if (
            # Soit c'est moi
            request.user.pk == user.pk or
            # Soit j'ai le droit sur tous les cantons
            has_permission(request.user, 'cantons_all') or
            # Soit il est dans mes cantons et j'ai droit
            (
                usercantons and
                (
                    # Il est dans mes cantons d'affiliation
                    user.profile.affiliation_canton in usercantons or
                    (
                        # Je ne fais que le consulter et il est dans mes
                        # cantons d'activité
                        not edit and
                        user.profile.activity_cantons and
                        len(
                            set(user.profile.activity_cantons)
                            .intersection(usercantons)
                            ) != 0
                    )

                ) and
                has_permission(request.user, self.required_permission)
            )
        ):
            return (
                super(UserSelfAccessMixin, self)
                .dispatch(request, *args, **kwargs)
            )
        else:
            raise PermissionDenied
    def test_does_not_creates_if_permission_does_not_exists_in_role(self):
        user = self.user

        Role1.assign_role_to_user(user)

        self.assertFalse(has_permission(user, 'different_permission'))

        try:
            permission = UserPermission.objects.get(user=user, 
                permission_name='different_permission')
        except:
            permission = None

        self.assertIsNone(permission)
Ejemplo n.º 26
0
    def form_valid(self, form):
        ret = super(ProfileMixin, self).form_valid(form)
        """
        Write the non-model fields
        """
        try:
            user = self.object
        except AttributeError:
            user = self.get_object()

        update_profile_fields = PERSONAL_FIELDS
        # if the edit user has access, extend the update_profile_fields
        if has_permission(self.request.user, 'user_crud_dv_public_fields'):
            update_profile_fields += DV_PUBLIC_FIELDS
        if has_permission(self.request.user, 'user_crud_dv_private_fields'):
            update_profile_fields += DV_PRIVATE_FIELDS

        (userprofile, created) = (
            UserProfile.objects.get_or_create(user=user)
        )
        for field in update_profile_fields:
            if field in form.cleaned_data:
                # For field updates that have date markers, note them properly
                if field in ['status', 'bagstatus']:
                    oldstatus = int(getattr(userprofile, field))
                    try:
                        newstatus = int(form.cleaned_data[field])
                    except ValueError:
                        newstatus = 0
                    if oldstatus != newstatus:
                        setattr(userprofile, '%s_updatetime' % field,
                                timezone.now()
                                )
                setattr(userprofile, field, form.cleaned_data[field])
        userprofile.save()
        return ret
    def test_creates_permission_when_not_existent(self):
        user = self.user

        class Role4(AbstractUserRole):
            available_permissions = {
                'the_permission': True
            }
        RolesManager.register_role(Role4)

        Role4.assign_role_to_user(user)

        Role4.available_permissions = { 'different_one': True }

        self.assertTrue(has_permission(user, 'different_one'))

        permission = UserPermission.objects.get(user=user, permission_name='different_one')

        self.assertTrue(permission.is_granted)
Ejemplo n.º 28
0
 def dispatch(self, request, *args, **kwargs):
     if (
         # Check that the request user is alone in the potential_helpers
         (
             True in [
                 [request.user.pk] == [u.pk for u in users]
                 for (cat, users) in self.potential_helpers()
             ]
         ) or
         # Soit j'ai le droit
         has_permission(request.user, self.required_permission)
     ):
         return (
             super(SeasonAvailabilityMixin, self)
             .dispatch(request, bypassperm=True, *args, **kwargs)
         )
     else:
         raise PermissionDenied
Ejemplo n.º 29
0
def edit_edu(request, name):
  user_info = McUser.objects.get(norm_name=normalize_name(name))
  if not user_info.user.id == request.user.id and not has_permission(request.user, 'edit_all_info'):
    return redirect('edit_edu', request.user.mcuser.norm_name)
  degrees = Degree.objects.filter(user_id=user_info.id)
  if request.method == 'POST':
    degrees_formset = DegreeFormSet(request.POST, queryset=degrees, initial=[{'user': user_info.id}])
    if (degrees_formset.is_valid()):
      degrees_formset.save()
      messages.add_message(
        request, messages.SUCCESS,
        'Changes saved! Click <a href="%s">here</a> to view profile.' % reverse('profile', args=[user_info.get_link_name()]))
      update_last_updated(user_info, request.user)
      return redirect('edit_edu', user_info.norm_name)
  else:
    degrees_formset = DegreeFormSet(queryset=degrees, initial=[{'user': user_info.id}])
  context = {
      'degrees_formset': degrees_formset,
      'mcuser': user_info
      }
  return render(request, 'core/edit_edu.html', context)
Ejemplo n.º 30
0
def edit_info(request, name):
    user_info = McUser.objects.get(norm_name=normalize_name(name))
    if not user_info.user.id == request.user.id and not has_permission(
            request.user, 'edit_all_info'):
        return redirect('edit_info', request.user.mcuser.get_link_name())
    if request.method == 'POST':
        if has_role(request.user, 'staff'):
            form = McUserStaffForm(request.POST,
                                   request.FILES,
                                   instance=user_info,
                                   prefix='base')
        else:
            form = McUserForm(request.POST,
                              request.FILES,
                              instance=user_info,
                              prefix='base')
        if (form.is_valid()):
            mcuser = form.save(commit=False)
            hidden_fields = [
                key.replace('checkbox_', '') for key in request.POST
                if key.startswith('checkbox_')
            ]
            mcuser.hidden_fields = hidden_fields
            mcuser.save()
            messages.add_message(
                request, messages.SUCCESS,
                'Changes saved! Click <a href="%s">here</a> to view profile.' %
                reverse('profile', args=[mcuser.get_link_name()]))
            update_last_updated(user_info, request.user)
            return redirect('edit_info', user_info.norm_name)
    else:
        if has_role(request.user, 'staff'):
            form = McUserStaffForm(instance=user_info, prefix='base')
        else:
            form = McUserForm(instance=user_info, prefix='base')
    context = {'form': form, 'mcuser': user_info}
    template = 'core/edit_info.html'
    if has_role(user_info.user, 'staff'):
        template = 'core/edit_info_staff.html'
    return render(request, template, context)
Ejemplo n.º 31
0
 def has_permission(self, request, view):
     """
     Returns True if the user has the 'can_advance_search' permission.
     """
     return has_permission(request.user, Permissions.CAN_ADVANCE_SEARCH)
Ejemplo n.º 32
0
    def test_user_with_no_role(self):
        user = mommy.make(get_user_model())

        self.assertFalse(has_permission(user, 'permission1'))
Ejemplo n.º 33
0
    def test_revoke_revoked_permission(self):
        user = self.user

        self.assertTrue(revoke_permission(user, 'permission4'))

        self.assertFalse(has_permission(user, 'permission4'))
Ejemplo n.º 34
0
    def test_grat_granted_permission(self):
        user = self.user

        self.assertTrue(grant_permission(user, 'permission3'))

        self.assertTrue(has_permission(user, 'permission3'))
Ejemplo n.º 35
0
 def test_none_user_param(self):
     self.assertFalse(has_permission(None, 'ver_role1'))
Ejemplo n.º 36
0
    def test_not_existent_permission(self):
        user = self.user

        self.assertFalse(has_permission(user, 'not_a_permission'))
    def test_revoke_permission(self):
        user = self.user

        self.assertTrue(revoke_permission(user, 'permission3'))

        self.assertFalse(has_permission(user, 'permission3'))
Ejemplo n.º 38
0
  def wrapper(request, *args, **kwargs):

    if get_state().current == 1:
      if not (has_role(request.user, ['staff', 'dev', 'selection']) or has_permission(request.user, 'edit_applicants')):
        raise Http404('App not available until later.')
    return f(request, *args, **kwargs)
def has_role_template_tag(user, role):
    return has_permission(user, role)
Ejemplo n.º 40
0
 def has_permission(self, request, view):
     """
     Returns True if the user has the 'can_message_learners' permission.
     """
     return has_permission(request.user, Permissions.CAN_MESSAGE_LEARNERS)
    def test_dos_not_have_Role1_permission(self):
        user = self.user

        Role1.assign_role_to_user(user)

        self.assertFalse(has_permission(user, 'permission3'))
    def test_grat_granted_permission(self):
        user = self.user

        self.assertTrue(grant_permission(user, 'permission3'))

        self.assertTrue(has_permission(user, 'permission3'))
Ejemplo n.º 43
0
def has_role_template_tag(user, role):
    return has_permission(user, role)
    def test_not_existent_permission(self):
        user = self.user

        self.assertFalse(has_permission(user, 'not_a_permission'))
Ejemplo n.º 45
0
    def test_has_VerRole1_permission(self):
        user = self.user

        self.assertTrue(has_permission(user, 'permission1'))
    def test_user_with_no_role(self):
        user = mommy.make(get_user_model())

        self.assertFalse(has_permission(user, 'permission1'))
Ejemplo n.º 47
0
    def test_dos_not_have_VerRole1_permission(self):
        user = self.user

        VerRole1.assign_role_to_user(user)

        self.assertFalse(has_permission(user, 'permission3'))
Ejemplo n.º 48
0
 def choices_for_request(self):
     self.choices = self.get_choices()
     if has_permission(self.request.user, self.required_permission):
         return super(PersonAutocomplete, self).choices_for_request()
     else:
         raise PermissionDenied
    def test_has_Role1_permission(self):
        user = self.user

        self.assertTrue(has_permission(user, 'permission1'))