Add user api
This commit is contained in:
@@ -3,7 +3,16 @@ from fastapi import FastAPI, Depends, HTTPException, status, Query
|
||||
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from pydantic import BaseModel
|
||||
from model import Log, SessionLocal, Script, Settings, Subscription, Notification, User
|
||||
from model import (
|
||||
Base,
|
||||
Log,
|
||||
SessionLocal,
|
||||
Script,
|
||||
Settings,
|
||||
Subscription,
|
||||
Notification,
|
||||
User,
|
||||
)
|
||||
from run_scripts import run_scripts, update_requirements, update_environment
|
||||
import uvicorn
|
||||
from passlib.context import CryptContext
|
||||
@@ -49,6 +58,11 @@ class UserCreate(BaseModel):
|
||||
password: str
|
||||
|
||||
|
||||
class UserResponse(BaseModel):
|
||||
id: int
|
||||
username: str
|
||||
|
||||
|
||||
class Token(BaseModel):
|
||||
access_token: str
|
||||
token_type: str
|
||||
@@ -87,6 +101,47 @@ def hello():
|
||||
return {"message": "Welcome to the Project Monitor API"}
|
||||
|
||||
|
||||
# User Management Endpoints
|
||||
@app.get("/users", response_model=list[UserResponse])
|
||||
def list_users(current_user: User = Depends(get_current_user)):
|
||||
db = SessionLocal()
|
||||
users = db.query(User).all()
|
||||
db.close()
|
||||
return users
|
||||
|
||||
|
||||
@app.put("/users/{user_id}")
|
||||
def update_user(
|
||||
user_id: int,
|
||||
user: UserCreate,
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
db = SessionLocal()
|
||||
existing_user = db.query(User).filter(User.id == user_id).first()
|
||||
if not existing_user:
|
||||
db.close()
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
existing_user.username = user.username
|
||||
existing_user.password_hash = get_password_hash(user.password)
|
||||
db.commit()
|
||||
db.refresh(existing_user)
|
||||
db.close()
|
||||
return {"message": "User updated successfully"}
|
||||
|
||||
|
||||
@app.delete("/users/{user_id}")
|
||||
def delete_user(user_id: int, current_user: User = Depends(get_current_user)):
|
||||
db = SessionLocal()
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
db.close()
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
db.delete(user)
|
||||
db.commit()
|
||||
db.close()
|
||||
return {"message": "User deleted successfully"}
|
||||
|
||||
|
||||
@app.post("/register", response_model=Token)
|
||||
def register(user: UserCreate):
|
||||
db = SessionLocal()
|
||||
|
||||
Reference in New Issue
Block a user