Merge pull request 'events' (#7) from events into master

Reviewed-on: #7
This commit is contained in:
v4l3n71n 2023-11-20 23:43:15 +01:00
commit ff3cb878c4
5 changed files with 339 additions and 45 deletions

View File

@ -1,7 +1,7 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from .routers import users, token, mail
from .routers import users, token, mail, events
from .dependencies import user_add
import os
@ -24,6 +24,7 @@ app.add_middleware(
app.include_router(users.router)
app.include_router(token.router)
app.include_router(mail.router)
app.include_router(events.router)
@app.on_event("startup")

44
app/models/events.py Normal file
View File

@ -0,0 +1,44 @@
from pydantic import BaseModel, EmailStr
from pydantic_mongo import AbstractRepository, ObjectIdField
from datetime import datetime, date
class Event(BaseModel):
id: ObjectIdField = None
name: str
place: str
status: int = 0
latitude: float = 0.0
longitude: float = 0.0
organizers: list[str] = []
start_date: datetime | None = None
end_date: datetime | None = None
created_at: datetime = datetime.today()
updated_at: datetime | None = None
deleted_at: datetime | None = None
disabled_at: datetime | None = None
class EventOut(BaseModel):
id: ObjectIdField = None
name: str
place: str
status: int = 0
start_date: datetime | None = None
end_date: datetime | None = None
class EventIn(BaseModel):
name: str
place: str
status: int = 0
organizers: list[str] = []
start_date: datetime | None = None
end_date: datetime | None = None
latitude: float = 0.0
longitude: float = 0.0
class EventIDS(BaseModel):
ids: list[str]
class EventRepository(AbstractRepository[Event]):
class Meta:
collection_name = "events"

View File

@ -14,8 +14,9 @@ class User(BaseModel):
birth: str | None = None
created_at: datetime = datetime.today()
connected_at: datetime | None = None
updated_at: datetime = datetime.today()
updated_at: datetime | None = None
deleted_at: datetime | None = None
disabled_at: datetime | None = None
class UserOut(BaseModel):
id: ObjectIdField = None

View File

@ -0,0 +1,234 @@
from fastapi import APIRouter, Depends, HTTPException, status, Response
from fastapi.responses import JSONResponse
from datetime import datetime
from ..dependencies import users_token, permissions_checker, database
from ..models import events, users
from pydantic import EmailStr
from typing import Annotated
from bson import ObjectId
router = APIRouter()
@router.get("/events", tags=["events"], response_model=list[events.EventOut])
async def read_events(authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))], skip: int = 0, limit: int = 20, id_event: str | None = None, name: str | None = None, status: int | None = None):
if limit < 1 or skip < 0 or limit < skip:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="skip should be greater than 0 and limit should be greater than 1. Limit should be greater than skip"
)
limit = limit + skip
listEvents = []
event_repository = events.EventRepository(database=database.database)
object_search = {}
if status is not None:
object_search = {"status":{"$eq": status}}
if id_event is not None:
eventid = ObjectId(id_event)
object_search = {"id": {"$regex": userid}}
if status is not None:
object_search = {"$and":[{"id":{"$regex": eventid}}, {"status":{"$eq":status}}]}
if name is not None:
object_search = {"name": {"$regex": name}}
if status is not None:
object_search = {"$and":[{"name":{"$regex": name}}, {"status":{"$eq":status}}]}
for event_index in event_repository.find_by(object_search, limit=limit, skip=skip):
event = events.EventOut(id=event_index.id, name=event_index.name, place=event_index.place, status=event_index.status, start_date=event_index.start_date, end_date=event_index.end_date)
listEvents.append(event)
return listEvents
@router.get("/events/me",tags=["events"])
async def read_users_me(current_user: Annotated[users.User, Depends(users_token.get_current_active_user)], authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))]):
event_repository = events.EventRepository(database=database.database)
listOrganizers = []
for event_index in event_repository.find_by({"organizers":{"$eq": current_user.username}}, limit=limit, skip=skip):
event = events.EventOut(id=event_index.id, name=event_index.name, place=event_index.place, status=event_index.status, start_date=event_index.start_date, end_date=event_index.end_date)
listOrganizers.append(event)
content = {"organizers":listOrganizers}
response = JSONResponse(content=content)
return response
@router.get("/events/count", tags=["events"])
async def read_events_count(authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))]):
count = database.database.get_collection("events").estimated_document_count()
content = {"count":count}
response = JSONResponse(content=content)
return response
@router.get("/events/{item_id}", tags=["events"], response_model=events.Event)
async def read_events_id(item_id : str, authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))]):
event_repository = events.EventRepository(database=database.database)
event = event_repository.find_one_by_id(ObjectId(item_id))
return event
@router.delete("/events/me/{item_id}", tags=["events"])
async def delete_event_me(item_id: str, current_user: Annotated[users.User, Depends(users_token.get_current_active_user)], authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))], remove: bool = False):
event_repository = events.EventRepository(database=database.database)
event = event_repository.find_one_by_id(ObjectId(item_id))
if remove is True:
event.deleted_at = datetime.today()
event.status = -1
content = {"message": "event is deleted"}
else:
event.status = 0
event.deleted_at = datetime.today()
content = {"message": "event is disabled"}
event_repository.save(event)
response = JSONResponse(content=content)
return response
@router.delete("/events/groups",tags=["events"])
async def delete_events_groups(authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))], remove: bool = False, eventids: events.EventIDS | None = None):
if len(eventids.ids) == 0:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="eventids should be greater than 0"
)
event_repository = event.EventRepository(database=database.database)
for i in eventids.ids:
event = event_repository.find_one_by_id(ObjectId(i))
if remove is True:
event.status = -1
event.deleted_at = datetime.today()
content = {"message": "events are deleted "}
else:
event.status = 0
event.disabled_at = datetime.today()
content = {"message": "events are disabled"}
event_repository.save(event)
response = JSONResponse(content=content)
return response
@router.delete("/events/{item_id}", tags=["events"])
async def delete_events_id(item_id : str, authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))], remove : bool = False):
event_repository = events.EventRepository(database=database.database)
event = event_repository.find_one_by_id(ObjectId(item_id))
if remove is True:
event.status = -1
event.deleted_at = datetime.today()
content = {"message": "events are deleted"}
else:
event.status = 0
event.disabled_at = datetime.today()
content = {"message": "events are disabled"}
event_repository.save(event)
response = JSONResponse(content=content)
return response
@router.put("/events/me/{item_id}",tags=["events"])
async def update_events_me(item_id: str, current_user: Annotated[users.User, Depends(users_token.get_current_active_user)], authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))], eventSingle: events.EventIn | None = None):
event_repository = event.EventRepository(database=database.database)
event = event_repository.find_one_by_id(ObjectId(item_id))
event.name = EventSingle.name
event.place = EventSingle.place
event.start_date = eventSingle.start_date
event.end_date = eventSingle.end_date
event.latitude = eventSingle.latitude
event.longitude = eventSingle.longitude
event.updated_at = datetime.today()
event_repository.save(event)
content = {"message": "event is updated"}
response = JSONResponse(content=content)
return response
@router.put("/events", tags=["events"], status_code=status.HTTP_201_CREATED)
async def update_events(authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))], eventSingle: events.EventIn | None = None):
if eventSingle is None:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Body request is empty"
)
event_repository = events.EventRepository(database=database.database)
event = event_repository.find_one_by({"name": {'$eq': eventSingle.name}})
if event is not None:
raise HTTPException(
status_code=status.HTTP_204_NO_CONTENT,
detail="name"
)
event = events.Event(name=eventSingle.name, place=eventSingle.place)
event.start_date = eventSingle.start_date
event.end_date = eventSingle.end_date
event.organizers = eventSingle.organizers
event.latitude = eventSingle.latitude
event.longitude = eventSingle.longitude
event.created_at = datetime.today()
event_repository.save(event)
content = {"message": "event is created"}
response = JSONResponse(content=content, status_code=status.HTTP_201_CREATED)
return response
@router.put("/events/{item_id}", tags=["events"], status_code=status.HTTP_200_OK)
async def update_events_id(item_id: str, authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))], eventSingle: events.EventIn | None = None, response: Response = Response):
if eventSingle is None:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Body request is empty"
)
event_repository = events.EventRepository(database=database.database)
event = event_repository.find_one_by({"id": {'$eq': ObjectId(item_id)}})
if event is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Event not found"
)
event.name = eventSingle.name
event.place = eventSingle.place
event.start_date = eventSingle.start_date
event.end_date = eventSingle.end_date
event.organizers = eventSingle.organizers
event.latitude = eventSingle.latitude
event.longitude = eventSingle.longitude
event.updated_at = datetime.today()
event_repository.save(event)
content = {"message": "event is updated"}
response = JSONResponse(content=content)
return response
@router.patch("/events/groups",tags=["events"])
async def patch_events_groups(authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))], eventids: events.EventIDS | None = None):
if len(eventids.ids) == 0:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="eventids should be greater than 0"
)
event_repository = events.EventRepository(database=database.database)
content = {"message": "events are enabled"}
for i in eventids.ids:
event = event_repository.find_one_by_id(ObjectId(i))
event.status = 1
event.disabled_at = None
event.deleted_at = None
event_repository.save(event)
response = JSONResponse(content=content)
return response
@router.patch("/events/{item_id}", tags=["events"])
async def patch_events_id(item_id : str, authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))]):
event_repository = events.EventRepository(database=database.database)
event = event_repository.find_one_by_id(ObjectId(item_id))
event.status = 1
event.disabled_at = None
event.deleted_at = None
event_repository.save(event)
content = {"message": "event is enabled"}
response = JSONResponse(content=content)
return response

