Skip to content

Commit

Permalink
Merge pull request #9 from Swahilipot-Hub-Developers/jilo
Browse files Browse the repository at this point in the history
backend
  • Loading branch information
jrmugweru authored Dec 13, 2023
2 parents 907f3b9 + 8958577 commit cc88c8d
Show file tree
Hide file tree
Showing 21 changed files with 411 additions and 166 deletions.
Binary file modified backend/authentication/__pycache__/__init__.cpython-312.pyc
Binary file not shown.
Binary file modified backend/authentication/__pycache__/admin.cpython-312.pyc
Binary file not shown.
Binary file modified backend/authentication/__pycache__/apps.cpython-312.pyc
Binary file not shown.
Binary file modified backend/authentication/__pycache__/models.cpython-312.pyc
Binary file not shown.
Binary file modified backend/authentication/__pycache__/urls.cpython-312.pyc
Binary file not shown.
Binary file modified backend/authentication/__pycache__/views.cpython-312.pyc
Binary file not shown.
2 changes: 1 addition & 1 deletion backend/authentication/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@

class AuthenticationConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'authentication'
name = 'authentication_app'
18 changes: 13 additions & 5 deletions backend/authentication/serializers.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
# authentication/serializers.py
# # authentication/serializers.py

from django.contrib.auth.models import User
# from django.contrib.auth.models import User
# from rest_framework import serializers

# class UserSerializer(serializers.ModelSerializer):
# class Meta:
# model = User
# fields = ['id', 'username', 'email', 'password']
# extra_kwargs = {'password': {'write_only': True}}
# serializers.py
from rest_framework import serializers
from django.contrib.auth import get_user_model

class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'username', 'email', 'password']
extra_kwargs = {'password': {'write_only': True}}
model = get_user_model()
fields = ('username', 'password') # Add other fields as needed
20 changes: 14 additions & 6 deletions backend/authentication/urls.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
# authentication/urls.py
# # authentication/urls.py

# from django.urls import path
# #from .views import CustomAuthToken, UserInfoView
# from .views import SignupView

# urlpatterns = [
# # path('api-token-auth/', CustomAuthToken.as_view(), name='api_token_auth'),
# # path('user-info/', UserInfoView.as_view(), name='user_info'),
# path('SignUp/', SignupView.as_view(), name='SignUp'),
# ]
# urls.py
from django.urls import path
#from .views import CustomAuthToken, UserInfoView
from .views import SignupView
from .views import LoginView

urlpatterns = [
# path('api-token-auth/', CustomAuthToken.as_view(), name='api_token_auth'),
# path('user-info/', UserInfoView.as_view(), name='user_info'),
path('SignUp/', SignupView.as_view(), name='SignUp'),
path('login/', LoginView.as_view(), name='login'),
# Add other URL patterns as needed
]
28 changes: 24 additions & 4 deletions backend/authentication/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,30 @@
# return Response({'user_id': request.user.pk, 'username': request.user.username})
# authentication/views.py

from rest_framework import generics
# from rest_framework import generics
# from rest_framework.response import Response
# from rest_framework import status
# from .serializers import UserSerializer

# class SignupView(generics.CreateAPIView):
# serializer_class = UserSerializer
# views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .serializers import UserSerializer
from rest_framework.authtoken.models import Token
from django.contrib.auth import authenticate

class LoginView(APIView):
def post(self, request, *args, **kwargs):
username = request.data.get('username')
password = request.data.get('password')

user = authenticate(username=username, password=password)

if user:
token, created = Token.objects.get_or_create(user=user)
return Response({'success': True, 'token': token.key}, status=status.HTTP_200_OK)
else:
return Response({'success': False, 'message': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED)

class SignupView(generics.CreateAPIView):
serializer_class = UserSerializer
Binary file modified backend/backend/__pycache__/__init__.cpython-312.pyc
Binary file not shown.
Binary file modified backend/backend/__pycache__/settings.cpython-312.pyc
Binary file not shown.
Binary file modified backend/backend/__pycache__/urls.cpython-312.pyc
Binary file not shown.
Binary file modified backend/backend/__pycache__/wsgi.cpython-312.pyc
Binary file not shown.
16 changes: 15 additions & 1 deletion backend/backend/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,10 @@
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'authentication.apps',
'authentication',
'rest_framework',
'corsheaders',
'rest_framework.authtoken',
]

MIDDLEWARE = [
Expand All @@ -49,10 +51,22 @@
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',
]
# Allow all origins for development, you might want to restrict this in production
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000", # Replace with the actual URL of your React app
]
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
'rest_framework.authentication.TokenAuthentication',
),
}


ROOT_URLCONF = 'backend.urls'

Expand Down
17 changes: 10 additions & 7 deletions backend/backend/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
URL configuration for backend project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/5.0/topics/http/urls/
https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
Expand All @@ -14,14 +14,17 @@
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""

from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path,include
from django.urls import path, include

urlpatterns = [
path('auth/', include('authentication.urls')),
path('admin/', admin.site.urls),
path('accounts/', include('django.contrib.auth.urls')), # Include authentication URLs

path('',include('django.contrib.auth.urls'),)
# Add your other app URLs here
path('api/', include("artistsmgmt.urls"))

]

