Package: openwisp-users
Implementation of user management and multi-tenancy for OpenWISP (built with python & django).Table of Contents:Deploy it in productionInstall stable version from pypiInstall development versionSetup (integrate in an existing django project)Installing for developmentSettingsOPENWISP_ORGANIZATION_USER_ADMINOPENWISP_ORGANIZATION_OWNER_ADMINOPENWISP_USERS_AUTH_APIOPENWISP_USERS_AUTH_THROTTLE_RATEOPENWISP_USERS_AUTH_BACKEND_AUTO_PREFIXESREST APILive documentationBrowsable web interfaceObtain Authentication TokenAuthenticating with the user tokenList of endpointsChange User passwordList GroupsCreate new GroupGet Group detailChange Group detailPatch Group detailDelete GroupList Email AddressesAdd Email AddressGet Email AddressChange Email AddressPatch Email AddressMake/Unmake Email Address PrimaryMark/Unmark Email Address as VerifiedRemove Email AddressList OrganizationsCreate new OrganizationGet Organization detailChange Organization detailPatch Organization detailDelete OrganizationList UsersCreate UserGet User detailChange User detailPatch User detailDelete UserOrganization permissionsOrganization OwnersOrganization membership helpersis_member(org)is_manager(org)is_owner(org)organizations_dictorganizations_managedorganizations_ownedAuthentication BackendDjango REST Framework Authentication Classes1.openwisp_users.api.authentication.BearerAuthentication2.openwisp_users.api.authentication.SesameAuthenticationDjango REST Framework Permission Classesorganization_fieldDjangoModelPermissionsDjango REST Framework MixinsFiltering items by organizationChecking parent objectsMulti-tenant serializers for the browsable web UIAdmin Multitenancy mixinsExtend openwisp-users1. Initialize your custom module2. Installopenwisp-users3. AddEXTENDED_APPS4. Addopenwisp_utils.staticfiles.DependencyFinder5. Addopenwisp_utils.loaders.DependencyLoader6. Inherit the AppConfig class7. Create your custom models8. Add swapper configurations9. Create database migrations10. Create the admin1. Monkey patching2. Inheriting admin classes11. Create root URL configuration12. Import the automated testsOther base classes that can be inherited and extended1. Extending the API ViewsContributingSupportChangelogLicenseDeploy it in productionAn automated installer is available atansible-openwisp2.Install stable version from pypiInstall from pypi:pipinstallopenwisp-usersInstall development versionInstall tarball:pipinstallhttps://github.com/openwisp/openwisp-users/tarball/masterAlternatively you can install via pip using git:pipinstall-egit+git://github.com/openwisp/openwisp-users#egg=openwisp_usersSetup (integrate in an existing django project)INSTALLED_APPSinsettings.pyshould look like the following:INSTALLED_APPS=['django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','openwisp_utils.admin_theme',# overrides some templates in django-allauth'openwisp_users.accounts','django_extensions','allauth','allauth.account','allauth.socialaccount','rest_framework','rest_framework.authtoken',# must come before the django admin# to override the admin login page'openwisp_users','django.contrib.admin','django.contrib.sites','drf_yasg',]also addAUTH_USER_MODEL,SITE_IDandAUTHENTICATION_BACKENDSto yoursettings.py:AUTH_USER_MODEL='openwisp_users.User'SITE_ID=1AUTHENTICATION_BACKENDS=['openwisp_users.backends.UsersAuthenticationBackend',]urls.py:fromdjango.conf.urlsimportinclude,urlfromdjango.contribimportadminfromdjango.contrib.staticfiles.urlsimportstaticfiles_urlpatternsurlpatterns=[url(r'^admin/',include(admin.site.urls)),url(r'^accounts/',include('allauth.urls')),url(r'^api/v1/',include('openwisp_users.api.urls')),]urlpatterns+=staticfiles_urlpatterns()Add following insettings.pyto configure email verification success view:ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL='email_confirmation_success'ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL='email_confirmation_success'For additional steps to properly configureallauthin your project,
please refer to their documentation:allauth documentation installation section.Installing for developmentInstall sqlite:sudoapt-getinstallsqlite3libsqlite3-devopenssllibssl-devInstall your forked repo:gitclonegit://github.com/<your_fork>/openwisp-userscdopenwisp-users/pipinstall-e.[rest]Install test requirements:pipinstall-rrequirements-test.txtStart Redisdocker-composeup-dCreate database:cdtests/./manage.pymigrate./manage.pycreatesuperuserLaunch development server:./manage.pyrunserverYou can access the admin interface athttp://127.0.0.1:8000/admin/.Run tests with:# --parallel and --keepdb are optional but help to speed up the operation./runtests.py--parallel--keepdbSettingsOPENWISP_ORGANIZATION_USER_ADMINtype:booleandefault:FalseIndicates whether the admin section for managingOrganizationUseritems
is enabled or not.It is disabled by default because these items can be managed via inline items
in the user administration section.OPENWISP_ORGANIZATION_OWNER_ADMINtype:booleandefault:TrueIndicates whether the admin section for managingOrganizationOwneritems
is enabled or not.Find out more information aboutorganization owners.OPENWISP_USERS_AUTH_APItype:booleandefault:TrueIndicates whether theREST APIis enabled or not.OPENWISP_USERS_AUTH_THROTTLE_RATEtype:strdefault:100/dayIndicates the rate throttling for theObtain AuthenticationAPI endpoint.Please note that the current rate throttler is very basic and will
also count valid requests for rate limiting. For more information,
check Django-rest-frameworkthrottling guide.OPENWISP_USERS_AUTH_BACKEND_AUTO_PREFIXEStype:tupledefault:tuple()A tuple or list of international prefixes which will be automatically
tested bythe authentication backend of openwisp-userswhen parsing phone numbers.Each prefix will be prepended to the username string automatically and
parsed with thephonenumberslibrary to find out if the result
is a valid number of not.This allows users to log in by using only the national phone number,
without having to specify the international prefix.REST APITo enable the API the settingOPENWISP_USERS_AUTH_APImust be set toTrue.Live documentationA general live API documentation (following the OpenAPI specification) at/api/v1/docs/.Browsable web interfaceAdditionally, opening any of the endpoints listed below
directly in the browser will show thebrowsable API interface of Django-REST-Framework,
which makes it even easier to find out the details of each endpoint.Obtain Authentication Token/api/v1/users/token/This endpoint only accepts thePOSTmethod and is used to retrieve the
Bearer token that is required to make API requests to other endpoints.Example usage of the endpoint:httpPOSTlocalhost:8000/api/v1/users/token/username=openwisppassword=1234HTTP/1.1200OKAllow:POST,OPTIONSContent-Length:52Content-Type:application/jsonDate:Wed,13May202010:59:34GMTServer:WSGIServer/0.2CPython/3.6.9Vary:CookieX-Content-Type-Options:nosniffX-Frame-Options:DENY{"token":"7a2e1d3d008253c123c61d56741003db5a194256"}Authenticating with the user tokenThe authentication classopenwisp_users.api.authentication.BearerAuthenticationis used across the different OpenWISP modules for authentication.To use it, first of all get the user token as described above inObtain Authentication Token, then send
the token in theAuthorizationheader:# get tokenTOKEN=$(httpPOST:8000/api/v1/users/token/username=openwisppassword=1234|jq-r.token)# send bearer tokenhttpGETlocalhost:8000/api/v1/firmware/build/"Authorization: Bearer$TOKEN"List of endpointsSince the detailed explanation is contained in theLive documentationand in theBrowsable web pageof each point,
here we’ll provide just a list of the available endpoints,
for further information please open the URL of the endpoint in your browser.Change User passwordPUT /api/v1/users/user/{id}/password/List GroupsGET /api/v1/users/group/Create new GroupPOST /api/v1/users/group/Get Group detailGET /api/v1/users/group/{id}/Change Group detailPUT /api/v1/users/group/{id}/Patch Group detailPATCH /api/v1/users/group/{id}/Delete GroupDELETE /api/v1/users/group/{id}/List Email AddressesGET /api/v1/users/user/{id}/email/Add Email AddressPOST/api/v1/users/user/{id}/email/Get Email AddressGET /api/v1/users/user/{id}/email/{id}/Change Email AddressPUT /api/v1/users/user/{id}/email/{id}/Patch Email AddressPATCH /api/v1/users/user/{id}/email/{id}/Make/Unmake Email Address PrimaryPATCH /api/v1/users/user/{id}/email/{id}/Mark/Unmark Email Address as VerifiedPATCH /api/v1/users/user/{id}/email/{id}/Remove Email AddressDELETE /api/v1/users/user/{id}/email/{id}/List OrganizationsGET /api/v1/users/organization/Create new OrganizationPOST /api/v1/users/organization/Get Organization detailGET /api/v1/users/organization/{id}/Change Organization detailPUT /api/v1/users/organization/{id}/Patch Organization detailPATCH /api/v1/users/organization/{id}/Delete OrganizationDELETE /api/v1/users/organization/{id}/List UsersGET /api/v1/users/user/Create UserPOST /api/v1/users/user/Get User detailGET /api/v1/users/user/{id}/Change User detailPUT /api/v1/users/user/{id}/Patch User detailPATCH /api/v1/users/user/{id}/Delete UserDELETE /api/v1/users/user/{id}/Organization permissionsHere’s a summary of the default permissions:All users who belong to the Administrators group and are organization
managers (OrganizationUser.is_admin=True), have the permission to edit
the organizations details which they administrate.Only super users have the permission to add and delete organizations.Only super users andorganization ownershave the permission to change theOrganizationOwnerinline or delete the relation.Organization OwnersAn organization owner is a user who is designated as the owner
of a particular organization and this owner can not be deleted
or edited by other administrators, only superusers have the permission to do this.By default, the first manager of an organization is designated as the owner of that organization.If theOrganizationUserinstance related to the owner of an organization is deleted
or flagged asis_admin=False, the admin interface will return an error informing
users that the operation is not allowed, the owner should be changed before attempting to do that.Organization membership helpersTheUsermodel provides methods to check whether the user
is a member, manager or owner of an organization in an efficient way.These methods are needed because an user may be administrator in one organization,
but simple end-user is another organization, so we need to easily distinguish
between the different use cases and at the same time avoid to generate too
many database queries.importswapperUser=swapper.load_model('openwisp_users','User')Organization=swapper.load_model('openwisp_users','Organization')user=User.objects.first()org=Organization.objects.first()user.is_member(org)user.is_manager(org)user.is_owner(org)# also valid (avoids query to retrieve Organization instance)device=Device.objects.first()user.is_member(device.organization_id)user.is_manager(device.organization_id)user.is_owner(device.organization_id)is_member(org)ReturnsTrueif the user is member of theOrganizationinstance passed.
Alternatively,UUIDorstrcan be passed instead of an organization instance,
which will be interpreted as the organization primary key; this second option is
recommended when building the organization instance requires an extra query.This check shall be used when access needs to be granted to end-users who
need to consume a service offered by an organization they’re member of
(eg: authenticate to a public wifi service).is_manager(org)ReturnsTrueif the user is member of theOrganizationinstance
and has theOrganizationUser.is_adminfield set toTrue.
Alternatively,UUIDorstrcan be passed instead of an organization instance,
which will be interpreted as the organization primary key; this second option is
recommended when building the organization instance requires an extra query.This check shall be used when access needs to be granted to the managers of
an organization users who need to perform administrative tasks
(eg: download the firmware image of their organization).is_owner(org)ReturnsTrueif the user is member of theOrganizationinstance
and is owner of the organization (checks the presence of anOrganizationOwnerinstance for the user).
Alternatively,UUIDorstrcan be passed instead of an organization instance,
which will be interpreted as the organization primary key; this second option is
recommended when building the organization instance requires an extra query.There can be only one owner for each organization.This check shall be used to avoid that managers would be able to take control
of an organization and exclude the original owner without their consent.organizations_dictThe methods described above use theorganizations_dictproperty method under
the hood, which builds a dictionary in which each key contains the primary key
of the organization the user is member of, and each key contains another dictionary
which allows to easily determine if the user is manager (is_admin) and owner
(is_owner).This data structure is cached automatically and accessing it multiple times
over the span of multiple requests will not generate multiple database queries.The cache invalidation also happens automatically whenever anOrganizationUseror anOrganizationOwnerinstance is added, changed or deleted.Usage exmaple:>>>user.organizations_dict...{'20135c30-d486-4d68-993f-322b8acb51c4':{'is_admin':True,'is_owner':False}}>>>user.organizations_dict.keys()...dict_keys(['20135c30-d486-4d68-993f-322b8acb51c4'])organizations_managedThis attribute returns a list containing the primary keys of the organizations
which the user can manage.Usage example:>>>user.organizations_managed...['20135c30-d486-4d68-993f-322b8acb51c4']organizations_ownedThis attribute returns a list containing the primary keys of the organizations
which the user owns.Usage example:>>>user.organizations_owned...['20135c30-d486-4d68-993f-322b8acb51c4']Authentication BackendThe authentication backend inopenwisp_users.backends.UsersAuthenticationBackendallows users to authenticate using theiremailorphone_numberinstead of theirusername.
Authenticating with theusernameis still allowed,
butemailhas precedence.If the username string passed is parsed as a valid phone number, thenphone_numberhas precedence.Phone numbers are parsed using thephonenumberslibrary, which means
that even if the user adds characters like spaces, dots or dashes, the number
will be recognized anyway.When parsing phone numbers, theOPENWISP_USERS_AUTH_BACKEND_AUTO_PREFIXESsetting allows to specify a list of international prefixes that can
be prepended to the username string automatically in order to allow
users to log in without having to type the international prefix.The authentication backend can also be used as follows:fromopenwisp_users.backendsimportUsersAuthenticationBackendbackend=UsersAuthenticationBackend()backend.authenticate(request,identifier,password)Django REST Framework Authentication Classes1.openwisp_users.api.authentication.BearerAuthenticationBased on therest_framework.authentication.TokenAuthentication,BearerAuthenticationis the primary authentication class for REST APIs
implemented across all modules of OpenWISP.Kindly refer toauthenticating with the user tokensection for usage information.2.openwisp_users.api.authentication.SesameAuthenticationIt provides authentication to a REST view using tokens generated bydjango-sesame.
It is primarily used for providing password-less authentication
e.g. in magic login links.Configuration ofdjango-sesameis required for the functioning
of this authentication class. Please refer todjango-sesame documentationfor more information.Django REST Framework Permission ClassesThe customDjango REST Frameworkpermission classesIsOrganizationMember,IsOrganizationManagerandIsOrganizationOwnercan be used in the API to ensure that the
request user is in the same organization as requested object and is
organization member, manager or owner respectively. Usage example:fromopenwisp_users.api.permissionsimportIsOrganizationManagerfromrest_frameworkimportgenericsclassMyApiView(generics.APIView):permission_classes=(IsOrganizationManager,)organization_fieldtype:stringdefault:organizationorganization_fieldcan be used to define where to look to
find the organization of the current object.
In most cases this won’t need to be changed, but it does need to
be changed when theorganizationis defined only on a parent object.For example, inopenwisp-firmware-upgrader,organizationis defined onCategoryandBuildhas a relation
tocategory, so the organization of Build instances is inferred from
the organization of the Category.Therefore, to implement the permission class correctly, we would have to do:fromopenwisp_users.api.permissionsimportIsOrganizationManagerfromrest_frameworkimportgenericsclassMyApiView(generics.APIView):permission_classes=(IsOrganizationManager,)organization_field='category__organization'This will translate into accessingobj.category.organization.
Ensure the queryset of your views make use ofselect_relatedin these cases to avoid generating too many queries.DjangoModelPermissionsThe defaultDjangoModelPermissionsclass doesn’t checks for theviewpermission of any object forGETrequests. The extendedDjangoModelPermissionsclass overcomes this problem. In order to
allowGETrequests on any object it checks for the availability
of eithervieworchangepermissions.Usage example:fromopenwisp_users.api.permissionsimportDjangoModelPermissionsfromrest_framework.genericsimportListCreateAPIViewclassTemplateListCreateView(ListCreateAPIView):serializer_class=TemplateSerializerpermission_classes=(DjangoModelPermissions,)queryset=Template.objects.all()Note:DjangoModelPermissionsallows users who
are either organization managers or owners to view
shared objects in read only mode.Standard users will not be able to view or list shared objects.Django REST Framework MixinsFiltering items by organizationThe customDjango REST FrameworkmixinsFilterByOrganizationMembership,FilterByOrganizationManagedandFilterByOrganizationOwnedcan be used in the API views to ensure
that the current user is able to see only the data related to their
organization when accessing the API view.They work by filtering the queryset so that only items related
to organizations the user is member, manager or owner of, respectively.These mixins ship the Django REST Framework’sIsAuthenticatedpermission class by default because the organization filtering
works only on authenticated users.
Always remember to include this class when
overridingpermission_classesin a view.Usage example:fromopenwisp_users.api.mixinsimportFilterByOrganizationManagedfromrest_frameworkimportgenericsclassUsersListView(FilterByOrganizationManaged,generics.ListAPIView):"""
    UsersListView will show only users from organizations managed
    by current user in the list.
    """passclassExampleListView(FilterByOrganizationManaged,generics.ListAPIView):"""
    Example showing how to extend ``permission_classes``.
    """permission_classes=FilterByOrganizationManaged.permission_classes+[# additional permission classes here]Checking parent objectsSometimes, the API view needs to check the existence and theorganizationfield of a parent object.In such cases,FilterByParentMembership,FilterByParentManagedandFilterByParentOwnedcan be used.For example, given a hypotetical URL/api/v1/device/{device_id}/config/,
the view must check that{device_id}exists and that the user
has access to it, here’s how to do it:importswapperfromrest_frameworkimportgenericsfromopenwisp_users.api.mixinsimportFilterByParentManagedDevice=swapper.load_model('config','Device')Config=swapper.load_model('config','Config')# URL is:# /api/v1/device/{device_id}/config/classConfigListView(FilterByParentManaged,generics.DetailAPIView):model=Configdefget_parent_queryset(self):qs=Device.objects.filter(pk=self.kwargs['device_id'])returnqsMulti-tenant serializers for the browsable web UIDjango REST Frameworkprovides a browsable API which can be used to create HTTP requests right
from the browser.The relationship fields in this interface show all the relationships,
without filtering by the organization the user has access to, which
breaks multi-tenancy.TheFilterSerializerByOrgMembership,FilterSerializerByOrgManagedandFilterSerializerByOrgOwnedcan be used to solve this issue.These serializers do not allow non-superusers to create shared objects.Usage example:fromopenwisp_users.api.mixinsimportFilterSerializerByOrgOwnedfromrest_framework.serializersimportModelSerializerfrom.modelsimportDeviceclassDeviceSerializer(FilterSerializerByOrgOwned,ModelSerializer):classMeta:model=Devicefields='__all__'Theinclude_sharedboolean attribute can be used to include shared
objects in the accepted values of the multi-tenant serializers.Shared objects have theorganizationfield set toNoneand can
be used by any organization. A common use case isshared templates
in OpenWISP Controller.Usage example:fromopenwisp_users.api.mixinsimportFilterSerializerByOrgOwnedfromrest_framework.serializersimportModelSerializerfrom.modelsimportBookclassBookSerializer(FilterSerializerByOrgOwned,ModelSerializer):include_shared=TrueclassMeta:model=Bookfields='__all__'To filter items based on theorganizationof their parent object,organization_fieldattribute can be defined in the view function
which is inheriting any of the mixin classes.Usage example:organization_field.Admin Multitenancy mixinsMultitenantAdminMixin: adding this mixin to aModelAdminclass
will make it multitenant-capable (users will only be able to see items
of the organizations they manage or own).This class has two important attributes that can be set:multitenant_shared_relations: if the model has relations (eg:ForeignKey,OneToOne) to other models which are also
multitenant (that is, they have anorganizationfield),
you want the admin to only show the relations the user can manage,
the way to do that is to list those model attributes here as a list
of strings.
Seehow it is used in OpenWISP Controllerfor a real world example.multitenant_parent: if the admin model does not have anorganizationfield, but instead relies on a parent model
which has the field, then you can specify here the field which
points to the parent.
Seehow it is used in OpenWISP Firmware Upgraderfor a real world example.MultitenantOrgFilter: admin filter that shows only organizations
the current user can manage in its available choices.MultitenantRelatedOrgFilter: similarMultitenantOrgFilterbut
shows only objects which have a relation with one of the organizations
the current user can manage, this shall be used when the model does not
have its own organization field but relies on a parent model which
has the organization field.Extend openwisp-usersOne of the core values of the OpenWISP project isSoftware Reusability,
for this reasonopenwisp-usersprovides a set of base classes
which can be imported, extended and reused to create derivative apps.This will be extreme beneficial for you if you want to create additional
fields for User model, example asking for Social Security Number of the
User for registeration.In order to implement your custom version ofopenwisp-users,
you need to perform the steps described in this section.When in doubt, the code in thetest projectand thesample appwill serve you as source of truth:
just replicate and adapt that code to get a basic derivative ofopenwisp-usersworking.Premise: if you plan on using a customized version of this module,
we suggest to start with it since the beginning, because migrating your data
from the default module to your extended version may be time consuming.1. Initialize your custom moduleThe first thing you need to do is to create a new django app which will
contain your custom version ofopenwisp-users.A django app is nothing more than apython package(a directory of python scripts), in the following examples we’ll call this django appmyusers, but you can name it how you want:django-admin startapp myusersKeep in mind that the command mentioned above must be called from a directory
which is available in yourPYTHON_PATHso that you can then import the result into your project.Now you need to addmyuserstoINSTALLED_APPSin yoursettings.py,
ensuring also thatopenwisp_usershas been removed:INSTALLED_APPS=[# ... other apps ...# 'openwisp_users'  <-- comment out or delete this line'myusers']For more information about how to work with django projects and django apps, please refer
to thedjango documentation.2. Installopenwisp-usersInstall (and add to the requirement of your project) openwisp-users:pip install openwisp-users3. AddEXTENDED_APPSAdd the following to yoursettings.py:EXTENDED_APPS=('openwisp_users',)4. Addopenwisp_utils.staticfiles.DependencyFinderAddopenwisp_utils.staticfiles.DependencyFindertoSTATICFILES_FINDERSin yoursettings.py:STATICFILES_FINDERS=['django.contrib.staticfiles.finders.FileSystemFinder','django.contrib.staticfiles.finders.AppDirectoriesFinder','openwisp_utils.staticfiles.DependencyFinder',]5. Addopenwisp_utils.loaders.DependencyLoaderAddopenwisp_utils.loaders.DependencyLoadertoTEMPLATESbeforedjango.template.loaders.app_directories.Loaderin yoursettings.py:TEMPLATES=[{'BACKEND':'django.template.backends.django.DjangoTemplates','OPTIONS':{'loaders':['django.template.loaders.filesystem.Loader','openwisp_utils.loaders.DependencyLoader','django.template.loaders.app_directories.Loader',],'context_processors':['django.template.context_processors.debug','django.template.context_processors.request','django.contrib.auth.context_processors.auth','django.contrib.messages.context_processors.messages',],},}]6. Inherit the AppConfig classPlease refer to the following files in the sample app of the test project:openwisp_users/__init__.pyopenwisp_users/apps.pyYou have to replicate and adapt that code in your project.For more information regarding the concept ofAppConfigplease refer to
the“Applications” section in the django documentation.7. Create your custom modelsFor the purpose of showing an example, we added a simplesocial_security_numberfield in User model to themodels of the sample app in the test project.You can add fields in a similar way in yourmodels.pyfile.For doubts regarding how to use, extend or develop models please refer to the“Models” section in the django documentation.8. Add swapper configurationsOnce you have created the models, add the following to yoursettings.py:# Setting models for swapper moduleAUTH_USER_MODEL='myusers.User'OPENWISP_USERS_GROUP_MODEL='myusers.Group'OPENWISP_USERS_ORGANIZATION_MODEL='myusers.Organization'OPENWISP_USERS_ORGANIZATIONUSER_MODEL='myusers.OrganizationUser'OPENWISP_USERS_ORGANIZATIONOWNER_MODEL='myusers.OrganizationOwner'# The following model is not used in OpenWISP yet# but users are free to implement it in their projects if needed# for more information refer to the django-organizations docs:# https://django-organizations.readthedocs.io/OPENWISP_USERS_ORGANIZATIONINVITATION_MODEL='myusers.OrganizationInvitation'Substitutemyuserswith the name you chose in step 1.9. Create database migrationsCreate database migrations:./manage.py makemigrationsNow, manually create a file0004_default_groups.pyin the migrations directory
just created by themakemigrationscommand and copy contents of
thesample_users/migrations/0004_default_groups.py.Then, run the migrations:./manage.py migrateNote: the0004_default_groupsis required because other OpenWISP modules
depend on it. If it’s not created as documented here, the migrations of
other OpenWISP modules will fail.10. Create the adminRefer to theadmin.py file of the sample app.To introduce changes to the admin, you can do it in two main ways which are described below.For more information regarding how the django admin works, or how it can be customized, please refer to“The django admin site” section in the django documentation.1. Monkey patchingIf the changes you need to add are relatively small, you can resort to monkey patching.For example:fromopenwisp_users.adminimport(UserAdmin,GroupAdmin,OrganizationAdmin,OrganizationOwnerAdmin,BaseOrganizationUserAdmin,)# OrganizationAdmin.field += ['example_field'] <-- Monkey patching changes exampleFor your convenience of adding fields in User forms, we provide the following functions:usermodel_add_formWhen monkey patching theUserAdminclass to add add fields in the
“Add user” form, you can use this function. In the example,Social Security Number is added in the add form:usermodel_change_formWhen monkey patching theUserAdminclass to add fields in the
“Change user” form to change / modify user form’s profile section,
you can use this function. In the example,Social Security Number
is added in the change form:usermodel_list_and_searchWhen monkey patching theUserAdminclass you can use this
function to make field searchable and add it to the user
display list view. In the example,Social Security Number is added in the changelist view:2. Inheriting admin classesIf you need to introduce significant changes and/or you don’t want to resort to
monkey patching, you can proceed as follows:fromdjango.contribimportadminfromopenwisp_users.adminimport(UserAdminasBaseUserAdmin,GroupAdminasBaseGroupAdmin,OrganizationAdminasBaseOrganizationAdmin,OrganizationOwnerAdminasBaseOrganizationOwnerAdmin,OrganizationUserAdminasBaseOrganizationUserAdmin,)fromswapperimportload_modelfromdjango.contrib.authimportget_user_modelGroup=load_model('openwisp_users','Group')Organization=load_model('openwisp_users','Organization')OrganizationOwner=load_model('openwisp_users','OrganizationOwner')OrganizationUser=load_model('openwisp_users','OrganizationUser')User=get_user_model()admin.site.unregister(Group)admin.site.unregister(Organization)admin.site.unregister(OrganizationOwner)admin.site.unregister(OrganizationUser)admin.site.unregister(User)@admin.register(Group)classGroupAdmin(BaseGroupAdmin):pass@admin.register(Organization)classOrganizationAdmin(BaseOrganizationAdmin):pass@admin.register(OrganizationOwner)classOrganizationOwnerAdmin(BaseOrganizationOwnerAdmin):pass@admin.register(OrganizationUser)classOrganizationUserAdmin(BaseOrganizationUserAdmin):pass@admin.register(User)classUserAdmin(BaseUserAdmin):pass11. Create root URL configurationPlease refer to theurls.pyfile in the sample project.For more information about URL configuration in django, please refer to the“URL dispatcher” section in the django documentation.12. Import the automated testsWhen developing a custom application based on this module, it’s a good
idea to import and run the base tests too, so that you can be sure the
changes you’re introducing are not breaking some of the existing
features ofopenwisp-users.In case you need to add breaking changes, you can overwrite the tests
defined in the base classes to test your own behavior.See thetests of the sample appto find out how to do this.You can then run tests with:# the --parallel flag is optional
./manage.py test --parallel myusersSubstitutemyuserswith the name you chose in step 1.Other base classes that can be inherited and extendedThe following steps are not required and are intended for more advanced customization.1. Extending the API ViewsThe API view classes can be extended into other django applications as well. Note
that it is not required for extendingopenwisp-usersto your app and this change
is required only if you plan to make changes to the API views.Create a view file as done inAPI views.py.Remember to use these views in root URL configurations in point 11.For more information about django views, please refer to theviews section in the django documentation.ContributingPlease refer to theOpenWISP contributing guidelines.SupportSeeOpenWISP Support Channels.ChangelogSeeCHANGES.LicenseSeeLICENSE.