Package: drf-auth-service
Django Rest Framework Authorization ServiceOverview :lock:An authentication serviceorchestrates single sign-on (SSO) between multiple apps.
If the user has already signed on to one app, the login page will not be shown again and the user will be logged in via this service.Single sign-on (SSO)is an authentication scheme that allows a user to log in with
a single ID and password to any of several related, yet independent, software systems.Features :zap:Register and login by different register_types: email, phone_number, phone_number_code and nicknameRegister with confirmation flow managed by aRegisterBackendReset Password with multiple optionsphone/emailmanaged by register_type of userSocial authenticationApple/Facebook/GoogleServicemodel approach for login and registerUseredit/block/unblock/set-password/resend-confirmation/deletefeature based on a Secret TokenCustomizableIntegration workflowRegistration with confirmationLoginRestore passwordRefresh expired access tokenInstallationInstall usingpip...pip install drf-auth-serviceAdd'drf_auth_service'to yourINSTALLED_APPSsetting.INSTALLED_APPS = [
    ...
    'drf_auth_service',
]Add package urls to your applicationurls.pyfile.urlpatterns = [
    path("", include("drf_auth_service.urls"))
]Before project start run migrate of database..../manage.py migrateConfigurationConfiguration for DRF Auth Service is all namespaced inside a single Django setting, named DRF_AUTH_SERVICE.For example your project's settings.py file might include something like this:DRF_AUTH_SERVICE = {
    'WORK_MODE': 'standalone',
    'REGISTER_TYPES': [],
    'SEND_CONFIRMATION': True
}Available Settings :mag_right:KeyDescriptionDefaultWORK_MODEMode of servicestandaloneREGISTER_TYPESAvailable register types['email', 'phone_number', 'phone_number_code', 'nickname']SEND_CONFIRMATIONBoolean if you want to send confirmation on registerTrueDOMAIN_ADDRESSCommon domain address used in Single Sign On authenticationNoneRESET_PASSWORD_EXPIREToken expiration hours for reset password and confirmation token24SEND_RESET_PASSWORD_URLBase url where is append tokenhttps://example.com/reset-password/SEND_CONFIRMATION_URLBase url where is append tokenhttps://example.com/confirm-emailSMS_CONFIRMATION_MESSAGESms message on confirmationConfirmation code {{ code }}SMS_RESET_PASSWORD_MESSAGESms message on reset passwordReset password code {{ code }}HTML_DEFAULT_FROM_EMAILFrom address in sending emailsEMAIL_USERNAME valueHTML_RESET_PASSWORD_SUBJECTSubject on reset password emailReset passwordHTML_CONFIRMATION_SUBJECTSubject on confirmation emailConfirm accountHTML_EMAIL_RESET_TEMPLATEPath to reset password template if no one is defined, default is usedinternal templateHTML_EMAIL_CONFIRM_TEMPLATEPath to confirmation template if no one is defined, default is usedinternal templateSENDINBLUE_RESET_PASS_TEMPLATETemplate ID for reset password from sendinblue serviceNoneSENDINBLUE_CONFIRMATION_TEMPLATETemplate ID for confirmation from sendinblue serviceNoneSENDINBLUE_API_KEYSendInBlue API_KEYNoneMAILCHIMP_RESET_PASS_TEMPLATETemplate ID for reset password from Mailchimp serviceNoneMAILCHIMP_CONFIRMATION_TEMPLATETemplate ID for confirmation from Mailchimp serviceNoneMAILCHIMP_USERNAMEMailchimp UsernameNoneMAILCHIMP_SECRET_KEYMailchimp SECRET_KEYNoneTWILIO_ACCOUNT_SIDTwilio SIDNoneTWILIO_AUTH_TOKENTwilio TOKENNoneTWILIO_FROM_NUMBERTwilio from phone numberNoneEMAIL_HOSTEmail SMTP hostDjango EMAIL_HOST valueEMAIL_PORTEmail SMTP portDjango EMAIL_HOST valueEMAIL_USERNAMEEmail SMTP usernameDjango EMAIL_HOST_USER valueEMAIL_PASSWORDEmail SMTP passwordDjango EMAIL_HOST_PASSWORD valueEMAIL_USE_TLSEmail SMTP TLS useDjango EMAIL_USE_TLS valueSERIALIZERSHere is a Dict of serializers that you can overrideVIEWSHere is a Dict of views that you can overridePERMISSIONSHere is a Dict of permissions that you can overrideBACKENDSHere is a Dict of backends that you can overrideENUMSHere is a Dict of enums that you can overrideCustomizationChange User model :family:User model is based on swappable settings from Django model and to config your own model
of user you just have to give model toAUTH_USER_MODEL = 'my_application.CustomUser'fromdrf_auth_service.modelsimportAbstractSSOUser# Add phone number to user tableclassCustomUser(AbstractSSOUser):phone_number=models.CharField(max_length=120)Create a new registration backend :package:In case you want to use your own backends you will have to overridefromdrf_auth_service.common.backendsimportBaseBackendfromdrf_auth_service.common.managersimportPhoneManagerclassCustomRegisterBackend(BaseBackend):name='email'manager=PhoneManager# This method will be called on registerdefregister_user(self):user=get_user_model().objects.create(service=self.request.service,register_type=self.name,username=self.request.data['username'],# insert with new field valuephone_number=self.request.data['phone_number'])# return created userreturnuserIn order to work withRegisterBackedit's a must to inheritBaseBackendfrom sso package:name: register_type name, based on this name received in register body will identify what register backend to usemanager: What manager(PhoneManager/EmailManager)to use for sending confirmation in case you have this functionalityChange Register Backend in setting.py:DRF_AUTH_SERVICE={'BACKENDS':{'REGISTER_BACKENDS':['my_application.backends.CustomRegisterBackend']}}Create a new SMS backend :envelope:At the moment we have onlyTwilioBackendwhich can be easily change withfromdrf_auth_service.common.sms_backendsimportTwilioBackendclassCustomPhoneProvider(TwilioBackend):defsend(self,to_phone,message,from_phone=None):response=requests.post('http://anothersmsprovider.com/send',data={to_phone_number=f"+{to_phone}",from_phone_number=from_phone,body=message})ifnotresponse.is_ok:raiseValidationError(dict(details=response.json()))Change SMS Backend in setting.py:DRF_AUTH_SERVICE={'BACKENDS':{'SMS_BACKEND':['my_application.backends.CustomPhoneProvider']}}Change the Email Backend :mailbox_closed:We have 3 options for email backends(MailchimpBackend/SendInBlueBackend/HtmlTemplateBackend)with defaultHtmlTemplateBackend, in order to change or add new backend just add to sso settingsDRF_AUTH_SERVICE={'BACKENDS':{'EMAIL_BACKEND':['drf_auth_service.common.email_backends.SendInBlueBackend']}}Change Views/Serializers/PermissionsEvery view/serializer/permission can be change from package settings and a good example how to do this:Create new serializerclassRegisterSerializer(serializers.Serializer):phone_number=serializers.CharField(required=True)username=serializers.EmailField(required=True)register_type=serializers.HiddenField(default=RegisterType.EMAIL)defvalidate(self,attrs):user_exists=get_user_model().objects.filter(username=attrs['username'],service=self.context['request'].service).exists()ifuser_exists:raiseValidationError({'username':f"User '{attrs['username']}' already exists"})returnattrsChange Serializer in setting.py:DRF_AUTH_SERVICE={'SERIALIZERS':{'REGISTER_SERIALIZER':"apps.authentication.serializers.RegisterSerializer"}}