Commit 59c49f08 authored by konrad-ivelic's avatar konrad-ivelic
Browse files

Code refactor

Code refactoring of all the files except js
parent e1ea3e71
# Default ignored files
/shelf/
/workspace.xml
# Datasource local storage ignored files
/../../../../../../../../../:\Users\konra\Desktop\Universidad\9no_Semestre\Advanced Software Engineering\tdt4242-base\.idea/dataSources/
/dataSources.local.xml
# Editor-based HTTP Client requests
/httpRequests/
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="JSHint" enabled="true" level="ERROR" enabled_by_default="true" />
<inspection_tool class="PyPep8Inspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<option name="ignoredErrors">
<list>
<option value="E501" />
</list>
</option>
</inspection_tool>
<inspection_tool class="SqlNoDataSourceInspection" enabled="false" level="WARNING" enabled_by_default="false" />
</profile>
</component>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.9 (tdt4242-base)" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/tdt4242-base.iml" filepath="$PROJECT_DIR$/.idea/tdt4242-base.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="PyDocumentationSettings">
<option name="format" value="PLAIN" />
<option name="myDocStringFormat" value="Plain" />
</component>
<component name="TemplatesService">
<option name="TEMPLATE_FOLDERS">
<list>
<option value="$MODULE_DIR$/frontend/node_modules/cordova-android/bin/templates" />
</list>
</option>
</component>
</module>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
from django.shortcuts import render
from rest_framework import generics, mixins
from comments.models import Comment, Like
from rest_framework import permissions
......@@ -8,11 +7,11 @@ from comments.serializers import CommentSerializer, LikeSerializer
from django.db.models import Q
from rest_framework.filters import OrderingFilter
# Create your views here.
class CommentList(
mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView
):
# queryset = Comment.objects.all()
serializer_class = CommentSerializer
permission_classes = [permissions.IsAuthenticated]
filter_backends = [OrderingFilter]
......@@ -40,22 +39,20 @@ class CommentList(
- The comment is on a coach visibility workout and the user is the workout owner's coach
- The comment is on a workout owned by the user
"""
# The code below is kind of duplicate of the one in ./permissions.py
# We should replace it with a better solution.
# Or maybe not.
qs = Comment.objects.filter(
Q(workout__visibility="PU")
| Q(owner=self.request.user)
| (
Q(workout__visibility="CO")
& Q(workout__owner__coach=self.request.user)
Q(workout__visibility="CO")
& Q(workout__owner__coach=self.request.user)
)
| Q(workout__owner=self.request.user)
).distinct()
return qs
# Details of comment
class CommentDetail(
mixins.RetrieveModelMixin,
......
......@@ -4,18 +4,16 @@ from .models import Offer, AthleteFile
from django.contrib.auth import get_user_model
from .forms import CustomUserChangeForm, CustomUserCreationForm
# Register your models here.
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = get_user_model()
# list_display = UserAdmin.list_display + ('coach',)
fieldsets = UserAdmin.fieldsets + ((None, {"fields": ("coach",)}),)
add_fieldsets = UserAdmin.add_fieldsets + ((None, {"fields": ("coach",)}),)
# Register your models here.
admin.site.register(get_user_model(), CustomUserAdmin)
admin.site.register(Offer)
admin.site.register(AthleteFile)
from django.urls import path, include
from django.urls import path
from .views import ChangePasswordView
from users import views
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [
path("api/users/", views.UserList.as_view(), name="user-list"),
......@@ -15,7 +14,7 @@ urlpatterns = [
path(
"api/athlete-files/<int:pk>/",
views.AthleteFileDetail.as_view(),
name="athletefile-detail",
name="athlete-file-detail",
),
path('api/change_password/<int:pk>/', ChangePasswordView.as_view(), name='auth_change_password'),
path('api/change_password/<int:pk>/', ChangePasswordView.as_view(), name='auth_change_password'),
]
import django
from .serializers import ChangePasswordSerializer
from rest_framework import mixins, generics
from workouts.mixins import CreateListModelMixin
......@@ -11,19 +10,17 @@ from users.serializers import (
UserGetSerializer,
)
from rest_framework.permissions import (
AllowAny,
IsAdminUser,
IsAuthenticated,
IsAuthenticatedOrReadOnly,
)
from users.models import Offer, AthleteFile
from django.contrib.auth import get_user_model
from django.db.models import Q
from django.shortcuts import get_object_or_404
from rest_framework.parsers import MultiPartParser, FormParser
from users.permissions import IsCurrentUser, IsAthlete, IsCoach
from workouts.permissions import IsOwner, IsReadOnly
# Create your views here.
class UserList(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView):
serializer_class = UserSerializer
......@@ -82,12 +79,13 @@ class UserDetail(
def patch(self, request, *args, **kwargs):
return self.partial_update(request, *args, **kwargs)
class ChangePasswordView(generics.UpdateAPIView):
class ChangePasswordView(generics.UpdateAPIView):
queryset = get_user_model().objects.all()
permission_classes = (IsAuthenticated,)
serializer_class = ChangePasswordSerializer
class OfferList(
mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView
):
......@@ -104,7 +102,6 @@ class OfferList(
serializer.save(owner=self.request.user)
def get_queryset(self):
qs = Offer.objects.none()
result = Offer.objects.none()
if self.request.user:
......
......@@ -46,6 +46,41 @@ class WorkoutFileSerializer(serializers.HyperlinkedModelSerializer):
return WorkoutFile.objects.create(**validated_data)
def updateInstances(exercise_instances, exercise_instances_data):
# zip() will yield n 2-tuples, where n is
# min(len(exercise_instance), len(exercise_instance_data))
for exercise_instance, exercise_instance_data in zip(
exercise_instances.all(), exercise_instances_data
):
exercise_instance.exercise = exercise_instance_data.get(
"exercise", exercise_instance.exercise
)
exercise_instance.number = exercise_instance_data.get(
"number", exercise_instance.number
)
exercise_instance.sets = exercise_instance_data.get(
"sets", exercise_instance.sets
)
exercise_instance.save()
def add_instances(instance, exercise_instances, exercise_instances_data):
# If exercise instances have been added from the workout, then add them
if len(exercise_instances_data) > len(exercise_instances.all()):
for i in range(len(exercise_instances.all()), len(exercise_instances_data)):
exercise_instance_data = exercise_instances_data[i]
ExerciseInstance.objects.create(
workout=instance, **exercise_instance_data
)
def delete_instances(exercise_instances, exercise_instances_data):
# If exercise instances have been removed from the workout, then delete them
if len(exercise_instances_data) < len(exercise_instances.all()):
for i in range(len(exercise_instances_data), len(exercise_instances.all())):
exercise_instances.all()[i].delete()
class WorkoutSerializer(serializers.HyperlinkedModelSerializer):
"""Serializer for a Workout. Hyperlinks are used for relationships by default.
......@@ -137,33 +172,13 @@ class WorkoutSerializer(serializers.HyperlinkedModelSerializer):
# Handle ExerciseInstances
# This updates existing exercise instances without adding or deleting object.
# zip() will yield n 2-tuples, where n is
# min(len(exercise_instance), len(exercise_instance_data))
for exercise_instance, exercise_instance_data in zip(
exercise_instances.all(), exercise_instances_data
):
exercise_instance.exercise = exercise_instance_data.get(
"exercise", exercise_instance.exercise
)
exercise_instance.number = exercise_instance_data.get(
"number", exercise_instance.number
)
exercise_instance.sets = exercise_instance_data.get(
"sets", exercise_instance.sets
)
exercise_instance.save()
# If new exercise instances have been added to the workout, then create them
if len(exercise_instances_data) > len(exercise_instances.all()):
for i in range(len(exercise_instances.all()), len(exercise_instances_data)):
exercise_instance_data = exercise_instances_data[i]
ExerciseInstance.objects.create(
workout=instance, **exercise_instance_data
)
# Else if exercise instances have been removed from the workout, then delete them
elif len(exercise_instances_data) < len(exercise_instances.all()):
for i in range(len(exercise_instances_data), len(exercise_instances.all())):
exercise_instances.all()[i].delete()
updateInstances(exercise_instances, exercise_instances_data)
# This adds objects included in the database
add_instances(instance, exercise_instances, exercise_instances_data)
# This deletes instances removed from the database
delete_instances(exercise_instances, exercise_instances_data)
# Handle WorkoutFiles
......@@ -189,7 +204,8 @@ class WorkoutSerializer(serializers.HyperlinkedModelSerializer):
return instance
def get_owner_username(self, obj):
@staticmethod
def get_owner_username(obj):
"""Returns the owning user's username
Args:
......
......@@ -7,7 +7,6 @@ from rest_framework.parsers import (
JSONParser,
)
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
from django.db.models import Q
from rest_framework import filters
......@@ -29,7 +28,6 @@ from workouts.serializers import ExerciseInstanceSerializer, WorkoutFileSerializ
from django.core.exceptions import PermissionDenied
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework.response import Response
import json
from collections import namedtuple
import base64, pickle
from django.core.signing import Signer
......@@ -65,16 +63,16 @@ class RememberMe(
serializer_class = RememberMeSerializer
def get(self, request):
if request.user.is_authenticated == False:
if not request.user.is_authenticated:
raise PermissionDenied
else:
return Response({"remember_me": self.rememberme()})
return Response({"remember_me": self.remember_me()})
def post(self, request):
cookieObject = namedtuple("Cookies", request.COOKIES.keys())(
cookie_object = namedtuple("Cookies", request.COOKIES.keys())(
*request.COOKIES.values()
)
user = self.get_user(cookieObject)
user = self.get_user(cookie_object)
refresh = RefreshToken.for_user(user)
return Response(
{
......@@ -83,19 +81,20 @@ class RememberMe(
}
)
def get_user(self, cookieObject):
decode = base64.b64decode(cookieObject.remember_me)
def get_user(self, cookie_object):
decode = base64.b64decode(cookie_object.remember_me)
user, sign = pickle.loads(decode)
# Validate signature
if sign == self.sign_user(user):
return user
def rememberme(self):
def remember_me(self):
creds = [self.request.user, self.sign_user(str(self.request.user))]
return base64.b64encode(pickle.dumps(creds))
def sign_user(self, username):
@staticmethod
def sign_user(username):
signer = Signer()
signed_user = signer.sign(username)
return signed_user
......
<?xml version='1.0' encoding='utf-8'?>
<widget id="io.cordova.hellocordova" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
<name>HelloCordova</name>
<name>SecFit</name>
<description>
A sample Apache Cordova application that responds to the deviceready event.
The most secure fitness logging application there is.
</description>
<author email="dev@cordova.apache.org" href="http://cordova.io">
Apache Cordova Team
<author email="kyleo@stud.ntnu.no">
Kyle Orlando
</author>
<content src="index.html" />
<allow-intent href="http://*/*" />
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment