Re-develop the Jumpserver user authentication module and invoke the independent authentication Interface (ii)

Source: Internet
Author: User

First, urls.py
#--*--coding:utf-8--*-- fromDjango.conf.urlsImportpatterns, Urlurlpatterns= Patterns ('Myauth.login', the URL (r'^login/$','Do_login', name='Login'), url (r'^logout/$','Do_logout', name='Logout'),                       )
Second, myauth_backend.py

Jms_users is the Abstractuser class that inherits Django, and the USER model in setting that specifies the authentication background is Auth_user_model = ' juser. User ', so there is no need to save the Django User object (note section). This is just token verification after direct return to the user, the real authentication process in login implementation

#--*--coding:utf-8--*--#Author:arthurmok fromDjango.contrib.auth.modelsImportUser as Contrib_users fromJuser.modelsImportUser as Jms_users fromJumpserver.settingsImportDjango_auth_token fromItsdangerousImportTimedjsonwebsignatureserializer as SerializerclassMyauthbackend (object):defAuthenticate (self, auth_token=none, token=None): s=Serializer (django_auth_token) Username=s.loads (Auth_token)Try: User= Jms_Users.objects.get (username=username)exceptjms_users.doesnotexist:returnNoneElse:            #The user has been authenticated by the unified interface, where the Django authentication module is rewritten and token verification is used            iftoken = =Django_auth_token:#Try:                #Contrib_user = Contrib_Users.objects.get (username=user.username)                #except contrib_users.doesnotexist:                ## When there is no such user in Django, create                #Contrib_user = Contrib_users (Username=user.username, Password=auth_token)                #Contrib_user.is_staff = True                #Contrib_user.save ()                #return Contrib_user                returnUserElse:                returnNonedefGet_user (Self, user_id):Try:            returnJms_Users.objects.get (pk=user_id)exceptjms_users.doesnotexist:returnNone
Third, login.py
Call the authentication interface Sso_url realize the user's authentication and obtain the user information, and save the user information. Primarily the _add_user and Do_login functions, other calls to the authentication interface are ignored for the procedure.
def_add_user (request, username, name, mobile, email, Department): Jms_user= Jms_Users.objects.get (username=username)ifJms_user:Pass    Else: Password= Pycrypt.gen_rand_pass (16) groups=[] admin_groups=[] Role='CU'Uuid_r=Uuid.uuid4 (). Get_hex () ssh_key_pwd= Pycrypt.gen_rand_pass (16)        if  notEmail:email= username+'@'+Email_domain is_active=True send_mail_need=TrueTry: User= Db_add_user (Username=username, Name=name, Phone=mobile, department=Department, Password=Password, email=email, Role=role, uuid=Uuid_r, Groups=groups, admin_groups=admin_groups, Ssh_key_pwd=ssh_key_pwd, Is_active=is_active, date_joined=Datetime.datetime.now ()) Server_add_user (username=username, ssh_key_pwd=ssh_key_pwd) User= Get_object (Jms_users, username=username)ifgroups:user_groups= []                 foruser_group_idinchGroups:user_groups.extend (UserGroup.objects.filter (ID=user_group_id)) exceptIndexerror, E:error= u'failed to add user%s%s'%(username, e) logger.error (Error)returnFalseElse: User_add_mail (user, Kwargs=locals ()) MSG= get_display_msg (user, Password=password, ssh_key_pwd=ssh_key_pwd, send_mail_need=send_mail_need) logger.info (msg)returnTrue
defDo_login (Request): Local_login_url='/ http'+request.get_host () +reverse ('Login') Tmp_token= Request. Get.get ('token')    #Next_url = Request. Get.get (' Next ', '/')    ifrequest.user.is_authenticated ():returnHttpresponseredirect (Reverse ('Index', args=()))    Else:        ifTmp_token:token=_sso_token (Request, Tmp_token)iftoken: user_info  =   _sso_user_info (request, token) # Authentication through and access to user information ifuser_info: _add_user (Request, user_info[  'um', user_info['name'], user_info['  Mobile'], user_info['email', User_ info['Department'  ]) s=Serializer (django_auth_token) Auth_token= S.dumps (user_info['um']) Contrib_user= Authenticate (Auth_token=auth_token, token=Django_auth_token) Login (Request, Contrib_user) #登录ifContrib_user.role = ='SU': request.session['role_id'] = 2elifContrib_user.role = ='GA': request.session['role_id'] = 1Else: request.session['role_id'] =0returnHttpresponseredirect (Reverse ('Index', args=())) Sso_login_url= Sso_login_url%(Sso_url, Local_login_url)returnHttpresponseredirect (Sso_login_url)

Re-develop the Jumpserver user authentication module and invoke the independent authentication Interface (ii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.