Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions chalicelib/api/listings.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,16 @@ def toggle_visibility(id):
listings_api.log.debug(e)


@listings_api.route("/listings/{id}/toggle/encryption", methods=["PATCH"], cors=True)
@auth(listings_api, roles=[Roles.ADMIN])
def toggle_encryption(id):
"""Encrypts a listing with the given ID."""
try:
return listing_service.toggle_encryption(id)
except Exception as e:
listings_api.log.debug(e)


@listings_api.route("/listings/{id}/update-field", methods=["PATCH"], cors=True)
@auth(listings_api, roles=[Roles.ADMIN, Roles.MEMBER])
@handle_exceptions
Expand Down
35 changes: 34 additions & 1 deletion chalicelib/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,38 @@ def toggle_visibility(self, table_name: str, key: dict):
# Return None if the item doesn't exist
return None

@add_env_suffix
def toggle_encryption(self, table_name: str, key: dict):
"""Toggles the encryption boolean for an item identified by the key."""
# Get a reference to the DynamoDB table
table = self.resource.Table(table_name)

# Fetch the current item
listing_item = table.get_item(Key=key)
if "Item" not in listing_item:
return None

curr_listing = Listing.from_dynamodb_item(listing_item["Item"])

# If the item exists, update the isEncrypted field to the opposite value
if curr_listing:
is_encrypted = curr_listing.isEncrypted
updated_encryption_value = (
not is_encrypted if is_encrypted is not None else True
)

# Update the item with the new isEncrypted value
table.update_item(
Key=key,
UpdateExpression="SET isEncrypted = :value",
ExpressionAttributeValues={":value": updated_encryption_value},
)

return True

# Return None if the item doesn't exist
return None

@add_env_suffix
def update_listing_field(
self,
Expand Down Expand Up @@ -146,4 +178,5 @@ def update_listing_field(

return listing_item["Item"]

db = DBResource()

db = DBResource()
2 changes: 2 additions & 0 deletions chalicelib/models/listing.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ class Listing(BaseModel):
dateCreated: str
deadline: str
isVisible: Union[bool, None]
isEncrypted: Union[bool, None]
questions: List[Question]
title: str

Expand All @@ -23,6 +24,7 @@ def from_dynamodb_item(cls, item: dict):
dateCreated=item.get("dateCreated"),
deadline=item.get("deadline"),
isVisible=item.get("isVisible"),
isEncrypted=item.get("isEncrypted"),
questions=[Question(**q) for q in item.get("questions", [])],
title=item.get("title"),
)
4 changes: 4 additions & 0 deletions chalicelib/services/ApplicantService.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from chalicelib.services.EventsRushService import events_rush_service
from chalice import BadRequestError
import json
from chalicelib.utils import hash_value


class ApplicantService:
Expand Down Expand Up @@ -32,6 +33,9 @@ def get_all_from_listing(self, id: str):
email=applicant["email"], attendees=attendees, events=events
)

if "isEncrypted" in listing and listing["isEncrypted"]:
data = hash_value(data)

return data

def _get_rush_analytics(self, rush_category_id: str) -> dict:
Expand Down
20 changes: 19 additions & 1 deletion chalicelib/services/ListingService.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ def create(self, data: dict):
# if includeEventsAttended, create corresponding rush category (and create foreign-key)
if data.get("includeEventsAttended", None):
events_rush_data = {"name": data["title"], "defaultRushCategory": False}
rush_category_id = events_rush_service.create_rush_category(data=events_rush_data)
rush_category_id = events_rush_service.create_rush_category(
data=events_rush_data
)
data["rushCategoryId"] = str(rush_category_id)

db.put_data(table_name="zap-listings", data=data)
Expand Down Expand Up @@ -156,6 +158,22 @@ def toggle_visibility(self, id: str):
except Exception as e:
return json.dumps({"statusCode": 500, "message": str(e)})

def toggle_encryption(self, id: str):
try:
# Perform encryption toggle in the database
data = db.toggle_encryption(
table_name="zap-listings", key={"listingId": id}
)

# Check the result and return the appropriate response
if data:
return json.dumps({"statusCode": 200})
else:
return json.dumps({"statusCode": 400, "message": "Invalid listing ID"})

except Exception as e:
return json.dumps({"statusCode": 500, "message": str(e)})

def update_field_route(self, id, data):
try:
request_body = UpdateFieldRequest(**data)
Expand Down
24 changes: 23 additions & 1 deletion chalicelib/utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import base64
import random
import hashlib


def decode_base64(base64_data):
Expand Down Expand Up @@ -30,5 +32,25 @@ def get_file_extension_from_base64(base64_data):

return extension


def get_prev_image_version(version: str):
return "v" + str(int(version[1:]) - 1)
return "v" + str(int(version[1:]) - 1)


def hash_value(value):
"""Helper function to hash a single value."""
# If value is a dictionary or list, recursively hash the nested data
if isinstance(value, dict):
return {key: hash_value(val) for key, val in value.items()}
elif isinstance(value, list):
return [hash_value(item) for item in value]
else:
# Convert the value to a string and apply SHA-256 hash
hash_object = hashlib.sha256(str(value).encode("utf-8"))
hashed_value = hash_object.hexdigest()

# Generate a random length between 7 and 20
random_length = random.randint(7, 20)

# Return a truncated version of the hashed value
return hashed_value[:random_length]
2 changes: 1 addition & 1 deletion tests/services/test_listing_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ def test_update_field_validation_error(service):
assert exc_msgs[0] == "1 validation error for UpdateFieldRequest"
assert (
exc_msgs[2]
== "Value error, Invalid field: non_existent_field. Allowed fields: ['listingId', 'dateCreated', 'deadline', 'isVisible', 'questions', 'title'] [type=value_error, input_value='non_existent_field', input_type=str]"
== "Value error, Invalid field: non_existent_field. Allowed fields: ['listingId', 'dateCreated', 'deadline', 'isVisible', 'isEncrypted', 'questions', 'title'] [type=value_error, input_value='non_existent_field', input_type=str]"
)


Expand Down
Loading