GithubHelp home page GithubHelp logo

fastapi-users / fastapi-users Goto Github PK

View Code? Open in Web Editor NEW
4.1K 4.1K 355.0 12.93 MB

Ready-to-use and customizable users management for FastAPI

Home Page: https://fastapi-users.github.io/fastapi-users/

License: MIT License

Python 99.93% HTML 0.07%
async asyncio fastapi fastapi-users python starlette users

fastapi-users's Introduction

FastAPI Users

FastAPI Users

Ready-to-use and customizable users management for FastAPI

build codecov PyPI version Downloads

All Contributors

Subscribe


Documentation: https://fastapi-users.github.io/fastapi-users/

Source Code: https://github.com/fastapi-users/fastapi-users


Add quickly a registration and authentication system to your FastAPI project. FastAPI Users is designed to be as customizable and adaptable as possible.

Features

  • Extensible base user model
  • Ready-to-use register, login, reset password and verify e-mail routes
  • Ready-to-use social OAuth2 login flow
  • Dependency callables to inject current user in route
  • Pluggable password validation
  • Customizable database backend
  • Multiple customizable authentication backends
    • Transports: Authorization header, Cookie
    • Strategies: JWT, Database, Redis
  • Full OpenAPI schema support, even with several authentication backends

In a hurry? Discover Fief, the open-source authentication platform

Fief

Fief

Implementing registration, login, social auth is hard and painful. We know it. With our highly secure and open-source users management platform, you can focus on your app while staying in control of your users data.

  • Based on FastAPI Users!
  • Open-source: self-host it for free
  • Pre-built login and registration pages: clean and fast authentication so you don't have to do it yourself
  • Official Python client with built-in FastAPI integration

It's free!

Contributors and sponsors ✨☕️

Thanks goes to these wonderful people (emoji key):

François Voron
François Voron

🚧
Paolo Dina
Paolo Dina

💵 💻
Dmytro Ohorodnik
Dmytro Ohorodnik

🐛
Matthew D. Scholefield
Matthew D. Scholefield

🐛 💻
roywes
roywes

🐛 💻
Satwik Kansal
Satwik Kansal

📖
Edd Salkield
Edd Salkield

💻 📖
mark-todd
mark-todd

💻 📖
lill74
lill74

🐛 💻 📖
SelfhostedPro
SelfhostedPro

🛡️ 💻
Oskar Gmerek
Oskar Gmerek

📖
Martin Collado
Martin Collado

🐛 💻
Eric Lopes
Eric Lopes

📖 🛡️
Beau Breon
Beau Breon

💻
Niyas Mohammed
Niyas Mohammed

📖
prostomarkeloff
prostomarkeloff

📖 💻
Marius Mézerette
Marius Mézerette

🐛 🤔
Nickolas Grigoriadis
Nickolas Grigoriadis

🐛
Open Data Coder
Open Data Coder

🤔
Mohammed Alshehri
Mohammed Alshehri

🤔
Tyler Renelle
Tyler Renelle

🤔
collerek
collerek

💻
Robert Bracco
Robert Bracco

💵
Augusto Herrmann
Augusto Herrmann

📖
Smithybrewer
Smithybrewer

🐛
silllli
silllli

📖
alexferrari88
alexferrari88

💵
sandalwoodbox
sandalwoodbox

🐛 📖
Vlad Hoi
Vlad Hoi

📖
Joe Nudell
Joe Nudell

🐛
Ben
Ben

💻
BoYanZh
BoYanZh

📖
David Brochart
David Brochart

📖 💻
Daan Beverdam
Daan Beverdam

💻
Stéphane Raimbault
Stéphane Raimbault

⚠️ 🐛
Sondre Lillebø Gundersen
Sondre Lillebø Gundersen

📖
Maxim
Maxim

📖 🐛
scottdavort
scottdavort

💵
John Dukewich
John Dukewich

📖
Yasser Tahiri
Yasser Tahiri

💻
Brandon H. Goding
Brandon H. Goding

💻 📖
PovilasK
PovilasK

💻
Just van den Broecke
Just van den Broecke

💵
jakemanger
jakemanger

🐛 💻
Ikko Ashimine
Ikko Ashimine

💻
Matyáš Richter
Matyáš Richter

💻
Hazedd
Hazedd

🐛 📖
Luis Roel
Luis Roel

💵
Alexandr Makurin
Alexandr Makurin

💻 🐛
Leon Thurner
Leon Thurner

📖
Goran Mekić
Goran Mekić

📦
Gaganpreet
Gaganpreet

💻
Joe Taylor
Joe Taylor

💻
Richard Friberg
Richard Friberg

🐛
Kenton Parton
Kenton Parton

💵
Adrian Ciołek
Adrian Ciołek

🐛
⭕Alexander Rymdeko-Harvey
⭕Alexander Rymdeko-Harvey

📖
schwannden
schwannden

🚧 💻
Jimmy Angel Pérez Díaz
Jimmy Angel Pérez Díaz

🛡️
Austin Orr
Austin Orr

🚧
Carlo Eugster
Carlo Eugster

🛡️
Vittorio Zamboni
Vittorio Zamboni

💻
Andrey
Andrey

📖
Can H. Tartanoglu
Can H. Tartanoglu

🐛
Filipe Nascimento
Filipe Nascimento

🛡️
dudulu
dudulu

💵 🐛 💬
Toni Alatalo
Toni Alatalo

💻 📖
Börge Kiss
Börge Kiss

📖
Guilherme Caminha
Guilherme Caminha

📖
Téva KRIEF
Téva KRIEF

💻
Essa Alshammri
Essa Alshammri

📖
0xJan
0xJan

🐛
Justin Thomas
Justin Thomas

💻
Adam Israel
Adam Israel

💻
Nerixjk
Nerixjk

🐛 💻
Mike Fotinakis
Mike Fotinakis

💻 🐛
lifengmds
lifengmds

💵
raindata5
raindata5

📖
Mark Donnelly
Mark Donnelly

📖

This project follows the all-contributors specification. Contributions of any kind welcome!

Development

Setup environment

We use Hatch to manage the development environment and production build. Ensure it's installed on your system.

Run unit tests

You can run all the tests with:

hatch run test:test

Format the code

Execute the following command to apply linting and check typing:

hatch run lint

Serve the documentation

You can serve the documentation locally with the following command:

hatch run docs

The documentation will be available on http://localhost:8000.

License

This project is licensed under the terms of the MIT license.

fastapi-users's People

Contributors

allcontributors[bot] avatar antont avatar bkis avatar brandongoding avatar davidbrochart avatar dependabot-preview[bot] avatar dependabot[bot] avatar fotinakis avatar frankie567 avatar hazedd avatar hgalytoby avatar jakemanger avatar mark-todd avatar martincolladodev avatar matyasrichter avatar maxim-le avatar nerixjk avatar niazangels avatar nullhack avatar oskar-gmerek avatar paolodina avatar povilaskud avatar ricfri avatar rnd42 avatar satwikkansal avatar selfhostedpro avatar sondrelg avatar sorasful avatar vladhoi avatar yezz123 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fastapi-users's Issues

help about signin and logout

i don't see on below the Authenticated and Superuser in the swagger(openAPI)
based on the example doc

Authenticated
GET /me
PATCH /me
Superuser
GET /
GET /{user_id}
PATCH /{user_id}
DELETE /{user_id}

image

btw: that will be nice to have doc that explain the flow method authentication
question 2:
the logout of the JWT Authentication are not implemented
my question: it's bug or should inheriting from the class JWTAuthentication and i need to implement the method,
and also in the class SQLAlchemyBaseUserTable i should to implement and put user as inactive?

thanks in advance

Swagger issue for endpoints register & update

Hi,
First of all, great job. It's a very useful library.

However, after having setup my project. I noticed a few issues in the generated Swagger documentation. Indeed, the request body is pre-filled with the following information:

{
  "id": "string",
  "email": "[email protected]",
  "is_active": true,
  "is_superuser": false,
  "password": "string"
}

However, according to your documentation, only the fields email & password are required. It can lead to some misunderstandings for someone wanting to use the API for the first time since the Swagger (or redoc) should describe how to use the API.

I think it's a cheap fix that can be very useful for when you'll find a solution for adding auth in the Swagger. Indeed, after having had a look at your code, one solution could be to make the models BaseUserCreate and BaseUserUpdate not to inherit from BaseUser but BaseModel instead.

Looking forward to hearing from you :)

Advanced rights system

Hello, firstly i wanna say you that this library really good and useful, thank you!
My question will be about delimitation user access to some methods.
What about rights system? Now out of the box we can use only is_superuser as rights check.
In future fastapi-users will support more ways to checking rights? This library looks to me really good, but however i must write custom rights system for not 1 file project. Or for more efficient should we create a new library for it?

Dependabot can't resolve your Python dependency files

Dependabot can't resolve your Python dependency files.

As a result, Dependabot couldn't update your dependencies.

The error Dependabot encountered was:

ERROR: ERROR: Could not find a version that matches pymdown-extensions<6.3,>=6.2,>=6.3
Tried: 1.0.0, 1.0.0, 1.0.1, 1.0.1, 1.1, 1.1, 1.2, 1.2, 1.3, 1.3, 1.4, 1.4, 1.5, 1.5, 1.6, 1.6, 1.6.1, 1.6.1, 1.7, 1.7, 1.8, 1.8, 2.0, 2.0, 3.0, 3.0, 3.1, 3.1, 3.2, 3.2, 3.2.1, 3.2.1, 3.3, 3.3, 3.4, 3.4, 3.5, 3.5, 4.0, 4.0, 4.1, 4.1, 4.2, 4.2, 4.3, 4.3, 4.4, 4.4, 4.5, 4.5, 4.5.1, 4.5.1, 4.6, 4.6, 4.7, 4.7, 4.8, 4.8, 4.9, 4.9, 4.9.1, 4.9.1, 4.9.2, 4.9.2, 4.10, 4.10, 4.10.1, 4.10.1, 4.10.2, 4.10.2, 4.11, 4.11, 4.12, 4.12, 5.0, 5.0, 6.0, 6.0, 6.1, 6.1, 6.2, 6.2, 6.2.1, 6.2.1, 6.3, 6.3
There are incompatible versions in the resolved dependencies.
[pipenv.exceptions.ResolutionFailure]:       req_dir=requirements_dir
[pipenv.exceptions.ResolutionFailure]:   File "/usr/local/.pyenv/versions/3.7.6/lib/python3.7/site-packages/pipenv/utils.py", line 726, in resolve_deps
[pipenv.exceptions.ResolutionFailure]:       req_dir=req_dir,
[pipenv.exceptions.ResolutionFailure]:   File "/usr/local/.pyenv/versions/3.7.6/lib/python3.7/site-packages/pipenv/utils.py", line 480, in actually_resolve_deps
[pipenv.exceptions.ResolutionFailure]:       resolved_tree = resolver.resolve()
[pipenv.exceptions.ResolutionFailure]:   File "/usr/local/.pyenv/versions/3.7.6/lib/python3.7/site-packages/pipenv/utils.py", line 395, in resolve
[pipenv.exceptions.ResolutionFailure]:       raise ResolutionFailure(message=str(e))
[pipenv.exceptions.ResolutionFailure]:       pipenv.exceptions.ResolutionFailure: ERROR: ERROR: Could not find a version that matches pymdown-extensions<6.3,>=6.2,>=6.3
[pipenv.exceptions.ResolutionFailure]:       Tried: 1.0.0, 1.0.0, 1.0.1, 1.0.1, 1.1, 1.1, 1.2, 1.2, 1.3, 1.3, 1.4, 1.4, 1.5, 1.5, 1.6, 1.6, 1.6.1, 1.6.1, 1.7, 1.7, 1.8, 1.8, 2.0, 2.0, 3.0, 3.0, 3.1, 3.1, 3.2, 3.2, 3.2.1, 3.2.1, 3.3, 3.3, 3.4, 3.4, 3.5, 3.5, 4.0, 4.0, 4.1, 4.1, 4.2, 4.2, 4.3, 4.3, 4.4, 4.4, 4.5, 4.5, 4.5.1, 4.5.1, 4.6, 4.6, 4.7, 4.7, 4.8, 4.8, 4.9, 4.9, 4.9.1, 4.9.1, 4.9.2, 4.9.2, 4.10, 4.10, 4.10.1, 4.10.1, 4.10.2, 4.10.2, 4.11, 4.11, 4.12, 4.12, 5.0, 5.0, 6.0, 6.0, 6.1, 6.1, 6.2, 6.2, 6.2.1, 6.2.1, 6.3, 6.3
[pipenv.exceptions.ResolutionFailure]: Warning: Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies.
  First try clearing your dependency cache with $ pipenv lock --clear, then try the original command again.
 Alternatively, you can use $ pipenv install --skip-lock to bypass this mechanism, then run $ pipenv graph to inspect the situation.
  Hint: try $ pipenv lock --pre if it is a pre-release dependency.
ERROR: ERROR: Could not find a version that matches pymdown-extensions<6.3,>=6.2,>=6.3
Tried: 1.0.0, 1.0.0, 1.0.1, 1.0.1, 1.1, 1.1, 1.2, 1.2, 1.3, 1.3, 1.4, 1.4, 1.5, 1.5, 1.6, 1.6, 1.6.1, 1.6.1, 1.7, 1.7, 1.8, 1.8, 2.0, 2.0, 3.0, 3.0, 3.1, 3.1, 3.2, 3.2, 3.2.1, 3.2.1, 3.3, 3.3, 3.4, 3.4, 3.5, 3.5, 4.0, 4.0, 4.1, 4.1, 4.2, 4.2, 4.3, 4.3, 4.4, 4.4, 4.5, 4.5, 4.5.1, 4.5.1, 4.6, 4.6, 4.7, 4.7, 4.8, 4.8, 4.9, 4.9, 4.9.1, 4.9.1, 4.9.2, 4.9.2, 4.10, 4.10, 4.10.1, 4.10.1, 4.10.2, 4.10.2, 4.11, 4.11, 4.12, 4.12, 5.0, 5.0, 6.0, 6.0, 6.1, 6.1, 6.2, 6.2, 6.2.1, 6.2.1, 6.3, 6.3
There are incompatible versions in the resolved dependencies.

['Traceback (most recent call last):\n', '  File "/usr/local/.pyenv/versions/3.7.6/lib/python3.7/site-packages/pipenv/utils.py", line 501, in create_spinner\n    yield sp\n', '  File "/usr/local/.pyenv/versions/3.7.6/lib/python3.7/site-packages/pipenv/utils.py", line 649, in venv_resolve_deps\n    c = resolve(cmd, sp)\n', '  File "/usr/local/.pyenv/versions/3.7.6/lib/python3.7/site-packages/pipenv/utils.py", line 539, in resolve\n    sys.exit(c.return_code)\n', 'SystemExit: 1\n']

If you think the above is an error on Dependabot's side please don't hesitate to get in touch - we'll do whatever we can to fix it.

View the update logs.

How to make custom routes require user auth?

Hello I have looked over the document and not really sure if I missed it but. I am trying to use Jwt with mongodb to create a project how can I use fastapi users to prevent access to custom routes. For example someone who is not logged in and authenticated cannot view a /orders , /profile, /settings or any custom page that requires logged in users?

Seperate routers for login and users

Having the login, register etc. endpoints tied to the users router seems a bit unnatural, especially if the api is versioned. It is nicer to have these endpoints on the root, and then all user CRUD functionality on a users/ endpoint.

