Exemple #1
0
    def forge(user, follow, photo, file, tag, collect, comment):
        """Generate fake data."""

        from server.fakes import fake_admin, fake_comment, fake_follow, fake_photo, fake_file, fake_tag, fake_user, fake_collect

        db.drop_all()
        db.create_all()

        click.echo('Initializing the roles and permissions...')
        Role.init_role()
        click.echo('Generating the administrator...')
        fake_admin()
        click.echo('Generating %d users...' % user)
        fake_user(user)
        click.echo('Generating %d follows...' % follow)
        fake_follow(follow)
        click.echo('Generating %d tags...' % tag)
        fake_tag(tag)
        click.echo('Generating %d photos...' % photo)
        fake_photo(photo)
        click.echo("Generating files ")
        fake_file(file)
        click.echo('Generating %d collects...' % photo)
        fake_collect(collect)
        click.echo('Generating %d comments...' % comment)
        fake_comment(comment)
        click.echo('Done.')
Exemple #2
0
    def init():
        """Initialize server."""
        click.echo('Initializing the database...')
        db.create_all()

        click.echo('Initializing the roles and permissions...')
        Role.init_role()

        click.echo('Done.')
    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
        ]
Exemple #5
0
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}")
Exemple #6
0
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)})