Repository navigation
Backend/srv/auth srv #33
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
Closed
Closed
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
cd00cf5
Initial commit
Sigmagor c20c7b4
test
Sigmagor 6dffe88
Add: .gitignore
Sigmagor ebd8e9e
Added Python structure & __init__.py files
Sigmagor d1af8c5
Added Python structure & __init__.py files
Sigmagor 3a87126
Removed previous code
Sigmagor e7a5d67
Add: exceptions.py
Sigmagor 61b9a94
Add: config.py
Sigmagor 47c5fc9
Change: changed host to 8000
Sigmagor 7653abb
Add: security.py
Sigmagor 96bf36e
Add: src/core
Sigmagor e06604d
Add: src/domain
Sigmagor 40317e2
Add: src/schemes
Sigmagor 6c09046
Add: src/services
Sigmagor 37c890a
Add: src/*.py
Sigmagor e457057
Add: tests
Sigmagor 519a298
Add: Readme.md
Sigmagor 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -100,6 +100,7 @@ helm/charts/ | |
|
|
||
| # CMake и сборка | ||
| CMakeCache.txt | ||
| CMakeLists.txt | ||
| CMakeFiles/ | ||
| CMakeScripts/ | ||
| Makefile | ||
|
|
||
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
This file was deleted.
Oops, something went wrong.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
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,2 @@ | ||
| """auth-service - microservice for authentication & authorization""" | ||
| __version__ = "0.1.0" |
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 @@ | ||
| """API: HTTP & gRPC interfaces""" |
File renamed without changes.
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 @@ | ||
| """gRPC API""" |
Empty file.
File renamed without changes.
Empty file.
File renamed without changes.
Empty file.
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 @@ | ||
| """HTTP API""" |
File renamed without changes.
File renamed without changes.
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 @@ | ||
| """Core module: configuration, security & exceptions""" |
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,61 @@ | ||||||||||||||||
| from functools import lru_cache | ||||||||||||||||
| from pydantic import PostgresDsn, RedisDsn, field_validator | ||||||||||||||||
| from pydantic_settings import BaseSettings, SettingsConfigDict | ||||||||||||||||
|
|
||||||||||||||||
|
|
||||||||||||||||
| class Settings(BaseSettings): | ||||||||||||||||
| model_config = SettingsConfigDict( | ||||||||||||||||
| env_file=".env", | ||||||||||||||||
| env_file_encoding="utf-8", | ||||||||||||||||
| case_sensitive=False, | ||||||||||||||||
| ) | ||||||||||||||||
|
|
||||||||||||||||
| # App | ||||||||||||||||
| APP_NAME: str = "auth-service" | ||||||||||||||||
| APP_ENV: str = "development" | ||||||||||||||||
| DEBUG: bool = False | ||||||||||||||||
|
|
||||||||||||||||
| # HTTP Server | ||||||||||||||||
| HTTP_HOST: str = "0.0.0.0" | ||||||||||||||||
| HTTP_PORT: int = 8000 | ||||||||||||||||
|
|
||||||||||||||||
| # gRPC Server | ||||||||||||||||
| GRPC_HOST: str = "0.0.0.0" | ||||||||||||||||
| GRPC_PORT: int = 50051 | ||||||||||||||||
|
|
||||||||||||||||
| # JWT | ||||||||||||||||
| JWT_SECRET_KEY: str | ||||||||||||||||
| JWT_ALGORITHM: str = "HS256" | ||||||||||||||||
| JWT_ACCESS_TOKEN_EXPIRE_MINUTES: int = 30 | ||||||||||||||||
| JWT_REFRESH_TOKEN_EXPIRE_DAYS: int = 7 | ||||||||||||||||
|
|
||||||||||||||||
| # PostgreSQL | ||||||||||||||||
| POSTGRES_DSN: PostgresDsn | ||||||||||||||||
|
|
||||||||||||||||
| # Redis | ||||||||||||||||
| REDIS_DSN: RedisDsn | ||||||||||||||||
|
|
||||||||||||||||
| # Kafka | ||||||||||||||||
| KAFKA_BOOTSTRAP_SERVERS: str | ||||||||||||||||
| KAFKA_TOPIC_USER_EVENTS: str = "user-events" | ||||||||||||||||
| KAFKA_CONSUMER_GROUP_ID: str = "auth-service-group" | ||||||||||||||||
|
|
||||||||||||||||
| # Password hashing | ||||||||||||||||
| BCRYPT_ROUNDS: int = 12 | ||||||||||||||||
|
|
||||||||||||||||
| @field_validator("APP_ENV") | ||||||||||||||||
| @classmethod | ||||||||||||||||
| def validate_app_env(cls, v: str) -> str: | ||||||||||||||||
| allowed = {"development", "staging", "production"} | ||||||||||||||||
| if v not in allowed: | ||||||||||||||||
| raise ValueError(f"APP_ENV must be one of {allowed}") | ||||||||||||||||
| return v | ||||||||||||||||
|
Comment on lines
+46
to
+52
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||||||||
|
|
||||||||||||||||
| @property | ||||||||||||||||
| def is_production(self) -> bool: | ||||||||||||||||
| return self.APP_ENV == "production" | ||||||||||||||||
|
|
||||||||||||||||
|
|
||||||||||||||||
| @lru_cache | ||||||||||||||||
| def get_settings() -> Settings: | ||||||||||||||||
| return Settings() | ||||||||||||||||
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,70 @@ | ||
| from http import HTTPStatus | ||
|
|
||
|
|
||
| class AppException(Exception): | ||
| """Base application exception.""" | ||
|
|
||
| status_code: int = HTTPStatus.INTERNAL_SERVER_ERROR | ||
| detail: str = "An unexpected error occurred." | ||
|
|
||
| def __init__(self, detail: str | None = None) -> None: | ||
| self.detail = detail or self.__class__.detail | ||
| super().__init__(self.detail) | ||
|
|
||
|
|
||
| # --- Auth --- | ||
|
|
||
| class AuthException(AppException): | ||
| """Base auth exception.""" | ||
|
|
||
|
|
||
| class InvalidCredentialsError(AuthException): | ||
| status_code = HTTPStatus.UNAUTHORIZED | ||
| detail = "Invalid email or password." | ||
|
|
||
|
|
||
| class InvalidTokenError(AuthException): | ||
| status_code = HTTPStatus.UNAUTHORIZED | ||
| detail = "Token is invalid or has expired." | ||
|
|
||
|
|
||
| class TokenExpiredError(AuthException): | ||
| status_code = HTTPStatus.UNAUTHORIZED | ||
| detail = "Token has expired." | ||
|
|
||
|
|
||
| class InsufficientPermissionsError(AuthException): | ||
| status_code = HTTPStatus.FORBIDDEN | ||
| detail = "You do not have permission to perform this action." | ||
|
|
||
|
|
||
| # --- User --- | ||
|
|
||
| class UserException(AppException): | ||
| """Base user exception.""" | ||
|
|
||
|
|
||
| class UserNotFoundError(UserException): | ||
| status_code = HTTPStatus.NOT_FOUND | ||
| detail = "User not found." | ||
|
|
||
|
|
||
| class UserAlreadyExistsError(UserException): | ||
| status_code = HTTPStatus.CONFLICT | ||
| detail = "A user with this email already exists." | ||
|
|
||
|
|
||
| class UserInactiveError(UserException): | ||
| status_code = HTTPStatus.FORBIDDEN | ||
| detail = "This user account is inactive." | ||
|
|
||
|
|
||
| # --- Validation --- | ||
|
|
||
| class ValidationException(AppException): | ||
| status_code = HTTPStatus.UNPROCESSABLE_ENTITY | ||
| detail = "Validation failed." | ||
|
|
||
|
|
||
| class WeakPasswordError(ValidationException): | ||
| detail = "Password does not meet the minimum security requirements." |
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,91 @@ | ||
| from datetime import datetime, timedelta, timezone | ||
| from typing import Any | ||
| from uuid import UUID | ||
|
|
||
| import bcrypt | ||
| from jose import JWTError, jwt | ||
|
|
||
| from src.core.config import get_settings | ||
| from src.core.exceptions import InvalidTokenError, TokenExpiredError | ||
|
|
||
| settings = get_settings() | ||
|
|
||
|
|
||
| # PASSWORD HASHING | ||
| def hash_password(plain: str) -> str: | ||
| """Return a bcrypt hash of *plain*.""" | ||
| salt = bcrypt.gensalt(rounds=settings.BCRYPT_ROUNDS) | ||
| return bcrypt.hashpw(plain.encode(), salt).decode() | ||
|
|
||
|
|
||
| def verify_password(plain: str, hashed: str) -> bool: | ||
| """Return True if *plain* matches *hashed*.""" | ||
| return bcrypt.checkpw(plain.encode(), hashed.encode()) | ||
|
|
||
|
|
||
| # JWT | ||
| _ACCESS = "access" | ||
| _REFRESH = "refresh" | ||
|
|
||
|
|
||
| def _create_token( | ||
| subject: str | UUID, | ||
| token_type: str, | ||
| expires_delta: timedelta, | ||
| extra_claims: dict[str, Any] | None = None, | ||
| ) -> str: | ||
| now = datetime.now(tz=timezone.utc) | ||
| payload: dict[str, Any] = { | ||
| "sub": str(subject), | ||
| "type": token_type, | ||
| "iat": now, | ||
| "exp": now + expires_delta, | ||
| } | ||
| if extra_claims: | ||
| payload.update(extra_claims) | ||
| return jwt.encode(payload, settings.JWT_SECRET_KEY, algorithm=settings.JWT_ALGORITHM) | ||
|
|
||
|
|
||
| def create_access_token(user_id: str | UUID, extra_claims: dict[str, Any] | None = None) -> str: | ||
| return _create_token( | ||
| subject=user_id, | ||
| token_type=_ACCESS, | ||
| expires_delta=timedelta(minutes=settings.JWT_ACCESS_TOKEN_EXPIRE_MINUTES), | ||
| extra_claims=extra_claims, | ||
| ) | ||
|
|
||
|
|
||
| def create_refresh_token(user_id: str | UUID) -> str: | ||
| return _create_token( | ||
| subject=user_id, | ||
| token_type=_REFRESH, | ||
| expires_delta=timedelta(days=settings.JWT_REFRESH_TOKEN_EXPIRE_DAYS), | ||
| ) | ||
|
|
||
|
|
||
| def decode_token(token: str, expected_type: str = _ACCESS) -> dict[str, Any]: | ||
| """ | ||
| Decode and validate *token*. | ||
| Raises: | ||
| TokenExpiredError: if the token is past its expiry. | ||
| InvalidTokenError: if the token is malformed or has an unexpected type. | ||
| """ | ||
| try: | ||
| payload = jwt.decode( | ||
| token, | ||
| settings.JWT_SECRET_KEY, | ||
| algorithms=[settings.JWT_ALGORITHM], | ||
| ) | ||
| except jwt.ExpiredSignatureError: | ||
| raise TokenExpiredError() | ||
| except JWTError: | ||
| raise InvalidTokenError() | ||
|
|
||
| if payload.get("type") != expected_type: | ||
| raise InvalidTokenError("Unexpected token type.") | ||
|
|
||
| return payload | ||
|
|
||
|
|
||
| def decode_refresh_token(token: str) -> dict[str, Any]: | ||
| return decode_token(token, expected_type=_REFRESH) |
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,5 @@ | ||
| """Domain: Business entities""" | ||
|
|
||
| from src.domain.entities import RefreshToken, User, UserRole, UserStatus | ||
|
|
||
| __all__ = ["User", "UserRole", "UserStatus", "RefreshToken"] |
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.