Flask - geetest learning and use

Posted by stretchy on Sun, 24 Nov 2019 23:25:14 +0100

Catalog

I. relevant documents

II. Back end logic sorting

III. sorting out the verification ideas

IV. initialization of related functions

4-1 validation initialization preprocessing

4-2 validation initialization result return

V. quadratic check correlation function

5-1 front end verification calls function successfully

5-2 front end verification failure calling function

Vi. DEMO related demonstration

VII. Precautions for DEMO operation

I. relevant documents

Official documents

Official github demo

II. Back end logic sorting

# Initialization verification code related parameters
# Please apply for ID on the official website. The sample ID cannot be used
pc_geetest_id = "48a6ebac4ebc6642d68c217fca33eb4d"
pc_geetest_key = "4f1c085290bec5afdc54df73535fc361"
mobile_geetest_id = "48a6ebac4ebc6642d68c217fca33eb4d"
mobile_geetest_key = "4f1c085290bec5afdc54df73535fc361"

# The first back-end verification, used to generate the verification code
@app.route('/pc-geetest/register', methods=["GET"])
def get_pc_captcha():
    # User ID, if you are worried about the risk of user information, you can do preprocessing (such as hash processing) and provide it again
    user_id = 'test'
    gt = GeetestLib(pc_geetest_id, pc_geetest_key)
    # The initialization result ID status (status=1 indicates successful initialization, status=0 indicates down state) needs to be saved by the user, and will be taken out for logical judgment during subsequent secondary validation.
    status = gt.pre_process(user_id)
    session[gt.GT_STATUS_SESSION_KEY] = status
    session["user_id"] = user_id
    response_str = gt.get_response_str()
    # {"success": 1, "gt": "48a6ebac4ebc6642d68c217fca33eb4d", "challenge": "f320ead2467b8132dbb5a91042748dbb"}
    return response_str

# The second verification accepts three front-end parameters
# When status=0 is taken out, it means that the polar inspection is down. At this time, the process enters failback mode. The subsequent logic is completed on your server, and no network request will be sent to the polar inspection server.
# In this SDK demo, for the failback mode, only the request parameters are simply verified. You can also design your own.
@app.route('/pc-geetest/validate', methods=["POST"])
def pc_validate_captcha():
    print(request.form)
    gt = GeetestLib(pc_geetest_id, pc_geetest_key)
    challenge = request.form[gt.FN_CHALLENGE]
    validate = request.form[gt.FN_VALIDATE]
    seccode = request.form[gt.FN_SECCODE]
    status = session[gt.GT_STATUS_SESSION_KEY]
    user_id = session["user_id"]
    if status:
        result = gt.success_validate(challenge, validate, seccode, user_id)
        print(result)
    else:
        result = gt.failback_validate(challenge, validate, seccode)
    result = "<html><body><h1>Login successfully</h1></body></html>" if result else "<html><body><h1>Login failed</h1></body></html>"
    return result

III. sorting out the verification ideas

  • Data initialization
    • gt = GeetestLib(pc_geetest_id, pc_geetest_key)
    • Put the status in the session, status = gt.pre_process(user_id)
    • Response ﹐ STR = GT. Get ﹐ response ﹐ str() returns data to the front end
  • Two check
    • Accept the parameters transmitted by the front-end form, geetest_challenge, geetest_validate, geetest_seccode
    • Judge the status in the session
      • result = gt.success_validate(challenge, validate, seccode, user_id)
      • Error callback with status 0 result = gt.failback_validate(challenge, validate, seccode)
    • The result after gt execution is used to determine whether the verification is passed, and the response parameter is returned.

IV. initialization of related functions

4-1 validation initialization preprocessing

#How to use
status = gt.pre_process(user_id)

#Source code analysis
def pre_process(self, user_id=None):
    """
    Verify initialization preprocessing
    """
    status, challenge = self._register(user_id)
    self._response_str = self._make_response_format(status, challenge)
    return status

4-2 validation initialization result return

# Usage mode
response_str = gt.get_response_str()

# Source code analysis
def get_response_str(self):
    return self._response_str
# self._response_str = ""
# Pre process put in data make response format (status, challenge)
def _make_response_format(self, success=1, challenge=None):
	if not challenge:
		challenge = self._make_fail_challenge()
	string_format = json.dumps(
		{'success': success, 'gt':self.captcha_id, 'challenge': challenge})
	return string_format

V. quadratic check correlation function

5-1 Front end verification successfully calls function

# Usage mode
result = gt.success_validate(challenge, validate, seccode, user_id)

# Source code analysis
def success_validate(self, challenge, validate, seccode, user_id=None,gt=None,data='',userinfo=''):
    """
    //Second verification mode of normal mode. Request verification result from geetest server
    """
    if not self._check_para(challenge, validate, seccode):
        return 0
    if not self._check_result(challenge, validate):
        return 0
    # Splicing request to obtain server data
    validate_url = "{api_url}{handler}".format(
        api_url=self.API_URL, handler=self.VALIDATE_HANDLER)
    query = {
        "seccode": seccode,
        "sdk": ''.join( ["python_",self.sdk_version]),
        "user_id": user_id,
        "data":data,
        "timestamp":time.time(),
        "challenge":challenge,
        "userinfo":userinfo,
        "captchaid":gt
    }
    backinfo = self._post_values(validate_url, query)
    if backinfo == self._md5_encode(seccode):
        return 1
    else:
        return 0
    
def _post_values(self, apiserver, data):
    response = requests.post(apiserver, data)
    return response.text

5-2 front end verification failure calling function

# Usage mode
result = gt.failback_validate(challenge, validate, seccode)

# Source code analysis    
def failback_validate(self, challenge, validate, seccode):
    """
    failback Mode of secondary verification.Make a simple judgment on the track locally and return the verification result.
    """
    if not self._check_para(challenge, validate, seccode):
        return 0
    validate_str = validate.split('_')
    encode_ans = validate_str[0]
    encode_fbii = validate_str[1]
    encode_igi = validate_str[2]
    decode_ans = self._decode_response(challenge, encode_ans)
    decode_fbii = self._decode_response(challenge, encode_fbii)
    decode_igi = self._decode_response(challenge, encode_igi)
    validate_result = self._validate_fail_image(
        decode_ans, decode_fbii, decode_igi)
    return validate_result

Vi. DEMO related demonstration

VII. Precautions for DEMO operation

  • Note the read path of gt.js
<! -- introduce the interface encapsulating failback -- initgeetest -- >
<script src="/static/gt.js"></script>
  • Front end submit request parameters need to be modified in demo
<form class="popup" action="/pc-geetest/validate" method="post">

 

Topics: Session SDK github network