diff --git a/server/database/app.js b/server/database/app.js index 00f52b2008..e79cf6ba15 100644 --- a/server/database/app.js +++ b/server/database/app.js @@ -17,6 +17,7 @@ mongoose.connect("mongodb://mongo_db:27017/",{'dbName':'dealershipsDB'}); const Reviews = require('./review'); const Dealerships = require('./dealership'); +const dealership = require('./dealership'); try { Reviews.deleteMany({}).then(()=>{ @@ -59,16 +60,32 @@ app.get('/fetchReviews/dealer/:id', async (req, res) => { // Express route to fetch all dealerships app.get('/fetchDealers', async (req, res) => { //Write your code here +try { + const documents = await Dealerships.find(); + res.json(documents); +} catch (error) { + res.status(500).json({ error: 'Error fetching documents' }); +} }); // Express route to fetch Dealers by a particular state app.get('/fetchDealers/:state', async (req, res) => { -//Write your code here + try { + const documents = await Dealerships.find({ state: req.params.state }); + res.json(documents); + } catch (error) { + res.status(500).json({ error: 'Error fetching documents' }); + } }); // Express route to fetch dealer by a particular id app.get('/fetchDealer/:id', async (req, res) => { -//Write your code here + try { + const documents = await Dealerships.find({ id: req.params.id }); + res.json(documents); + } catch (error) { + res.status(500).json({ error: 'Error fetching documents' }); + } }); //Express route to insert review diff --git a/server/djangoapp/.env b/server/djangoapp/.env index 01822e542a..2ceed465e8 100644 --- a/server/djangoapp/.env +++ b/server/djangoapp/.env @@ -1,2 +1,2 @@ -backend_url =your backend url +backend_url =http://localhost:3030/ sentiment_analyzer_url=your code engine deployment url diff --git a/server/djangoapp/admin.py b/server/djangoapp/admin.py index 433657fc64..5230b5ca21 100644 --- a/server/djangoapp/admin.py +++ b/server/djangoapp/admin.py @@ -1,8 +1,14 @@ # from django.contrib import admin # from .models import related models +from django.contrib import admin +from .models import CarMake, CarModel +# Registering models with their respective admins + # Register your models here. +admin.site.register(CarMake) +admin.site.register(CarModel) # CarModelInline class diff --git a/server/djangoapp/models.py b/server/djangoapp/models.py index eb101a68c8..ea05d8adf7 100644 --- a/server/djangoapp/models.py +++ b/server/djangoapp/models.py @@ -1,8 +1,8 @@ # Uncomment the following imports before adding the Model code -# from django.db import models -# from django.utils.timezone import now -# from django.core.validators import MaxValueValidator, MinValueValidator +from django.db import models +from django.utils.timezone import now +from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. @@ -13,6 +13,13 @@ # - Any other fields you would like to include in car make model # - __str__ method to print a car make object +class CarMake(models.Model): + name = models.CharField(max_length=100) + description = models.TextField() + # Other fields as needed + + def __str__(self): + return self.name # Return the name as the string representation # Create a Car Model model `class CarModel(models.Model):`: # - Many-To-One relationship to Car Make model (One Car Make has many @@ -23,3 +30,23 @@ # - Year (IntegerField) with min value 2015 and max value 2023 # - Any other fields you would like to include in car model # - __str__ method to print a car make object + +class CarModel(models.Model): + car_make = models.ForeignKey(CarMake, on_delete=models.CASCADE) # Many-to-One relationship + name = models.CharField(max_length=100) + CAR_TYPES = [ + ('SEDAN', 'Sedan'), + ('SUV', 'SUV'), + ('WAGON', 'Wagon'), + # Add more choices as required + ] + type = models.CharField(max_length=10, choices=CAR_TYPES, default='SUV') + year = models.IntegerField(default=2023, + validators=[ + MaxValueValidator(2023), + MinValueValidator(2015) + ]) + # Other fields as needed + + def __str__(self): + return self.name # Return the name as the string representation \ No newline at end of file diff --git a/server/djangoapp/populate.py b/server/djangoapp/populate.py index 1927e09e18..7a340ec248 100644 --- a/server/djangoapp/populate.py +++ b/server/djangoapp/populate.py @@ -1,2 +1,38 @@ +from .models import CarMake, CarModel + def initiate(): - print("Populate not implemented. Add data manually") + car_make_data = [ + {"name":"NISSAN", "description":"Great cars. Japanese technology"}, + {"name":"Mercedes", "description":"Great cars. German technology"}, + {"name":"Audi", "description":"Great cars. German technology"}, + {"name":"Kia", "description":"Great cars. Korean technology"}, + {"name":"Toyota", "description":"Great cars. Japanese technology"}, + ] + + car_make_instances = [] + for data in car_make_data: + car_make_instances.append(CarMake.objects.create(name=data['name'], description=data['description'])) + + + # Create CarModel instances with the corresponding CarMake instances + car_model_data = [ + {"name":"Pathfinder", "type":"SUV", "year": 2023, "car_make":car_make_instances[0]}, + {"name":"Qashqai", "type":"SUV", "year": 2023, "car_make":car_make_instances[0]}, + {"name":"XTRAIL", "type":"SUV", "year": 2023, "car_make":car_make_instances[0]}, + {"name":"A-Class", "type":"SUV", "year": 2023, "car_make":car_make_instances[1]}, + {"name":"C-Class", "type":"SUV", "year": 2023, "car_make":car_make_instances[1]}, + {"name":"E-Class", "type":"SUV", "year": 2023, "car_make":car_make_instances[1]}, + {"name":"A4", "type":"SUV", "year": 2023, "car_make":car_make_instances[2]}, + {"name":"A5", "type":"SUV", "year": 2023, "car_make":car_make_instances[2]}, + {"name":"A6", "type":"SUV", "year": 2023, "car_make":car_make_instances[2]}, + {"name":"Sorrento", "type":"SUV", "year": 2023, "car_make":car_make_instances[3]}, + {"name":"Carnival", "type":"SUV", "year": 2023, "car_make":car_make_instances[3]}, + {"name":"Cerato", "type":"Sedan", "year": 2023, "car_make":car_make_instances[3]}, + {"name":"Corolla", "type":"Sedan", "year": 2023, "car_make":car_make_instances[4]}, + {"name":"Camry", "type":"Sedan", "year": 2023, "car_make":car_make_instances[4]}, + {"name":"Kluger", "type":"SUV", "year": 2023, "car_make":car_make_instances[4]}, + # Add more CarModel instances as needed + ] + + for data in car_model_data: + CarModel.objects.create(name=data['name'], car_make=data['car_make'], type=data['type'], year=data['year']) diff --git a/server/djangoapp/restapis.py b/server/djangoapp/restapis.py index 90709d9e3b..0aef6a753e 100644 --- a/server/djangoapp/restapis.py +++ b/server/djangoapp/restapis.py @@ -1,5 +1,5 @@ # Uncomment the imports below before you add the function code -# import requests +import requests import os from dotenv import load_dotenv @@ -13,6 +13,24 @@ # def get_request(endpoint, **kwargs): # Add code for get requests to back end +def get_request(endpoint, **kwargs): + params = "" + if kwargs: + # Correctly format parameters + params = "&".join([f"{key}={value}" for key, value in kwargs.items()]) + + request_url = backend_url+endpoint+"?"+params + + print("GET from {} ".format(request_url)) + try: + # Call get method of requests library with URL and parameters + response = requests.get(request_url) + response.raise_for_status() # Check for HTTP request errors + return response.json() + except requests.exceptions.RequestException as e: + # If any error occurs, print the error + print(f"Network exception occurred: {e}") + return None # def analyze_review_sentiments(text): # request_url = sentiment_analyzer_url+"analyze/"+text diff --git a/server/djangoapp/tests.py b/server/djangoapp/tests.py new file mode 100644 index 0000000000..fb107fef46 --- /dev/null +++ b/server/djangoapp/tests.py @@ -0,0 +1,9 @@ +# Import the function to be tested +from restapis import get_request # Replace `your_module_name` with the actual module name + +# Test the get_request function +response = get_request("/api/example", param1="value1", param2="value2") +if response: + print(response) +else: + print("Failed to get a valid response.") \ No newline at end of file diff --git a/server/djangoapp/urls.py b/server/djangoapp/urls.py index 0edc274f90..34e98fb8dc 100644 --- a/server/djangoapp/urls.py +++ b/server/djangoapp/urls.py @@ -1,16 +1,22 @@ # Uncomment the imports before you add the code -# from django.urls import path +from django.urls import path from django.conf.urls.static import static from django.conf import settings -# from . import views +from django.contrib.auth import views as auth_views +from django.http import HttpResponse +from . import views app_name = 'djangoapp' + urlpatterns = [ # # path for registration # path for login - # path(route='login', view=views.login_user, name='login'), - + path(route='login', view=views.login_user, name='login'), + path('logout/', views.logout_request, name='logout'), + path('register/', views.registration, name='register'), + path('get_cars/', views.get_cars, name='get_cars'), + # path for dealer reviews view # path for add a review view diff --git a/server/djangoapp/views.py b/server/djangoapp/views.py index b16409f419..90f5b89a93 100644 --- a/server/djangoapp/views.py +++ b/server/djangoapp/views.py @@ -1,12 +1,12 @@ # Uncomment the required imports before adding the code -# from django.shortcuts import render -# from django.http import HttpResponseRedirect, HttpResponse -# from django.contrib.auth.models import User -# from django.shortcuts import get_object_or_404, render, redirect -# from django.contrib.auth import logout -# from django.contrib import messages -# from datetime import datetime +from django.shortcuts import render +from django.http import HttpResponseRedirect, HttpResponse +from django.contrib.auth.models import User +from django.shortcuts import get_object_or_404, render, redirect +from django.contrib.auth import logout +from django.contrib import messages +from datetime import datetime from django.http import JsonResponse from django.contrib.auth import login, authenticate @@ -14,6 +14,8 @@ import json from django.views.decorators.csrf import csrf_exempt # from .populate import initiate +from .models import CarMake, CarModel +from .populate import initiate # Get an instance of a logger @@ -39,13 +41,43 @@ def login_user(request): return JsonResponse(data) # Create a `logout_request` view to handle sign out request -# def logout_request(request): -# ... +@csrf_exempt +def logout_request(request): + if request.method == 'POST': + logout(request) + return JsonResponse({'status': 'success'}) + return JsonResponse({'status': 'fail', 'message': 'Invalid request method'}, status=400) # Create a `registration` view to handle sign up request -# @csrf_exempt -# def registration(request): -# ... +@csrf_exempt +def registration(request): + context = {} + data = json.loads(request.body) + username = data['userName'] + password = data['password'] + first_name = data['firstName'] + last_name = data['lastName'] + email = data['email'] + username_exist = False + email_exist = False + try: + # Check if user already exists + User.objects.get(username=username) + username_exist = True + except: + # If not, simply log this is a new user + logger.debug("{} is new user".format(username)) + # If it is a new user + if not username_exist: + # Create user in auth_user table + user = User.objects.create_user(username=username, first_name=first_name, last_name=last_name,password=password, email=email) + # Login the user and redirect to list page + login(request, user) + data = {"userName":username,"status":"Authenticated"} + return JsonResponse(data) + else : + data = {"userName":username,"error":"Already Registered"} + return JsonResponse(data) # # Update the `get_dealerships` view to render the index page with # a list of dealerships @@ -63,3 +95,16 @@ def login_user(request): # Create a `add_review` view to submit a review # def add_review(request): # ... + + +@csrf_exempt +def get_cars(request): + count = CarMake.objects.filter().count() + print(count) + if(count == 0): + initiate() + car_models = CarModel.objects.select_related('car_make') + cars = [] + for car_model in car_models: + cars.append({"CarModel": car_model.name, "CarMake": car_model.car_make.name}) + return JsonResponse({"CarModels":cars}) \ No newline at end of file diff --git a/server/djangoproj/settings.py b/server/djangoproj/settings.py index e0b1092a5c..f70d101802 100644 --- a/server/djangoproj/settings.py +++ b/server/djangoproj/settings.py @@ -14,6 +14,8 @@ from pathlib import Path +APPEND_SLASH = True + # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent @@ -28,8 +30,8 @@ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True -ALLOWED_HOSTS = [] -CSRF_TRUSTED_ORIGINS = [] +ALLOWED_HOSTS=['localhost','127.0.0.1'] +CSRF_TRUSTED_ORIGINS=[] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [], @@ -51,6 +53,7 @@ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', @@ -61,7 +64,11 @@ TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'DIRS': [], + 'DIRS': [ + os.path.join(BASE_DIR, 'frontend/static'), + os.path.join(BASE_DIR, 'frontend/build'), + os.path.join(BASE_DIR, 'frontend/build/static'), + ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ @@ -134,5 +141,15 @@ DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' -STATICFILES_DIRS = [] +STATICFILES_DIRS = [ + os.path.join(BASE_DIR, 'frontend/static'), + os.path.join(BASE_DIR, 'frontend/build'), + os.path.join(BASE_DIR, 'frontend/build/static'), +] + +LOGOUT_REDIRECT_URL = '/' + +SESSION_COOKIE_NAME = 'sessionid' +SESSION_EXPIRE_AT_BROWSER_CLOSE = True + diff --git a/server/djangoproj/urls.py b/server/djangoproj/urls.py index 6808da9141..eaf6254de6 100644 --- a/server/djangoproj/urls.py +++ b/server/djangoproj/urls.py @@ -23,4 +23,8 @@ path('admin/', admin.site.urls), path('djangoapp/', include('djangoapp.urls')), path('', TemplateView.as_view(template_name="Home.html")), + path('about/', TemplateView.as_view(template_name="About.html")), + path('contact/', TemplateView.as_view(template_name="Contact.html")), + path('login/', TemplateView.as_view(template_name="index.html")), + path('register/', TemplateView.as_view(template_name="index.html")), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) diff --git a/server/frontend/package-lock.json b/server/frontend/package-lock.json index 0797425307..b9244446c9 100644 --- a/server/frontend/package-lock.json +++ b/server/frontend/package-lock.json @@ -16,6 +16,9 @@ "react-router-dom": "^6.19.0", "react-scripts": "5.0.1", "web-vitals": "^2.1.4" + }, + "devDependencies": { + "@babel/plugin-proposal-private-property-in-object": "^7.21.11" } }, "node_modules/@aashutoshrathi/word-wrap": { @@ -646,9 +649,17 @@ } }, "node_modules/@babel/plugin-proposal-private-property-in-object": { - "version": "7.21.0-placeholder-for-preset-env.2", - "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.0-placeholder-for-preset-env.2.tgz", - "integrity": "sha512-SOSkfJDddaM7mak6cPEpswyTRnuRltl429hMraQEglW+OkovnCzsiszTmsrlY//qLFjCpQDFRvjdm2wA5pPm9w==", + "version": "7.21.11", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.11.tgz", + "integrity": "sha512-0QZ8qP/3RLDVBwBFoWAwCtgcDZJVwA5LUJRZU8x2YFfKNuFq161wK3cuGrALu5yiPu+vzwTAg/sMWVNeWeNyaw==", + "deprecated": "This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-private-property-in-object instead.", + "dev": true, + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.18.6", + "@babel/helper-create-class-features-plugin": "^7.21.0", + "@babel/helper-plugin-utils": "^7.20.2", + "@babel/plugin-syntax-private-property-in-object": "^7.14.5" + }, "engines": { "node": ">=6.9.0" }, @@ -1891,6 +1902,17 @@ "@babel/core": "^7.0.0-0" } }, + "node_modules/@babel/preset-env/node_modules/@babel/plugin-proposal-private-property-in-object": { + "version": "7.21.0-placeholder-for-preset-env.2", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.0-placeholder-for-preset-env.2.tgz", + "integrity": "sha512-SOSkfJDddaM7mak6cPEpswyTRnuRltl429hMraQEglW+OkovnCzsiszTmsrlY//qLFjCpQDFRvjdm2wA5pPm9w==", + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, "node_modules/@babel/preset-env/node_modules/semver": { "version": "6.3.1", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", diff --git a/server/frontend/src/App.js b/server/frontend/src/App.js index aceac6974d..647d0afd42 100644 --- a/server/frontend/src/App.js +++ b/server/frontend/src/App.js @@ -1,10 +1,12 @@ import LoginPanel from "./components/Login/Login" +import Register from "./components/Register/Register" import { Routes, Route } from "react-router-dom"; function App() { return ( } /> + } /> ); } diff --git a/server/frontend/src/components/Register/Register.jsx b/server/frontend/src/components/Register/Register.jsx new file mode 100644 index 0000000000..dfae839934 --- /dev/null +++ b/server/frontend/src/components/Register/Register.jsx @@ -0,0 +1,96 @@ +import React, { useState } from "react"; +import "./Register.css"; +import user_icon from "../assets/person.png" +import email_icon from "../assets/email.png" +import password_icon from "../assets/password.png" +import close_icon from "../assets/close.png" + +const Register = () => { + const [userName, setUserName] = useState(""); + const [password, setPassword] = useState(""); + const [email, setEmail] = useState(""); + const [firstName, setFirstName] = useState(""); + const [lastName, setlastName] = useState(""); + + const gohome = () => { + window.location.href = window.location.origin; + } + + const register = async (e) => { + e.preventDefault(); + + let register_url = window.location.origin + "/djangoapp/register/"; // Ensure trailing slash + + const res = await fetch(register_url, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + "userName": userName, + "password": password, + "firstName": firstName, + "lastName": lastName, + "email": email + }), + }); + + const json = await res.json(); + if (json.status) { + sessionStorage.setItem('username', json.userName); + window.location.href = window.location.origin; + } + else if (json.error === "Already Registered") { + alert("The user with the same username is already registered"); + window.location.href = window.location.origin; + } + }; + + return ( +
+
+ SignUp +
+ { gohome() }} style={{ justifyContent: "space-between", alignItems: "flex-end" }}> + X + +
+
+
+ +
+
+
+ Username + setUserName(e.target.value)} /> +
+
+ First Name + setFirstName(e.target.value)} /> +
+ +
+ Last Name + setlastName(e.target.value)} /> +
+ +
+ Email + setEmail(e.target.value)} /> +
+ +
+ password + setPassword(e.target.value)} /> +
+ +
+
+ +
+
+
+ ) +} + +export default Register; diff --git a/server/frontend/static/About.html b/server/frontend/static/About.html index 484efd960f..3294fecbf5 100644 --- a/server/frontend/static/About.html +++ b/server/frontend/static/About.html @@ -1,6 +1,7 @@ - + +