본문 바로가기

Web Development/Flask

User Authentication

Login Authentication

# Authentication
######################################################################################
# login
'''
Json object example:
{
    "username": "sunwoojgfh",
    "password": "jsw1025"
}
'''
######################################################################################

@app.route('/login', methods=['POST'])
def login_user():
    print(request.json)
    try:
        body = request.json
        username = body['username']
        password = body['password']
        hash_password = hashlib.sha256(password.encode('utf-8')).hexdigest()
        # Find the user with the entered id and pw
        result = db.user.find_one({'username': username, 'password': hash_password}, {'_id': False})
        # If the user is found, make a token using jwt
        if result is not None:
            # token with 3 hours time expiration
            payload = {
                'username': username,
                'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=3)
            }
            token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')
            return Response(
                response=json.dumps({'username': username, 'token': token}),
                status=200,
                mimetype="application/json"
            )
        # If there is no such id and pw pair
        else:
            result = db.user.find_one({'username': username}, {'_id': False})
            if result is None:
                return Response(
                response=json.dumps({"message":"No such username exist in DB"}),
                status=400,
                mimetype="application/json"
            )
            else:
                return Response(
                response=json.dumps({"message":"Wrong Password"}),
                status=400,
                mimetype="application/json"
            )
    except Exception as e:
        return Response(
            response=json.dumps({"message":"Cannot login"}),
            status=500,
            mimetype="application/json"
        )

 

Validate Token

######################################################################################
# ValidToken : Checking if given token is still valid (not expired)
'''
example: /validtoken/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InN1bndvb2pnZmgiLCJleHAiOjE2NzQ0MTUxMDR9.Wv8qdk_9BGEhytsen2HlvnmRiJI6Jn9JnWcrwuTm3H8
'''
######################################################################################

@app.route('/validtoken/<path:token>', methods=['GET'])
def valid_token(token):
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
        user = db.user.find_one({'username': payload['username']}, {'_id': False})
        return Response(
                response=json.dumps({'result': user, 'message': 'Checking validtoken success'}),
                status=200,
                mimetype="application/json"
            )
    except jwt.ExpiredSignatureError:
        return Response(
            response=json.dumps({"message":"Log in time is expired. Please log in again."}),
            status=400,
            mimetype="application/json"
        )
    except Exception as e:
        return Response(
            response=json.dumps({"message":"Cannot check valid token"}),
            status=500,
            mimetype="application/json"
        )

'Web Development > Flask' 카테고리의 다른 글

Setting up MongoDB Atlas connection  (0) 2023.01.19
Python Flask MongoDB - Complete CRUD in one video  (0) 2022.11.25
Basics  (0) 2022.11.04