Skip to content

Commit

Permalink
Merge pull request #6627 from hotosm/fastapi-refactor
Browse files Browse the repository at this point in the history
Register user, retrieve org by id and slug and user interests refactored
  • Loading branch information
prabinoid authored Nov 12, 2024
2 parents df9b38b + d2ad9c3 commit be90e47
Show file tree
Hide file tree
Showing 11 changed files with 91 additions and 135 deletions.
1 change: 0 additions & 1 deletion backend/api/comments/resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,6 @@ async def post(
message=message,
user_id=user.id,
project_id=project_id,
# timestamp=datetime.now(),
timestamp=datetime.utcnow(),
username=user.username,
)
Expand Down
105 changes: 30 additions & 75 deletions backend/api/organisations/resources.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from databases import Database
from fastapi import APIRouter, Depends, Query, Request
from fastapi import APIRouter, Depends, Query, Request, Path
from fastapi.responses import JSONResponse, Response
from loguru import logger

Expand Down Expand Up @@ -28,89 +28,52 @@
)


@router.get("/{organisation_id}/", response_model=OrganisationDTO)
async def retrieve_organisation(
request: Request,
organisation_id: int,
async def get_organisation_by_identifier(
identifier: str = Path(..., description="Either organisation ID or slug"),
db: Database = Depends(get_db),
omit_managers: bool = Query(
False,
alias="omitManagerList",
description="Omit organization managers list from the response.",
),
):
"""
Retrieves an organisation
---
tags:
- organisations
produces:
- application/json
parameters:
- in: header
name: Authorization
description: Base64 encoded session token
type: string
default: Token sessionTokenHere==
- name: organisation_id
in: path
description: The unique organisation ID
required: true
type: integer
default: 1
- in: query
name: omitManagerList
type: boolean
description: Set it to true if you don't want the managers list on the response.
default: False
responses:
200:
description: Organisation found
401:
description: Unauthorized - Invalid credentials
404:
description: Organisation not found
500:
description: Internal Server Error
"""
request: Request = None,
) -> OrganisationDTO:
authenticated_user_id = request.user.display_name if request.user else None
if authenticated_user_id is None:
user_id = 0
else:
user_id = authenticated_user_id
organisation_dto = await OrganisationService.get_organisation_by_id_as_dto(
organisation_id, user_id, omit_managers, db
)
user_id = authenticated_user_id or 0

try:
organisation_id = int(identifier)
organisation_dto = await OrganisationService.get_organisation_by_id_as_dto(
organisation_id, user_id, omit_managers, db
)
except ValueError:
organisation_dto = await OrganisationService.get_organisation_by_slug_as_dto(
identifier, user_id, omit_managers, db
)

if not organisation_dto:
return JSONResponse(
content={"Error": "Organisation not found."}, status_code=404
)

return organisation_dto


