Web application multi-account system design and implement micro-channel scan code Login

1 Introduction Overview

After the company for functional testing, performance testing, security testing and so on have done a better automated urgent need to MIS systems to a unified management and reporting these results.

This MIS system characteristics are as follows:

  • Internal use by personnel
  • Deployed in the public network

Based on the above characteristics, apparently so such a man's internal system and implement a complete account is not realistic, to take into account the needs of privacy and convenience, the authors think the use of micro-channel scan code to do is login authentication, and back office management member of the audit, so that you can achieve the following results:

  • It can be achieved without registration threshold (sweep the micro-channel registration is completed), to ensure the convenience
  • No system of auditors by the isolation, to ensure the privacy

Then, after completion of the development of this system, and then feel the need to summarize what sublimation and small, so there is motivation for writing this article.

More than two accounts principle

The original purpose of this paper is to "achieve micro-channel scan codes to sign" , but then I thought just to achieve this, the conception of this paper and it looks too low. So here's expand it as "multi-account login authorization system" .

In recent years, as more and more Internet development and collaboration, the current system login more and more, far beyond the previous single username way up. In addition to user name and password, the site also offers the following general login:

    • Third Party Authorization

      Micro-channel / QQ / Sina Weibo (China) Google / Facebook / Github (abroad)

    • Binding account

      Phone numbers mailbox number

Based on several login above, it is formed as a "multi-account system of FIG Login" :

img

Fundamental:

    • Third Party Authorization

      It can be obtained from a trusted third party to return the corresponding value (user information), and then user_id binding does not require additional re-enter the password authentication process will be completed in the future will create a group that can be modified user_id as a placeholder user after successful authentication setting session state

    • Binding account

      Already accomplished a user_id registered to complete the corresponding account binding, it means recognition and user_id can log in and use the user_id same or different passwords to log system to complete the setup session after successful authentication authentication status (generally use the same password)

About binding account approach is relatively simple, not repeat them here.

Based on third-party authorized manner, it is more subtle, learning can be relatively strong because the Internet increasingly open nature based on this approach will definitely be more and more applications, more and more mainstream. The following will micro-channel scan code of unauthorized access as an example to explain.

3 login logic scan code

Using micro-channel scan code unauthorized access logic is as follows:

img

Which mainly deal with the following things:

  • Initiates an authentication request to a third party
  • Third-party authentication callback
  • MIS systems and local user_id relationship system (new user)
  • Set session login status
  • Different processing result display interface

Process of micro-channel scan code 4

Micro-letter code used to log sweep people will experience the following process (known as social networking sites know almost as an example):

  1. Open know almost home page, click on the "micro-letters Login" icon
  2. Browser is redirected to a micro channel domain (see reference numeral 1) The following two-dimensional code page
  3. Micro-channel open out the phone user, sweep the
  4. Click on the phone micro-channel authorization
  5. PC page display above the two-dimensional code is successfully authorized, and turned to know almost home, the authentication is successful

The whole process for the end user, only a few seconds, and do not enter any password can be said to be a very safe and convenient experience.

So the question is, by scanning the two-dimensional micro-letter code, log in and complete the registration MIS system just a few seconds this time inside, in the end what's happening?

Browser capture of several key communications process analysis.

img

PC browser will in turn initiate two long connections (in a long time pending request status) of:

  • Waiting mobile terminal microcells scan code (labeled on FIG. 2)
  • Waiting for the phone micro letter click "OK Login" button (marked on Figure 3)

These two states are fed back to the two-dimensional code page of the PC side, after confirming the completion of the phone side, PC browser page above the page will be directed to the students after authorization (such as know almost home).

Specific parties communication timing is as follows:

img

FIG object on the whole process involved in the communication has been clearly described, on the portion of FIG numerals have annotated as follows:

  1. Incoming server with the micro-channel API callback url parameters
  2. Mobile micro-channel scan two-dimensional code by the camera, the optical principle of communicating data on the complete
  3. Inquiry scan code state long connection status return value received on the PC browser, and update prompt
  4. Queries mobile client PC Click the OK button on the browser's status value, and update prompt, and then redirected to process 1 passed the url address
  5. Site server after the authorization is completed successfully, the user of the system's business logic Register or Log in
  6. The server redirects the user to a successful login interface (if no additional audit if the new registered users)

About micro-channel scan developing code authentication portion, this will not go, given only the following considerations:

  • A variety of micro-channel platform API interface, please refer to: WeChat open platform to provide official documentation
  • Micro-channel scan code development rights need to be logged in enterprise qualification WeChat open platform (individual users can not be obtained)
  • Callback url domain registration required to fill in the WeChat open platform, the transfer of local development callback url parameter must be consistent and for the record

