def index(self): request = self.request total_registered_users = UserService.total_count( db_session=request.dbsession) latest_logged_user = UserService.latest_logged_user( db_session=request.dbsession) latest_registered_user = UserService.latest_registered_user( db_session=request.dbsession) return { 'total_registered_users': total_registered_users, 'latest_logged_user': latest_logged_user, 'latest_registered_user': latest_registered_user, }
def index(self): request = self.request total_registered_users = UserService.total_count(db_session=request.dbsession) latest_logged_user = UserService.latest_logged_user( db_session=request.dbsession ) latest_registered_user = UserService.latest_registered_user( db_session=request.dbsession ) return { "total_registered_users": total_registered_users, "latest_logged_user": latest_logged_user, "latest_registered_user": latest_registered_user, }
def user_get(self, user_id): request = self.request user = UserService.get(safe_integer(user_id), db_session=request.dbsession) if not user: raise pyramid.httpexceptions.HTTPNotFound() return user
def lost_password_generate(self): """ Shows new password form - perform time check and set new password for user """ request = self.request user = UserService.by_user_name_and_security_code( request.params.get("user_name"), request.params.get("security_code"), db_session=request.dbsession, ) delta = 0 if user: delta = datetime.utcnow() - user.security_code_date if user and delta.total_seconds() < 600: form = UserNewPasswordForm(request.POST, context={"context": request}) if request.method == "POST" and form.validate(): user.set_password(form.password.data) msg = { "msg": self.translate(_("You can sign in with your new password.")), "level": "success", } request.session.flash(msg) return HTTPFound(location=request.route_url("register")) else: return {"update_password_form": form} else: return Response("Security code expired")
def user_permission_delete(self): request = self.request resource = self.request.context.resource user = UserService.by_user_name( request.GET.get("user_name"), db_session=self.request.dbsession ) permission = self.shared.user_permission_get( resource.resource_id, user.id, request.GET.get("perm_name") ) back_url = request.route_url( "admin_object", object=resource.plural_type, object_id=resource.resource_id, verb="GET", ) if request.method == "POST": self.shared.user_permission_delete( resource, user.id, request.GET.get("perm_name") ) return httpexceptions.HTTPFound(location=back_url) return { "parent_obj": user, "member_obj": permission, "confirm_url": request.current_route_url(), "back_url": back_url, }
def user_get_by_username(self, user_name): request = self.request user = UserService.by_user_name(user_name, db_session=request.dbsession) if not user: raise pyramid.httpexceptions.HTTPNotFound() return user
def permission_post(self): request = self.request user = self.shared.user_get(request.matchdict["object_id"]) user_form = UserAdminUpdateForm( request.POST, obj=user, context={"request": request, "modified_obj": user} ) permission_form = DirectPermissionForm( request.POST, context={"request": request} ) permissions_grid = UserPermissionsGrid( UserService.permissions(user), request=request, user=user ) if request.method == "POST" and permission_form.validate(): permission_name = permission_form.perm_name.data self.shared.permission_post(user, permission_name) url = request.route_url( "admin_object", object="users", object_id=user.id, verb="GET" ) return pyramid.httpexceptions.HTTPFound(location=url) return { "user": user, "user_form": user_form, "permission_form": permission_form, "permissions_grid": permissions_grid, }
def validate_email(self, value): request = self.context["request"] modified_obj = self.context.get("modified_obj") user = UserService.by_email(value, db_session=request.dbsession) if user: if not modified_obj or modified_obj.id != user.id: msg = _("Email already exists in database") raise validate.ValidationError(msg)
def allow_root_access(request, context): """ Adds ALL_PERMISSIONS to every resource if user has 'root_permission' """ if getattr(request, "user"): permissions = UserService.permissions(request.user) for perm in permission_to_pyramid_acls(permissions): if perm[2] == "root_administration": context.__acl__.append((perm[0], perm[1], ALL_PERMISSIONS))
def collection_list(self, page=1, filter_params=None): request = self.request self.page = page user_paginator = UserService.get_paginator( page=self.page, items_per_page=USERS_PER_PAGE, # url_maker gets passed to SqlalchemyOrmPage url_maker=lambda p: request.current_route_url(_query={"page": p}), filter_params=filter_params, db_session=request.dbsession) return user_paginator
def groupfinder(userid, request): # registers _reified_user_obj that will be used later by request.user property # we cache it so we don't have to query the db more than once if not getattr(request, '_reified_user_obj', None) and userid: user = UserService.get(userid, db_session=request.dbsession) request._reified_user_obj = user elif userid: user = request._reified_user_obj if user: groups = ["group:%s" % g.id for g in user.groups] return groups
def collection_list(self, page=1, filter_params=None): request = self.request self.page = page user_paginator = UserService.get_paginator( page=self.page, items_per_page=USERS_PER_PAGE, # url_maker gets passed to SqlalchemyOrmPage url_maker=lambda p: request.current_route_url(_query={"page": p}), filter_params=filter_params, db_session=request.dbsession, ) return user_paginator
def validate_user_name(self, value): request = self.context["request"] modified_obj = self.context.get("modified_obj") user = UserService.by_user_name(value, db_session=request.dbsession) by_admin = request.has_permission("root_administration") if modified_obj and not by_admin and (modified_obj.user_name != value): msg = _("Only administrator can change usernames") raise validate.ValidationError(msg) if user: if not modified_obj or modified_obj.id != user.id: msg = _("User already exists in database") raise validate.ValidationError(msg)
def populate_instance(self, instance, data, *args, **kwargs): # this is safe and doesn't overwrite user_password with cleartext instance.populate_obj(data, *args, **kwargs) self.request.session.flash( {"msg": self.translate(_("User updated.")), "level": "success"} ) log.info( "user_populate_instance", extra={ "action": "updated", "x": datetime.now(), "y": datetime.utcnow().date(), "user_id": instance.id, }, ) if data.get("password"): # set hashed password UserService.set_password(instance, data["password"]) self.request.session.flash( {"msg": self.translate(_("User password updated.")), "level": "success"} ) log.info("user_GET_PATCH", extra={"action": "password_updated"})
def post(self): resource = self.request.context.resource schema = UserResourcePermissionSchema( context={"request": self.request, "resource": resource} ) data = schema.load(self.request.unsafe_json_body).data user = UserService.by_user_name( data["user_name"], db_session=self.request.dbsession ) perm_inst = self.shared.user_permission_post( resource, user.id, data["perm_name"] ) self.request.dbsession.flush() return perm_inst.get_dict()
def delete(self): resource = self.request.context.resource schema = UserResourcePermissionSchema( context={"request": self.request, "resource": resource} ) params = { "user_name": self.request.GET.get("user_name"), "perm_name": self.request.GET.get("perm_name"), } data = schema.load(params).data user = UserService.by_user_name( data["user_name"], db_session=self.request.dbsession ) self.shared.user_permission_delete(resource, user.id, data["perm_name"]) return True
def lost_password(self): """ Presents lost password page - sends password reset link to specified email address. This link is valid only for 10 minutes """ request = self.request form = UserLostPasswordForm(request.POST, context={"request": request}) if request.method == "POST" and form.validate(): user = UserService.by_email(form.email.data, db_session=request.dbsession) if user: user.regenerate_security_code() user.security_code_date = datetime.utcnow() title = self.translate( _( "${project} :: New password request", mapping={"project": "testscaffold"}, ) ) email_vars = {"user": user, "request": request, "email_title": title} ev = EmailEvent( request, recipients=[user.email], tmpl_vars=email_vars, tmpl_loc="testscaffold:templates/emails/" "lost_password.jinja2", ) request.registry.notify(ev) msg = { "msg": self.translate( _( "Password reset email had been sent. " "Please check your mailbox for further instructions." "If you can't see the message please check " "your spam box." ) ), "level": "success", } request.session.flash(msg) return HTTPFound(location=request.route_url("lost_password")) else: msg = {"msg": "Email not found", "level": "warning"} request.session.flash(msg) return {"lost_password_form": form}
def user_permission_post(self): request = self.request resource = self.request.context.resource came_from = request.headers.get("Referer") schema = UserResourcePermissionSchema( context={"request": self.request, "resource": resource} ) data = { "user_name": self.request.POST.get("user_name"), "perm_name": self.request.POST.get("perm_name"), } data = schema.load(data).data user = UserService.by_user_name( data["user_name"], db_session=self.request.dbsession ) perm_inst = self.shared.user_permission_post( resource, user.id, data["perm_name"] ) location = came_from or request.route_url("admin") return httpexceptions.HTTPFound(location=location)
def __init__(self, request): self.__acl__ = [] # general page factory - append custom non resource permissions if getattr(request, 'user'): permissions = UserService.permissions(request.user, db_session=request.dbsession) has_admin_panel_access = False panel_perms = ['admin_panel', ALL_PERMISSIONS] for outcome, perm_user, perm_name in permission_to_pyramid_acls( permissions): perm_tuple = rewrite_root_perm(outcome, perm_user, perm_name) if perm_tuple[0] is Allow and perm_tuple[2] in panel_perms: has_admin_panel_access = True self.__acl__.append(perm_tuple) # users have special permission called `admin_panel` # it should be prerequisite for other `admin*` permissions # if it is not present let's deny other admin permissions if not has_admin_panel_access: self.__acl__ = list( filter(filter_admin_panel_perms, self.__acl__))
def __init__(self, request): self.__acl__ = [] # general page factory - append custom non resource permissions if getattr(request, "user"): permissions = UserService.permissions( request.user, db_session=request.dbsession ) has_admin_panel_access = False panel_perms = ["admin_panel", ALL_PERMISSIONS] for outcome, perm_user, perm_name in permission_to_pyramid_acls( permissions ): perm_tuple = rewrite_root_perm(outcome, perm_user, perm_name) if perm_tuple[0] is Allow and perm_tuple[2] in panel_perms: has_admin_panel_access = True self.__acl__.append(perm_tuple) # users have special permission called `admin_panel` # it should be prerequisite for other `admin*` permissions # if it is not present let's deny other admin permissions if not has_admin_panel_access: self.__acl__ = list(filter(filter_admin_panel_perms, self.__acl__))
def validate_user_name(self, value): request = self.context["request"] user = UserService.by_user_name(value, db_session=request.dbsession) if not user: raise validate.ValidationError(_("User not found"))
def get_user(request): userid = unauthenticated_userid(request) if userid is not None: # this should return None if the user doesn't exist # in the database return UserService.get(userid, db_session=request.dbsession)