current position:Home>Django docking pin login system

Django docking pin login system

2022-01-29 21:52:05 Jin Fengjun

Little knowledge , Great challenge ! This article is participating in 「 A programmer must have a little knowledge 」 Creative activities

This article also participates in  「 Digging force Star Program 」   , Win a creative gift bag , Challenge creation incentive fund

demand :

Business needs , At present H5 The application needs to be embedded in the nail for use

Basic configuration

  • Create nails H5 Microapplication ( Address : Nail development platform -> application development -> Enterprise internal development -> Create an )

image.png

  • Get basic application information

image.png

  • Permission opening

image.png

  • To configure IP Exits and links

image.png

Development ( Only the main packaging code is given here )

The structure is roughly as shown in the figure image.png

Server code :

  • obtain token
@retry(reraise=True, stop=(stop_after_delay(10) | stop_after_attempt(3)), wait=wait_random(min=1, max=3),
       retry=retry_if_exception_type())
def get_token(self, *args, **kwargs) -> dict:
    '''
    :result   obtain access_token
    '''
    path = 'gettoken'
    params = {
        "appkey": self.__appkey,
        "appsecret": self.__appsecret
    }
    response = self.conn.get(
        path=path,
        params=params,
        timeout=5
    )
    data = response.json()
    errcode = data.get('errcode', -1)
    if str(errcode) == "0":
        result = data.get('access_token', {})
        result = result if isinstance(result, str) else ""
        return result
    return {}
 Copy code 
  • adopt code Get personnel information
def getuserinfo(self, code: str, *args, **kwargs):
    path = "/user/getuserinfo"
    params = {
        "access_token": self.get_token(),
        "code": code
    }
    response = self.conn.get(
        path=path,
        params=params,
        timeout=5
    )
    data = response.json()
    errcode = data.get('errcode', -1)
    if str(errcode) == '0':
        result = data
        result = result if isinstance(result, dict) else {}
        user_id = result.get('userid')
        response = self._get_user_detail(user_id)
        return response
    return {}

 Copy code 
  • Get personnel details
def _get_user_detail(self, user_id: str, *args, **kwargs):
    key = str(user_id) + "_get_user_detail"
    info = redisClient.authcache('get', key)
    if info:
        return info
    path = '/topapi/v2/user/get?access_token={}'.format(self.get_token())
    params = {
        "language": "zh_CN",
        "userid": user_id
    }
    response = self.conn.post(
        path=path,
        params=params,
        timeout=5
    )
    data = response.json()
    errcode = data.get('errcode', -1)
    if str(errcode) == '0':
        result = data.get('result', {})
        result = result if isinstance(result, dict) else {}
        redisClient.authcache('set', key, result)
        return result
    return {}
 Copy code 

The front-end code

  • PC End code
<script src="https://g.alicdn.com/dingding/dingtalk-jsapi/2.10.3/dingtalk.open.js"></script>
<p>Opening with system default browser(Google Chrome Recommened) ... ...</p>
<script>
   dd.ready(function () {
       dd.runtime.permission.requestAuthCode({
           corpId: "{{ corpId }}", //  Enterprises id
           onSuccess: function (result) {
               dd.biz.util.openLink({
                   url: window.location.protocol + "//" + window.location.host + "{{ uri }}&code=" + result.code,// The address to open the link 
                   onSuccess: function (result) {
                       /**/
                   },
                   onFail: function (err) {
                   }
               });
           },
           onFail: function (error) {
               alert(` Nail authentication failed ! ${JSON.stringify(error)}`);
           }
       });
   });
</script>
 Copy code 
  • mob End code
<script src="https://g.alicdn.com/dingding/dingtalk-jsapi/2.10.3/dingtalk.open.js"></script>
<script>
   dd.ready(function () {
       dd.runtime.permission.requestAuthCode({
           corpId: "{{ corpId }}", //  Enterprises id
           onSuccess: function (result) {
               dd.biz.navigation.replace({
                   url: window.location.protocol + "//" + window.location.host + "{{ uri }}&code=" + result.code,// The address to open the link 
                   onSuccess: function (result) {
                       /**/
                   },
                   onFail: function (err) {
                   }
               });
           },
           onFail: function (error) {
               alert(` Nail authentication failed ! ${JSON.stringify(error)}`);
           }
       });
   });
</script>
 Copy code 
  • Log in and jump to the home page ( Here we go session To deal with )
<script>
    setTimeout(function () {
        document.location.resession_dict
        document.location.replace("{{ uri }}");
    }, 0)
</script>
 Copy code 

Scan the login page to realize

<p align="value" style="text-align:center">{{ title }}</p>
<div id="login_container" style="text-align:center"></div>

<script src="https://g.alicdn.com/dingding/dinglogin/0.0.5/ddLogin.js"></script>

<script>
    var url = encodeURIComponent('users/login/');
    var goto = encodeURIComponent('https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid={{ appid }}&response_type=code&scope=snsapi_login&state=test&redirect_uri=' + window.location.protocol + "//" + window.location.host + url)

    var obj = DDLogin({
        id: "login_container",// Here you need to define a HTML Label and set id, for example <div id="login_container"></div> or <span id="login_container"></span>
        goto: goto,
        style: "border:none;background-color:#FFFFFF;",
        width: "300",
        height: "400"
    });

    var hanndleMessage = function (event) {
        var origin = event.origin;
        console.log("origin", event.origin);
        if (origin == "https://login.dingtalk.com") { // Judge whether it comes from ddLogin Code scanning Events .
            var loginTmpCode = event.data; // Get loginTmpCode After that, you can construct a jump link here to jump 
            console.log("loginTmpCode", loginTmpCode);
            var url2 = "https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid={{appid}}&response_type=code&scope=snsapi_login&state=NvSxTQh&redirect_uri=" + window.location.protocol + "//" + window.location.host + url + "&loginTmpCode=" + loginTmpCode;
            console.log("url2", url2)
            window.location.href = url2;
        }
    };

    if (typeof window.addEventListener != 'undefined') {
        window.addEventListener('message', hanndleMessage, false);
    } else if (typeof window.attachEvent != 'undefined') {
        window.attachEvent('onmessage', hanndleMessage);
    }

</script>
 Copy code 

copyright notice
author[Jin Fengjun],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201292152018819.html

Random recommended