users_api package

Module contents

class users_api.models.AuthenticationLog(*args, **kwargs)[source]

Bases: Model

A model to keep track of all requests for authentication.

Which email was used, when they were made and what number of consecutive failed attempts have been made on this email. The failed attempt counter is reset on a succesful login or a changed password.

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

email: EmailField

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

failed_attempt: IntegerField

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

static get_last_login_for(email: str) AuthenticationLog | None[source]

Get the latest authentication attempt for a specified email.

static get_locked_out_error(email: str) ValidationError[source]
get_next_by_time(*, field=<django.db.models.fields.DateTimeField: time>, is_next=True, **kwargs)
get_previous_by_time(*, field=<django.db.models.fields.DateTimeField: time>, is_next=False, **kwargs)
static get_remaining_lockout_time(email: str) float[source]

Get the remaining lockout time for a specified email.

id

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

static is_user_locked_out(email: str) bool[source]
static log_authentication_attempt(email: str, failed: bool) None[source]

Log an attempt for authentication.

objects = <django.db.models.manager.Manager object>
time: DateTimeField

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

class users_api.models.BaseVerificationCode(*args, **kwargs)[source]

Bases: Model

Base class for temporary codes for verifying the user without login.

class Meta[source]

Bases: object

abstract = False
classmethod create(user: WdaeUser) BaseVerificationCode[source]

Create an email verification code.

created_at: Field

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

classmethod get_code(user: WdaeUser) BaseVerificationCode | None[source]

Get a verification code for a user.

get_next_by_created_at(*, field=<django.db.models.fields.DateTimeField: created_at>, is_next=True, **kwargs)
get_previous_by_created_at(*, field=<django.db.models.fields.DateTimeField: created_at>, is_next=False, **kwargs)
path: Field

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

user: Field

Accessor to the related object on the forward side of a one-to-one relation.

In the example:

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Restaurant.place is a ForwardOneToOneDescriptor instance.

user_id
validate() bool[source]
class users_api.models.ResetPasswordCode(*args, **kwargs)[source]

Bases: BaseVerificationCode

Class used for verification of password resets.

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

created_at: Field

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

get_next_by_created_at(*, field=<django.db.models.fields.DateTimeField: created_at>, is_next=True, **kwargs)
get_previous_by_created_at(*, field=<django.db.models.fields.DateTimeField: created_at>, is_next=False, **kwargs)
id

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

objects = <django.db.models.manager.Manager object>
path: Field

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

user: Field

Accessor to the related object on the forward side of a one-to-one relation.

In the example:

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Restaurant.place is a ForwardOneToOneDescriptor instance.

user_id
validate() bool[source]
class users_api.models.SetPasswordCode(*args, **kwargs)[source]

Bases: BaseVerificationCode

Base class for temporary paths for verifying user without login.

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

created_at: Field

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

get_next_by_created_at(*, field=<django.db.models.fields.DateTimeField: created_at>, is_next=True, **kwargs)
get_previous_by_created_at(*, field=<django.db.models.fields.DateTimeField: created_at>, is_next=False, **kwargs)
id

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

objects = <django.db.models.manager.Manager object>
path: Field

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

user: Field

Accessor to the related object on the forward side of a one-to-one relation.

In the example:

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Restaurant.place is a ForwardOneToOneDescriptor instance.

user_id
validate() bool[source]
class users_api.models.WdaeUser(*args, **kwargs)[source]

Bases: AbstractBaseUser, PermissionsMixin

Class representing a user in wdae.

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

REQUIRED_FIELDS = ['name']
SUPERUSER_GROUP = 'admin'
UMLIMITED_DOWNLOAD_GROUP = 'unlimited'
USERNAME_FIELD = 'email'
property allowed_datasets: list[dict[str, Any]]
auth_token

Accessor to the related object on the reverse side of a one-to-one relation.

In the example:

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

static change_password(verification_path: SetPasswordCode | ResetPasswordCode, new_password: str) WdaeUser[source]

Initiate password reset for the user.

date_joined: DateTimeField

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

deauthenticate() None[source]
email: EmailField

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

email_user(subject: str, message: str, from_email: str | None = None) int[source]

Send an email to the user.

groups

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example:

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

property has_unlimited_download: bool
id

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

is_active: BooleanField

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

is_staff: BooleanField

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

is_superuser

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

last_login

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

name: CharField

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

oauth2_provider_accesstoken

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

oauth2_provider_application

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

oauth2_provider_grant

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

oauth2_provider_idtoken

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

oauth2_provider_refreshtoken

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

