Skip to content

Commit

Permalink
Merge pull request #36 from akirachix/dev
Browse files Browse the repository at this point in the history
From dev to staging
  • Loading branch information
Ndichu-shee authored Sep 27, 2024
2 parents ad3066f + 7b23cf9 commit c2ceb79
Show file tree
Hide file tree
Showing 9 changed files with 106 additions and 120 deletions.
43 changes: 20 additions & 23 deletions api/serializers.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

from rest_framework import serializers
from user.models import User, ROLE_CHOICES
from django.contrib.auth.models import User
Expand All @@ -6,45 +7,41 @@
from sensor.models import Sensor
from map.models import Device
from notification.models import Notification


from user.models import User
from django.contrib.auth.models import User as DjangoUser

class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True, required=True)

class Meta:
model = User
fields = [
"id",
"first_name",
"last_name",
"phone_number",
"email",
"role",
"password",
]
read_only_fields = ["id"]
fields = ['id', 'first_name', 'last_name', 'phone_number', 'email', 'role', 'password']
read_only_fields = ['id']

def create(self, validated_data):

django_user = DjangoUser.objects.create_user(
username=validated_data["email"],
email=validated_data["email"],
password=validated_data["password"],
username=validated_data['email'],
email=validated_data['email'],
password=validated_data['password']
)

user = User.objects.create(
user=django_user,
first_name=validated_data["first_name"],
last_name=validated_data["last_name"],
phone_number=validated_data["phone_number"],
email=validated_data["email"],
role=validated_data["role"],
first_name=validated_data['first_name'],
last_name=validated_data['last_name'],
email=validated_data['email'],
phone_number=validated_data['phone_number'],
role=validated_data['role']
)
return user

return user

class RoleSerializer(serializers.Serializer):
user_id = serializers.IntegerField()



class MonitoringDataSerializer(serializers.ModelSerializer):
class Meta:
model = MonitoringData
Expand All @@ -66,8 +63,7 @@ class Meta:
class DrainageSystemSerializer(serializers.ModelSerializer):
class Meta:
model = DrainageSystem
fields = "__all__"

fields = ['Drainage_ID', 'Location', 'waterlevel', 'waterpressure', 'Status', 'Timestamp']

class DeviceSerializer(serializers.ModelSerializer):
class Meta:
Expand All @@ -85,3 +81,4 @@ class Meta:
model = Notification
fields = ["id", "title", "message", "type", "created_at"]


43 changes: 12 additions & 31 deletions api/urls.py
Original file line number Diff line number Diff line change
@@ -1,46 +1,23 @@
from django.urls import path
from .views import UserListView, UserDetailView, RegisterView, LoginView, RoleBasedView
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import UserListView, UserDetailView, RegisterView, LoginView, RoleBasedView
from .views import MonitoringDataViewSet
from .views import DrainageSystemList, DrainageSystemDetail
from map.views import map_view
from map.views import MapDeviceListView, DeviceSearchView, map_view
from .views import DrainageSystemListCreateView
from map.views import map_view, MapDeviceListView, DeviceSearchView
from .views import SensorListCreateView, SensorDetailView
from .views import NotificationViewSet

router = DefaultRouter()
router.register(r"monitoring-data", MonitoringDataViewSet)
router = DefaultRouter()
router.register(r"notifications", NotificationViewSet)

urlpatterns = router.urls
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import (
UserListView, UserDetailView, RegisterView, LoginView, RoleBasedView,
MonitoringDataViewSet, DrainageSystemList, DrainageSystemDetail,
SensorListCreateView, SensorDetailView, NotificationViewSet
)
from map.views import map_view, MapDeviceListView, DeviceSearchView


router = DefaultRouter()
router.register(r"monitoring-data", MonitoringDataViewSet)
router.register(r"notifications", NotificationViewSet)