5 code implementation

According to the above principle, and finally we will provide specific implementation code for reference, for simplicity, there are some general utility functions implemented not posted out.

Use python3.5 achieve micro channel scan code login Web application shown in the following reference code.

Corresponds to the FIG. 1 identifies the code implemented:

class WeChatAuth(MyBaseHandler):
    """
    点击后直接重定向到微信登录界面

    - wechat QR扫码登录,web端
    - 直接重定向到微信的页面
    """

    def get(self):
        state = get_uuid1_key()  # 生成唯一的码

        wx_qr_param = dict(
            appid=wx_webapp.appid,
            # redirect_uri=wx_webapp.qr_auth_cb_url,
            redirect_uri='http://your.domain.com/wechat/wechat-auth-callback/',
            response_type='code',
            scope=wx_webapp.login_scope,
            state=state
        )  ##wechat_redirect

        wx_qr_url = 'https://open.weixin.qq.com/connect/qrconnect?%s#wechat_redirect' \
                    % urllib.parse.urlencode(wx_qr_param)

        self.redirect(wx_qr_url)
        
复制代码
class WeChatAuthCallback(MyBaseHandler):
    """
    微信第三方认证之后,开始将此用户在本系统沉淀下来

    - 用于微信服务器传回code的值
    - 此处要再请求获得access_token
    """

    async def get(self):
        wx_code = self.get_argument('code', '')
        wx_state = self.get_argument('state', '')

        if wx_code == '':
            res = ConstData.msg_forbidden
            dlog.debug(res)
            self.write(res)
            return

        dlog.debug('wx_code:%s,wx_state:%s' % (wx_code, wx_state))

        access_token_res = wx_webapp.get_auth_access_token(code=wx_code, state=wx_state)
        user_info = wx_webapp.get_auth_user_info(auth_access_token_res=access_token_res)
        """:type:WeChatUser"""  # 微信返回的用户信息串

        if user_info is None:
            res = ConstData.msg_forbidden
            dlog.debug(res)
            self.write(res)
            return

        wechat_user = await MisWeChatUser.objects.get(openid=user_info.openid, unionid=user_info.unionid)
        """:type:MisWeChatUser"""
        # 一个Open_id下面所有的id都是靠union来区分账号

        if wechat_user is not None:
            user = await User.objects.get(user_id=wechat_user.user_id)
            assert user is not None
            if user.active:
                if await user.is_online():
                    await self.update_session()  # 更新时间
                else:
                    await self.create_session(user)  # 新增加一个session
                self.write('in authorized page')
                # self.redirect('/')  # todo 重定向到登录授权后的主页
                return

        # 如果不存在wechat备案信息,则需要备案wechat信息,而且新注册初始账号
        default_new_user_id = 'u_' + get_uuid1_key()

        new_wechat_user = MisWeChatUser(
            openid=user_info.openid,
            nickname=user_info.nickname,
            unionid=user_info.unionid,
            # user_id=wx_webapp.appid + '_' + user_info.unionid,  # 通过微信号登录生成的一个唯一的用户名,后面可以提供修改
            user_id=default_new_user_id,
            appid=wx_webapp.appid
        )
        new_wechat_user.set_default_rc_tag()

        # rand_salt = get_rand_salt()
        new_user = User(
            user_id=default_new_user_id,
            # salt=rand_salt,  # 防止别人md5撞库反向破解的随机数
            # passwd=StringField()  # 密码,通过第三方登录的默认不设置
            first_name=user_info.nickname,
            status=FieldDict.user_status_init,  # 表示是可更改状态
            active=False,
        )
        new_user.set_default_rc_tag()

        await new_wechat_user.save()
        await new_user.save()
        self.write('in unauthorized page')

        # self.redirect(URL_ROOT)  # todo 导入到未授权的页面
复制代码

6 Functional Test

Design two test cases.

Check the micro-channel scan code when the user can complete the process described above:

  1. A scan codes to sign with the micro-letter account to see if auto-enrollment
  2. Whether prompt redirected to the "Unauthorized page"

A modified micro-channel in the database is automatically registered user status audit log after scan code by:

  1. A user status is modified active = True
  2. Whether prompt redirected to the "authorization page"
  3. Do you see logon session state in the database

Test shots are as follows:

img

7 Summary

If I was a product manager, if I do a web application product, then the product in the early stages, I would definitely choose a micro letter to sign in because in this way the login threshold is too low, the threshold is user trial products also to a minimum follow-up of at least the level of activity is not affected by the threshold login.

Guess you like

Origin juejin.im/post/5d7e12c7f265da03d316f1cf