objects = <users_api.models.WdaeUserManager object>
password

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

register_preexisting_user(name: str | None) None[source]

Register already existing user.

reset_password(by_admin: bool = False) None[source]
resetpasswordcode

Accessor to the related object on the reverse side of a one-to-one relation.

In the example:

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

set_password(raw_password: str | None) None[source]
set_unusable_password() None[source]
setpasswordcode

Accessor to the related object on the reverse side of a one-to-one relation.

In the example:

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

user_permissions

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example:

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

userquery_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

class users_api.models.WdaeUserManager(*args, **kwargs)[source]

Bases: BaseUserManager

User manager for wdae users.

create(**kwargs: Any) WdaeUser[source]

Create a new object with the given kwargs, saving it to the database and returning the created object.

create_superuser(email: str, password: str, **kwargs: Any) WdaeUser[source]

Create and save a superuser.

create_user(email: str, password: str | None = None, **kwargs: Any) WdaeUser[source]
get_or_create(**kwargs: Any) tuple[users_api.models.WdaeUser, bool][source]

Look up an object with the given kwargs, creating one if necessary. Return a tuple of (object, created), where created is a boolean specifying whether an object was created.

users_api.models.csrf_clear(view_func: Callable) Any[source]

Skips the CSRF checks by setting the ‘csrf_processing_done’ to true.

users_api.models.get_default_application() Application[source]
users_api.models.group_post_delete(sender: Type[Group], **kwargs: Any) None[source]

Automatically remove staff privileges of SUPERUSER_GROUP users.

Automatically remove staff privileges of users belonging to the SUPERUSER_GROUP group if that group is deleted.

users_api.models.group_pre_delete(sender: Type[Group], **kwargs: Any) None[source]

Attach user-ids when a group is being deleted.

When deleting a group, attaches the ids of the users who belonged to it in order to be used in the post_delete signal. Used only for the SUPERUSER_GROUP group.

users_api.models.send_already_existing_email(user: WdaeUser) None[source]

Send an email to already existing user.

users_api.models.send_reset_email(user: WdaeUser, verif_path: BaseVerificationCode, by_admin: bool = False) None[source]

Return dict with subject and message of the email.

users_api.models.send_reset_inactive_acc_email(user: WdaeUser) None[source]

Send an email to an inactive user.

users_api.models.send_verif_email(user: WdaeUser, verif_path: BaseVerificationCode) None[source]

Send a verification email to the user.

users_api.models.staff_update(sender: Any, **kwargs: Any) None[source]

Update if user is part of staff when SUPERUSER_GROUP is added/rmed.

class users_api.views.BasePasswordView(**kwargs)[source]

Bases: APIView

Base class for set/reset password views.

code_type: str | None = None
form: Form | None = None
get(request: Request) HttpResponse[source]

Render the password reset form.

post(request: Request) HttpResponse[source]

Handle the password reset form.

template: str | None = None
verification_code_model: Model | None = None
class users_api.views.FederationCredentials(**kwargs)[source]

Bases: APIView

API for handling federation credentials/applications.

authentication_classes = (<class 'utils.authentication.GPFOAuth2Authentication'>,)
delete(request: Request) Response[source]

Delete a given federation app.

get(request: Request) Response[source]

List all federation apps for a user.

post(request: Request) Response[source]

Create a new federation application and return its credentials.

put(request: Request) Response[source]

Update a given federation token’s name.

class users_api.views.ForgotPassword(**kwargs)[source]

Bases: APIView

View for forgotten password.

get(request: Request) HttpResponse[source]
post(request: Request) HttpResponse[source]

Send a reset password email to the user.

class users_api.views.RESTLoginView(**kwargs)[source]

Bases: APIView

View for REST session bases logging in.

post(request: Request) Response[source]

Supports a REST login endpoint.

class users_api.views.ResetPassword(**kwargs)[source]

Bases: BasePasswordView

code_type: str | None = 'reset'
form

alias of WdaeResetPasswordForm

template: str | None = 'users_api/registration/reset-password.html'
verification_code_model

alias of ResetPasswordCode

class users_api.views.SetPassword(**kwargs)[source]

Bases: BasePasswordView

code_type: str | None = 'set'
form

alias of WdaeRegisterPasswordForm

template: str | None = 'users_api/registration/set-password.html'
verification_code_model

alias of SetPasswordCode

class users_api.views.UserViewSet(**kwargs)[source]

Bases: ModelViewSet

API endpoint that allows users to be viewed or edited.