@router.get("/{slug}/", response_model=OrganisationDTO)
async def retrieve_organisation_by_slug(
request: Request,
slug: str,
db: Database = Depends(get_db),
omit_managers: bool = Query(
True,
alias="omitManagerList",
description="Omit organization managers list from the response.",
),
@router.get("/{identifier}/", response_model=OrganisationDTO)
async def retrieve_organisation(
organisation: OrganisationDTO = Depends(get_organisation_by_identifier),
):
"""
Retrieves an organisation
Retrieve an organisation by either ID or slug.
---
tags:
- organisations
produces:
- application/json
parameters:
- in: header
name: Authorization
description: Base64 encoded session token
type: string
default: Token sessionTokenHere==
- name: slug
in: path
description: The unique organisation slug
- in: path
name: identifier
description: The organisation ID or slug
required: true
type: string
default: hot
Expand All @@ -127,15 +90,7 @@ async def retrieve_organisation_by_slug(
500:
description: Internal Server Error
"""
authenticated_user_id = request.user.display_name if request.user else None
if authenticated_user_id is None:
user_id = 0
else:
user_id = authenticated_user_id
organisation_dto = await OrganisationService.get_organisation_by_slug_as_dto(
slug, user_id, omit_managers, db
)
return organisation_dto
return organisation


@router.post("/")
Expand Down
5 changes: 0 additions & 5 deletions backend/models/dtos/interests_dto.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,6 @@ class Config:
populate_by_name = True


class ListInterestDTO(BaseModel):
id: Optional[int] = None
name: Optional[str] = Field(default=None, min_length=1)


class InterestsListDTO(BaseModel):
"""DTO for a list of interests."""

Expand Down
6 changes: 3 additions & 3 deletions backend/models/dtos/message_dto.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,10 @@ class Config:
class ChatMessageDTO(BaseModel):
"""DTO describing an individual project chat message"""

id: Optional[int] = Field(None, alias="id", serialize_when_none=False)
id: Optional[int] = Field(None, alias="id")
message: str = Field(required=True)
user_id: int = Field(required=True, serialize_when_none=False)
project_id: int = Field(required=True, serialize_when_none=False)
user_id: int = Field(required=True)
project_id: int = Field(required=True)
picture_url: str = Field(default=None, alias="pictureUrl")
timestamp: datetime
username: str
Expand Down
4 changes: 2 additions & 2 deletions backend/models/postgis/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
from backend.db import Base
from backend.exceptions import NotFound
from backend.models.dtos.campaign_dto import CampaignDTO, ListCampaignDTO
from backend.models.dtos.interests_dto import ListInterestDTO
from backend.models.dtos.interests_dto import InterestDTO
from backend.models.dtos.project_dto import (
CustomEditorDTO,
DraftProjectDTO,
Expand Down Expand Up @@ -1786,7 +1786,7 @@ async def get_project_and_base_dto(project_id: int, db: Database) -> ProjectDTO:
WHERE pi.project_id = :project_id
"""
interests = await db.fetch_all(interests_query, {"project_id": project_id})
project_dto.interests = [ListInterestDTO(**i) for i in interests]
project_dto.interests = [InterestDTO(**i) for i in interests]
return project_dto

@staticmethod
Expand Down
1 change: 1 addition & 0 deletions backend/models/postgis/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ class ST_Y(GenericFunction):
def timestamp():
"""Used in SQL Alchemy models to ensure we refresh timestamp when new models initialised"""
return datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
# return datetime.datetime.now(datetime.timezone.utc)


# Based on https://stackoverflow.com/a/51916936
Expand Down
6 changes: 1 addition & 5 deletions backend/services/interests_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
InterestRateListDTO,
InterestsListDTO,
InterestDTO,
ListInterestDTO,
)
from backend.models.postgis.interests import (
Interest,
Expand Down Expand Up @@ -142,11 +141,8 @@ async def get_user_interests(user_id, db: Database) -> InterestsListDTO:
WHERE ui.user_id = :user_id
"""
rows = await db.fetch_all(query, {"user_id": user_id})

dto = InterestsListDTO()
dto.interests = [
ListInterestDTO(id=row["id"], name=row["name"]) for row in rows
]
dto.interests = [InterestDTO(id=row["id"], name=row["name"]) for row in rows]
return dto

@staticmethod
Expand Down
6 changes: 2 additions & 4 deletions backend/services/messaging/message_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def __init__(self, message):

class MessageService:
@staticmethod
def send_welcome_message(user: User):
async def send_welcome_message(user: User, db: Database):
"""Sends welcome message to new user at Sign up"""
org_code = settings.ORG_CODE
text_template = get_txt_template("welcome_message_en.txt")
Expand All @@ -65,9 +65,7 @@ def send_welcome_message(user: User):
welcome_message.to_user_id = user.id
welcome_message.subject = "Welcome to the {} Tasking Manager".format(org_code)
welcome_message.message = text_template
welcome_message.save()

return welcome_message.id
await Message.save(welcome_message, db)

@staticmethod
async def send_message_after_validation(
Expand Down
6 changes: 3 additions & 3 deletions backend/services/messaging/smtp_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ async def send_verification_email(to_address: str, username: str):
"VERIFICATION_LINK": verification_url,
}
html_template = get_template("email_verification_en.html", values)

subject = "Confirm your email address"
await SMTPService._send_message(to_address, subject, html_template)
return True
Expand Down Expand Up @@ -178,7 +177,7 @@ def send_email_alert(
return True

@staticmethod
def _send_message(
async def _send_message(
to_address: str, subject: str, html_message: str, text_message: str = None
):
"""Helper sends SMTP message"""
Expand All @@ -194,9 +193,10 @@ def _send_message(
logger.debug(f"Sending email via SMTP {to_address}")
if settings.LOG_LEVEL == "DEBUG":
logger.debug(msg.as_string())

else:
try:
mail.send_message(msg)
await mail.send_message(msg)
logger.debug(f"Email sent {to_address}")
except Exception as e:
# ERROR level logs are automatically captured by sentry so that admins are notified
Expand Down
9 changes: 5 additions & 4 deletions backend/services/users/authentication_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,10 +140,11 @@ async def login_user(osm_user_details, email, db, user_element="user") -> dict:
# User not found, so must be new user
changesets = osm_user.get("changesets")
changeset_count = int(changesets.get("count"))
new_user = UserService.register_user(
osm_id, username, changeset_count, user_picture, email
)
MessageService.send_welcome_message(new_user)
async with db.transaction():
new_user = await UserService.register_user(
osm_id, username, changeset_count, user_picture, email, db
)
await MessageService.send_welcome_message(new_user, db)

session_token = AuthenticationService.generate_session_token_for_user(osm_id)
return {
Expand Down
Loading

0 comments on commit be90e47

Please sign in to comment.