Search code examples
pythonfastapipassword-encryption

How to create the first user in an python web application with JWT tokens and encrypted passwords?


I have created a FastAPI application which has a database with postgresql. The application uses docker, a container for the app and another for the database. Furthermore, it implements authentication with JWT tokens and encrypts passwords with bcrypt. My problem is that logically the endpoint to create new users requires authentication. How do I create the first user? That is, temporarily remove authentication from the endpoint and create the user, but I must write the step by step for project delivery and I do not consider pertinent to give that solution. I tried to build the containers and write the steps to insert a user from the database container terminal. However the record is saved in the database but with the password unencrypted, so when I try to authenticate it doesn't work. In summary, how to create that first user?


Solution

  • You should define a startup event which would populate the database with an admin account for you. This way, you don't ever have to temporarily remove authentication while still having a valid account that you can use. Here's an example of how you could do it:

    from fastapi import FastAPI, Request
    from domain import *
    
    app = FastAPI()
    
    users = {}
    
    @app.on_event('startup')
    async def populate_admin():
        if "admin" not in users:
            users['admin'] = {
                'username': 'admin_user',
                'password': hash('totally_secret_password')
            }
    

    Naturally, you would want to use an actual database for your persistance layer and an actual hash function like bcrypt. Another thing commonly implemented is to read the username and password of the "admin" user from some config file or environment variables instead of having it hard-coded in the function. Hope this helps!