The assets Application

The assets application provides a REST-full API for assets.

Installation

Add the assets application to your INSTALLED_APPS configuration as usual. Make sure to configure the various ASSETS_OAUTH2_... settings.

Default settings

Default settings values for the assets application.

assets.defaultsettings.IAR_USERS_LOOKUP_GROUP = 'uis-iar-users'

Name of lookup group which a user must be a member of to have access to IAR.

assets.defaultsettings.LOOKUP_PEOPLE_CACHE_LIFETIME = 1800

Responses to the people endpoint of lookupproxy are cached to increase performance. We assume that lookup details on people change rarely. This setting specifies the lifetime of a single cached lookup resource for a person in seconds.

assets.defaultsettings.LOOKUP_ROOT = None

URL of the lookup proxy’s API root.

assets.defaultsettings.OAUTH2_CLIENT_ID = None

OAuth2 client id which the API server uses to identify itself to the OAuth2 token introspection endpoint.

assets.defaultsettings.OAUTH2_CLIENT_SECRET = None

OAuth2 client secret which the API server uses to identify itself to the OAuth2 token introspection endpoint.

assets.defaultsettings.OAUTH2_INTROSPECT_SCOPES = None

List of OAuth2 scopes the API server will request for the token it will use with the token introspection endpoint.

assets.defaultsettings.OAUTH2_INTROSPECT_URL = None

URL of the OAuth2 token introspection endpoint. The API server will first identify itself to the OAuth2 token endpoint and request an access token for this endpoint.

assets.defaultsettings.OAUTH2_LOOKUP_SCOPES = ['lookup:anonymous']

List of OAuth2 scopes the API server will request for the token it will use with lookup.

assets.defaultsettings.OAUTH2_MAX_RETRIES = 5

Maximum number of retries when fetching URLs from the OAuth2 endpoint or OAuth2 authenticated URLs. This applies only to failed DNS lookups, socket connections and connection timeouts, never to requests where data has made it to the server.

assets.defaultsettings.OAUTH2_TOKEN_URL = None

URL of the OAuth2 token endpoint the API server uses to request an authorisation token to perform OAuth2 token introspection.

Views and serializers

Views for the assets application.

class assets.views.AssetCounts(total, completed, with_personal_data)
completed

Alias for field number 1

total

Alias for field number 0

with_personal_data

Alias for field number 2

class assets.views.AssetFilter(data=None, queryset=None, prefix=None, strict=None, request=None)

A custom DjangoFilterBackend filter_class defining all filterable fields. It seems that simply using filter_fields doesn’t work with the is_complete fields.

This class was implemented using the example here: https://django-filter.readthedocs.io/en/latest/guide/rest_framework.html#adding-a-filterset-with-filter-class

class assets.views.AssetStats(queryset)

Given a queryset of matching non-annotated asset records, calculate some statistics for all assets and assets grouped by department. We need the non-annotated queryset to work around a bug in Django. See https://code.djangoproject.com/ticket/28762 and https://github.com/uisautomation/iar-backend/issues/55.

Parameters:

queryset – Non-annotated queryset of assets.models.Asset objects

Variables:
  • all (AssetCounts) – Counts for all assets
  • by_institution (dict) – An AssetCounts instance for each institution keyed by Lookup instid.
class assets.views.AssetViewSet(**kwargs)

API endpoint that allows assets to be created, viewed, searched, filtered, and ordered by any field.

To order by a specific field you need to include in your GET request a parameter called ordering with the name of the field you want to order by. You can also order in reverse by adding the character “-” at the beginning of the name of the field.

You can also use the parameter search in your request with the text that you want to search. This text will be searched on all fields and will return all possible results

You can also filter by a specific field. For example if you only want to return those assets with name “foobar” you can add to your GET request a parameter called name (name of the field) and the value you want to filter by. Example ?name=foobar (this will return all assets that have as name “foobar”).

filter_class

alias of AssetFilter

finalize_response(request, response, *args, **kwargs)

Returns the final response object.

get_queryset()

get_queryset is patched to only return those assets that are not private or that are private but the user doing the request belongs to department that owns the asset.

Also, if the user is not in IAR_USERS_LOOKUP_GROUP, they can’t see assets.

initial(request, *args, **kwargs)

Runs anything that needs to occur prior to calling the method handler.

perform_destroy(instance)

perform_destroy patched to not delete the instance but instead flagged as deleted.

serializer_class

alias of assets.serializers.AssetSerializer

update(request, *args, **kwargs)

We force a refresh after an update, so we can get the up to date annotation data.

