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

login Response when user not found #351

Closed
Master-Y0da opened this issue Sep 29, 2020 · 9 comments
Closed

login Response when user not found #351

Master-Y0da opened this issue Sep 29, 2020 · 9 comments
Labels
question Further information is requested

Comments

@Master-Y0da
Copy link

I send the login params and if the user is not found on db, the app just raise an internal console exception with this message:

tortoise.exceptions.DoesNotExist: Object does not exist

I have a frontend interface running on different port...so when I try to see the response from the login request, there is no message on browser console, just error 500, with no description. Is there a way of add one ?

@frankie567 frankie567 added the question Further information is requested label Sep 30, 2020
@frankie567
Copy link
Member

That shouldn't happen. If a user does not exist, the login should answer with an HTTP 400 and a message LOGIN_BAD_CREDENTIALS (see https://frankie567.github.io/fastapi-users/usage/routes/#post-login).

Could you post your fastapi-users configuration?

@Master-Y0da
Copy link
Author

Here it is:

        from fastapi_users import FastAPIUsers
        from fastapi_users.authentication import JWTAuthentication
        from db.models import user_db
        from endpoints.user.UserEndpoint import User, UserCreate, UserUpdate, UserDB

        SECRET = "SECRET"
        auth_backends = []

       jwt_authentication = JWTAuthentication(secret=SECRET, lifetime_seconds=900, name='jwt-auth')


       fastapi_users_admin = FastAPIUsers(
         user_db,
         [jwt_authentication],
        User,
        UserCreate,
        UserUpdate,
       UserDB,
      )

     auth_backends.append(jwt_authentication)

@frankie567
Copy link
Member

Could you also paste the database part?

@Master-Y0da
Copy link
Author

@frankie567

     from tortoise import fields, models
     from tortoise.contrib.pydantic import pydantic_model_creator
     from fastapi_users.db import TortoiseBaseUserModel, TortoiseUserDatabase
     from endpoints.user.UserEndpoint import UserDB

    class UserModel(TortoiseBaseUserModel):

         nombre = fields.CharField(max_length=100)
         apellidos = fields.CharField(max_length=100)
         fecha_nacimiento = fields.DateField(default=None)
         telefono = fields.CharField(max_length=20)
         rut = fields.CharField(max_length=10)
         is_doctor = fields.BooleanField(default=False)


      user_db = TortoiseUserDatabase(UserDB, UserModel)
      Users_read = pydantic_model_creator(UserModel, name="UserOut", exclude_readonly=True)
      Users_admin = pydantic_model_creator(UserModel, name="UserAdmin", exclude_readonly=True, exclude=('nombre', 'apellidos','fecha_nacimiento','rut', 'telefono','hashed_password'))

Also have this. I have admin panel and app views on the same project, so I want to check if user trying to log in on my admin panel is superuser and not a simple user:

    async def CheckLoginUserType(request: Request):

    body = await request.form()

   if body['username'] and body['password']:
       email = body['username']
       user = await Users_admin.from_queryset_single(UserModel.get(email=email))

       if user:
          if user.is_superuser:
              pass
         else:
            raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Bad Permission")
     else:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not Found")
else:
    raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Bad Request")

 #Route 
  app.include_router(fastapi_users_admin.get_auth_router(auth.jwt_authentication), prefix="/admin/auth/jwt", tags=["auth"], dependencies=[Depends(CheckLoginUserType)])

@frankie567
Copy link
Member

Ok, so the problem comes from this CheckLoginUserType function. What's wrong in your code is that you don't catch tortoise.exceptions.DoesNotExist if the user does not exist.

Actually, you don't need to implement this yourself. You can use the get_current_superuser dependency callable, which is exactly here for this purpose.

@Master-Y0da
Copy link
Author

@frankie567 I already try that one... "get_current_superuser"...but it gives me 401 unauthorized every time I try to login...does this function check if you are sending a token ?...cause since I try to login there is no token yet on the request.

@frankie567
Copy link
Member

Yes, you have to be authenticated with a token/cookie to be authorized. The flow is this:

  • You login using the /login endpoint and obtain a valid token/cookie
  • You can now call other endpoints that need authentication by passing this valid token/cookie

See: https://frankie567.github.io/fastapi-users/usage/flow/

@Master-Y0da
Copy link
Author

Ok now I get it.

So following the flow you give me and applying it to my case.

A simple user could send log in credentials into my admin panel and get his token although he is not superadmin, since my two user type share the same table on db.
After he gets the token I redirect to Home route in this case.
Since the home route is protected with get_current_superuser will discriminate if a user can access the page or not.

@frankie567
Copy link
Member

Exactly! You have only one login endpoint, for every users.

If the user has the is_superuser flag to True, he will be able to access the route protected by get_current_superuser. Otherwise, he will get a 403 error.

In your frontend app, you can use the /me route to get the details of the user, including the is_superuser flag. This way, you can adapt your interface if the user is admin (e.g. show the admin menu).

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

No branches or pull requests

2 participants