if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
23 changes: 23 additions & 0 deletions frontend/package-lock.json

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

1 change: 1 addition & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"axios": "^1.6.2",
"bootstrap": "^5.3.2",
"next": "13.5.4",
"nookies": "^2.5.2",
"react": "^18",
"react-bootstrap": "^2.9.1",
"react-dom": "^18",
Expand Down
132 changes: 83 additions & 49 deletions frontend/src/pages/LogIn.js
Original file line number Diff line number Diff line change
@@ -1,49 +1,57 @@
// components/LoginForm.js


import { useState } from 'react';
import axios from 'axios';
import { useRouter } from 'next/router';
import Link from 'next/link';
// Update the import statements as needed
import Head from "next/head";
import axios from "axios";
import { useState } from "react";
import Router from "next/router";
import { setCookie } from "nookies";
import Link from "next/link";

const LoginForm = () => {
const router = useRouter();
const [formData, setFormData] = useState({
username: '',
password: '',
username: "", // Change these as per your form fields
password: "",
});

const [errorMessage, setErrorMessage] = useState("");

const handleChange = (e) => {
const { id, value } = e.target;
setFormData((prevData) => ({
...prevData,
[id]: value,
}));
setFormData({ ...formData, [e.target.id]: e.target.value });
};

const handleSubmit = async (e) => {
const handleLogin = async (e) => {
e.preventDefault();

try {
// Replace 'YOUR_BACKEND_ENDPOINT' with the actual endpoint for your backend
const response = await axios.post('YOUR_BACKEND_ENDPOINT', formData);

console.log('Form submitted successfully:', response.data);

// Check if the login was successful, you might need to adjust based on your backend response
if (response.data.success) {
// Redirect to the home page
router.push('/home');
const response = await axios.post(
"http://127.0.0.1:8000/api/login",
formData
);

if (response.status === 200) {
// Successful login handling
setErrorMessage("");
const { token } = response.data;

// Set the received token as a cookie
setCookie(null, "token", token, {
maxAge: 30 * 24 * 60 * 60, // Expiry in seconds (e.g., 30 days)
path: "/",
secure: true,
sameSite: "strict",
});

setErrorMessage("");
Router.push("/dashboard/homepage");
} else {
// Optionally, you can handle unsuccessful login here
console.log('Login failed:', response.data.message);
// Handle other possible responses (e.g., invalid credentials)
setErrorMessage("Invalid credentials. Please try again.");
Router.push("/login");
}
} catch (error) {
console.error('Error submitting form:', error);
// Handle errors or provide user feedback
console.error("Error during login:", error);
setErrorMessage("Error during login. Please try again.");
}
};

return (
<section className="h-100 gradient-form" style={{ backgroundColor: '#eee' }}>
<div className="container py-5 h-100">
Expand All @@ -57,44 +65,70 @@ const LoginForm = () => {
<div className="text-center mt-1 mb-5 pb-1">
<img src="/images/logo.png"
style={{ width: '185px' }} alt="logo" />

</div>

<form onSubmit={handleSubmit}>
<form onSubmit={handleLogin}>
<p>Please login to your account</p>

<div className="form-outline mb-4">
<input type="email" id="form2Example11" className="form-control"
placeholder="Phone number or email address" />
<label className="form-label" htmlFor="form2Example11">Username</label>
<input
type="text"
id="username"
className="form-control"
placeholder="Username"
value={formData.username}
onChange={handleChange}

/>
<label className="form-label" htmlFor="form2Example11">
Username
</label>
</div>

<div className="form-outline mb-4">
<input type="password" id="form2Example22" className="form-control" />
<label className="form-label" htmlFor="form2Example22">Password</label>
<input
type="password"
id="password"
className="form-control"
value={formData.password}
onChange={handleChange}
/>
<label className="form-label" htmlFor="form2Example22">
Password
</label>
</div>

<div className="text-center pt-1 mb-5 pb-1">
<button className="btn btn-primary btn-block fa-lg gradient-custom-2 mb-3" type="submit">Log
in</button>
<a className="text-muted" href="#!">Forgot password?</a>
<button
className="btn btn-primary btn-block fa-lg gradient-custom-2 mb-3"
type="submit"
>
Log in
</button>
<a className="text-muted" href="#!">
Forgot password?
</a>
</div>

{errorMessage && <p className="text-danger">{errorMessage}</p>}

<p>
Don't have an account?{' '}
<Link href="/SignUp" className="link-info">
Register here
</Link>
</p>
Don't have an account?{' '}
<Link href="/SignUp" className="link-info">
Register here
</Link>
</p>

</form>

</div>
</div>
<div className="col-lg-6 d-flex align-items-center gradient-custom-2">
<div className="text-white px-3 py-4 p-md-5 mx-md-4">
<h4 className="mb-4">Welcome to Swahilipot Hub Management System</h4>
<p className="small mb-0">This is Swahilipot hu event management system where one can create an event
create tickets for the events, input banner for the events</p>
<p className="small mb-0">
This is Swahilipot hu event management system where one can create an event create tickets for the
events, input banner for the events
</p>
</div>
</div>
</div>
Expand Down
Loading

0 comments on commit cc88c8d

Please sign in to comment.