Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom Token checker function not working #19

Closed
techxonia opened this issue Nov 7, 2020 · 3 comments
Closed

Custom Token checker function not working #19

techxonia opened this issue Nov 7, 2020 · 3 comments

Comments

@techxonia
Copy link

techxonia commented Nov 7, 2020

I try to separate the logic of checking JWT tokens from one function so that it can be reused. But when I try to run the code, it does not work. I manage an access token in my database and check if it exists or not. The last generated token will be valid only for the access token. This access token must be checked at every protected endpoint. Here is my code:


@router.get('/user')
async def items(Authorize: AuthJWT = Depends(), db: AsyncIOMotorClient = Depends(get_database)):
    try:
        await jwt_token_checker(Authorize, db)
        return {"asd"}   

    except Exception as ex:
        return error

Helper Function:

async def jwt_token_checker( Authorize: AuthJWT , conn: AsyncIOMotorClient):
    try:
        Authorize.jwt_required()
        jti = Authorize.get_raw_jwt()['jti']
        current_user = Authorize.get_jwt_subject()
        access_token_check = await check_access_token(conn, Authorize, jti, current_user)
        
        errorMessage = ""
        if access_token_check == AuthEnum.FORBIDDEN_UNAUTHORIZED_ACCESS:
            errorMessage = Locale(
                language, strings.FORBIDDEN_UNAUTHORIZED_ACCESS).string
            return errorMessage
    except Exception as ex:
        return error

Is this right way to separate the token checker function? If not then can you please suggest me some solution.

@techxonia techxonia changed the title Token helper function not working Custom Token helper function not working Nov 7, 2020
@techxonia techxonia changed the title Custom Token helper function not working Custom Token checker function not working Nov 7, 2020
@IndominusByte
Copy link
Owner

You return error, not return ex. check your code again when I testing in my machine is working

@app.get('/user')
def user(Authorize: AuthJWT = Depends()):
    try:
        current_user = jwt_token_checker(Authorize)
    except Exception as ex:
        return ex # return ex not error

    return {"user": current_user}

def jwt_token_checker(Authorize: AuthJWT):
    try:
        Authorize.jwt_required()
        return Authorize.get_jwt_subject()
    except Exception as ex:
        return ex # return ex not error

Screen Shot 2020-11-07 at 16 57 01

@techxonia
Copy link
Author

techxonia commented Nov 7, 2020

Here is actual code: It is not working:

@router.get('/user')
async def items(Authorize: AuthJWT = Depends(), db: AsyncIOMotorClient = Depends(get_database)):
    try:
        """ If there was an exception, the function must throw an error and must not execute next line of code """"
        await jwt_token_checker(Authorize, db)

        """ but now it always returns a success true if wrong token pass """
        return {"success": true} 
              

    except Exception as ex:
        return JSONResponse(
        status_code=200,
        content={
            "data": None,
            "code": 400,
            "message": "Some thing Went Wrong,
            "status": False
        }
    )

Helper Function:

async def jwt_token_checker(language: str, Authorize: AuthJWT , conn: AsyncIOMotorClient):
    try:
    
        Authorize.jwt_required()
        
        jti = Authorize.get_raw_jwt()['jti']
        current_user = Authorize.get_jwt_subject()
        access_token_check = await check_access_token(conn, Authorize, jti, current_user)
        
        errorMessage = ""
        if access_token_check == AuthEnum.FORBIDDEN_UNAUTHORIZED_ACCESS:
            errorMessage = Locale(
                language, strings.FORBIDDEN_UNAUTHORIZED_ACCESS).string
                return JSONResponse(
                  status_code=200,
                   content={
                   "data": None,
                   "code": 400,
                  "message": errorMessage
                  "status": False
                }
            )

    except AuthJWTException as e:
        return JSONResponse(
                  status_code=401,
                   content={
                   "data": None,
                   "code": 401,
                  "message": "UnAuthorize User"
                  "status": False
                }
            )

@IndominusByte
Copy link
Owner

you must raise an exception not return a response

@app.get('/user')
async def user(Authorize: AuthJWT = Depends()):
    try:
        await jwt_token_checker(Authorize)

        return {"success": True}
    except Exception:
        return JSONResponse(
            status_code=200,
            content={
                "data": None,
                "code": 400,
                "message": "Some thing Went Wrong",
                "status": False
            }
        )

async def jwt_token_checker(Authorize: AuthJWT):
    try:
        Authorize.jwt_required()
    except AuthJWTException:
        raise # raise exception

Screen Shot 2020-11-07 at 17 48 19

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants