-
Notifications
You must be signed in to change notification settings - Fork 0
User endpoint #24
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
Merged
Merged
User endpoint #24
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
8b2cc11
User endpoint for authentication
MehmedGIT 04fc05d
remove dummy auth
MehmedGIT 170910f
refactor: UserAccount -> UserAccountDB
MehmedGIT 7416814
implement first portion of feedbacks
MehmedGIT f47f35e
verify admin validation of user
MehmedGIT d6284c3
ref: verified -> approved, check for approval
MehmedGIT ed5552b
apply feedback changes
MehmedGIT f5260c3
version v0.11.0
MehmedGIT File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| from hashlib import sha512 | ||
| from random import random | ||
| from typing import Tuple | ||
|
|
||
| from .database import create_user, get_user | ||
| from .exceptions import AuthenticationError, RegistrationError | ||
|
|
||
|
|
||
| async def authenticate_user(email: str, password: str): | ||
| db_user = await get_user(email=email) | ||
| if not db_user: | ||
| raise AuthenticationError(f"User not found: {email}") | ||
| password_status = validate_password( | ||
| plain_password=password, | ||
| encrypted_password=db_user.encrypted_pass | ||
| ) | ||
| if not password_status: | ||
| raise AuthenticationError(f"Wrong credentials for: {email}") | ||
| if not db_user.approved_user: | ||
| raise AuthenticationError(f"The account was not approved by the admin yet.") | ||
|
|
||
|
|
||
| async def register_user(email: str, password: str, approved_user=False): | ||
| salt, encrypted_password = encrypt_password(password) | ||
| db_user = await get_user(email) | ||
| if db_user: | ||
| raise RegistrationError(f"User is already registered: {email}") | ||
| created_user = await create_user( | ||
| email=email, | ||
| encrypted_pass=encrypted_password, | ||
| salt=salt, | ||
| approved_user=approved_user | ||
| ) | ||
| if not created_user: | ||
| raise RegistrationError(f"Failed to register user: {email}") | ||
|
|
||
|
|
||
| def encrypt_password(plain_password: str) -> Tuple[str, str]: | ||
| salt = get_random_salt() | ||
| hashed_password = get_hex_digest(salt, plain_password) | ||
| encrypted_password = f'{salt}${hashed_password}' | ||
| return salt, encrypted_password | ||
|
|
||
|
|
||
| def get_hex_digest(salt: str, plain_password: str): | ||
| return sha512(f'{salt}{plain_password}'.encode('utf-8')).hexdigest() | ||
|
|
||
|
|
||
| def get_random_salt() -> str: | ||
| return sha512(f'{hash(str(random()))}'.encode('utf-8')).hexdigest()[:8] | ||
|
|
||
|
|
||
| def validate_password(plain_password: str, encrypted_password: str) -> bool: | ||
| salt, hashed_password = encrypted_password.split('$', 1) | ||
| return hashed_password == get_hex_digest(salt, plain_password) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| from pydantic import BaseModel, Field | ||
|
|
||
|
|
||
| class UserAction(BaseModel): | ||
| email: str = Field( | ||
| ..., # the field is required, no default set | ||
| description='Email linked to this User' | ||
| ) | ||
| action: str = Field( | ||
| default='Description of the user action', | ||
| description='Description of the user action' | ||
| ) | ||
|
|
||
| class Config: | ||
| allow_population_by_field_name = True | ||
|
|
||
| @staticmethod | ||
| def create(email: str, action: str): | ||
| if not action: | ||
| action = "User Action" | ||
| return UserAction(email=email, action=action) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| """ | ||
| module for implementing the authentication section of the api | ||
| """ | ||
| import logging | ||
| from fastapi import APIRouter, Depends, HTTPException, status | ||
| from fastapi.security import HTTPBasic, HTTPBasicCredentials | ||
|
|
||
| from ocrd_webapi.authentication import authenticate_user, register_user | ||
| from ocrd_webapi.exceptions import AuthenticationError, RegistrationError | ||
| from ocrd_webapi.models.user import UserAction | ||
|
|
||
| router = APIRouter( | ||
| tags=["User"], | ||
| ) | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
| # TODO: This may not be ideal, discussion needed | ||
| security = HTTPBasic() | ||
|
|
||
|
|
||
| @router.get("/user/login", responses={"200": {"model": UserAction}}) | ||
| async def user_login(auth: HTTPBasicCredentials = Depends(security)): | ||
| email = auth.username | ||
| password = auth.password | ||
| if not (email and password): | ||
| raise HTTPException( | ||
| status_code=status.HTTP_401_UNAUTHORIZED, | ||
| headers={"WWW-Authenticate": "Basic"}, | ||
| detail="Missing e-mail or password field" | ||
| ) | ||
|
|
||
| # Authenticate user e-mail and password | ||
| try: | ||
| await authenticate_user( | ||
| email=email, | ||
| password=password | ||
| ) | ||
| except AuthenticationError as error: | ||
| logger.info(f"User failed to authenticate: {email}, reason: {error}") | ||
| raise HTTPException( | ||
| status_code=status.HTTP_401_UNAUTHORIZED, | ||
| headers={"WWW-Authenticate": "Basic"}, | ||
| detail=f"Invalid login credentials or unapproved account." | ||
| ) | ||
|
|
||
| return UserAction(email=email, action="Successfully logged!") | ||
|
|
||
|
|
||
| @router.post("/user/register", responses={"201": {"model": UserAction}}) | ||
| async def user_register(email: str, password: str): | ||
| try: | ||
| await register_user( | ||
| email=email, | ||
| password=password, | ||
| approved_user=False | ||
| ) | ||
| except RegistrationError as error: | ||
| logger.info(f"User failed to register: {email}, reason: {error}") | ||
| raise HTTPException( | ||
| status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, | ||
| headers={"WWW-Authenticate": "Basic"}, | ||
| detail=f"Failed to register user" | ||
| ) | ||
| action = f"Successfully registered new account: {email}. " \ | ||
| f"Please contact the OCR-D team to get your account validated." | ||
| return UserAction(email=email, action=action) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.