The way I see this is that fastapi_users should contain a auth_router and a user_router such that they can be prefixed separately.

Default values when call endpoint /me with custom User Model

Hi Frankie567
First of all thanks for this promising plugin !

I have added new fields to the User Model class like mentioned in documentation:

class User(BaseUser):
    fullname: Optional[str] = None
    creation_date: Optional[datetime] = datetime.utcnow()

When I call the register endpoint, the User is correctly saved with all fields completed.

fullname = 'test'
creation_date = '2020-01-02T08:23:34.014678"

But when after login I call the endpoint /me, only the 'base' fields (email, password, is_active) are set with the database value, the new fields (fullname, creation_date) are shown with their default value.

{"id":"8ce5f915-3218-41b0-a75f-a18055b11176","email":"[email protected]","is_active":true,"is_superuser":true,"fullname":null,"creation_date":"2020-01-03T09:36:27.023413"}

So maybe I'm missing a point or I need to surcharge other methods in my User Model class ?

OAuth2 client

I think this codebase provides a couple of good examples on how FastAPI can be extended. Would you consider implementing OAuth2 as well for user registration so that I can just specify the OAuth2 parameters (like url, callback, client_id and client_secret), perform the authentication and create a user in the database. A specific example I have in mind would be GitLab or Github.

ImportError: cannot import name 'models' from 'fastapi_users' (./fastapi_users.py)

Hi,

I am pretty new to fastapi.
Sorry might sound really silly but here is what I did:

I tried this for both SQLAlchemy and Tortoise ORM and got the same result.

I created a new file main.py under fastapi_users directory and copied the example, from:
https://frankie567.github.io/fastapi-users/configuration/databases/sqlalchemy/

