Skip to content

auth models

Base models to store users, permissions and roles.

AbstractUser

Abstract user class serving as a base to implement a concrete user model.

date_joined

Stores the current datetime (UTC) when the user is created in the database.

email

Required (nullable=False) and must be unique.

first_name

Optional (nullable=True)

hashed_password

Stores the hashed user password. Every time the user logs in, the hash of the provided password is compared against hashed_password. Hash algorithm is defined by the HASH_ALGORITHM setting.

id

Primary key Required (nullable=False) and must be

is_staff

Indicates if the user is a "staff" member. Staff is a special role stored in database as a convenience. It's up to you to define what's "staff" means in your use case.

last_name

Optional (nullable=True)

username

Required (nullable=False) and must be unique. username is used to create user JWT and retrieve roles and.

add_role(self, role=None, name=None) async

Adds a role to the user.

The role can be given either as a Role object, or by its name.

Parameters:

Name Type Description Default
role Optional[turbulette.apps.auth.models.Role]

The Role to add.

None
name Optional[str]

Name of the role to add.

None
Source code in turbulette/apps/auth/models.py
async def add_role(self, role: Optional[Role] = None, name: Optional[str] = None):
    """Adds a role to the user.

    The role can be given either as a
    [Role][turbulette.apps.auth.models.Role] object, or by its name.

    Args:
        role: The [Role][turbulette.apps.auth.models.Role] to add.
        name: Name of the role to add.
    """
    role_ = await self._get_object(Role, "name", role, name)
    await UserRole.create(user=self.id, role=role_.id)

get_by_username(username) async classmethod

Get the user object from its username.

Parameters:

Name Type Description Default
username str

username

required

Exceptions:

Type Description
DoesNotExist

Raised if no user match the given username

Returns:

Type Description
User

Returns a user object of type defined by AUTH_USER_MODEL

Source code in turbulette/apps/auth/models.py
@classmethod
async def get_by_username(cls, username: str):
    """Get the user object from its `username`.

    Args:
        username: username

    Raises:
        DoesNotExist: Raised if no user match the given username

    Returns:
        User: Returns a user object of type defined by `AUTH_USER_MODEL`
    """
    user = await cls.query.where(  # type: ignore [attr-defined] # pylint: disable=no-member
        getattr(cls, cls.USERNAME_FIELD) == username
    ).gino.first()
    if not user:
        raise DoesNotExist(cls)
    return user

get_perms(self) async

Get permissions this user has through their roles.

Returns:

Type Description
List[turbulette.apps.auth.models.Permission]

A list of Permission

Source code in turbulette/apps/auth/models.py
async def get_perms(self) -> List[Permission]:
    """Get permissions this user has through their roles.

    Returns:
        A list of [Permission][turbulette.apps.auth.models.Permission]
    """
    query = UserRole.join(Role).join(RolePermission).join(Permission).select()

    return (
        await query.gino.load(Permission.load())
        .query.where(UserRole.user == self.id)
        .gino.all()
    )

get_roles(self) async

Get all the roles to which the user belongs.

Returns:

Type Description
List[turbulette.apps.auth.models.Role]

A list of Role

Source code in turbulette/apps/auth/models.py
async def get_roles(self) -> List[Role]:
    """Get all the roles to which the user belongs.

    Returns:
        A list of [Role][turbulette.apps.auth.models.Role]
    """
    query = UserRole.join(Role).select()
    return (
        await query.gino.load(Role.load())
        .query.where(UserRole.user == self.id)
        .gino.all()
    )

get_username(self)

Return username of this user using USERNAME_FIELD attribute.

Returns:

Type Description
str

str: The username

Source code in turbulette/apps/auth/models.py
def get_username(self) -> str:
    """Return username of this user using `USERNAME_FIELD` attribute.

    Returns:
        str: The username
    """
    return str(getattr(self, self.USERNAME_FIELD))

remove_role(self, role=None, name=None) async

Removes a user role.

The role can be given either as a Role object, or by its name.

Parameters:

Name Type Description Default
role Optional[turbulette.apps.auth.models.Role]

Role to remove.

None
name Optional[str]

Name of the role to remove.

None
Source code in turbulette/apps/auth/models.py
async def remove_role(
    self, role: Optional[Role] = None, name: Optional[str] = None
):
    """Removes a user role.

    The role can be given either as a
    [Role][turbulette.apps.auth.models.Role] object, or by its name.

    Args:
        role: [Role][turbulette.apps.auth.models.Role] to remove.
        name: Name of the role to remove.
    """
    role_ = await self._get_object(Role, "name", role, name)
    await UserRole.delete.where(
        UserRole.user == self.id and UserRole.role == role_.id
    ).gino.status()

role_perms(self) async

Loads user roles and permissions.

Returns:

Type Description
List[turbulette.apps.auth.models.Role]

List of Role an their permissions

Source code in turbulette/apps/auth/models.py
async def role_perms(self) -> List[Role]:
    """Loads user roles and permissions.

    Returns:
        List of [Role][turbulette.apps.auth.models.Role] an their permissions
    """
    query = UserRole.join(Role).join(RolePermission).join(Permission).select()
    return (
        await query.where(UserRole.user == self.id)
        .gino.load(Role.distinct(Role.id).load(add_permission=Permission.load()))
        .query.gino.all()
    )

set_password(username, password) async classmethod

Changes user password.

The new password will be hashed using the hash algorithm defined by the HASH_ALGORITHM setting, and the resulting hash stored in the hashed_password column.

Parameters:

Name Type Description Default
username str

Identify the user for whom the password needs to be updated

required
password str

The new password

required
Source code in turbulette/apps/auth/models.py
@classmethod
async def set_password(cls, username: str, password: str) -> None:
    """Changes user password.

    The new password will be hashed using the hash algorithm defined
    by the `HASH_ALGORITHM` setting, and the resulting hash stored
    in the `hashed_password` column.

    Args:
        username (str): Identify the user for whom the password needs to be updated
        password (str): The new password
    """
    user = await cls.get_by_username(username)
    hashed_password = auth.get_password_hash(password)
    await user.update(hashed_password=hashed_password).apply()

Permission

A permission specify a certain right a user has.

id

Primary key Required (nullable=False) and must be

key

Required (nullable=False), and must be unique. Used to identify the permission in JWT.

name

Required (nullable=False). Should be human readable.

Role

A role is a permission group to which users belong.

id

Primary key Required (nullable=False) and must be

name

Required (nulllable=False) and must be unique Must be unique. Used to identify the role in JWT.

RolePermission

Simple table to link roles and permissions.

permission

Foreign key to the linked permission. Part of the primary key.

role

Foreign key to the linked role. Part of the primary key.

UserRole

Link users to roles.

role

Foreign key to the associated role. Part of the primary key.

user

Foreign key to the user defined by AUTH_USER_MODEL setting. part of the primary key.

auth_user_tablename()

Get the auth table name from settings or generate it.

Source code in turbulette/apps/auth/models.py
def auth_user_tablename() -> str:
    """Get the auth table name from settings or generate it."""
    return settings.AUTH_USER_MODEL_TABLENAME or get_tablename(
        settings.AUTH_USER_MODEL.rsplit(".", 3)[-3],
        settings.AUTH_USER_MODEL.split(".")[-1],
    )

Last update: 2021-02-18