urlpatterns = [

path('users/', UserListView.as_view(), name='user-list'),
path('users/<int:id>/', UserDetailView.as_view(), name='user-detail'),
path('users/register/', RegisterView.as_view(), name='user-register'),
path('users/login/', LoginView.as_view(), name='user-login'),
path('users/role-based/', RoleBasedView.as_view(), name='role-based'),
path("", include(router.urls)),
path("users/", UserListView.as_view(), name="user-list"),
path("users/<int:id>/", UserDetailView.as_view(), name="user-detail"),
path("users/register/", RegisterView.as_view(), name="user-register"),
path("users/login/", LoginView.as_view(), name="user-login"),
path("users/role-based/", RoleBasedView.as_view(), name="role-based"),
path("drainage-systems/", DrainageSystemList.as_view(), name="DrainageSystemList"),
path("drainage-systems/<int:pk>/", DrainageSystemDetail.as_view(), name="DrainageSystemDetail"),
path("api", map_view, name="map_view"),
path("map/", map_view, name="map_view"),
path("devices/", MapDeviceListView.as_view(), name="device-list"),
path("search/", DeviceSearchView.as_view(), name="device-search"),
Expand All @@ -49,5 +26,9 @@
path("notifications/", NotificationViewSet.as_view({"get": "list", "post": "create"})),
path("datamonitoring/", MonitoringDataViewSet.as_view({"get": "list", "post": "create"})),
path("notifications/<int:pk>/", NotificationViewSet.as_view({"get": "retrieve", "put": "update", "delete": "destroy"})),
path('api/drainage-systems/', DrainageSystemListCreateView.as_view(), name='drainage-system-list-create'),
]




87 changes: 41 additions & 46 deletions api/views.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
from django.shortcuts import render
import logging
from rest_framework import status,generics
from rest_framework import status, generics
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from django.contrib.auth.hashers import make_password
from user.models import User
from .serializers import UserSerializer, RoleSerializer
from django.contrib.auth import authenticate
from rest_framework.authtoken.models import Token
from rest_framework import viewsets
from datamonitoring.models import MonitoringData
from .serializers import MonitoringDataSerializer
Expand All @@ -19,12 +20,10 @@
from notification.models import Notification
from .serializers import NotificationSerializer


logger = logging.getLogger(__name__)


class UserListView(APIView):

def get(self, request):
users = User.objects.all()
serializer = UserSerializer(users, many=True)
Expand All @@ -36,27 +35,32 @@ def get(self, request, id):
try:
user = User.objects.get(id=id)
except User.DoesNotExist:
return Response(
{"detail": "User not found."}, status=status.HTTP_404_NOT_FOUND
)
return Response({"detail": "User not found."}, status=status.HTTP_404_NOT_FOUND)

serializer = UserSerializer(user)
logger.info(f"User with ID {id} retrieved successfully.")
return Response(serializer.data)


class RegisterView(APIView):
def post(self, request):
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
serializer.validated_data['password'] = make_password(serializer.validated_data['password'])
serializer.validated_data["password"] = make_password(
serializer.validated_data["password"]
)

user = serializer.save()
logger.info(f"User registered successfully: {user.email}")
return Response(UserSerializer(user).data, status=status.HTTP_201_CREATED)
logger.error(f"User registration failed: {serializer.errors}")
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
try:
user = serializer.save()
logger.info(f'User registered successfully: {user.email}')
return Response(UserSerializer(user).data, status=status.HTTP_201_CREATED)
except Exception as e:
logger.error(f'User registration failed: {str(e)}')
return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)

logger.error(f'User registration failed: {serializer.errors}')
serializer.validated_data['password'] = make_password(serializer.validated_data['password'])
serializer.validated_data["password"] = make_password(serializer.validated_data["password"])

user = serializer.save()
logger.info(f"User registered successfully: {user.email}")
return Response(UserSerializer(user).data, status=status.HTTP_201_CREATED)


class LoginView(APIView):
Expand All @@ -81,13 +85,17 @@ def post(self, request):

django_user = authenticate(username=email, password=password)
if django_user:
logger.info(f"User logged in successfully: {email}")
return Response({}, status=status.HTTP_200_OK)

