Skip to content

Commit

Permalink
Merge pull request #563 from M03ED/API
Browse files Browse the repository at this point in the history
API Improvment
  • Loading branch information
SaintShit authored Oct 17, 2023
2 parents 0712061 + d4c3de2 commit dd98660
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 4 deletions.
3 changes: 2 additions & 1 deletion app/db/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def get_db(): # Dependency
get_or_create_inbound, get_system_usage, get_user,
get_user_by_id, get_users, get_users_count, remove_admin,
remove_user, revoke_user_sub, update_admin, update_user,
update_user_status, update_user_sub)
update_user_status, update_user_sub, set_owner)
from .models import JWT, System, User # noqa

__all__ = [
Expand All @@ -44,6 +44,7 @@ def get_db(): # Dependency
"update_user_status",
"update_user_sub",
"revoke_user_sub",
"set_owner",
"get_system_usage",
"get_jwt_secret_key",
"get_admin",
Expand Down
6 changes: 6 additions & 0 deletions app/db/crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,12 @@ def update_user_status(db: Session, dbuser: User, status: UserStatus):
db.refresh(dbuser)
return dbuser

def set_owner(db: Session, dbuser: User, admin: Admin):
dbuser.admin = admin
db.commit()
db.refresh(dbuser)
return dbuser


def get_system_usage(db: Session):
return db.query(System).first()
Expand Down
64 changes: 63 additions & 1 deletion app/views/user.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from datetime import datetime
from datetime import datetime, timezone

import sqlalchemy
from fastapi import BackgroundTasks, Depends, HTTPException
Expand Down Expand Up @@ -287,3 +287,65 @@ def get_user(username: str,
usages = crud.get_user_usages(db, dbuser, start_date, end_date)

return {"usages": usages, "username": username}


@app.put("/api/user/{username}/set-owner", tags=['User'], response_model=UserResponse)
def set_owner(username: str,
admin_username: str,
db: Session = Depends(get_db),
admin: Admin = Depends(Admin.get_current)):

if not admin.is_sudo:
raise HTTPException(status_code=403, detail="You're not allowed")

dbuser = crud.get_user(db, username)
if not dbuser:
raise HTTPException(status_code=404, detail="User not found")

new_admin = crud.get_admin(db, username=admin_username)
if not new_admin:
raise HTTPException(status_code=404, detail="Admin not found")

dbuser = crud.set_owner(db, dbuser, new_admin)
user = UserResponse.from_orm(dbuser)

logger.info(f"{user.username}\"owner successfully set to{admin.username}")

return user


@app.delete("/api/users/expired", tags=['User'])
def delete_expired(passed_time: int,
bg: BackgroundTasks,
db: Session = Depends(get_db),
admin: Admin = Depends(Admin.get_current)):
"""
Delete expired users
- **passed_time** must be a timestamp
- This function will delete all expired users that meet the specified number of days passed and can't be undone.
"""

dbusers = crud.get_users(db=db,
status=[UserStatus.expired, UserStatus.limited],
admin=admin if not admin.is_sudo else None)

current_time = int(datetime.now(timezone.utc).timestamp())
expiration_threshold = current_time - passed_time
expired_users = [user for user in dbusers if user.expire <= expiration_threshold]

if not expired_users:
raise HTTPException(status_code=404, detail=f'No expired user found.')

for dbuser in expired_users:
crud.remove_user(db, dbuser)

bg.add_task(xray.operations.remove_user, dbuser=dbuser)

bg.add_task(
report.user_deleted,
username=dbuser.username,
by=admin.username)

logger.info(f"User \"{dbuser.username}\" deleted")

return {}
3 changes: 1 addition & 2 deletions cli/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@ def set_owner(
):
utils.error("Aborted.")

user.admin = dbadmin
db.commit()
crud.set_owner(db, user, dbadmin)

utils.success(f'{username}\'s owner successfully set to "{admin}".')

0 comments on commit dd98660

Please sign in to comment.