Skip to content

App and admin authentication

This work has not particular value on its own, except aggregating different sources of very skilled people in a hopefully user friendly manner.

Sources that can be cited:

app authentication

Here we detail the main methods that should prove useful to people. At the end the section we list all the other available (not explained here) methods.

attempt_to_log

The method attempt_to_log is used to retrieve a Json Web Token corresponding to a user, characterized by its user and password.

from sqlmodel import Session
from ecodev_core import attempt_to_log
from ecodev_core import engine

with Session(engine) as session:
    token = attempt_to_log('monitoring', 'monitoring', session)

Warning

The method raises

  • a HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=INVALID_USER) error when the user is not found in db (more on AppUser here). INVALID_USER is a hopefully clear error message
  • a HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=INVALID_CREDENTIALS) error when the user is found in db but the password is incorrect(more on AppUser here). INVALID_CREDENTIALS is a hopefully clear error message

If the request is valid, the token is returned like so:

{'access_token': 'FIRST_HASH.SECOND_HASH.THIRD_HASH', 'token_type': 'bearer'}

Two Factor Authentication (>=0.0.18)

ecodev-core now supports two factor authentication. attempt_to_log can now take an (optional) argument tfa_value to be added encoded to the token returned.

A good library to generate TFA codes is pyotp.

get_current_user

The method get_current_user returns a AppUser (more on AppUser here). given a valid JWT. It expects a str token as its input

from ecodev_core import get_current_user

client = get_current_user(CLIENT_TOKEN)

Warning

The method raises an HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=INVALID_USER) error when the token does not correspond to any valid user. INVALID_USER is a hopefully clear error message

Two Factor Authentication (>=0.0.18)

get_current_user now takes two additional optional arguments:

  • tfa_check: whether or not to perform TFA check. False by default
  • tfa_value: the plain TFA value to be compared with the one encoded in the passed token. Not used if tfa_check is False. None by default.

Other available methods/classes

  • safe_get_user: expects a dictionary
      {'token': {'access_token': <HASH>, 'token_type': 'bearer'}}
    
    and returns the corresponding AppUser if the token HASH is valid, None otherwise
  • is_admin_user checks if the AppUser correspondding to the passed str token argument has Admin permissions (more on permissions AppUser here), and if so returns the AppUser
  • is_monitoring_user checks if the AppUser correspondding to the passed str token is the monitoring user (more on monitoring here), and if so returns the AppUser
  • is_authorized_user checks if the AppUser correspondding to the passed str token is a valid one (returns a bool)
  • get_user morally the same has get_current_user, can be used interchangeably (one of them should be deprecated in the future)
  • get_app_services more on this in here, related to AppRight
  • Token is a simple class for storing an access_token and its token_type

Two Factor Authentication (>=0.0.18)

All the above methods now support TFA when it makes sense, thanks to the two additional optional arguments:

  • tfa_check: whether or not to perform TFA check. False by default
  • tfa_value: the plain TFA value to be compared with the one encoded in the passed token. Not used if tfa_check is False. None by default.

admin authentication

ecodev-core uses Sqladmin as its admin interface. It is a very simple to use library, user friendly and the library owner is very nice and responsive (thanks Amin !! 😊).

sqladmin does not come out of the box with an authentication mechanism, but it is pretty straightforward to implement with the official documentation.

We did just so at EcoAct.

JwtAuth

To use sqladmin, one just has to instanciate it:

from ecodev_core import AUTH
from ecodev_core import JwtAuth
from ecodev_core import engine
from fastapi import FastAPI
from sqladmin import Admin

app = FastAPI()
admin = Admin(app, engine,
              authentication_backend=JwtAuth(secret_key=AUTH.secret_key))

Here secret_key should be set via environment variables. More on AUTH here.

Afterwards, adding an admin view on a table is as simple as

from ecodev_core import AppUser
from sqladmin import ModelView

class AppUserAdmin(ModelView, model=AppUser):  # type: ignore
    """
    AppUser admin view
    """
    column_list = [AppUser.id,
                   AppUser.user,
                   AppUser.permission,
                   AppUser.client,]
    column_searchable_list = [AppUser.user]
admin.add_view(AppUserAdmin)

More on column_searchable_list and other sqladmin awesome configurations here.

Sqladmin example

Example of sqladmin rendering. You should go read the official documentation now 😊