For SQLAlchemy I changed the following line:
engine = sqlalchemy.create_engine(
DATABASE_URL, connect_args={"sqlite:///": False}

As I am testing it with SQLite.
I ran the uvicorn command line: uvicorn main:app --reload

Then I get the error:
module = importlib.import_module(module_str)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/init.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 1006, in _gcd_import
File "", line 983, in _find_and_load
File "", line 967, in _find_and_load_unlocked
File "", line 677, in _load_unlocked
File "", line 728, in exec_module
File "", line 219, in _call_with_frames_removed
File "./main.py", line 4, in
from fastapi_users import FastAPIUsers, models
File "./fastapi_users.py", line 7, in
from fastapi_users import models
ImportError: cannot import name 'models' from 'fastapi_users' (./fastapi_users.py)

I tried it with tortoise and get the same error, but I am still confused with the following line:
register_tortoise(app, modules={"models": ["path_to_your_package"]})
what path do I supply there I checked another post for Tortoise ORM and it just stated like this:
register_tortoise(app, modules={"models": ["models"]})

I am in the correct Virtualenv - (fastapi-users) and also I checked pip freeze and it appears all the correct modules are there. There is quite a lot of them, for tortoise ORM I installed the 3 others stated on the docs of fastapi_users.

Can someone help me please? I am including my main.py file --> had to rename it to main.txt for github!
main.txt

Using TextField as user.id index is a bad idea.

Specifically referring to: https://github.com/frankie567/fastapi-users/blob/master/fastapi_users/db/tortoise.py#L11

I'm sorry I got here so late (via #59 from tortoise/tortoise-orm#246), but a TextField is a really bad primary key.

It is a very-large text field, as in a gigabyte large. Also MySQL will at best index the first 1023 bytes (about 255 Unicode chars) and then just stop indexing.
So this is wide open for abuse, and bugs.
It will also perform terribly as both MySQL and PostgreSQL will only ever store a reference to an external block for the row.

A better, and preferable option would be fields.CharField(max_len=255, pk=True)

Custom model validation

Hi,
I need to add some validators to my custom User model, that raise a ValueError if some set of constraints isn't respected. For example,

class User(models.BaseUser):
    referrer_id: Optional[int] = None

    @pydantic.validator('referrer_id')
    def check_referrer(cls, v, values):
        if v is None and not values.get('is_superuser', False):
            raise ValueError('Referrer needed for standard user')

I expected any validation error to be caught when trying to access the /users/register route, so that the status code of the response would be 422, and the response body containing the standard validation error message.

Instead, I get a 500.

Any pointer to what I'm missing will be deeply appreciated. And 👍 for this awesome work!

Routes for email verification

First of all, well done 👏🏼
I'm really impressed by the ideas, quality of code and documentation.

I'm thinking about adding email verification. Yes, it has some complexity, because you need to verify email after registration and when changing email but it's still essential for many apps.

I got inspired by forgot-password and reset-password routes. Here is my idea:

  1. generate-token route that takes an email as input and returns a token.
  2. on_after_generate_token event to handle email sending or what ever.
  3. verify-token route that takes the generated token and returns a relevant status code.

Do you think it would work that way or there is a better way?

How to use Oauth2 authentication in a Fastapi app ?

Just some thoughts as I try to understand how to use the Oauth2 implementation inside a fastapi app.

The official tutorial is here: https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/ and it is what I want to achieve.

As I already use this nice fastapi-users plugin I assume I can use it to simplify the integration.

So I'm wondering if I need to use the Oauth2 Generic client (https://frankie567.github.io/httpx-oauth/oauth2/) to achieve this or just use the endpoint JWTAuthentication ?

(I understand the other usecases using Google/Github/ others OAuth providers and the documentation is clear about that).

But for me the articulation to secure my API is a little confusing as I see some similar/overlapping methods between the official tutorial which use : oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token") providing an 'Authorization' Button on the swagger api and the Fastapi-users implementation who apparently does'nt.

Also I don't understand in which usecases the OAuth2AuthorizeCallback is needed ? (https://frankie567.github.io/httpx-oauth/fastapi/)

ideal Postman workflow for fastapi-users

Hi Frankie! Thank you so much for putting this package together. I am trying to implement your user management system for a ReactJS front-end application. This is my first time implementing an end-to-end authentication system, so I am still in the early stages of understanding JWT vs Cookie based authentication. I assume I should be using CookieAuthentication for this type of project? I will be building a separate FastAPI resource for handling all the information gathering required for my web application. I am trying to understand the workflow you'd use in a login/logout scenario. Would you mind sharing a workflow via Postman? I am successful in logging in, but upon logout I am returned an Unauthorized message. Any thoughts? I would appreciate any insight on the design paradigm for best practice if serving a front-end React app with auth and a lot of data flows.

PS - I copied your example from: https://frankie567.github.io/fastapi-users/configuration/full_example/ and replaced JWT auth with Cookie.

Thanks again!

Add error codes to error responses

For a better user experience, it would be nice to have more detailed error messages.

To not force us to use a localization engine, let's define some codes and let the front-end interpret them. The codes should be however clear enough for an API user to understand what is going on.

Possible list:

  • REGISTER_USER_ALREADY_EXISTS
  • LOGIN_BAD_CREDENTIALS
  • RESET_PASSWORD_BAD_TOKEN

Improve authentication

Currently, only one authentication backend is allowed at a time. This is wrong. One could wish for example to use both Cookie and a Bearer token strategies.

Still taking inspiration from Django, the goal would be to be able to define a list of auth backends. There would be then a wrapper that would run sequentially until it finds a strategy that yield a user ; or raise 401.

Here is a non-working first attempt: 5160dba

This approach is promising but currently blocked by tiangolo/fastapi#679.

broken link between OpenAPI-UI authorize button and app ?

A new user registers via OpenAPI-UI

User 31da2387-4071-4702-9f10-0e861677354a has registered.
INFO:	127.0.0.1:44508 - "POST /users/register HTTP/1.1" 201 Created

the user can log in via OpenAPI-UI

INFO:	127.0.0.1:44522 - "POST /users/login HTTP/1.1" 200 OK

However, using the Authorize button of the OpenAPI-UI does not work.

INFO:	127.0.0.1:44526 - "POST /login HTTP/1.1" 404 Not Found

The logs shown above indicate that the prefix is not understood by the app. Possibly a fast-api issue? But I currently can't judge it from my flask background.

app.include_router(fa_users.router, prefix='/users', tags=['users'])

user handling with HTML template

hello, how do I pass a ValidationError or 400 error back to the login.html template?

for example if user enters empty username or incorrect password, they just get a text return,

1 validation error for Request
body -> password
  field required (type=value_error.missing)
Validation Error: 

How can I pass this error back to login.html template as a warning?

Thank you

Make easy to override Responses and HTTPException

Hello! At the moment, i can't override values which returns fastapi-users. For example:
When user have bad credentials fastapi-user simple raise the FastAPI HTTPException, but in some cases it isn't well :( My idea is to make a classvars (or global vars?) of responses (errors) classes, which user easy can override.

Cookie issue

Hi, love this project! Super cool and useful. I'm trying to implement it but having some issues using cookies.

After logging in and being issued a cookie, every protected route returns a 401: "detail": "Unauthorized"
I've checked and:

  • my only auth_backends is CookieAuthentication

  • my SECRET variable is linked

  • and cookies are attached to the headers of my responses in the browser. Currently, using Insomnia REST to test my API which automatically attaches/manages cookies.

Is there something else I could be missing?

Use username instead of email ?

Quick question, can I change using a nick_name as a login name instead of email?
How to make email field optional, but not mandatory?

How to login with cookie?

Hi, I create a login form page , I want to login it with cookie, How to do it? I test it , but not work.

auth_backends = [
    CookieAuthentication(secret=SECRET, lifetime_seconds=3600),
    # JWTAuthentication(secret=SECRET, lifetime_seconds=3600),
]

fastapi_users = FastAPIUsers(
    user_db, auth_backends, User, UserCreate, UserUpdate, UserDB, SECRET,
)
app.include_router(fastapi_users.router, prefix="/users", tags=["users"])

templates = Jinja2Templates(directory='templates')
...

@app.get("/")
async def read_root(user: User = Depends(fastapi_users.get_current_active_user)):
    return {"Hello": f"{user.email}"}


@app.route("/login", methods=['GET'])
async def login(request):
    return templates.TemplateResponse('login.html', {'request': request})

template

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
<h1>Login</h1>
<form method="post" action="/users/login/cookie">
    <input name="username" autocomplete="off">
    <input name="password" autocomplete="off">
    <button>submit</button>
</form>
</body>
</html>

I access Login page and input username and password, then submit it, response null, then I access homepage "http://127.0.0.1:8000", but still display {"detail":"Unauthorized"}

AttributeError: module 'importlib._bootstrap' has no attribute 'SourceFileLoader'

I'm getting this from yesterday only for fastapi-users package:

   File "./users/routers.py", line 1, in <module>
     from fastapi_users import FastAPIUsers
   File "/usr/local/lib/python3.8/site-packages/fastapi_users/__init__.py", line 6, in <module>
     from fastapi_users.fastapi_users import FastAPIUsers  # noqa: F401
   File "/usr/local/lib/python3.8/site-packages/fastapi_users/fastapi_users.py", line 7, in <module>
     from fastapi_users.authentication import Authenticator, BaseAuthentication
   File "/usr/local/lib/python3.8/site-packages/fastapi_users/authentication/__init__.py", line 7, in <module>
     from fastapi_users.authentication.base import BaseAuthentication  # noqa: F401
   File "/usr/local/lib/python3.8/site-packages/fastapi_users/authentication/base.py", line 6, in <module>
     from fastapi_users.db import BaseUserDatabase
   File "/usr/local/lib/python3.8/site-packages/fastapi_users/db/__init__.py", line 1, in <module>
     from fastapi_users.db.base import BaseUserDatabase  # noqa: F401
   File "/usr/local/lib/python3.8/site-packages/fastapi_users/db/base.py", line 5, in <module>
     from fastapi_users import password
   File "/usr/local/lib/python3.8/site-packages/fastapi_users/password.py", line 3, in <module>
     from passlib import pwd
   File "/usr/local/lib/python3.8/site-packages/passlib/pwd.py", line 16, in <module>
     import pkg_resources
   File "/usr/local/lib/python3.8/site-packages/pkg_resources.py", line 1479, in <module>
     register_loader_type(importlib_bootstrap.SourceFileLoader, DefaultProvider)
 AttributeError: module 'importlib._bootstrap' has no attribute 'SourceFileLoader'

I figure out that the issue only exists when I have also socketio package installed.

separate mongodb dependency for tests and packaged code

Hey,
first, thanks for sharing!

MongoDB is neat, but I don't use it and two issues arise from that:

  1. this specific test fails - obviously - because I don't have MongoDB installed

  2. importing fastapi_user after $ pip install fastapi-users[sqlalchemy] fails (see stack trace below)

While the first issue is arguably a development issue the second seems to affect any user of the package.

ideas for 1.

  • mock a MongoDB connection and don't connect to a real MongoDB database
  • add pytest configuration file to separate MongoDB related tests for human devs and CI

ideas for 2.

my stack trace shows the missing motor package (MongoDB async driver). it works ok after installing motor via $ pip install motor. But if this dependency is intended it should be listed in the pipenv file?
This happend although I used $ pip install fastapi-users[sqlalchemy]. But I am not familiar with the underlying pip/PyPi/pipenv logic. Did the logic break?

/home/user/dev/py/fa/.venv2/bin/python /home/user/dev/py/fa/user/main.py
Traceback (most recent call last):
  File "/home/user/dev/py/fa/user/main.py", line 9, in <module>
    from src.db import db
  File "/home/user/dev/py/fa/user/src/db.py", line 3, in <module>
    from fastapi_users.fastapi_users.db import SQLAlchemyUserDatabase
  File "/home/user/dev/py/fa/.venv2/lib/python3.7/site-packages/fastapi_users/__init__.py", line 5, in <module>
    from fastapi_users.fastapi_users import FastAPIUsers  # noqa: F401
  File "/home/user/dev/py/fa/.venv2/lib/python3.7/site-packages/fastapi_users/fastapi_users.py", line 3, in <module>
    from fastapi_users.authentication import BaseAuthentication
  File "/home/user/dev/py/fa/.venv2/lib/python3.7/site-packages/fastapi_users/authentication/__init__.py", line 1, in <module>
    from fastapi_users.authentication.base import BaseAuthentication  # noqa: F401
  File "/home/user/dev/py/fa/.venv2/lib/python3.7/site-packages/fastapi_users/authentication/base.py", line 7, in <module>
    from fastapi_users.db import BaseUserDatabase
  File "/home/user/dev/py/fa/.venv2/lib/python3.7/site-packages/fastapi_users/db/__init__.py", line 2, in <module>
    from fastapi_users.db.mongodb import MongoDBUserDatabase  # noqa: F401
  File "/home/user/dev/py/fa/.venv2/lib/python3.7/site-packages/fastapi_users/db/mongodb.py", line 3, in <module>
    from motor.motor_asyncio import AsyncIOMotorCollection
ModuleNotFoundError: No module named 'motor'

TypeError: on_after_register() takes 1 positional argument but 2 were given

I just test register a user, display error in console.

from fastapi import FastAPI
from fastapi_users import FastAPIUsers, models
from fastapi_users.authentication import JWTAuthentication
from fastapi_users.db import TortoiseBaseUserModel, TortoiseUserDatabase
from tortoise.contrib.starlette import register_tortoise

DATABASE_URL = "sqlite://./test.db"
SECRET = "SECRET"


class User(models.BaseUser):
    pass


class UserCreate(User, models.BaseUserCreate):
    pass


class UserUpdate(User, models.BaseUserUpdate):
    pass


class UserDB(User, models.BaseUserDB):
    pass


class UserModel(TortoiseBaseUserModel):
    pass


user_db = TortoiseUserDatabase(UserDB, UserModel)
app = FastAPI()
register_tortoise(app, db_url=DATABASE_URL, modules={"models": ["main"]}, generate_schemas=False)

auth_backends = [
    JWTAuthentication(secret=SECRET, lifetime_seconds=3600),
]

fastapi_users = FastAPIUsers(
    user_db, auth_backends, User, UserCreate, UserUpdate, UserDB, SECRET,
)
app.include_router(fastapi_users.router, prefix="/users", tags=["users"])


@fastapi_users.on_after_register()
def on_after_register(user: User):
    print(f"User {user.id} has registered.")


@fastapi_users.on_after_forgot_password()
def on_after_forgot_password(user: User, token: str):
    print(f"User {user.id} has forgot their password. Reset token: {token}")

Implement forgot/reset password routes

Forgot and reset password routes are essential.

To fit with our highly customisable philosophy and to focus only on users logic, we will propose hooks so that end-developers implement their own logic when a password reset is requested (send a e-mail, call an API...).

"on before registration" event handler

Hi François,

I would like to secure my registration process using a recaptcha token which I need to validate before registering the user.

I wonder what is the better approach to process the token using the default fastapi-users /register route.

Maybe adding a new "on before registration" event handler could be a solution ? (if its possible to cancel the registration process in the case the token is invalid).

Or maybe you have a better suggestion for this usecase ? (I also try to avoid implementing this token validation using pydantic validators for my User object class)

Can't connect to mongo docker

okey, spend a day, but still can't make this work

.env

# Mongo DB
MONGO_INITDB_ROOT_USERNAME=admin-user
MONGO_INITDB_ROOT_PASSWORD=admin-password
MONGO_INITDB_DATABASE=container

docker-compose.yml

 mongo-db:
    image: mongo:4.2.3
    env_file:
      - .env
    ports:
      - 27017:27107
    volumes:
      - ./bin/mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro
    #    restart: always add this production


  api:
    build:
      context: ./backend
      dockerfile: Dockerfile
    command: uvicorn app.main:app --host 0.0.0.0 --port 8006 --reload
    volumes:
      - ./backend:/app
    env_file:
      - .env
    depends_on:
      - mongo-db
    ports:
      - "8006:8006"

mongo-init.js

db.auth('admin-user', 'admin-password')

db = db.getSiblingDB('container')

db.createUser({
    user: 'test-user',
    pwd: 'test-password',
    roles: [
        {
            role: 'root',
            db: 'admin',
        },
    ],
});

using this as example - https://frankie567.github.io/fastapi-users/configuration/full_example/

changed few lines:
DATABASE_URL = "mongodb://test-user:test-password@mongo-db/container"

client = motor.motor_asyncio.AsyncIOMotorClient(DATABASE_URL)
db = client["container"]
collection = db["users"]
user_db = MongoDBUserDatabase(UserDB, collection)

so think Fatapi is linked to Mongo container
image

but when i try to register user using Fastapi docks section, i get
"Internal server error"

what I left unfinished?

Tortoise ORM support

At the moment tortoise-orm is growing up and i think it's good reason for adding it. I plan start work of it soon.

Add Development/Contributing documentation and tag unit tests

Following the questions of @erkandem in #35, we should improve the documentation and tooling improvements regarding unit tests. More specifically:

  • Add a Development/Contributing section in the README to explain how to run the tests.
  • Add pytest markers on the tests so that we can properly skip the ones we are not interested in.

Probem querying added user with psql

I have just added "Full example" to my fast api project with postgres.
After adding a user with cookie authentication, Trying to query and see recently added user by psql. when I query "user" table just see a table with single user column with a postgres value.
P.S: authentication is working but when i try to logout cookie authed users, i can't.

fastapi: 0.54.1
fastapi-users: 0.8.0

Dependabot can't resolve your Python dependency files

Dependabot can't resolve your Python dependency files.

As a result, Dependabot couldn't update your dependencies.

The error Dependabot encountered was:

ERROR: ERROR: Could not find a version that matches pymdown-extensions<6.3,>=6.2,>=6.3
Tried: 1.0.0, 1.0.0, 1.0.1, 1.0.1, 1.1, 1.1, 1.2, 1.2, 1.3, 1.3, 1.4, 1.4, 1.5, 1.5, 1.6, 1.6, 1.6.1, 1.6.1, 1.7, 1.7, 1.8, 1.8, 2.0, 2.0, 3.0, 3.0, 3.1, 3.1, 3.2, 3.2, 3.2.1, 3.2.1, 3.3, 3.3, 3.4, 3.4, 3.5, 3.5, 4.0, 4.0, 4.1, 4.1, 4.2, 4.2, 4.3, 4.3, 4.4, 4.4, 4.5, 4.5, 4.5.1, 4.5.1, 4.6, 4.6, 4.7, 4.7, 4.8, 4.8, 4.9, 4.9, 4.9.1, 4.9.1, 4.9.2, 4.9.2, 4.10, 4.10, 4.10.1, 4.10.1, 4.10.2, 4.10.2, 4.11, 4.11, 4.12, 4.12, 5.0, 5.0, 6.0, 6.0, 6.1, 6.1, 6.2, 6.2, 6.2.1, 6.2.1, 6.3, 6.3
There are incompatible versions in the resolved dependencies.
[pipenv.exceptions.ResolutionFailure]:       req_dir=requirements_dir
[pipenv.exceptions.ResolutionFailure]:   File "/usr/local/.pyenv/versions/3.7.6/lib/python3.7/site-packages/pipenv/utils.py", line 726, in resolve_deps
[pipenv.exceptions.ResolutionFailure]:       req_dir=req_dir,
[pipenv.exceptions.ResolutionFailure]:   File "/usr/local/.pyenv/versions/3.7.6/lib/python3.7/site-packages/pipenv/utils.py", line 480, in actually_resolve_deps
[pipenv.exceptions.ResolutionFailure]:       resolved_tree = resolver.resolve()
[pipenv.exceptions.ResolutionFailure]:   File "/usr/local/.pyenv/versions/3.7.6/lib/python3.7/site-packages/pipenv/utils.py", line 395, in resolve
[pipenv.exceptions.ResolutionFailure]:       raise ResolutionFailure(message=str(e))
[pipenv.exceptions.ResolutionFailure]:       pipenv.exceptions.ResolutionFailure: ERROR: ERROR: Could not find a version that matches pymdown-extensions<6.3,>=6.2,>=6.3
[pipenv.exceptions.ResolutionFailure]:       Tried: 1.0.0, 1.0.0, 1.0.1, 1.0.1, 1.1, 1.1, 1.2, 1.2, 1.3, 1.3, 1.4, 1.4, 1.5, 1.5, 1.6, 1.6, 1.6.1, 1.6.1, 1.7, 1.7, 1.8, 1.8, 2.0, 2.0, 3.0, 3.0, 3.1, 3.1, 3.2, 3.2, 3.2.1, 3.2.1, 3.3, 3.3, 3.4, 3.4, 3.5, 3.5, 4.0, 4.0, 4.1, 4.1, 4.2, 4.2, 4.3, 4.3, 4.4, 4.4, 4.5, 4.5, 4.5.1, 4.5.1, 4.6, 4.6, 4.7, 4.7, 4.8, 4.8, 4.9, 4.9, 4.9.1, 4.9.1, 4.9.2, 4.9.2, 4.10, 4.10, 4.10.1, 4.10.1, 4.10.2, 4.10.2, 4.11, 4.11, 4.12, 4.12, 5.0, 5.0, 6.0, 6.0, 6.1, 6.1, 6.2, 6.2, 6.2.1, 6.2.1, 6.3, 6.3
[pipenv.exceptions.ResolutionFailure]: Warning: Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies.
  First try clearing your dependency cache with $ pipenv lock --clear, then try the original command again.
 Alternatively, you can use $ pipenv install --skip-lock to bypass this mechanism, then run $ pipenv graph to inspect the situation.
  Hint: try $ pipenv lock --pre if it is a pre-release dependency.
ERROR: ERROR: Could not find a version that matches pymdown-extensions<6.3,>=6.2,>=6.3
Tried: 1.0.0, 1.0.0, 1.0.1, 1.0.1, 1.1, 1.1, 1.2, 1.2, 1.3, 1.3, 1.4, 1.4, 1.5, 1.5, 1.6, 1.6, 1.6.1, 1.6.1, 1.7, 1.7, 1.8, 1.8, 2.0, 2.0, 3.0, 3.0, 3.1, 3.1, 3.2, 3.2, 3.2.1, 3.2.1, 3.3, 3.3, 3.4, 3.4, 3.5, 3.5, 4.0, 4.0, 4.1, 4.1, 4.2, 4.2, 4.3, 4.3, 4.4, 4.4, 4.5, 4.5, 4.5.1, 4.5.1, 4.6, 4.6, 4.7, 4.7, 4.8, 4.8, 4.9, 4.9, 4.9.1, 4.9.1, 4.9.2, 4.9.2, 4.10, 4.10, 4.10.1, 4.10.1, 4.10.2, 4.10.2, 4.11, 4.11, 4.12, 4.12, 5.0, 5.0, 6.0, 6.0, 6.1, 6.1, 6.2, 6.2, 6.2.1, 6.2.1, 6.3, 6.3
There are incompatible versions in the resolved dependencies.

['Traceback (most recent call last):\n', '  File "/usr/local/.pyenv/versions/3.7.6/lib/python3.7/site-packages/pipenv/utils.py", line 501, in create_spinner\n    yield sp\n', '  File "/usr/local/.pyenv/versions/3.7.6/lib/python3.7/site-packages/pipenv/utils.py", line 649, in venv_resolve_deps\n    c = resolve(cmd, sp)\n', '  File "/usr/local/.pyenv/versions/3.7.6/lib/python3.7/site-packages/pipenv/utils.py", line 539, in resolve\n    sys.exit(c.return_code)\n', 'SystemExit: 1\n']

If you think the above is an error on Dependabot's side please don't hesitate to get in touch - we'll do whatever we can to fix it.

View the update logs.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.