PyArch-CLI 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pyarch/__init__.py +1 -0
- pyarch/cli/__init__.py +1 -0
- pyarch/cli/add.py +27 -0
- pyarch/cli/app.py +83 -0
- pyarch/cli/common.py +28 -0
- pyarch/cli/generate.py +34 -0
- pyarch/config/__init__.py +1 -0
- pyarch/config/manifest.py +161 -0
- pyarch/config/models.py +51 -0
- pyarch/generators/__init__.py +1 -0
- pyarch/generators/common/__init__.py +1 -0
- pyarch/generators/common/commands.py +6 -0
- pyarch/generators/common/filesystem.py +55 -0
- pyarch/generators/common/gitignore.py +65 -0
- pyarch/generators/common/renderer.py +32 -0
- pyarch/generators/integration/__init__.py +1 -0
- pyarch/generators/integration/auth.py +158 -0
- pyarch/generators/module/__init__.py +1 -0
- pyarch/generators/module/layered.py +186 -0
- pyarch/generators/project/__init__.py +1 -0
- pyarch/generators/project/base.py +52 -0
- pyarch/generators/project/layered.py +167 -0
- pyarch/main.py +9 -0
- pyarch/services/__init__.py +1 -0
- pyarch/services/add_integration.py +37 -0
- pyarch/services/create_module.py +46 -0
- pyarch/services/create_project.py +20 -0
- pyarch/templates/layered/alembic_env.py.j2 +58 -0
- pyarch/templates/layered/auth/config.py.j2 +30 -0
- pyarch/templates/layered/auth/dependencies.py.j2 +75 -0
- pyarch/templates/layered/auth/refresh_session_model.py.j2 +31 -0
- pyarch/templates/layered/auth/routes.py.j2 +51 -0
- pyarch/templates/layered/auth/schemas.py.j2 +31 -0
- pyarch/templates/layered/auth/service.py.j2 +160 -0
- pyarch/templates/layered/auth/tokens.py.j2 +29 -0
- pyarch/templates/layered/auth/user_model.py.j2 +52 -0
- pyarch/templates/layered/auth/utils.py.j2 +70 -0
- pyarch/templates/layered/config.py.j2 +14 -0
- pyarch/templates/layered/env.example.j2 +7 -0
- pyarch/templates/layered/models_init.py.j2 +5 -0
- pyarch/templates/layered/module/module_model.py.j2 +25 -0
- pyarch/templates/layered/module/module_repo.py.j2 +49 -0
- pyarch/templates/layered/module/module_router.py.j2 +87 -0
- pyarch/templates/layered/module/module_router_protected.py.j2 +97 -0
- pyarch/templates/layered/module/module_schema.py.j2 +30 -0
- pyarch/templates/layered/module/module_service.py.j2 +76 -0
- pyarch/templates/layered/mongodb/config.py.j2 +15 -0
- pyarch/templates/layered/mongodb/conftest.py.j2 +36 -0
- pyarch/templates/layered/mongodb/env.example.j2 +2 -0
- pyarch/templates/layered/mongodb/module/module_model.py.j2 +11 -0
- pyarch/templates/layered/mongodb/module/module_repo.py.j2 +99 -0
- pyarch/templates/layered/mongodb/module/module_router.py.j2 +97 -0
- pyarch/templates/layered/mongodb/module/module_service.py.j2 +69 -0
- pyarch/templates/layered/mongodb/session.py.j2 +14 -0
- pyarch/templates/layered/router.py.j2 +8 -0
- pyarch/templates/layered/session.py.j2 +33 -0
- pyarch/templates/project/base/README.md.j2 +22 -0
- pyarch/templates/project/base/conftest.py.j2 +101 -0
- pyarch/templates/project/base/main.py.j2 +11 -0
- pyarch_cli-0.1.0.dist-info/METADATA +378 -0
- pyarch_cli-0.1.0.dist-info/RECORD +64 -0
- pyarch_cli-0.1.0.dist-info/WHEEL +4 -0
- pyarch_cli-0.1.0.dist-info/entry_points.txt +2 -0
- pyarch_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
from logging.config import fileConfig
|
|
2
|
+
|
|
3
|
+
from alembic import context
|
|
4
|
+
from sqlalchemy import engine_from_config, pool
|
|
5
|
+
|
|
6
|
+
from app.core.config import settings
|
|
7
|
+
from app.db.session import Base
|
|
8
|
+
import app.models # noqa: F401
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
config = context.config
|
|
12
|
+
|
|
13
|
+
if config.config_file_name is not None:
|
|
14
|
+
fileConfig(config.config_file_name)
|
|
15
|
+
|
|
16
|
+
config.set_main_option(
|
|
17
|
+
"sqlalchemy.url",
|
|
18
|
+
settings.database_url.replace("%", "%%"),
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
target_metadata = Base.metadata
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def run_migrations_offline() -> None:
|
|
25
|
+
context.configure(
|
|
26
|
+
url=config.get_main_option("sqlalchemy.url"),
|
|
27
|
+
target_metadata=target_metadata,
|
|
28
|
+
literal_binds=True,
|
|
29
|
+
dialect_opts={"paramstyle": "named"},
|
|
30
|
+
compare_type=True,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
with context.begin_transaction():
|
|
34
|
+
context.run_migrations()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def run_migrations_online() -> None:
|
|
38
|
+
connectable = engine_from_config(
|
|
39
|
+
config.get_section(config.config_ini_section, {}),
|
|
40
|
+
prefix="sqlalchemy.",
|
|
41
|
+
poolclass=pool.NullPool,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
with connectable.connect() as connection:
|
|
45
|
+
context.configure(
|
|
46
|
+
connection=connection,
|
|
47
|
+
target_metadata=target_metadata,
|
|
48
|
+
compare_type=True,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
with context.begin_transaction():
|
|
52
|
+
context.run_migrations()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
if context.is_offline_mode():
|
|
56
|
+
run_migrations_offline()
|
|
57
|
+
else:
|
|
58
|
+
run_migrations_online()
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
|
|
3
|
+
from pydantic import BaseModel, Field
|
|
4
|
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
BASE_DIR = Path(__file__).resolve().parents[2]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class AuthJWTSettings(BaseModel):
|
|
11
|
+
public_key_path: Path = BASE_DIR / "certs" / "public.pem"
|
|
12
|
+
private_key_path: Path = BASE_DIR / "certs" / "private.pem"
|
|
13
|
+
algorithm: str = "RS256"
|
|
14
|
+
access_token_expire_minutes: int = 15
|
|
15
|
+
refresh_token_expire_days: int = 30
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Settings(BaseSettings):
|
|
19
|
+
database_url: str
|
|
20
|
+
auth_jwt: AuthJWTSettings = Field(default_factory=AuthJWTSettings)
|
|
21
|
+
|
|
22
|
+
model_config = SettingsConfigDict(
|
|
23
|
+
env_file=".env",
|
|
24
|
+
env_file_encoding="utf-8",
|
|
25
|
+
env_nested_delimiter="__",
|
|
26
|
+
extra="ignore",
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
settings = Settings() # type: ignore[call-arg]
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
from fastapi import Depends, HTTPException, status
|
|
4
|
+
from fastapi.security import OAuth2PasswordBearer
|
|
5
|
+
from jwt.exceptions import InvalidTokenError
|
|
6
|
+
from sqlalchemy.orm import Session
|
|
7
|
+
|
|
8
|
+
from app.auth import utils as auth_utils
|
|
9
|
+
from app.db.session import get_db
|
|
10
|
+
from app.models.user import User, UserRole
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def invalid_token_error() -> HTTPException:
|
|
17
|
+
return HTTPException(
|
|
18
|
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
19
|
+
detail="Invalid token",
|
|
20
|
+
headers={"WWW-Authenticate": "Bearer"},
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def get_current_token_payload(token: str = Depends(oauth2_scheme)) -> dict[str, Any]:
|
|
25
|
+
try:
|
|
26
|
+
payload = auth_utils.decode_jwt(token=token)
|
|
27
|
+
except InvalidTokenError as error:
|
|
28
|
+
raise invalid_token_error() from error
|
|
29
|
+
|
|
30
|
+
if payload.get("type") != "access":
|
|
31
|
+
raise invalid_token_error()
|
|
32
|
+
|
|
33
|
+
return payload
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def get_current_user(
|
|
37
|
+
payload: dict[str, Any] = Depends(get_current_token_payload),
|
|
38
|
+
db: Session = Depends(get_db),
|
|
39
|
+
) -> User:
|
|
40
|
+
user_id = payload.get("sub")
|
|
41
|
+
|
|
42
|
+
if user_id is None:
|
|
43
|
+
raise invalid_token_error()
|
|
44
|
+
|
|
45
|
+
try:
|
|
46
|
+
user = db.get(User, int(user_id))
|
|
47
|
+
except (TypeError, ValueError) as error:
|
|
48
|
+
raise invalid_token_error() from error
|
|
49
|
+
|
|
50
|
+
if not user:
|
|
51
|
+
raise invalid_token_error()
|
|
52
|
+
|
|
53
|
+
return user
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def get_current_active_user(
|
|
57
|
+
user: User = Depends(get_current_user),
|
|
58
|
+
) -> User:
|
|
59
|
+
if not user.is_active:
|
|
60
|
+
raise HTTPException(
|
|
61
|
+
status_code=status.HTTP_403_FORBIDDEN,
|
|
62
|
+
detail="User inactive",
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
return user
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def require_admin(user: User = Depends(get_current_active_user)) -> User:
|
|
69
|
+
if user.role != UserRole.ADMIN:
|
|
70
|
+
raise HTTPException(
|
|
71
|
+
status_code=status.HTTP_403_FORBIDDEN,
|
|
72
|
+
detail="Admin privileges required",
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
return user
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
|
|
3
|
+
from sqlalchemy import DateTime, ForeignKey, String, func
|
|
4
|
+
from sqlalchemy.orm import Mapped, mapped_column
|
|
5
|
+
|
|
6
|
+
from app.db.session import Base
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class RefreshSession(Base):
|
|
10
|
+
__tablename__ = "refresh_sessions"
|
|
11
|
+
|
|
12
|
+
id: Mapped[int] = mapped_column(primary_key=True)
|
|
13
|
+
jti: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)
|
|
14
|
+
user_id: Mapped[int] = mapped_column(
|
|
15
|
+
ForeignKey("users.id", ondelete="CASCADE"),
|
|
16
|
+
nullable=False,
|
|
17
|
+
index=True,
|
|
18
|
+
)
|
|
19
|
+
expires_at: Mapped[datetime] = mapped_column(
|
|
20
|
+
DateTime(timezone=True),
|
|
21
|
+
nullable=False,
|
|
22
|
+
)
|
|
23
|
+
revoked_at: Mapped[datetime | None] = mapped_column(
|
|
24
|
+
DateTime(timezone=True),
|
|
25
|
+
nullable=True,
|
|
26
|
+
)
|
|
27
|
+
created_at: Mapped[datetime] = mapped_column(
|
|
28
|
+
DateTime(timezone=True),
|
|
29
|
+
server_default=func.now(),
|
|
30
|
+
nullable=False,
|
|
31
|
+
)
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
from typing import Annotated
|
|
2
|
+
|
|
3
|
+
from fastapi import APIRouter, Depends, Form, status
|
|
4
|
+
from sqlalchemy import select
|
|
5
|
+
from sqlalchemy.orm import Session
|
|
6
|
+
|
|
7
|
+
from app.auth import service as auth_service
|
|
8
|
+
from app.auth.dependencies import get_current_active_user, require_admin
|
|
9
|
+
from app.auth.schemas import RefreshToken, TokenPair, UserCreate, UserRead
|
|
10
|
+
from app.db.session import get_db
|
|
11
|
+
from app.models.user import User
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
router = APIRouter(prefix="/auth", tags=["auth"])
|
|
15
|
+
DbSession = Annotated[Session, Depends(get_db)]
|
|
16
|
+
CurrentUser = Annotated[User, Depends(get_current_active_user)]
|
|
17
|
+
AdminUser = Annotated[User, Depends(require_admin)]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@router.post("/register", response_model=UserRead, status_code=status.HTTP_201_CREATED)
|
|
21
|
+
def register_user(payload: UserCreate, db: DbSession) -> User:
|
|
22
|
+
return auth_service.register_user(payload, db)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@router.post("/login", response_model=TokenPair)
|
|
26
|
+
def login_user(
|
|
27
|
+
username: Annotated[str, Form()],
|
|
28
|
+
password: Annotated[str, Form()],
|
|
29
|
+
db: DbSession,
|
|
30
|
+
) -> TokenPair:
|
|
31
|
+
return auth_service.login_user(username, password, db)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@router.post("/logout")
|
|
35
|
+
def logout_user(payload: RefreshToken, db: DbSession) -> dict[str, str]:
|
|
36
|
+
return auth_service.logout_user(payload.refresh_token, db)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@router.post("/refresh", response_model=TokenPair)
|
|
40
|
+
def refresh_tokens(payload: RefreshToken, db: DbSession) -> TokenPair:
|
|
41
|
+
return auth_service.refresh_tokens(payload.refresh_token, db)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@router.get("/users/me", response_model=UserRead)
|
|
45
|
+
def get_me(user: CurrentUser) -> User:
|
|
46
|
+
return user
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@router.get("/users", response_model=list[UserRead])
|
|
50
|
+
def get_all_users(_user: AdminUser, db: DbSession) -> list[User]:
|
|
51
|
+
return list(db.scalars(select(User).order_by(User.id)).all())
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
|
|
3
|
+
from pydantic import BaseModel, ConfigDict, EmailStr, Field
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class UserCreate(BaseModel):
|
|
7
|
+
username: str = Field(min_length=3, max_length=55)
|
|
8
|
+
email: EmailStr
|
|
9
|
+
password: str = Field(min_length=6)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class UserRead(BaseModel):
|
|
13
|
+
model_config = ConfigDict(from_attributes=True)
|
|
14
|
+
|
|
15
|
+
id: int
|
|
16
|
+
username: str
|
|
17
|
+
email: str
|
|
18
|
+
role: str
|
|
19
|
+
is_active: bool
|
|
20
|
+
created_at: datetime
|
|
21
|
+
updated_at: datetime
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class RefreshToken(BaseModel):
|
|
25
|
+
refresh_token: str
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class TokenPair(BaseModel):
|
|
29
|
+
access_token: str
|
|
30
|
+
refresh_token: str
|
|
31
|
+
token_type: str = "Bearer"
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
from datetime import datetime, timezone
|
|
2
|
+
|
|
3
|
+
from fastapi import HTTPException, status
|
|
4
|
+
from jwt.exceptions import InvalidTokenError
|
|
5
|
+
from sqlalchemy import select
|
|
6
|
+
from sqlalchemy.orm import Session
|
|
7
|
+
|
|
8
|
+
from app.auth import utils as auth_utils
|
|
9
|
+
from app.auth.schemas import TokenPair, UserCreate
|
|
10
|
+
from app.auth.tokens import create_access_token, create_refresh_token
|
|
11
|
+
from app.models.refresh_session import RefreshSession
|
|
12
|
+
from app.models.user import User
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def invalid_token_error() -> HTTPException:
|
|
16
|
+
return HTTPException(
|
|
17
|
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
18
|
+
detail="Invalid token",
|
|
19
|
+
headers={"WWW-Authenticate": "Bearer"},
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def decode_refresh_payload(refresh_token: str) -> dict:
|
|
24
|
+
try:
|
|
25
|
+
token_payload = auth_utils.decode_jwt(token=refresh_token)
|
|
26
|
+
except InvalidTokenError as error:
|
|
27
|
+
raise invalid_token_error() from error
|
|
28
|
+
|
|
29
|
+
if token_payload.get("type") != "refresh":
|
|
30
|
+
raise invalid_token_error()
|
|
31
|
+
|
|
32
|
+
if token_payload.get("jti") is None:
|
|
33
|
+
raise invalid_token_error()
|
|
34
|
+
|
|
35
|
+
return token_payload
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def get_refresh_session(db: Session, jti: str) -> RefreshSession:
|
|
39
|
+
refresh_session = db.scalar(select(RefreshSession).where(RefreshSession.jti == jti))
|
|
40
|
+
|
|
41
|
+
if not refresh_session:
|
|
42
|
+
raise invalid_token_error()
|
|
43
|
+
|
|
44
|
+
return refresh_session
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def create_token_pair(user: User, db: Session) -> TokenPair:
|
|
48
|
+
access_token = create_access_token(user)
|
|
49
|
+
refresh_token, refresh_jti, refresh_expires_at = create_refresh_token(user)
|
|
50
|
+
|
|
51
|
+
refresh_session = RefreshSession(
|
|
52
|
+
jti=refresh_jti,
|
|
53
|
+
user_id=user.id,
|
|
54
|
+
expires_at=refresh_expires_at,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
db.add(refresh_session)
|
|
58
|
+
db.commit()
|
|
59
|
+
|
|
60
|
+
return TokenPair(access_token=access_token, refresh_token=refresh_token)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def register_user(payload: UserCreate, db: Session) -> User:
|
|
64
|
+
existing_user = db.scalar(
|
|
65
|
+
select(User).where(
|
|
66
|
+
(User.username == payload.username) | (User.email == payload.email)
|
|
67
|
+
)
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
if existing_user:
|
|
71
|
+
raise HTTPException(
|
|
72
|
+
status_code=status.HTTP_409_CONFLICT,
|
|
73
|
+
detail="Username or email are already taken",
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
user = User(
|
|
77
|
+
username=payload.username,
|
|
78
|
+
email=payload.email,
|
|
79
|
+
hashed_password=auth_utils.hash_password(payload.password),
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
db.add(user)
|
|
83
|
+
db.commit()
|
|
84
|
+
db.refresh(user)
|
|
85
|
+
|
|
86
|
+
return user
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def authenticate_user(username: str, password: str, db: Session) -> User:
|
|
90
|
+
user = db.scalar(select(User).where(User.username == username))
|
|
91
|
+
|
|
92
|
+
if not user:
|
|
93
|
+
raise HTTPException(
|
|
94
|
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
95
|
+
detail="Invalid credentials",
|
|
96
|
+
headers={"WWW-Authenticate": "Bearer"},
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
if not auth_utils.validate_password(password, user.hashed_password):
|
|
100
|
+
raise HTTPException(
|
|
101
|
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
102
|
+
detail="Invalid credentials",
|
|
103
|
+
headers={"WWW-Authenticate": "Bearer"},
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
if not user.is_active:
|
|
107
|
+
raise HTTPException(
|
|
108
|
+
status_code=status.HTTP_403_FORBIDDEN,
|
|
109
|
+
detail="User inactive",
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
return user
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def login_user(username: str, password: str, db: Session) -> TokenPair:
|
|
116
|
+
user = authenticate_user(username, password, db)
|
|
117
|
+
return create_token_pair(user, db)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def logout_user(refresh_token: str, db: Session) -> dict[str, str]:
|
|
121
|
+
token_payload = decode_refresh_payload(refresh_token)
|
|
122
|
+
refresh_session = get_refresh_session(db, token_payload["jti"])
|
|
123
|
+
|
|
124
|
+
refresh_session.revoked_at = datetime.now(timezone.utc)
|
|
125
|
+
db.commit()
|
|
126
|
+
|
|
127
|
+
return {"message": "Logged out"}
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def refresh_tokens(refresh_token: str, db: Session) -> TokenPair:
|
|
131
|
+
token_payload = decode_refresh_payload(refresh_token)
|
|
132
|
+
refresh_session = get_refresh_session(db, token_payload["jti"])
|
|
133
|
+
|
|
134
|
+
if refresh_session.revoked_at is not None:
|
|
135
|
+
raise invalid_token_error()
|
|
136
|
+
|
|
137
|
+
expires_at = refresh_session.expires_at
|
|
138
|
+
if expires_at.tzinfo is None:
|
|
139
|
+
expires_at = expires_at.replace(tzinfo=timezone.utc)
|
|
140
|
+
|
|
141
|
+
now = datetime.now(timezone.utc)
|
|
142
|
+
if expires_at < now:
|
|
143
|
+
raise invalid_token_error()
|
|
144
|
+
|
|
145
|
+
user_id = token_payload.get("sub")
|
|
146
|
+
|
|
147
|
+
if user_id is None:
|
|
148
|
+
raise invalid_token_error()
|
|
149
|
+
|
|
150
|
+
try:
|
|
151
|
+
user = db.get(User, int(user_id))
|
|
152
|
+
except (TypeError, ValueError) as error:
|
|
153
|
+
raise invalid_token_error() from error
|
|
154
|
+
|
|
155
|
+
if not user or not user.is_active:
|
|
156
|
+
raise invalid_token_error()
|
|
157
|
+
|
|
158
|
+
refresh_session.revoked_at = now
|
|
159
|
+
|
|
160
|
+
return create_token_pair(user, db)
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
from datetime import datetime, timedelta, timezone
|
|
2
|
+
from uuid import uuid4
|
|
3
|
+
|
|
4
|
+
from app.auth import utils as auth_utils
|
|
5
|
+
from app.core.config import settings
|
|
6
|
+
from app.models.user import User
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def create_access_token(user: User) -> str:
|
|
10
|
+
payload = {
|
|
11
|
+
"sub": str(user.id),
|
|
12
|
+
"type": "access",
|
|
13
|
+
"username": user.username,
|
|
14
|
+
"email": user.email,
|
|
15
|
+
"role": user.role.value,
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
return auth_utils.encode_jwt(payload)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def create_refresh_token(user: User) -> tuple[str, str, datetime]:
|
|
22
|
+
jti = str(uuid4())
|
|
23
|
+
expire_timedelta = timedelta(days=settings.auth_jwt.refresh_token_expire_days)
|
|
24
|
+
expires_at = datetime.now(timezone.utc) + expire_timedelta
|
|
25
|
+
|
|
26
|
+
payload = {"sub": str(user.id), "type": "refresh", "jti": jti}
|
|
27
|
+
token = auth_utils.encode_jwt(payload, expire_timedelta=expire_timedelta)
|
|
28
|
+
|
|
29
|
+
return token, jti, expires_at
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
from enum import Enum
|
|
3
|
+
|
|
4
|
+
from sqlalchemy import DateTime, Enum as SAEnum, String, func
|
|
5
|
+
from sqlalchemy.orm import Mapped, mapped_column
|
|
6
|
+
|
|
7
|
+
from app.db.session import Base
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class UserRole(str, Enum):
|
|
11
|
+
USER = "user"
|
|
12
|
+
ADMIN = "admin"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class User(Base):
|
|
16
|
+
__tablename__ = "users"
|
|
17
|
+
|
|
18
|
+
id: Mapped[int] = mapped_column(primary_key=True)
|
|
19
|
+
username: Mapped[str] = mapped_column(
|
|
20
|
+
String(55),
|
|
21
|
+
nullable=False,
|
|
22
|
+
unique=True,
|
|
23
|
+
index=True,
|
|
24
|
+
)
|
|
25
|
+
email: Mapped[str] = mapped_column(
|
|
26
|
+
String(255),
|
|
27
|
+
nullable=False,
|
|
28
|
+
unique=True,
|
|
29
|
+
index=True,
|
|
30
|
+
)
|
|
31
|
+
hashed_password: Mapped[str] = mapped_column(String(255), nullable=False)
|
|
32
|
+
role: Mapped[UserRole] = mapped_column(
|
|
33
|
+
SAEnum(
|
|
34
|
+
UserRole,
|
|
35
|
+
name="user_role",
|
|
36
|
+
values_callable=lambda enum_cls: [item.value for item in enum_cls],
|
|
37
|
+
),
|
|
38
|
+
nullable=False,
|
|
39
|
+
default=UserRole.USER,
|
|
40
|
+
)
|
|
41
|
+
is_active: Mapped[bool] = mapped_column(nullable=False, default=True)
|
|
42
|
+
created_at: Mapped[datetime] = mapped_column(
|
|
43
|
+
DateTime(timezone=True),
|
|
44
|
+
server_default=func.now(),
|
|
45
|
+
nullable=False,
|
|
46
|
+
)
|
|
47
|
+
updated_at: Mapped[datetime] = mapped_column(
|
|
48
|
+
DateTime(timezone=True),
|
|
49
|
+
server_default=func.now(),
|
|
50
|
+
onupdate=func.now(),
|
|
51
|
+
nullable=False,
|
|
52
|
+
)
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
from datetime import datetime, timedelta, timezone
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
import bcrypt
|
|
5
|
+
import jwt
|
|
6
|
+
from jwt.exceptions import InvalidTokenError
|
|
7
|
+
|
|
8
|
+
from app.core.config import settings
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def encode_jwt(
|
|
12
|
+
payload: dict[str, Any],
|
|
13
|
+
private_key: str | None = None,
|
|
14
|
+
algorithm: str | None = None,
|
|
15
|
+
expire_minutes: int | None = None,
|
|
16
|
+
expire_timedelta: timedelta | None = None,
|
|
17
|
+
) -> str:
|
|
18
|
+
key = (
|
|
19
|
+
private_key
|
|
20
|
+
if private_key is not None
|
|
21
|
+
else settings.auth_jwt.private_key_path.read_text(encoding="utf-8")
|
|
22
|
+
)
|
|
23
|
+
token_algorithm = algorithm or settings.auth_jwt.algorithm
|
|
24
|
+
access_expire_minutes = (
|
|
25
|
+
expire_minutes
|
|
26
|
+
if expire_minutes is not None
|
|
27
|
+
else settings.auth_jwt.access_token_expire_minutes
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
to_encode = payload.copy()
|
|
31
|
+
now = datetime.now(timezone.utc)
|
|
32
|
+
expire = now + (
|
|
33
|
+
expire_timedelta or timedelta(minutes=access_expire_minutes)
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
to_encode.update(exp=expire, iat=now)
|
|
37
|
+
return jwt.encode(to_encode, key, algorithm=token_algorithm)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def decode_jwt(
|
|
41
|
+
token: str | bytes,
|
|
42
|
+
public_key: str | None = None,
|
|
43
|
+
algorithm: str | None = None,
|
|
44
|
+
) -> dict[str, Any]:
|
|
45
|
+
key = (
|
|
46
|
+
public_key
|
|
47
|
+
if public_key is not None
|
|
48
|
+
else settings.auth_jwt.public_key_path.read_text(encoding="utf-8")
|
|
49
|
+
)
|
|
50
|
+
token_algorithm = algorithm or settings.auth_jwt.algorithm
|
|
51
|
+
|
|
52
|
+
decoded = jwt.decode(token, key, algorithms=[token_algorithm])
|
|
53
|
+
|
|
54
|
+
if not isinstance(decoded, dict):
|
|
55
|
+
raise InvalidTokenError("Invalid token payload")
|
|
56
|
+
|
|
57
|
+
return decoded
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def hash_password(password: str) -> str:
|
|
61
|
+
salt = bcrypt.gensalt()
|
|
62
|
+
hashed = bcrypt.hashpw(password.encode(), salt)
|
|
63
|
+
return hashed.decode("utf-8")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def validate_password(password: str, hashed_password: str) -> bool:
|
|
67
|
+
return bcrypt.checkpw(
|
|
68
|
+
password=password.encode(),
|
|
69
|
+
hashed_password=hashed_password.encode("utf-8"),
|
|
70
|
+
)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class Settings(BaseSettings):
|
|
5
|
+
database_url: str
|
|
6
|
+
|
|
7
|
+
model_config = SettingsConfigDict(
|
|
8
|
+
env_file=".env",
|
|
9
|
+
env_file_encoding="utf-8",
|
|
10
|
+
extra="ignore",
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
settings = Settings() # type: ignore[call-arg]
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{% if database == "postgres" -%}
|
|
2
|
+
DATABASE_URL=postgresql+psycopg://postgres:postgres@localhost:5432/app
|
|
3
|
+
TEST_DATABASE_URL=postgresql+psycopg://postgres:postgres@localhost:5432/app_test
|
|
4
|
+
{% else -%}
|
|
5
|
+
DATABASE_URL=sqlite:///./app.db
|
|
6
|
+
TEST_DATABASE_URL=sqlite:///./app_test.db
|
|
7
|
+
{% endif %}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
|
|
3
|
+
from sqlalchemy import DateTime, String, func
|
|
4
|
+
from sqlalchemy.orm import Mapped, mapped_column
|
|
5
|
+
|
|
6
|
+
from app.db.session import Base
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class {{ model_name }}(Base):
|
|
10
|
+
__tablename__ = "{{ table_name }}"
|
|
11
|
+
|
|
12
|
+
id: Mapped[int] = mapped_column(primary_key=True)
|
|
13
|
+
title: Mapped[str] = mapped_column(String(55), nullable=False)
|
|
14
|
+
description: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
|
15
|
+
|
|
16
|
+
created_at: Mapped[datetime] = mapped_column(
|
|
17
|
+
DateTime(timezone=True), server_default=func.now(), nullable=False
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
updated_at: Mapped[datetime] = mapped_column(
|
|
21
|
+
DateTime(timezone=True),
|
|
22
|
+
onupdate=func.now(),
|
|
23
|
+
server_default=func.now(),
|
|
24
|
+
nullable=False,
|
|
25
|
+
)
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
from sqlalchemy import select
|
|
4
|
+
from sqlalchemy.orm import Session
|
|
5
|
+
|
|
6
|
+
from app.models.{{ module_name }} import {{ model_name }}
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def add_item(db: Session, values: dict[str, Any]) -> {{ model_name }}:
|
|
10
|
+
item = {{ model_name }}(**values)
|
|
11
|
+
db.add(item)
|
|
12
|
+
db.flush()
|
|
13
|
+
return item
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def get_items(
|
|
17
|
+
db: Session,
|
|
18
|
+
*,
|
|
19
|
+
offset: int = 0,
|
|
20
|
+
limit: int = 100,
|
|
21
|
+
) -> list[{{ model_name }}]:
|
|
22
|
+
statement = (
|
|
23
|
+
select({{ model_name }})
|
|
24
|
+
.order_by({{ model_name }}.id)
|
|
25
|
+
.offset(offset)
|
|
26
|
+
.limit(limit)
|
|
27
|
+
)
|
|
28
|
+
return list(db.scalars(statement).all())
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def get_item(db: Session, item_id: int) -> {{ model_name }} | None:
|
|
32
|
+
return db.get({{ model_name }}, item_id)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def patch_item(
|
|
36
|
+
db: Session,
|
|
37
|
+
item: {{ model_name }},
|
|
38
|
+
values: dict[str, Any],
|
|
39
|
+
) -> {{ model_name }}:
|
|
40
|
+
for field, value in values.items():
|
|
41
|
+
setattr(item, field, value)
|
|
42
|
+
|
|
43
|
+
db.flush()
|
|
44
|
+
return item
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def delete_item(db: Session, item: {{ model_name }}) -> None:
|
|
48
|
+
db.delete(item)
|
|
49
|
+
db.flush()
|