assets.views.REQUIRED_SCOPES = ['assetregister']

List of OAuth2 scopes required by this client.

assets.views.SCHEMA_DECORATOR(view_method)

Decorator to apply to DRF methods which sets the appropriate security requirements.

class assets.views.Stats(**kwargs)

Returns Assets stats: total number of assets, total number of assets completed, total number of assets with personal data, and assets per department (total, completed, with personal data)

get_object()

Returns the object the view is displaying.

You may want to override this if you need to provide non-standard queryset lookups. Eg if objects are referenced using multiple keyword arguments in the url conf.

serializer_class

alias of assets.serializers.AssetStatsSerializer

Django REST framework serialisers.

class assets.serializers.AssetCountsSerializer(instance=None, data=<class 'rest_framework.fields.empty'>, **kwargs)

Serialise a assets.views.AssetCounts object.

class assets.serializers.AssetDeptStatsSerializer(instance=None, data=<class 'rest_framework.fields.empty'>, **kwargs)

Asset Stats per Department serializer

class assets.serializers.AssetSerializer(instance=None, data=<class 'rest_framework.fields.empty'>, **kwargs)

Serialise a assets.models.Asset object.

If the request and view fields of the context are set then they are used to query the allowed methods on this object. These fields are set by the default get_serializer_context() implementation on ViewSets.

get_allowed_methods(obj)

Retrieve a list of allowed_methods the current user has on the object being serialised if the current request and view are present in the context.

class assets.serializers.AssetStatsSerializer(instance=None, data=<class 'rest_framework.fields.empty'>, **kwargs)

Serialise a assets.views.AssetStats object.

assets.serializers.setting_request_method(request, method)

A context manager which temporarily changes the method of a request object. As a context manager, it guarantees that the method is reset to the original even if an exception is thrown.

Permissions

OAuth2 token-based permissions for Django REST Framework views.

assets.permissions.AndPermission(*args)

This is a function posing as a class. An example of it’s intended usage is

..code::
permission_classes = (OrPermission(AndPermission(A, B), C), )

where A & B are both class that extend from BasePermission. The function returns a class that, when instantiated authorise a request when both A and B authorise that request.

Parameters:args – a tuple of BasePermission subclasses
Returns:an AndPermissionClass closure
class assets.permissions.HasScopesPermission

Django REST framework permission which requires that the scopes granted to an OAuth2 token are a superset of those required for the view. The requires scopes are specified by the required_scopes attribute of the view class.

has_permission(request, view)

Return True if permission is granted, False otherwise.

assets.permissions.OrPermission(*args)

This is a function posing as a class. An example of it’s intended usage is

..code::
permission_classes = (OrPermission(A, B), )

where A & B are both class that extend from BasePermission. The function returns a class that, when instantiated authorise a request when either A or B authorise that request.

Parameters:args – a tuple of BasePermission subclasses
Returns:an OrPermissionClass closure
class assets.permissions.UserInIARGroupPermission

Django REST framework permission which requires that the user be in the IAR_USERS_LOOKUP_GROUP.

has_permission(request, view)

Return True if permission is granted, False otherwise.

class assets.permissions.UserInInstitutionPermission

Django REST framework permission which requires that the user acting on an asset be associated with the department that the asset belongs to.

has_object_permission(request, view, obj)

When a new asset is changed/deleted check that the user is associated with the department of the existing asset AND (in the case of changed) is also associated with the given department.

has_permission(request, view)

When a new asset is created check that the user is associated with the given department.

Extensions to drf-yasg

Extensions to drf-yasg.

class assets.inspectors.SwaggerAutoSchema(view, path, method, components, request, overrides)

An extension to the drf_yasg.inspectors.SwaggerAutoSchema class which knows about a few more Operation properties.

extra_properties = ['security']

Additional properties which may be set on operations. Prefix the properties with operation_ and pass them as additional keyword arguments to swagger_auto_schema().

get_operation(*args, **kwargs)

Get an Operation for the given API endpoint (path, method). This includes query, body parameters and response schemas.

Parameters:operation_keys (tuple[str]) – an array of keys describing the hierarchical layout of this view in the API; e.g. ('snippets', 'list'), ('snippets', 'retrieve'), etc.
Return type:openapi.Operation

Default URL routing

Application configuration

class assets.apps.AssetsConfig(app_name, app_module)

Configuration for assets application.

name = 'assets'

The short name for this application.

ready()

Perform application initialisation once the Django platform has been initialised.

verbose_name = 'Information Assets Register'

The human-readable verbose name for this application.