Spaces:
Sleeping
Sleeping
Commit ·
2d2110c
0
Parent(s):
Auth, Login, main , token schema user schema database.py and security.py added
Browse filesFiles changed (21)
- .gitignoreAdded+27
- alembic.iniAdded+149
- alembic/READMEAdded+1
- alembic/env.pyAdded+50
- alembic/script.py.makoAdded+28
- alembic/versions/6f056783c0d8_create_users_table.pyAdded+39
- app/__init__.pyAdded
- app/cores/__init__.pyAdded
- app/cores/config.pyAdded+19
- app/cores/database.pyAdded+19
- app/cores/security.pyAdded+48
- app/main.pyAdded+10
- app/models/__init__.pyAdded
- app/models/user.pyAdded+14
- app/routers/__init__.pyAdded
- app/routers/auth.pyAdded+25
- app/routers/user.pyAdded+33
- app/schemas/__init__.pyAdded
- app/schemas/token.pyAdded+8
- app/schemas/user.pyAdded+15
- requirements.txtAdded
123456789101112131415161718192021222324252627# Environment.env.env.*
# Python__pycache__/*.pyc*.pyo
# Virtual environmentvenv/env/.venv/
# Alembic - keep versions folder but ignore pycalembic/versions/*.pyc
# IDE.vscode/.idea/
# OS.DS_StoreThumbs.db
# Logs*.log123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149# A generic, single database configuration.
[alembic]# path to migration scripts.# this is typically a path given in POSIX (e.g. forward slashes)# format, relative to the token %(here)s which refers to the location of this# ini filescript_location = %(here)s/alembic
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s# Uncomment the line below if you want the files to be prepended with date and time# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file# for all available tokens# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s# Or organize into date-based subdirectories (requires recursive_version_locations = true)# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.# defaults to the current working directory. for multiple paths, the path separator# is defined by "path_separator" below.prepend_sys_path = .
# timezone to use when rendering the date within the migration file# as well as the filename.# If specified, requires the tzdata library which can be installed by adding# `alembic[tz]` to the pip requirements.# string value is passed to ZoneInfo()# leave blank for localtime# timezone =
# max length of characters to apply to the "slug" field# truncate_slug_length = 40
# set to 'true' to run the environment during# the 'revision' command, regardless of autogenerate# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without# a source .py file to be detected as revisions in the# versions/ directory# sourceless = false
# version location specification; This defaults# to <script_location>/versions. When using multiple version# directories, initial revisions must be specified with --version-path.# The path separator used here should be the separator specified by "path_separator"# below.# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
# path_separator; This indicates what character is used to split lists of file# paths, including version_locations and prepend_sys_path within configparser# files such as alembic.ini.# The default rendered in new alembic.ini files is "os", which uses os.pathsep# to provide os-dependent path splitting.## Note that in order to support legacy alembic.ini files, this default does NOT# take place if path_separator is not present in alembic.ini. If this# option is omitted entirely, fallback logic is as follows:## 1. Parsing of the version_locations option falls back to using the legacy# "version_path_separator" key, which if absent then falls back to the legacy# behavior of splitting on spaces and/or commas.# 2. Parsing of the prepend_sys_path option falls back to the legacy# behavior of splitting on spaces, commas, or colons.## Valid values for path_separator are:## path_separator = :# path_separator = ;# path_separator = space# path_separator = newline## Use os.pathsep. Default configuration used for new projects.path_separator = os
# set to 'true' to search source files recursively# in each "version_locations" directory# new in Alembic version 1.10# recursive_version_locations = false
# the output encoding used when revision files# are written from script.py.mako# output_encoding = utf-8
# database URL. This is consumed by the user-maintained env.py script only.# other means of configuring database URLs may be customized within the env.py# file.sqlalchemy.url = driver://user:pass@localhost/dbname
[post_write_hooks]# post_write_hooks defines scripts or Python functions that are run# on newly generated revision scripts. See the documentation for further# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint# hooks = black# black.type = console_scripts# black.entrypoint = black# black.options = -l 79 REVISION_SCRIPT_FILENAME
# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module# hooks = ruff# ruff.type = module# ruff.module = ruff# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Alternatively, use the exec runner to execute a binary found on your PATH# hooks = ruff# ruff.type = exec# ruff.executable = ruff# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Logging configuration. This is also consumed by the user-maintained# env.py script only.[loggers]keys = root,sqlalchemy,alembic
[handlers]keys = console
[formatters]keys = generic
[logger_root]level = WARNINGhandlers = consolequalname =
[logger_sqlalchemy]level = WARNINGhandlers =qualname = sqlalchemy.engine
[logger_alembic]level = INFOhandlers =qualname = alembic
[handler_console]class = StreamHandlerargs = (sys.stderr,)level = NOTSETformatter = generic
[formatter_generic]format = %(levelname)-5.5s [%(name)s] %(message)sdatefmt = %H:%M:%S1Generic single-database configuration.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950from app.cores.database import Basefrom logging.config import fileConfigfrom sqlalchemy import engine_from_configfrom sqlalchemy import poolfrom alembic import contextfrom app.cores.config import settingsfrom app.models.user import Userconfig = context.config
config.set_main_option("sqlalchemy.url", f"postgresql://{settings.DATABASE_USERNAME}:{settings.DATABASE_PASSWORD}@{settings.DATABASE_HOSTNAME}:{settings.DATABASE_PORT}/{settings.DATABASE_NAME}")
if config.config_file_name is not None: fileConfig(config.config_file_name)
target_metadata = Base.metadata
def run_migrations_offline() -> None: url = config.get_main_option("sqlalchemy.url") context.configure( url=url, target_metadata=target_metadata, literal_binds=True, dialect_opts={"paramstyle": "named"}, )
with context.begin_transaction(): context.run_migrations()
def run_migrations_online() -> None: connectable = engine_from_config( config.get_section(config.config_ini_section, {}), prefix="sqlalchemy.", poolclass=pool.NullPool, )
with connectable.connect() as connection: context.configure( connection=connection, target_metadata=target_metadata )
with context.begin_transaction(): context.run_migrations()
if context.is_offline_mode(): run_migrations_offline()else: run_migrations_online()12345678910111213141516171819202122232425262728"""${message}
Revision ID: ${up_revision}Revises: ${down_revision | comma,n}Create Date: ${create_date}
"""from typing import Sequence, Union
from alembic import opimport sqlalchemy as sa${imports if imports else ""}
# revision identifiers, used by Alembic.revision: str = ${repr(up_revision)}down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None: """Upgrade schema.""" ${upgrades if upgrades else "pass"}
def downgrade() -> None: """Downgrade schema.""" ${downgrades if downgrades else "pass"}123456789101112131415161718192021222324252627282930313233343536373839"""create users table
Revision ID: 6f056783c0d8Revises: Create Date: 2026-06-29 16:16:28.748674
"""from typing import Sequence, Union
from alembic import opimport sqlalchemy as sa
# revision identifiers, used by Alembic.revision: str = '6f056783c0d8'down_revision: Union[str, Sequence[str], None] = Nonebranch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: """Upgrade schema.""" # ### commands auto generated by Alembic - please adjust! ### op.create_table('users', sa.Column('id', sa.Integer(), nullable=False), sa.Column('email', sa.String(), nullable=False), sa.Column('hashed_password', sa.String(), nullable=False), sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('email') ) # ### end Alembic commands ###
def downgrade() -> None: """Downgrade schema.""" # ### commands auto generated by Alembic - please adjust! ### op.drop_table('users') # ### end Alembic commands ###12345678910111213141516171819from pydantic_settings import BaseSettingsfrom pathlib import Path
env_path = Path(__file__).resolve().parent.parent.parent / ".env"
class Settings(BaseSettings): DATABASE_HOSTNAME: str DATABASE_PORT: str DATABASE_PASSWORD: str DATABASE_NAME: str DATABASE_USERNAME: str SECRET_KEY: str ALGORITHM: str ACCESS_TOKEN_EXPIRE_MINUTES: int GROQ_API_KEY: str
model_config = {"env_file": str(env_path), "env_file_encoding": "utf-8"}
settings = Settings()12345678910111213141516171819from typing import final
from sqlalchemy import create_enginefrom sqlalchemy.orm import declarative_base, sessionmaker
from app.cores.config import settings
SQLALCHEMY_DATABASE_URL = f"postgresql://{settings.DATABASE_USERNAME}:{settings.DATABASE_PASSWORD}@{settings.DATABASE_HOSTNAME}:{settings.DATABASE_PORT}/{settings.DATABASE_NAME}"
engine = create_engine(SQLALCHEMY_DATABASE_URL)SessionLocal = sessionmaker(autocommit=False,autoflush=False,blind=engine)Base = declarative_base()
def get_db(): db = SessionLocal() try: yield db finally: db.close()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748from datetime import datetimefrom fastapi.security import OAuth2PasswordBearerfrom jose import jwtfrom app.cores.config import settingsfrom passlib.context import CryptContextfrom fastapi import Depends, HTTPException, statusfrom app.cores.database import get_dbfrom app.models.user import Userfrom app.schemas.token import TokenDatafrom sqlalchemy.orm import Session
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login")
def hash_password(password: str) -> str: return pwd_context.hash(password)
def verify_password(plain_password: str, hashed_password: str) -> str: return pwd_context.verify(plain_password,hashed_password)
def create_access_token(data: dict) -> str: to_encode = data.copy() expire = datetime.utcnow() + datetime.timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) to_encode.update["exp": expire] return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
def decode_token(token: str) -> dict: return jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
def get_current_user(token: str = Depends(oauth2_scheme), db: Session= Depends(get_db())): credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = decode_token(token) user_id: int = TokenData(payload.get("user_id")) if user_id is None: raise credentials_exception except: raise credentials_exception user = db.query(User).filter(user_id == User.id).first() if not user: raise credentials_exception return user
12345678910from fastapi import FastAPIfrom app.routers import auth, user
app = FastAPI(title="Job Tracker API")
app.include_router(auth.router)app.include_router(user.router)@app.get("/")def root(): return {"message": "Job Tracker API is running"}1234567891011121314from sqlalchemy import Column, DateTime, Integer, Stringfrom sqlalchemy.sql import funcfrom sqlalchemy.orm import relationshipfrom app.cores.database import Base
class User(Base): __tablename__ = "users"
id = Column(Integer, primary_key=True, nullable=False) email = Column(String, unique=True, nullable=False) hashed_password = Column(String, nullable=False) created_at = Column(DateTime(timezone=True), server_default=func.now())
application = relationship("Applications", back_populates="owner")12345678910111213141516171819202122232425from fastapi import APIRouter, Depends, HTTPExceptionfrom fastapi.security import OAuth2PasswordRequestFormfrom app.cores.security import create_access_token, verify_passwordfrom app.models.user import Userfrom app.schemas.token import Tokenfrom app.cores.database import get_dbfrom sqlalchemy.orm import Session
router = APIRouter(tags=["Authentication"])
router.post("/login", response_model=Token)def login(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db())): user = db.query(User).filter(User.email == form_data.username).first() if not user or not verify_password(form_data.password, user.hashed_password): raise HTTPException(status_code=401, detail="Invalid credentials") token = create_access_token({"user_id": user.id}) return { "access_token": token, "token_type": "bearer" }
123456789101112131415161718192021222324252627282930313233from fastapi import APIRouter, HTTPException, status, Dependsfrom sqlalchemy.orm import Sessionfrom app.cores.security import hash_passwordfrom app.models.user import Userfrom app.schemas.user import UserCreate, UserOutfrom app.cores.database import get_db
router = APIRouter( prefix="/users", tags=["login"])
@router.post("/", response_model=UserOut, status_code=status.HTTP_201_CREATED)def create_user(user: UserCreate, db: Session = Depends(get_db)): existing = db.query(User).filter(User.email == user.email).first()
if existing: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Email already registered" )
new_user = User( email=user.email, hashed_password=hash_password(user.password) )
db.add(new_user) db.commit() db.refresh(new_user)
return new_user12345678from pydantic import BaseModel
class Token(BaseModel): access_token: str token_type: str
class TokenData(BaseModel): id: int123456789101112131415from datetime import datetimefrom pydantic import BaseModel, EmailStr
class UserCreate(BaseModel): email: EmailStr password: str
class UserOut(BaseModel): id: int email: EmailStr created_at: datetime model_config = { "from_attribute": True }.gitignoreAdded+27
alembic.iniAdded+149
alembic/READMEAdded+1
alembic/env.pyAdded+50
alembic/script.py.makoAdded+28
alembic/versions/6f056783c0d8_create_users_table.pyAdded+39
app/__init__.pyAdded
app/cores/__init__.pyAdded
app/cores/config.pyAdded+19
app/cores/database.pyAdded+19
app/cores/security.pyAdded+48
app/main.pyAdded+10
app/models/__init__.pyAdded
app/models/user.pyAdded+14
app/routers/__init__.pyAdded
app/routers/auth.pyAdded+25
app/routers/user.pyAdded+33
app/schemas/__init__.pyAdded
app/schemas/token.pyAdded+8
app/schemas/user.pyAdded+15
requirements.txtAdded