Package: django-cloudspotlicense
django-cloudspotlicenseDjango package to integrate the authentication of the Cloudspot License Server in other django applications.Getting startedInstallInstall with pip.pipinstalldjango-cloudspotlicenseQuick startAdddjango_cloudspotlicenseto your INSTALLED_APPSINSTALLED_APPS=[...'django_cloudspotlicense']Include the URLConf in your project urls.pyurlpatterns=[path('auth/',include('django_cloudspotlicense.urls')),]Runpython manage.py migrateto create all the required modelsUse theLoginViewto let users log in using the Cloudspot License Serverimportdjango_cloudspotlicense.viewsasauth_viewsurlpatterns=[path('login',auth_views.LoginView.as_view(),name='login')]A basic html template with no styling will be provided. You can overwrite this template by simply creating a new template attemplates/auth/login.html.
The only requirement for this template is that it includes two input elements with the nameusernameandpassword.<inputtype="text"name="username"/><inputtype="password"name="password"/>Add the application ID as given by the Cloudspot License server to yoursettings.py.# settings.pyCLOUDSPOT_LICENSE_APP=config('CLOUDSPOT_LICENSE_APP')DoneSetting up the User modelYou can extend the User model as usual to add more attributes.django_cloudspotlicensealso uses the User model to store additional information, such as tokens and the company id.
If you want to add additional attributes, import the User class from the package and add your attributes as usual.fromdjango_cloudspotlicense.modelsimportCloudspotUserclassUser(CloudspotUser):extra_data=models.CharField(max_length=500,default='foobar')Use as normal.print(user.extra_data)# foobarPermission checkingThere are a few ways to check if the current user has the correct permission on the Cloudspot License server to do an action.
It's important that youdo not use the built-in permission checker from Django. This will always returnFalseon any given permission.Class-based viewsWhen using class-based views, you can import the modifiedPermissionRequiredMixinandLoginRequiredMixin.
When usingPermissionRequiredMixin, theLoginRequiredMixinis implied as an anonymous user can not have any permissions.fromdjango_cloudspotlicense.mixinsimportPermissionRequiredMixin,LoginRequiredMixin# Use as is normal within Django# The user needs the permission 'use_dashboard' to be able to view this templateclassDashboard(PermissionRequiredMixin,TemplateView):permission_required='use_dashboard'# use the permission code as shown in the Cloudspot License servertemplate_name='...'# OR# The user needs to be logged in and be assigned a company (which is always required) before he's able to see this viewclassProjects(LoginRequiredMixin,TemplateView):template_name='...'FunctionsYou can use the utility functionhas_perm()to check if a user has a permission.fromdjango_cloudspotlicense.utilsimporthas_permifhas_perm(user,'use_dashboard'):# user has the permission use_dashboard in Cloudspot License serverelse:# user does not have the permission! At this moment it's not possible to check multiple permissions at once. You will need to call the function for each permission.TemplatesInside a template, you can use a templatetag to check for the correct permission.<!-- This is REQUIRED, else the tag will not work -->{% load license_tags %}<!-- Use the tag 'has_perm' on a user object -->{% if request.user|has_perm:'list_projects' %}<!-- This piece of HTML will only be rendered if the user has the 'list_projects' permission --><h3>Projects</h3><ul><li>...</li></ul>{% endif %}WebhookThis package also provides a webhook where the Cloudspot License Server will send updates to whenever the permissions for a user changes.
The webhook is located athttps://example.com/auth/webhook. This webhook is automatically activated when importing the URLConf.Migrating to the License server from an existing applicationMigrating to the license server from an existing Django application that is using the local built-in user authentication is possible, but should be done withextreme careand careful consideration.
The following guide will step you through the required actions to succesfully migrate all the authentication to the license server.!! BACKUP YOUR DATABASE AND FILES BEFORE PROCEEDINGFailure to follow the provided steps can result in breaking changes. Always have a backup ready.SetupCopy themerge_with_license_server.pyscript located underscriptsto your management commands directory in your Django project.1. Add a new field 'backup_email' to the existing User modelThis field will be used to copy the current username/email to, which will be needed later on. Be sure to allow null as it will be empty at first.# models.py# THIS IS YOUR LOCAL USER MODELclassUser(AbstractUser):backup_email=models.CharField(max_length=500,null=True)# ...2. Make migrations and migratepythonmanage.pymakemigrationspythonmanage.pymigrate3. Run the first step of the migration scriptThis step will copy the existing username/email to the newly createdbackup_emailfield.pythonmanage.pymerge_with_license_server--step14. Install this package and add it to your INSTALLED_APPSpipinstalldjango-cloudspotlicense# settings.pyINSTALLED_APPS=[...'django_cloudspotlicense']5. Modify the existing User modelThe existing User model should not inherit fromAbstractUseranymore, but should be changed to a normal model at this point.# models.py# THIS IS YOUR LOCAL USER MODELclassUser(models.Model):# WAS: class User(AbstractUser)# ...Add the following fields at the top of the User model:# models.py# THIS IS YOUR LOCAL USER MODELclassUser(models.Model):# WAS: class User(AbstractUser)REQUIRED_FIELDS=[]USERNAME_FIELD='id'is_anonymous=False# can be either true or false, doesnt matteris_authenticated=True# can be either true or false, doesnt matter# ...6. Make migrations and migratepythonmanage.pymakemigrationspythonmanage.pymigrate7. Set AUTH_USER_MODEL in settings.pyChange theAUTH_USER_MODELin yoursettings.pytodjango_cloudspotlicense.CloudspotUser.# settings.pyAUTH_USER_MODEL='django_cloudspotlicense.CloudspotUser'8. Remove fields from existing User model and add new fieldRemove the fields that we added instep 5.
Import the CloudspotUser and CloudspotCompany models and add a new field:cloudspotuser_ptrwith a ForeignKey to CloudspotUser.# models.pyfromdjango_cloudspotlicense.modelsimportCloudspotUser,CloudspotCompany# THIS IS YOUR LOCAL USER MODELclassUser(models.Model):cloudspotuser_ptr=models.ForeignKey(CloudspotUser,on_delete=models.SET_NULL,null=True)9. Make migrations and migratepythonmanage.pymakemigrationspythonmanage.pymigrate10. Run the second step of the migration scriptThis step will duplicate the existing users and companies to the newly created CloudspotUser and CloudspotCompany, preserving ID's and usernames.!! You may have to modify the script to import your local User and Company modelspythonmanage.pymerge_with_license_server--step211. Modify the existing User model againRemove thecloudspotuser_ptrandidfields and let the User model inherit fromCloudspotUser.
In this step you can also remove any other garbage fields that will not be used anymore.# models.py# THIS IS YOUR LOCAL USER MODELclassUser(CloudspotUser):# ...12. Make migrations and migrateDuringmakemigrations, you will have to provide a one-off default UUID forcloudspotuser_ptr. This UUID needs to be v4 but can beanyUUID you like. This will not affect the existing data.
You can generate one here:https://www.uuidgenerator.net/pythonmanage.pymakemigrations# if asked, provide a one-off default for cloudspotuser_ptr and use a random UUIDv4pythonmanage.pymigrate13. Remove any other garbage fieldsIf there are any more garbage fields, you can delete them in this step and migrate again.14. Set AUTH_USER_MODEL back to your local User model in settings.pyChange theAUTH_USER_MODELagain to point at your local User model.# settings.pyAUTH_USER_MODEL='main.User'15. Migration doneThe migration is now done. Follow the quick start from step 2.