Dried food! Detailed explanation of the development of token verification interface for flash login and registration

Posted by greatstar00 on Wed, 04 Dec 2019 04:25:22 +0100

Today, I present the development of login and registration interface, which is based on token verification. Let's talk less and get to the point!

First look at the database model:

#pip install passlib
from passlib.apps import custom_app_context as pwd_context
class Shop_list(db.Model):
    __tablename__ = 'shop_list'
    userName = db.Column(db.BigInteger,primary_key = True) #Cell-phone number
    passWord = db.Column(db.Text,nullable=False)
    def hash_password(self, password): #Encrypt password
        self.passWord = pwd_context.encrypt(password)
 
    def verify_password(self, password): #Password verification method
        return pwd_context.verify(password, self.passWord)

The structure is very simple. I'll make a demo for you. The following two methods are encryption and password verification. Just remember

Next, look at the registration interface:

@app.route('/api/v1/admin/register',methods=['POST'])
def register():
    username = request.form.get('username')
    password = request.form.get('password')
    save = Shop_list(userName=username)
    save.hash_password(password) #Call password encryption method
    db.session.add(save)
    db.session.commit()
    return 'success'

There's nothing to explain about this. First, the data will be saved

Next is the login interface

@app.route('/api/v1/admin/login',methods=['POST'])
def login():
    username = request.form.get('username')
    password = request.form.get('password')
    obj = Shop_list.query.filter_by(userName=username).first()
    if not obj:
        return res_json(201,'','The user was not found')
    if obj.verify_password(password):
        token = generate_token(username)
        return res_json(200,{'token':token},'Login successfully')
    else:
        return res_json(201,'','Password error')

Explanation: res_json is a function encapsulated by me to return JSON data, and generate_token is a function to generate a token

Play: token generation and verification method

import time
import base64
import hmac
#Generate token input parameter: user id

def generate_token(key, expire=3600):
    ts_str = str(time.time() + expire)
    ts_byte = ts_str.encode("utf-8")
    sha1_tshexstr  = hmac.new(key.encode("utf-8"),ts_byte,'sha1').hexdigest() 
    token = ts_str+':'+sha1_tshexstr
    b64_token = base64.urlsafe_b64encode(token.encode("utf-8"))
    return b64_token.decode("utf-8")
#Verify token input parameters: user id and token
def certify_token(key, token):
    token_str = base64.urlsafe_b64decode(token).decode('utf-8')
    token_list = token_str.split(':')
    if len(token_list) != 2:
        return False
    ts_str = token_list[0]
    if float(ts_str) < time.time():
        # token expired
        return False
    known_sha1_tsstr = token_list[1]
    sha1 = hmac.new(key.encode("utf-8"),ts_str.encode('utf-8'),'sha1')
    calc_sha1_tsstr = sha1.hexdigest()
    if calc_sha1_tsstr != known_sha1_tsstr:
        # token certification failed
        return False 
    # token certification success
    return True

That's it. Have you learned?

Topics: Python SHA1 Session less Database