-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
185 additions
and
74 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,60 +1,60 @@ | ||
import string | ||
import secrets | ||
|
||
from django.db.models import signals, Max | ||
from django.dispatch import receiver | ||
from django.contrib.auth.hashers import make_password | ||
|
||
from . import models | ||
|
||
|
||
@receiver([signals.pre_init], sender=models.User) | ||
def load_user_fixture(sender, *args, **kwargs): | ||
if ( | ||
isinstance(kwargs.get("kwargs"), dict) | ||
and kwargs["kwargs"].get("email") | ||
and kwargs["kwargs"].get("id") # Comment out when id is not serialized | ||
): | ||
if not kwargs["kwargs"].get("id"): | ||
kwargs["kwargs"]["id"] = ( | ||
models.User.objects.aggregate(Max("id")).get("id__max", 0) + 1 | ||
) | ||
|
||
if not kwargs["kwargs"].get("password"): | ||
password = "".join( | ||
secrets.choice(string.ascii_letters + string.digits) for _ in range(10) | ||
) | ||
kwargs["kwargs"]["password"] = make_password(password) | ||
|
||
print(f"User {kwargs['kwargs']['id']}: {kwargs['kwargs']['email']} {password}") | ||
|
||
|
||
def user_created_hook(instance, *args, **kwargs): | ||
EATWELL_MAP = { | ||
"Carbohydrates": 6, | ||
"Fruits & Vegetables": 6, | ||
"Protein": 3, | ||
"Dairy": 3, | ||
"Oils & Fats": 1, | ||
} | ||
|
||
for portion_item in models.PortionItem.objects.filter(is_default=True): | ||
models.TrackItem.objects.create( | ||
item=portion_item, | ||
user=instance, | ||
target=EATWELL_MAP.get(portion_item.name, 1), | ||
order=portion_item.id, | ||
) | ||
|
||
|
||
def user_updated_hook(instance, *args, **kwargs): | ||
pass | ||
|
||
|
||
@receiver([signals.post_save], sender=models.User) | ||
def user_post_save(sender, instance, *args, **kwargs): | ||
( | ||
user_created_hook | ||
if (kwargs.get("created") or kwargs.get("raw")) | ||
else user_updated_hook | ||
)(instance, *args, **kwargs) | ||
import string | ||
import secrets | ||
|
||
from django.db.models import signals, Max | ||
from django.dispatch import receiver | ||
from django.contrib.auth.hashers import make_password | ||
|
||
from . import models | ||
|
||
|
||
@receiver([signals.pre_init], sender=models.User) | ||
def load_user_fixture(sender, *args, **kwargs): | ||
if ( | ||
isinstance(kwargs.get("kwargs"), dict) | ||
and kwargs["kwargs"].get("email") | ||
and kwargs["kwargs"].get("id") # Comment out when id is not serialized | ||
): | ||
if not kwargs["kwargs"].get("id"): | ||
kwargs["kwargs"]["id"] = ( | ||
models.User.objects.aggregate(Max("id")).get("id__max", 0) + 1 | ||
) | ||
|
||
if not kwargs["kwargs"].get("password"): | ||
password = "".join( | ||
secrets.choice(string.ascii_letters + string.digits) for _ in range(10) | ||
) | ||
kwargs["kwargs"]["password"] = make_password(password) | ||
|
||
print(f"User {kwargs['kwargs']['id']}: {kwargs['kwargs']['email']} {password}") | ||
|
||
|
||
def user_created_hook(instance, *args, **kwargs): | ||
EATWELL_MAP = { | ||
"Carbohydrates": 6, | ||
"Fruits & Vegetables": 6, | ||
"Protein": 3, | ||
"Dairy": 3, | ||
"Oils & Fats": 1, | ||
} | ||
|
||
for portion_item in models.PortionItem.objects.filter(is_default=True): | ||
models.TrackItem.objects.update_or_create( | ||
item=portion_item, | ||
user=instance, | ||
target=EATWELL_MAP.get(portion_item.name, 1), | ||
order=portion_item.id, | ||
) | ||
|
||
|
||
def user_updated_hook(instance, *args, **kwargs): | ||
pass | ||
|
||
|
||
@receiver([signals.post_save], sender=models.User) | ||
def user_post_save(sender, instance, *args, **kwargs): | ||
( | ||
user_created_hook | ||
if (kwargs.get("created") or kwargs.get("raw")) | ||
else user_updated_hook | ||
)(instance, *args, **kwargs) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
from rest_framework.permissions import BasePermission | ||
|
||
|
||
class IsAdminOrIsSelf(BasePermission): | ||
def has_object_permission(self, request, view, obj): | ||
return ( | ||
getattr(obj, 'user', obj) == request.user | ||
or request.user.is_staff | ||
or request.user.is_superuser | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,35 +1,102 @@ | ||
from datetime import timedelta | ||
from django.utils import timezone | ||
from rest_framework import serializers | ||
from main import models | ||
|
||
|
||
class UserSerializer(serializers.HyperlinkedModelSerializer): | ||
class DynamicFieldsModelSerializer(serializers.ModelSerializer): | ||
""" | ||
A ModelSerializer that takes an additional `fields` argument that | ||
controls which fields should be displayed. | ||
Source: https://www.django-rest-framework.org/api-guide/serializers/ | ||
""" | ||
|
||
def __init__(self, *args, **kwargs): | ||
# Don't pass the 'fields' arg up to the superclass | ||
fields = kwargs.pop("fields", None) | ||
|
||
# Don't pass the 'exclude' arg up to the superclass | ||
exclude = kwargs.pop("exclude", None) | ||
|
||
# Instantiate the superclass normally | ||
super().__init__(*args, **kwargs) | ||
|
||
if fields is not None: | ||
# Drop any fields that are not specified in the `fields` argument. | ||
allowed = set(fields) | ||
existing = set(self.fields) | ||
for field_name in existing - allowed: | ||
self.fields.pop(field_name) | ||
|
||
if exclude is not None: | ||
# Drop any fields that are specified in the `exclude` argument. | ||
for field_name in exclude: | ||
if field_name in self.fields: | ||
self.fields.pop(field_name) | ||
|
||
|
||
class UserSerializer(DynamicFieldsModelSerializer): | ||
items = serializers.SerializerMethodField() | ||
|
||
def get_items(self, obj): | ||
return TrackItemSerializer( | ||
obj.trackitem_set, many=True, exclude=["user", "logs"] | ||
).data | ||
|
||
class Meta: | ||
model = models.User | ||
fields = [ | ||
"url", | ||
"id", | ||
"email", | ||
"first_name", | ||
"last_name", | ||
"picture", | ||
"age", | ||
"height", | ||
"weight", | ||
"items", | ||
] | ||
|
||
|
||
class PortionItemSerializer(serializers.HyperlinkedModelSerializer): | ||
class PortionItemSerializer(DynamicFieldsModelSerializer): | ||
class Meta: | ||
model = models.PortionItem | ||
fields = ["url", "name", "is_default"] | ||
fields = ["id", "name", "is_default"] | ||
|
||
|
||
class TrackItemSerializer(DynamicFieldsModelSerializer): | ||
item = PortionItemSerializer() | ||
logs = serializers.SerializerMethodField() | ||
|
||
def get_logs(self, obj): | ||
return UserLogSerializer( | ||
obj.userlog_set.filter( | ||
timestamp__gte=timezone.now().replace( | ||
hour=0, minute=0, second=0, microsecond=0 | ||
) | ||
- timedelta(days=obj.frequency) | ||
), | ||
many=True, | ||
exclude=["item"], | ||
).data | ||
|
||
class TrackItemSerializer(serializers.HyperlinkedModelSerializer): | ||
class Meta: | ||
model = models.TrackItem | ||
fields = ["url", "item", "user", "target", "order", "frequency"] | ||
fields = [ | ||
"id", | ||
"item", | ||
"user", | ||
"target", | ||
"order", | ||
"frequency", | ||
"logs", | ||
] | ||
|
||
|
||
class UserLogSerializer(DynamicFieldsModelSerializer): | ||
item = TrackItemSerializer(exclude=["logs"]) | ||
|
||
class UserLogSerializer(serializers.HyperlinkedModelSerializer): | ||
class Meta: | ||
model = models.UserLog | ||
fields = ["url", "item", "timestamp"] | ||
fields = ["id", "item", "timestamp"] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters