def form_valid(self, form): user = self.object role = form.data.get('role') if not role: raise Exception('Role is required') clear_roles(user) if form.data.get('is_active'): assign_role(user, role) return super(EditUserView, self).form_valid(form)
def test_clear_roles(self): user = self.user assign_role(user, ShoRole1) assign_role(user, ShoRole2) assign_role(user, ShoRole3) clear_roles(user) self.assertListEqual([], get_user_roles(user))
def test_clear_roles(self): user = self.user assign_role(user, ShoRole1) assign_role(user, ShoRole2) assign_role(user, ShoRole3) clear_roles(user) self.assertListEqual([], get_user_roles(user))
def profile(request, account_slug): account = get_object_or_404(Account.objects.active(), slug=account_slug) can_modify_profile = (request.user == account or has_permission(request.user, "modify_profile")) user_group_form = StaffUserGroupForm(request.POST or None, request.FILES or None) if request.user.is_authenticated: if user_group_form.is_valid() and has_permission(request.user, "change_user_group"): group = user_group_form.cleaned_data['group'] clear_roles(account) assign_role(account, group) if group in ['administrator','moderator','janitor']: account.is_staff = True account.save() has_comment_priv = request.user.has_priv("can_comment") can_change_group = has_permission(request.user, "change_user_group") else: has_comment_priv = False can_change_group = False if request.method == "POST": newCommentTextarea = request.POST.get("newCommentTextarea") aboutUserTextarea = request.POST.get("aboutUserTextarea") if not request.user.is_authenticated: return redirect('account:login') elif newCommentTextarea and has_comment_priv: # Comment creating comment_content = newCommentTextarea Comment.objects.create(content=comment_content, author=request.user, content_object=account) return redirect('booru:profile', account_slug=account.slug) elif aboutUserTextarea and can_modify_profile: # About myself editing account.about = aboutUserTextarea account.save() return redirect('booru:profile', account_slug=account.slug) # TODO: I don't remember if I can safely pass account as # an parameter to the render. favorites = Post.objects.filter(favorites__account=account)[:5] context = { 'account' : account, 'recent_favorites' : favorites, 'recent_uploads' : account.get_posts().not_deleted().order_by('-id'), 'deleted_posts' : account.get_posts().deleted(), 'can_modify_profile': request.user.is_authenticated and can_modify_profile, 'can_comment': has_comment_priv, 'user_group_form': user_group_form, 'can_change_group': can_change_group } return render(request, 'booru/account/profile.html', context)
def test_request_mass_rename_by_logged_staff_no_perm_client(self): user = self.create_test_user(is_staff=True) clear_roles(user) assign_role(user, 'janitor') revoke_permission(user, 'mass_rename') self.assertFalse(has_permission(user, 'mass_rename')) c = Client() logged_in = c.login(username='******', password='******') response = c.get('/staff_page/mass_rename') self.assertEqual(302, response.status_code)
def update(self, instance, validated_data): positions_data = self.context['request'].data['positions'] user_id = self.context['request'].data['id'] user = get_object_or_404(User, pk=user_id) instance = super(UserDetailSerializer, self).update(instance, validated_data) new_positions = [] for row in positions_data: position = get_object_or_404(Position, pk=row) new_positions.append(position) current_positions = UserPosition.objects.filter(user=user_id) current_positions.delete() # TODO not delete already existing positions for new_pos in new_positions: UserPosition.objects.create(user=user, position=new_pos) categories_data = self.context['request'].data['categories'] new_categories = [] for row in categories_data: category = get_object_or_404(Category, pk=row) new_categories.append(category) current_categories = UserCategory.objects.filter(user=user_id) current_categories.delete() # TODO not delete already existing categories for new_cat in new_categories: UserCategory.objects.create(user=user, category=new_cat) units_data = self.context['request'].data['units'] new_units = [] for row in units_data: unit = get_object_or_404(Unit, pk=row) new_units.append(unit) current_units = UserUnit.objects.filter(user=user_id) current_units.delete() # TODO not delete already existing units for new_un in new_units: UserUnit.objects.create(user=user, unit=new_un) faculties_data = self.context['request'].data['faculties'] new_faculties = [] for row in faculties_data: faculty = get_object_or_404(Faculty, pk=row) new_faculties.append(faculty) current_faculties = UserFaculty.objects.filter(user=user_id) current_faculties.delete() # TODO not delete already existing faculties for new_fac in new_faculties: UserFaculty.objects.create(user=user, faculty=new_fac) role_data = self.context['request'].data['role'] clear_roles(user) for row in role_data: assign_role(user, retrieve_role(row)) return instance
def change_user_role(self, roles): """Changes User Role Requires: django-rolepermissions Params: user: User Object roles: A list containing new roles of the user This methods clears the previous roles of the user and replaces them with the new one. """ clear_roles(self) for role in roles: assign_role(self, role) return self
def get_set_user_info(request): """ Get the basic information for the current logged in user """ try: if request.session.session_key is not None: # update the session details User = get_user_model() cur_user = User.objects.get(id=request.user.id) clear_roles(cur_user) assign_role(cur_user, Pi) request.session[ 'cu_designation'] = cur_user.get_designation_display() request.session['cu_designation_id'] = cur_user.designation request.session['cu_last_name'] = cur_user.last_name request.session['cu_first_name'] = cur_user.first_name request.session['cu_email'] = cur_user.email request.session['cu_issuperuser'] = cur_user.is_superuser if cur_user.is_superuser: request.session['cu_designation'] = 'Super Administrator' cur_user_email = cur_user.email elif request.session.get('cu_email') is not None: cur_user_email = request.session['cu_email'] else: cur_user_email = None global user_permissions if cur_user_email: user_permissions = available_perm_names(cur_user) else: user_permissions = [] if settings.DEBUG: if cur_user.is_superuser and len(user_permissions) == 0: user_permissions = ['all'] return (cur_user_email, user_permissions) except User.DoesNotExist as e: terminal.tprint( "%s: A user who is not vetted is trying to log in. Kick them out." % str(e), 'fail') return None except Exception as e: send_sentry_message(str(e)) if settings.DEBUG: logging.error(traceback.format_exc()) # we need a default page to go to return render(request, 'dashboard/dashboard.html', params)
def form_valid(self, form): extra_fields = { 'first_name': form.instance.first_name, 'last_name': form.instance.last_name } try: user = User.objects.create_user(form.instance.email, form.instance.password, **extra_fields) role = form.data.get('role') if not role: raise Exception('Role is required') clear_roles(user) assign_role(user, role) messages.success(self.request, "User {} created".format(user.email)) except Exception as error: messages.error(self.request, "Failed on create. Error {}".format(error)) return HttpResponseRedirect(self.get_success_url())
def edit_users(request, d_type): params = get_basic_info(request) try: if d_type == 'edit_user': dash_views.update_user(request, pk_id) # lets update the permissions too edit_user = User.objects.get(id=pk_id) clear_roles(edit_user) for name, obj in inspect.getmembers( importlib.import_module("coinfection.settings.roles"), inspect.isclass): if inspect.isclass(obj): if name == 'AbstractUserRole': continue if obj.alias == edit_user.designation: assign_role(edit_user, obj) break return JsonResponse({ 'error': False, 'message': 'The user has been edited successfully' }) except DataError as e: transaction.rollback() if settings.DEBUG: terminal.tprint('%s (%s)' % (str(e), type(e)), 'fail') capture_exception(e) return JsonResponse({ 'error': True, 'message': 'Please check the entered data' }) except Exception as e: if settings.DEBUG: terminal.tprint('%s (%s)' % (str(e), type(e)), 'fail') capture_exception(e) return JsonResponse({ 'error': True, 'message': 'There was an error while updating the database' })
def handle(self, *args, **options): # Sync auth.Group with current registered roles (leaving existing groups intact!) for role in roles.RolesManager.get_roles(): group, created = role.get_or_create_group() if created: self.stdout.write("Created Group: %s from Role: %s" % (group.name, role.get_name())) # Sync auth.Permission with permissions for this role role.get_default_true_permissions() if options.get('reset_user_permissions', False): # dj1.7 compat # Push any permission changes made to roles and remove any unregistered roles from all auth.Users self.stdout.write("Resetting permissions for ALL Users to defaults defined by roles.") for user in get_user_model().objects.all(): user_roles = roles.get_user_roles(user=user) roles.clear_roles(user=user) for role in user_roles: roles.assign_role(user=user, role=role)
def put(self, request, user_id): try: user = User.objects.get(pk=user_id) except User.DoesNotExist: raise ApiException(request, _('User does not exist.'), status_code=HTTPStatus.NOT_FOUND) form = UserForms.Update.create_from_request(request) if not form.is_valid(): raise ValidationException(request, form) email = form.cleaned_data.get('email') assign_projects = form.cleaned_data.get('assign_projects') role = form.cleaned_data.get('role') if email != user.email: if User.objects.filter(email=email).exists(): raise ApiException(request, _('Email is already used.'), status_code=HTTPStatus.CONFLICT) form.fill(user) user.username = email if assign_projects is not None: user.assign_projects(request, assign_projects) if role: clear_roles(user) assign_role(user, role.value) user.save() return SingleResponse(request, data=user, status=HTTPStatus.OK, serializer=UserSerializer.Base)
def setRole(self): if self.is_staff or self.is_superuser: clear_roles(self) assign_role(self, 'administrador') self.role = 'Administrador' else: if self.role == 'Moderador': clear_roles(self) assign_role(self, 'moderador') else: clear_roles(self) assign_role(self, 'estudante') self.role = 'Estudante'
def remove_all_user_permission(auth_user): auth_user.is_superuser = False auth_user.is_staff = False auth_user.is_active = False clear_roles(auth_user) auth_user.save()
def tearDown(self): clear_roles(self.user)
def add_user(request): # given a user details add the user # 1. Get the next personnel code # 1. Add the details of the user and set is_active to 0. Generate a password # 2. Send email to the user with the activation link try: UserModel = get_user_model() nickname = request.POST.get('username') username = request.POST.get('username') designation = request.POST.get('designation') tel = request.POST.get('tel') email = request.POST.get('email') first_name = request.POST.get('first_name') last_name = request.POST.get('surname') new_user = UserModel(nickname=username, username=username, designation=designation, tel=tel, email=email, first_name=first_name, last_name=last_name, password=make_password('TestPass1234'), is_active=0) new_user.full_clean() new_user.save() # assign roles # ToDo: Find a way to clean the roles import clear_roles(new_user) for name, obj in inspect.getmembers( importlib.import_module("datahub.settings.roles"), inspect.isclass): if inspect.isclass(obj): if name == 'AbstractUserRole': continue if obj.alias == new_user.designation: assign_role(new_user, obj) # print("The user %s is now a %s", (edit_user.username, obj.perm_name)) break reg_view = RegistrationView() activation_link = reg_view.get_activation_key(new_user) # send an email to this user notify = Notification() uid = urlsafe_base64_encode(force_bytes(new_user.pk)) current_site = get_current_site(request) email_settings = { 'template': 'emails/verify_account.html', 'subject': '[%s] Confirm Registration' % settings.SITE_NAME, 'sender_email': settings.SENDER_EMAIL, 'recipient_email': email, 'site_name': settings.SITE_NAME, 'site_url': 'http://%s' % current_site.domain, 'title': 'Confirm Registration', 'salutation': 'Dear %s' % first_name, 'use_queue': getattr(settings, 'QUEUE_EMAILS', False), 'verification_link': 'http://%s/activate_new_user/%s/%s' % (current_site.domain, uid, activation_link), 'message': 'You have been registered successfully to the %s. We are glad to have you on board. Please click on the button below to activate your account. You will not be able to use your account until it is activated. The activation link will expire in %d hours' % (settings.SITE_NAME, settings.ACCOUNT_ACTIVATION_DAYS * 24), 'message_sub_heading': 'You have been registered successfully' } notify.send_email(email_settings) return JsonResponse({ 'error': False, 'message': 'The user has been saved successfully' }) except ValidationError as e: return JsonResponse({ 'error': True, 'message': 'There was an error while saving the user: %s' % str(e) }) except Exception as e: if settings.DEBUG: terminal.tprint(str(e), 'fail') capture_exception(e) raise