logger.error(f"Login failed for user: {email}")
return Response(
{"error": "Invalid credentials"}, status=status.HTTP_401_UNAUTHORIZED
)
token, _ = Token.objects.get_or_create(user=django_user)
user_data = UserSerializer(user).data
response_data = {
'token': token.key,
'user': user_data
}
logger.info(f'User logged in successfully: {email}')
return Response({'message': 'Login successful'})

logger.error(f'Login failed for user: {email}')
return Response({'error': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED)


class RoleBasedView(APIView):
Expand All @@ -96,8 +104,8 @@ class RoleBasedView(APIView):
def post(self, request):
serializer = RoleSerializer(data=request.data)
if serializer.is_valid():
user_id = serializer.validated_data["user_id"]
new_role = serializer.validated_data["role"]
user_id = serializer.validated_data['user_id']
new_role = serializer.validated_data['role']

try:
user = User.objects.get(id=user_id)
Expand All @@ -114,38 +122,26 @@ def post(self, request):
{"detail": "User not found"}, status=status.HTTP_404_NOT_FOUND
)
else:
logger.error(f"Invalid role update data: {serializer.errors}")
logger.error(f'Invalid role update data: {serializer.errors}')
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class MonitoringDataViewSet(viewsets.ModelViewSet):
queryset = MonitoringData.objects.all()
serializer_class = MonitoringDataSerializer


class DrainageSystemList(APIView):
def get(self, request):
drainagesystems = DrainageSystem.objects.all()
serializer = DrainageSystemSerializer(drainagesystems, many=True)
return Response(serializer.data)


class DrainageSystemList(generics.ListCreateAPIView):
class DrainageSystemListCreateView(generics.ListCreateAPIView):
queryset = DrainageSystem.objects.all()
serializer_class = DrainageSystemSerializer

def get(self, request, *args, **kwargs):
serializer = DrainageSystemSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


def get(self, request):
drainagesystems = self.get_queryset()
serializer = self.get_serializer(drainagesystems, many=True)
return Response(serializer.data)

class DrainageSystemDetail(APIView):
def post(self, request, *args, **kwargs):
serializer = DrainageSystemSerializer(data=request.data)
def post(self, request):
serializer = self.get_serializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
Expand Down Expand Up @@ -193,4 +189,3 @@ def delete(self, request, id):
class NotificationViewSet(viewsets.ModelViewSet):
queryset = Notification.objects.all()
serializer_class = NotificationSerializer

25 changes: 14 additions & 11 deletions aquasens/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@



ALLOWED_HOSTS = [ '*']
ALLOWED_HOSTS = ['localhost']



Expand All @@ -36,16 +36,18 @@
# Application definition

INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"authentication",
"user",
"api",
"rest_framework",

'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'authentication',
'user',
'api',
'rest_framework',
'rest_framework.authtoken',
"datamonitoring",
"drainagesystem",
"map",
Expand All @@ -66,6 +68,7 @@
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware",

]

CORS_ORIGIN_ALLOW_ALL = True
Expand Down
5 changes: 5 additions & 0 deletions aquasens/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,16 @@
from django.urls import path, include
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView


urlpatterns = [
path("admin/", admin.site.urls),
path("auth/", include("authentication.urls")),
path("api/", include("api.urls")),
path("api/token/", TokenObtainPairView.as_view(), name="token_obtain_pair"),
path("api/token/refresh/", TokenRefreshView.as_view(), name="token_refresh"),
path("map/", include("map.urls")),
path('api/', include('drainagesystem.urls')),



]
4 changes: 4 additions & 0 deletions authentication/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,7 @@
path("logout", views.logout, name="logout"),
path("callback", views.callback, name="callback"),
]




7 changes: 7 additions & 0 deletions drainagesystem/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@

from django.urls import path
from api.views import DrainageSystemListCreateView

urlpatterns = [
path('drainage-systems/', DrainageSystemListCreateView.as_view(), name='drainage-system-list-create'),
]
Loading

0 comments on commit c2ceb79

Please sign in to comment.