Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding temporary changes to Github #114

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
27 changes: 24 additions & 3 deletions server/database/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,17 +58,38 @@ 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 dealerships = await Dealerships.find(); // Fetch all dealerships from MongoDB
res.json(dealerships); // Return dealerships as JSON
} catch (error) {
res.status(500).json({ error: 'Error fetching dealerships' });
}
});

// Express route to fetch Dealers by a particular state
app.get('/fetchDealers/:state', async (req, res) => {
//Write your code here
try {
const state = req.params.state; // Extract state from request params
const dealerships = await Dealerships.find({ state: state }); // Fetch dealerships by state from MongoDB
res.json(dealerships); // Return dealerships for the given state as JSON
} catch (error) {
res.status(500).json({ error: 'Error fetching dealerships by state' });
}
});

// Express route to fetch dealer by a particular id
app.get('/fetchDealer/:id', async (req, res) => {
//Write your code here
try {
const dealerId = req.params.id; // Extract dealer ID from request params
const dealership = await Dealerships.findOne({ id: dealerId }); // Fetch dealership by ID from MongoDB
if (dealership) {
res.json(dealership); // Return the found dealership as JSON
} else {
res.status(404).json({ error: 'Dealership not found' }); // Return 404 if dealership not found
}
} catch (error) {
res.status(500).json({ error: 'Error fetching dealership by ID' });
}
});

//Express route to insert review
Expand Down
10 changes: 5 additions & 5 deletions server/djangoapp/urls.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
# 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 . import views

app_name = 'djangoapp'
urlpatterns = [
# # path for registration

path('register/', views.registration, name='register'),
# 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_user, name='logout'), # Add logout route
# path for dealer reviews view

# path for add a review view
Expand Down
130 changes: 88 additions & 42 deletions server/djangoapp/views.py
Original file line number Diff line number Diff line change
@@ -1,65 +1,111 @@
# 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.http import JsonResponse
from django.contrib.auth import login, authenticate
from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.contrib.auth.models import User
from django.contrib.auth import logout, login, authenticate
from django.views.decorators.csrf import csrf_exempt
import logging
import json
from django.views.decorators.csrf import csrf_exempt
# from .populate import initiate

from datetime import datetime
from .populate import initiate

# Get an instance of a logger
logger = logging.getLogger(__name__)


# Create your views here.

# Create a `login_request` view to handle sign in request
# Create a `login_user` view to handle sign in request
@csrf_exempt
def login_user(request):
# Get username and password from request.POST dictionary
data = json.loads(request.body)
username = data['userName']
password = data['password']
# Try to check if provide credential can be authenticated
user = authenticate(username=username, password=password)
data = {"userName": username}
if user is not None:
# If user is valid, call login method to login current user
login(request, user)
data = {"userName": username, "status": "Authenticated"}
return JsonResponse(data)
if request.method == 'POST':
# Get username and password from request body (JSON)
data = json.loads(request.body)
username = data.get('userName')
password = data.get('password')

# Create a `logout_request` view to handle sign out request
# def logout_request(request):
# ...
# Try to authenticate the user
user = authenticate(username=username, password=password)

if user is not None:
# If authentication is successful, log the user in
login(request, user)
response_data = {"userName": username, "status": "Authenticated"}
else:
# Authentication failed
response_data = {"status": "Error", "message": "Invalid credentials"}

return JsonResponse(response_data)

# If not POST, return an error
return JsonResponse({"status": "Error", "message": "Invalid request method"}, status=400)

# Create a `logout_user` view to handle logout request
def logout_user(request):
# Log the user out
logout(request)

# Return a JSON response
data = {"userName": ""}
return JsonResponse(data)

# Create a `registration` view to handle sign up request
# @csrf_exempt
# def registration(request):
# ...
@csrf_exempt
def registration(request):
try:
if request.method == 'POST':
# Load the JSON data from the request
data = json.loads(request.body)

# Extract user details from the request body
username = data.get('userName')
password = data.get('password')
first_name = data.get('firstName')
last_name = data.get('lastName')
email = data.get('email')

# Check if any required fields are missing
if not all([username, password, first_name, last_name, email]):
return JsonResponse({"error": "Missing fields"}, status=400)

# Check if the username already exists
if User.objects.filter(username=username).exists():
return JsonResponse({"userName": username, "error": "Already Registered"}, status=400)

# Create the new user
user = User.objects.create_user(
username=username,
password=password,
first_name=first_name,
last_name=last_name,
email=email
)

# Log in the user after creation
login(request, user)

# Return success response
return JsonResponse({"userName": username, "status": "Authenticated"}, status=201)

else:
return JsonResponse({"error": "Invalid request method"}, status=400)

except Exception as e:
# Log the exact error for debugging purposes
logger.error(f"Error during registration: {str(e)}")
return JsonResponse({"error": "Server Error", "details": str(e)}, status=500)


# # Update the `get_dealerships` view to render the index page with
# a list of dealerships
# Update the `get_dealerships` view to render the index page with a list of dealerships
# def get_dealerships(request):
# ...
# ...

# Create a `get_dealer_reviews` view to render the reviews of a dealer
# def get_dealer_reviews(request,dealer_id):
# ...
# def get_dealer_reviews(request, dealer_id):
# ...

# Create a `get_dealer_details` view to render the dealer details
# def get_dealer_details(request, dealer_id):
# ...
# ...

# Create a `add_review` view to submit a review
# def add_review(request):
# ...
# ...
18 changes: 14 additions & 4 deletions server/djangoproj/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,10 @@
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []
CSRF_TRUSTED_ORIGINS = []
ALLOWED_HOSTS = ['*'] # Allow all hosts during development
CSRF_TRUSTED_ORIGINS = [
'https://*.proxy.cognitiveclass.ai', # Matches all subdomains under this domain
]

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [],
Expand Down Expand Up @@ -61,7 +63,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': [
Expand Down Expand Up @@ -134,5 +140,9 @@

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'),
]

4 changes: 4 additions & 0 deletions server/djangoproj/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")), # Add this line
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
28 changes: 25 additions & 3 deletions server/frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion server/frontend/src/App.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import LoginPanel from "./components/Login/Login"
import React from "react";
import { Routes, Route } from "react-router-dom";
import LoginPanel from "./components/Login/Login";
import Register from "./components/Register/Register"; // Import the Register component

function App() {
return (
<Routes>
<Route path="/login" element={<LoginPanel />} />
<Route path="/register" element={<Register />} /> {/* Register route */}
</Routes>
);
}

export default App;
Loading