async def get_role(self, role_id): """Gets a role by its role id.""" query = "SELECT * FROM roles WHERE id=$1;" record = await self.pool.fetchrow(query, role_id) if not record: return None return Role( id=record["id"], name=record["name"], permissions=Permissions(record["permissions"]), created_at=record["created_at"], state=self.app, )
async def get_roles(self): """Gets all roles from the database.""" query = "SELECT * FROM roles ORDER BY created_at ASC;" records = await self.pool.fetch(query) if not records: return [] return [ Role( id=record["id"], name=record["name"], permissions=Permissions(record["permissions"]), created_at=record["created_at"], state=self.app, ) for record in records ]
def create_user(): email = click.prompt("Email") first_name = click.prompt("First name") last_name = click.prompt("Last name") password = click.prompt("Password", hide_input=True, confirmation_prompt=True) role = click.prompt("Role") try: user = User( email=email, first_name=first_name, last_name=last_name, password=password, confirmed=True, email_confirmed_at=datetime.utcnow(), ) role = Role(name=role) user.roles.append(role) db.session.add(user) db.session.commit() except Exception as e: print(f"Error: {e}")
def populate_roles(): Role(name="admin", description="Admin role", privileged=True).save() Role(name="usermanager", description="User Manager role", privileged=True).save() Role(name="user", description="User role").save()
def post(self, request, id=0): bodyUnicode = request.body.decode('utf-8') jsonRequestData = json.loads(bodyUnicode) targetUserId = jsonRequestData.get("userId", 0) canRead = jsonRequestData.get("read", False) if (canRead == "true" or canRead == True or canRead == "True"): canRead = True else: canRead = False canWrite = jsonRequestData.get("write", False) if (canWrite == "true" or canWrite == True or canWrite == "True"): canWrite = True else: canWrite = False username = jsonRequestData.get("username", "") password = jsonRequestData.get("password", "") # Check user authentication user = authenticate(username=username, password=password) if (user is None): return JsonResponse({ "status": "error", "message": "Autenticação falhou. Utilizador ou password errados." }) # Load the file file = None try: file = user.files.get(id=id) except File.DoesNotExist as ex: return JsonResponse({ "status": "error", "message": "Ficheiro não encontrado." }) # Load the target user targetUser = None try: targetUser = User.objects.get(id=targetUserId) except User.DoesNotExist as ex: return JsonResponse({ "status": "error", "message": "O utilizador a quem pretende adicionar permissões não foi encontrado." }) # If read = false and write = false then just delete a role if it exists if (canRead == False and canWrite == False): try: file.editors.get(user=targetUser).delete() return JsonResponse({'status': "success"}) except Role.DoesNotExist as ex: return JsonResponse({"status": "error", "message": str(ex)}) # Check if the role already exists, if yes updates it try: role = file.editors.get(user=targetUser) role.setReadPermission(canRead) role.setWritePermission(canWrite) role.save() return JsonResponse({'status': "success"}) except Role.DoesNotExist as ex: pass # If the role does not exists then create a new one try: role = Role() role.setUser(targetUser) role.setReadPermission(canRead) role.setWritePermission(canWrite) role.setFile(file) role.save() return JsonResponse({'status': "success"}) except Exception as ex: raise ex return JsonResponse({"status": "error", "message": str(ex)})