authentication_classes = [<class 'utils.authentication.SessionAuthenticationWithoutCSRF'>, <class 'utils.authentication.GPFOAuth2Authentication'>]
create(request: Request, *args: Any, **kwargs: Any) Response[source]
destroy(request: Request, *args: Any, pk: int | None = None, **kwargs: Any) Response[source]
filter_backends = (<class 'rest_framework.filters.SearchFilter'>,)
get_serializer_class() Type[UserWithoutEmailSerializer] | Type[UserSerializer][source]

Return the class to use for the serializer. Defaults to using self.serializer_class.

You may want to override this if you need to provide different serializations depending on the incoming request.

(Eg. admins get full serialization, others get basic serialization)

list(request: Request, *args: Any, **kwargs: Any) Response[source]
partial_update(request: Request, *args: Any, pk: int | None = None, **kwargs: Any) Response[source]
password_reset(request: Request, pk: int) Response[source]

Reset the password for a user.

permission_classes = (<class 'rest_framework.permissions.IsAdminUser'>,)
queryset
retrieve(request: Request, *args: Any, pk: int | None = None, **kwargs: Any) Response[source]
search_fields = ('email', 'name', 'groups__name')
serializer_class

alias of UserSerializer

Search for users and stream the results.

update(request: Request, *args: Any, pk: int | None = None, **kwargs: Any) Response[source]
class users_api.views.WdaeLoginView(**kwargs)[source]

Bases: APIView

View for logging in.

get(request: Request) HttpResponse[source]

Render the login form.

post(request: Request) Response | HttpResponse[source]

Handle the login form.

users_api.views.change_password(request, *args, **kwargs)[source]

Change the password for a user.

users_api.views.check_verif_code(request, *args, **kwargs)[source]

Check if a verification code is valid.

users_api.views.get_user_info(request, *args, **kwargs)[source]

Get user info for currently logged-in user.

users_api.views.iterator_to_json(users: Iterator[WdaeUser]) Generator[str, None, int][source]

Wrap an iterator over WdaeUser models to produce json objects.

users_api.views.logout(request, *args, **kwargs)[source]

Log out the currently logged-in user.

users_api.views.register(request, *args, **kwargs)[source]

Register a new user.

class users_api.serializers.CreatableSlugRelatedField(*args, **kwargs)[source]

Bases: SlugRelatedField

Try to get and return related field and create it if it does not exist.

Used for the ‘groups’ field in the user serializer - if a new group is given to a user, it will be created and then attached to the user.

to_internal_value(data: dict) Any[source]

Transform the incoming primitive data into a native value.

class users_api.serializers.DatasetSerializer(*args, **kwargs)[source]

Bases: BaseSerializer

Dataset serializer.

create(validated_data: Any) Any[source]

Do nothing, method is for DB objects only.

to_internal_value(data: Any) Any[source]

Do nothing, method is for DB objects only.

to_representation(instance: Any) Any[source]

Transform the outgoing native value into primitive data.

update(instance: Any, validated_data: Any) Any[source]

Do nothing, method is for DB objects only.

class users_api.serializers.UserSerializer(*args, **kwargs)[source]

Bases: ModelSerializer

User serializer.

class Meta[source]

Bases: object

fields = ('id', 'email', 'name', 'hasPassword', 'groups', 'allowedDatasets')
model

alias of WdaeUser

create(validated_data: dict) Any[source]

We have a bit of extra checking around this in order to provide descriptive messages when something goes wrong, but this method is essentially just:

return ExampleModel.objects.create(**validated_data)

If there are many to many fields present on the instance then they cannot be set until the model is instantiated, in which case the implementation is like so:

example_relationship = validated_data.pop(‘example_relationship’) instance = ExampleModel.objects.create(**validated_data) instance.example_relationship = example_relationship return instance

The default implementation also does not handle nested relationships. If you want to support writable nested relationships you’ll need to write an explicit .create() method.

run_validation(data: dict) Any[source]

Normalize email before validation.

to_representation(instance: WdaeUser) Any[source]

Object instance -> Dict of primitive datatypes.

update(instance: WdaeUser, validated_data: dict) WdaeUser[source]
validate(attrs: dict) Any[source]

Validate that no unknown fields are given.

class users_api.serializers.UserWithoutEmailSerializer(*args, **kwargs)[source]

Bases: UserSerializer

class Meta[source]

Bases: object

fields = ('id', 'name', 'hasPassword', 'groups', 'allowedDatasets')
model

alias of WdaeUser

class users_api.validators.SomeSuperuserLeftValidator[source]

Bases: object

Validates that at least one superuser is left in the system.

set_context(serializer_field: Any) None[source]

Set the context for the validator.