Package: garpix-user
Garpix UserAuth module for Django/DRF projects. Part of GarpixCMS.Used packages:django rest frameworksocial-auth-app-djangodjango-rest-framework-social-oauth2etc; see setup.pyQuickstartInstall with pip:pipinstallgarpix_userAdd thegarpix_userto yourINSTALLED_APPS:# settings.py# ...INSTALLED_APPS=[# ...'garpix_user',]and to migration modules:# settings.py# ...MIGRATION_MODULES={'garpix_user':'app.migrations.garpix_user',}Add tourls.py:fromgarpix_user.viewsimportLogoutView,LoginView# ...urlpatterns=[# ...# garpix_userpath('',include(('garpix_user.urls','user'),namespace='garpix_user')),path('logout/',LogoutView.as_view(url='/'),name="logout"),path('login/',LoginView.as_view(template_name="accounts/login.html"),name="authorize"),]UseGarpixUserfromgarpix_user.modelsas base for your user model class:# user.models.user.pyfromgarpix_user.modelsimportGarpixUserclassUser(GarpixUser):classMeta:verbose_name='Пользователь'verbose_name_plural='Пользователи'def__str__(self):returnself.usernameUseUserAdminfromgarpix_user.adminas base for your user admin class:fromdjango.contribimportadminfromgarpix_user.adminimportUserAdminfromuser.modelsimportUser@admin.register(User)classUserAdmin(UserAdmin):passFor custom auth with phone and/or email use this insettings.py:# ...AUTHENTICATION_BACKENDS=(# Django'garpix_user.utils.backends.CustomAuthenticationBackend')andUSERNAME_FIELDSto yourUsermodel:# user.models.user.pyfromgarpix_user.modelsimportGarpixUserclassUser(GarpixUser):USERNAME_FIELDS=('email',)# default is usernameclassMeta:verbose_name='Пользователь'verbose_name_plural='Пользователи'def__str__(self):returnself.usernameWith Django Rest FrameworkImport settings fromgarpix_user:# settings.pyfromgarpix_user.settingsimport*Add this for SPA:# ...INSTALLED_APPS+=[# ...'rest_framework','rest_framework.authtoken','oauth2_provider','social_django','rest_framework_social_oauth2',# ...]REST_FRAMEWORK={'DEFAULT_AUTHENTICATION_CLASSES':{'garpix_user.rest.authentication.MainAuthentication','oauth2_provider.contrib.rest_framework.OAuth2Authentication','rest_framework_social_oauth2.authentication.SocialAuthentication',}}JWT TokenYou can use JWT token. To do it setREST_AUTH_TOKEN_JWTsettings to True. You also need to
setJWT_SECRET_KEY,JWT_SERIALIZERsettings:# settings.py# ...GARPIX_USER={'REST_AUTH_TOKEN_JWT':True,'JWT_SECRET_KEY':env('JWT_SECRET_KEY'),# secret code to validate JWT token'JWT_SERIALIZER':'garpix_user.serializers.JWTDataSerializer'}# Hint: see all available settings in the end of this document.Authorization headersYou can override the Bearer authorization header byREST_AUTH_HEADER_KEYsetting.
And also allow this custom header for cors-headers:# settings.py# ...fromcorsheaders.defaultsimportdefault_headersGARPIX_USER={'REST_AUTH_HEADER_KEY':'HTTP_BEARER_AUTHORIZATION'}# Hint: see all available settings in the end of this document.CORS_ALLOW_HEADERS=list(default_headers)+["Bearer-Authorization",]Now you need to addBearer-Authorizationheader instead ofAuthorizationheader with your Bearer token to all
requests.Registrationgarpix_useradds default registration for withphoneand/oremailandpasswordfields. To add fields to this form overrideRegistrationSerializerand add it tosettings:# settings.pyGARPIX_USER={# registration'REGISTRATION_SERIALIZER':'app.serializers.RegistrationCustSerializer'}# Hint: see all available settings in the end of this document.# app.serializers.pyfromdjango.contrib.authimportget_user_modelfromrest_frameworkimportserializersfromgarpix_user.serializersimportRegistrationSerializerUser=get_user_model()classRegistrationCustSerializer(RegistrationSerializer):extra_field=serializers.CharField(write_only=True)classMeta(RegistrationSerializer.Meta):model=Userfields=RegistrationSerializer.Meta.fields+('extra_field',)You also can add password security settings:# settings.pyGARPIX_USER={# registration'MIN_LENGTH_PASSWORD':8,'MIN_DIGITS_PASSWORD':2,'MIN_CHARS_PASSWORD':2,'MIN_UPPERCASE_PASSWORD':1,}# Hint: see all available settings in the end of this document.Email and phone confirmation, password restoringTo use email and phone confirmation or (and) restore password functionality add thegarpix_notifyto yourINSTALLED_APPS:# settings.py# ...INSTALLED_APPS=[# ...'garpix_notify',]and to migration modules:# settings.pyMIGRATION_MODULES={'garpix_notify':'app.migrations.garpix_notify',}Add corresponding settings:# settings.pyGARPIX_USER={'USE_EMAIL_CONFIRMATION':True,'USE_PHONE_CONFIRMATION':True,'USE_EMAIL_RESTORE_PASSWORD':True,'USE_PHONE_RESTORE_PASSWORD':True,}# Hint: see all available settings in the end of this document.You also need to add notify events:# settings.pyNOTIFY_EVENTS.update(GARPIX_USER_NOTIFY_EVENTS)You can specify email and phone code length, lifetime, confirmation lifetime and time delay before next attempt:#settings.pyGARPIX_USER={'CONFIRM_PHONE_CODE_LENGTH':6,'CONFIRM_EMAIL_CODE_LENGTH':6,'TIME_LAST_REQUEST':1,'CONFIRM_PHONE_CODE_LIFE_TIME':5,# in minutes'CONFIRM_EMAIL_CODE_LIFE_TIME':2,'CONFIRM_EMAIL_CODE_LIFE_TIME_TYPE':'days',# available types are: ['days', 'minutes'], default is 'days''PHONE_CONFIRMATION_LIFE_TIME':2,# in days'EMAIL_CONFIRMATION_LIFE_TIME':2,# in days}# Hint: see all available settings in the end of this document.Notice: the minimum and maximum values forCONFIRM_CODE_LENGTHare 4 and 255. These values will be hard used in case your settings are not in this interval.If you need to use pre-registration email or phone confirmation, you need to set corresponding variables to True:# settings.pyGARPIX_USER={'USE_PREREGISTRATION_EMAIL_CONFIRMATION':True,'USE_PREREGISTRATION_PHONE_CONFIRMATION':True,}# Hint: see all available settings in the end of this document.If you need to use email confirmation by link, you need to set corresponding variable:# settings.pyGARPIX_USER={'USE_EMAIL_LINK_CONFIRMATION':True}# Hint: see all available settings in the end of this document.You can also overrideconfirm_link_redirect_urlmethod ofUsermodel to form confirmation link as you need.By default, users with unconfirmed email/phone number will be deleted in 10 days. You can set up it usingCONFIRMATION_DELAY:# settings.pyGARPIX_USER={# ...'CONFIRMATION_DELAY':10,# in days}# Hint: see all available settings in the end of this document.Referral linksYou can also use referral links in your project with garpix_user. To add this functionality, just add the corresponding settings:# settings.pyGARPIX_USER={'USE_REFERRAL_LINKS':True,'REFERRAL_REDIRECT_URL':'/',# link to the page user needs to see}# Hint: see all available settings in the end of this document.UserSessionUsinggarpix_useryou can also store info about unregistered user sessions. The package already consists of model and views for it.To create the unregistered user sendPOSTrequest to{API_URL}/user_session/create_user_session/The request returnsUserSessionobject withtoken_numberfield. You need to send this token number in each request passing in to header asuser-session-token.By default, on log in current user session instance will be dropped, if system hasregistereduser session instance for authorized user. You can overrideset_user_sessionmethod ofUsermodel to add custom logic.All available settings with default values# settings.pyGARPIX_USER={# base settings'USE_REFERRAL_LINKS':False,'REFERRAL_REDIRECT_URL':'/',# email/phone confirmation'USE_EMAIL_CONFIRMATION':True,'USE_PHONE_CONFIRMATION':True,'USE_PREREGISTRATION_EMAIL_CONFIRMATION':True,'USE_PREREGISTRATION_PHONE_CONFIRMATION':True,'USE_EMAIL_LINK_CONFIRMATION':True,'CONFIRM_PHONE_CODE_LENGTH':6,'CONFIRM_EMAIL_CODE_LENGTH':6,'TIME_LAST_REQUEST':1,'CONFIRM_PHONE_CODE_LIFE_TIME':5,# in minutes'CONFIRM_EMAIL_CODE_LIFE_TIME':2,'CONFIRM_EMAIL_CODE_LIFE_TIME_TYPE':'days','PHONE_CONFIRMATION_LIFE_TIME':2,# in days'EMAIL_CONFIRMATION_LIFE_TIME':2,# in days'CONFIRMATION_DELAY':10,# in days# restore password'USE_RESTORE_PASSWORD':True,# registration'USE_REGISTRATION':True,'REGISTRATION_SERIALIZER':'app.serializers.RegistrationCustSerializer','MIN_LENGTH_PASSWORD':8,'MIN_DIGITS_PASSWORD':2,'MIN_CHARS_PASSWORD':2,'MIN_UPPERCASE_PASSWORD':1,# authorization'REST_AUTH_HEADER_KEY':'HTTP_AUTHORIZATION','REST_AUTH_TOKEN_JWT':False,'JWT_SERIALIZER':'garpix_user.serializers.JWTDataSerializer',# response messages'WAIT_RESPONSE':'Не прошло 1 мин с момента предыдущего запроса','USER_REGISTERED_RESPONSE':'Пользователь с таким{field}уже зарегистрирован',# as 'field' will be used email/phone according to the request'INCORRECT_CODE_RESPONSE':'Некорретный код','NO_TIME_LEFT_RESPONSE':'Код недействителен. Запросите повторно','NOT_AUTHENTICATED_RESPONSE':'Учетные данные не были предоставлены'}Seegarpix_user/tests/test_api/*.pyfor examples.ChangelogSeeCHANGELOG.md.ContributingSeeCONTRIBUTING.md.LicenseMITDeveloped by Garpix /https://garpix.com