View File

@ -11,7 +11,7 @@ router = APIRouter()
@router.get("/users", tags=["users"], response_model=list[users.UserOut])
async def read_users(authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))], skip: int = 0, limit: int = 20, id_user: str | None = None, roles: str | None = None, status: int | None = None, email: EmailStr | None = None):
async def read_users(authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))], skip: int = 0, limit: int = 20, id_user: str | None = None, roles: str | None = None, status: int | None = None, email: EmailStr | None = None, name: str | None = None):
if limit < 1 or skip < 0 or limit < skip:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
@ -48,33 +48,22 @@ async def read_users(authorize: Annotated[bool, Depends(permissions_checker.Perm
if roles is not None:
object_search = {"$and":[{"email":{"$eq": email}}, {"roles":{"$eq":roles}}]}
if name is not None:
object_search = {"username": {"$regex": name}}
if status is not None and roles is not None:
object_search = {"$and":[{"username":{"$regex": name}}, {"roles":{"$eq": roles}}, {"status":{"$eq":status}}]}
else:
if status is not None:
object_search = {"$and":[{"username":{"$regex": name}}, {"status":{"$eq":status}}]}
if roles is not None:
object_search = {"$and":[{"username":{"$regex": name}}, {"roles":{"$eq":roles}}]}
for user_index in user_repository.find_by(object_search, limit=limit, skip=skip):
user = users.UserOut(id=user_index.id, username=user_index.username, email=user_index.email, status=user_index.status, roles=user_index.roles, firstName=user_index.firstName, name=user_index.name)
listUsers.append(user)
return listUsers
@router.get("/users/search", tags=["users"], response_model=list[users.UserOut])
async def read_users_search(authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))], skip: int = 0, limit: int = 20):
if limit < 1 or skip < 0 or limit < skip:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="skip should be greater than 0 and limit should be greater than 1. Limit should be greater than skip"
)
if key is None or value is None:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Key or/and value parameter is empty"
)
limit = limit + skip
listUsers = []
user_repository = users.UserRepository(database=database.database)
for user_index in user_repository.find_by({key: {'$regex': value}}, limit=limit, skip=skip):
user = users.UserOut(id=user_index.id, username=user_index.username, status=user_index.status, roles=user_index.roles, email=user_index.email, firstName=user_index.firstName, name=user_index.name)
listUsers.append(user)
return listUsers
@router.get("/users/me",tags=["users"], response_model=users.User, response_model_exclude=["id", "password", "roles", "status"])
async def read_users_me(current_user: Annotated[users.User, Depends(users_token.get_current_active_user)], authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))]):
return current_user
@ -94,14 +83,21 @@ async def read_users_id(item_id : str, authorize: Annotated[bool, Depends(permis
return user
@router.delete("/users/me",tags=["users"], response_model=users.User, response_model_exclude=["id", "password", "roles", "status"])
@router.delete("/users/me",tags=["users"])
async def delete_users_me(current_user: Annotated[users.User, Depends(users_token.get_current_active_user)], authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))], remove: bool = False):
user_repository = users.UserRepository(database=database.database)
current_user.status = 0
if remove is True:
current_user.deleted_at = datetime.today()
current_user.status = -1
content = {"message": "users are deleted"}
else:
current_user.status = 0
current_user.deleted_at = datetime.today()
content = {"message": "users are disabled"}
user_repository.save(current_user)
return current_user
response = JSONResponse(content=content)
return response
@router.delete("/users/groups",tags=["users"])
async def delete_users_groups(authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))], remove: bool = False, userids: users.UserIDS | None = None):
@ -112,30 +108,38 @@ async def delete_users_groups(authorize: Annotated[bool, Depends(permissions_che
)
user_repository = users.UserRepository(database=database.database)
content = {"message": "users are disabled"}
for i in userids.ids:
user = user_repository.find_one_by_id(ObjectId(i))
user.status = 0
if remove is True:
user.status = -1
user.deleted_at = datetime.today()
content = {"message": "users are deleted "}
else:
user.status = 0
user.disabled_at = datetime.today()
content = {"message": "users are disabled"}
user_repository.save(user)
response = JSONResponse(content=content)
return response
@router.delete("/users/{item_id}", tags=["users"], response_model=users.User)
@router.delete("/users/{item_id}", tags=["users"])
async def delete_users_id(item_id : str, authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))], remove : bool = False):
user_repository = users.UserRepository(database=database.database)
user = user_repository.find_one_by_id(ObjectId(item_id))
user.status = 0
if remove is True:
user.status = -1
user.deleted_at = datetime.today()
content = {"message": "users are deleted"}
else:
user.status = 0
user.disabled_at = datetime.today()
content = {"message": "users are disabled"}
user_repository.save(user)
return user
response = JSONResponse(content=content)
return response
@router.put("/users/me",tags=["users"], response_model=users.User, response_model_exclude=["id", "password", "roles", "status"])
@router.put("/users/me",tags=["users"])
async def update_users_me(current_user: Annotated[users.User, Depends(users_token.get_current_active_user)], authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))], userSingle: users.UserIn | None = None):
user_repository = users.UserRepository(database=database.database)
current_user.username = userSingle.username
@ -143,10 +147,12 @@ async def update_users_me(current_user: Annotated[users.User, Depends(users_toke
current_user.roles = userSingle.roles
current_user.email = userSingle.email
user_repository.save(current_user)
content = {"message": "user is updated"}
response = JSONResponse(content=content)
return current_user
@router.put("/users", tags=["users"], response_model=users.User, status_code=status.HTTP_201_CREATED)
async def update_users(authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))], userSingle: users.UserIn | None = None, response: Response = Response):
@router.put("/users", tags=["users"], status_code=status.HTTP_201_CREATED)
async def update_users(authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))], userSingle: users.UserIn | None = None):
if userSingle is None:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
@ -156,7 +162,6 @@ async def update_users(authorize: Annotated[bool, Depends(permissions_checker.Pe
user = user_repository.find_one_by({"$or":[{"username": {'$eq': userSingle.username}}, {"email": {"$eq": userSingle.email}}]})
if user is not None:
response.status_code = status.HTTP_201_CREATED
if user.username == userSingle.username:
raise HTTPException(
status_code=status.HTTP_204_NO_CONTENT,
@ -167,19 +172,20 @@ async def update_users(authorize: Annotated[bool, Depends(permissions_checker.Pe
status_code=status.HTTP_204_NO_CONTENT,
detail="email"
)
user.username = userSingle.username
user.password = users_token.get_password_hash(userSingle.password)
user = users.User(username=userSingle.username, password=users_token.get_password_hash(userSingle.password), email=userSingle.email)
user.roles = userSingle.roles
user.email = userSingle.email
user.firstName = userSingle.firstName
user.name = userSingle.name
user.birth = userSingle.birth
user.updated_at = datetime.today()
user.created_at = datetime.today()
user_repository.save(user)
return user
content = {"message": "user is created"}
response = JSONResponse(content=content, status_code=status.HTTP_201_CREATED)
return response
@router.put("/users/{item_id}", tags=["users"], response_model=users.User, status_code=status.HTTP_200_OK)
@router.put("/users/{item_id}", tags=["users"], status_code=status.HTTP_200_OK)
async def update_users_id(item_id: str, authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))], userSingle: users.UserIn | None = None, response: Response = Response):
if userSingle is None:
raise HTTPException(
@ -204,7 +210,9 @@ async def update_users_id(item_id: str, authorize: Annotated[bool, Depends(permi
user.birth = userSingle.birth
user.updated_at = datetime.today()
user_repository.save(user)
return user
content = {"message": "user is updated"}
response = JSONResponse(content=content)
return response
@router.patch("/users/groups",tags=["users"])
@ -220,6 +228,8 @@ async def patch_users_groups(authorize: Annotated[bool, Depends(permissions_chec
for i in userids.ids:
user = user_repository.find_one_by_id(ObjectId(i))
user.status = 1
user.disabled_at = None
user.deleted_at = None
user_repository.save(user)
@ -231,5 +241,9 @@ async def patch_users_id(item_id : str, authorize: Annotated[bool, Depends(permi
user_repository = users.UserRepository(database=database.database)
user = user_repository.find_one_by_id(ObjectId(item_id))
user.status = 1
user.disabled_at = None
user.deleted_at = None
user_repository.save(user)
return user
content = {"message": "user is enabled"}
response = JSONResponse(content=content)
return response