feat: initial commit - Band Management application

This commit is contained in:
2026-01-06 03:11:46 +01:00
commit 34e12e00b3
24543 changed files with 3991790 additions and 0 deletions

View File

@@ -0,0 +1,14 @@
from django.contrib import admin
from .models import Profile
# Register your models here.
class Member(admin.ModelAdmin):
list_display = (
"user",
"email",
"is_verified",
"created_at",
)
admin.site.register(Profile, Member)

View File

@@ -0,0 +1,7 @@
from django.apps import AppConfig
class AuthConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'auth'
label = 'accounts'

View File

@@ -0,0 +1,50 @@
from django.shortcuts import redirect
from django.contrib.auth.models import User
from django.contrib import messages
from django.conf import settings
from auth.helpers import send_password_reset_email
from auth.models import Profile # Import the Profile model
from auth.views import AuthView
from datetime import timedelta, datetime
import uuid
class ForgetPasswordView(AuthView):
def get(self, request):
if request.user.is_authenticated:
# If the user is already logged in, redirect them to the home page or another appropriate page.
return redirect("index") # Replace 'index' with the actual URL name for the home page
# Render the login page for users who are not logged in.
return super().get(request)
def post(self, request):
if request.method == "POST":
email = request.POST.get("email")
user = User.objects.filter(email=email).first()
if not user:
messages.error(request, "No user with this email exists.")
return redirect("forgot-password")
# Generate a token and send a password reset email here
token = str(uuid.uuid4())
# Set the token in the user's profile and add an expiration time (e.g., 24 hours from now)
expiration_time = datetime.now() + timedelta(hours=24)
user_profile, created = Profile.objects.get_or_create(user=user)
user_profile.forget_password_token = token
user_profile.forget_password_token_expiration = expiration_time
user_profile.save()
# Send the password reset email
send_password_reset_email(email, token)
if settings.EMAIL_HOST_USER and settings.EMAIL_HOST_PASSWORD:
messages.success(request, "A password reset email has been sent. Please check your inbox")
else:
messages.error(request, "Email settings are not configured. Unable to send verification email.")
return redirect("forgot-password")

View File

@@ -0,0 +1,28 @@
from django.core.mail import EmailMessage
from django.urls import reverse
from django.conf import settings
def send_email(subject, email, message):
try:
email_from = settings.EMAIL_HOST_USER
recipient_list = [email]
email = EmailMessage(subject, message, email_from, recipient_list)
email.send()
except Exception as e:
print(f"Failed to send email: {e}")
def get_absolute_url(path):
return settings.BASE_URL + path
def send_verification_email(email, token):
subject = "Verify your email"
verification_url = get_absolute_url(reverse('verify-email', kwargs={'token': token}))
message = f"Hi,\n\nPlease verify your email using this link: {verification_url}"
send_email(subject, email, message)
def send_password_reset_email(email, token):
subject = "Reset your password"
reset_url = get_absolute_url(reverse('reset-password', kwargs={'token': token}))
message = f"Hi,\n\nPlease reset your password using this link: {reset_url}"
send_email(subject, email, message)

View File

@@ -0,0 +1,50 @@
from django.shortcuts import redirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from django.contrib import messages
from auth.views import AuthView
class LoginView(AuthView):
def get(self, request):
if request.user.is_authenticated:
# If the user is already logged in, redirect them to the home page or another appropriate page.
return redirect("index") # Replace 'index' with the actual URL name for the home page
# Render the login page for users who are not logged in.
return super().get(request)
def post(self, request):
if request.method == "POST":
username = request.POST.get("email-username")
password = request.POST.get("password")
if not (username and password):
messages.error(request, "Please enter your username and password.")
return redirect("login")
if "@" in username:
user_email = User.objects.filter(email=username).first()
if user_email is None:
messages.error(request, "Please enter a valid email.")
return redirect("login")
username = user_email.username
user_email = User.objects.filter(username=username).first()
if user_email is None:
messages.error(request, "Please enter a valid username.")
return redirect("login")
authenticated_user = authenticate(request, username=username, password=password)
if authenticated_user is not None:
# Login the user if authentication is successful
login(request, authenticated_user)
# Redirect to the page the user was trying to access before logging in
if "next" in request.POST:
return redirect(request.POST["next"])
else: # Redirect to the home page or another appropriate page
return redirect("index")
else:
messages.error(request, "Please enter a valid username.")
return redirect("login")

View File

@@ -0,0 +1,33 @@
# Generated by Django 5.0 on 2023-12-08 05:28
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Profile',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('email', models.EmailField(max_length=100, unique=True)),
('email_token', models.CharField(blank=True, max_length=100, null=True)),
('forget_password_token', models.CharField(blank=True, max_length=100, null=True)),
('is_verified', models.BooleanField(default=False)),
('created_at', models.DateTimeField(auto_now_add=True)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='profile', to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'User Profile',
'verbose_name_plural': 'User Profiles',
},
),
]

View File

@@ -0,0 +1,25 @@
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
email = models.EmailField(max_length=100, unique=True) # Use unique=True for unique email addresses
email_token = models.CharField(max_length=100, blank=True, null=True)
forget_password_token = models.CharField(max_length=100, blank=True, null=True)
is_verified = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.user.username
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance, email=instance.email)
class Meta:
verbose_name = "User Profile"
verbose_name_plural = "User Profiles"

View File

@@ -0,0 +1,63 @@
from django.shortcuts import redirect
from django.contrib.auth.models import User, Group
from django.contrib import messages
from django.conf import settings
from auth.views import AuthView
from auth.helpers import send_verification_email
from auth.models import Profile
import uuid
class RegisterView(AuthView):
def get(self, request):
if request.user.is_authenticated:
# If the user is already logged in, redirect them to the home page or another appropriate page.
return redirect("index") # Replace 'index' with the actual URL name for the home page
# Render the login page for users who are not logged in.
return super().get(request)
def post(self, request):
username = request.POST.get("username")
email = request.POST.get("email")
password = request.POST.get("password")
# Check if a user with the same username or email already exists
if User.objects.filter(username=username, email=email).exists():
messages.error(request, "User already exists, Try logging in.")
return redirect("register")
elif User.objects.filter(email=email).exists():
messages.error(request, "Email already exists.")
return redirect("register")
elif User.objects.filter(username=username).exists():
messages.error(request, "Username already exists.")
return redirect("register")
# Create the user and set their password
created_user = User.objects.create_user(username=username, email=email, password=password)
created_user.set_password(password)
created_user.save()
# Add the user to the 'client' group (or any other group you want to use as default for new users)
user_group, created = Group.objects.get_or_create(name="client")
created_user.groups.add(user_group)
# Generate a token and send a verification email here
token = str(uuid.uuid4())
# Set the token in the user's profile
user_profile, created = Profile.objects.get_or_create(user=created_user)
user_profile.email_token = token
user_profile.email = email
user_profile.save()
send_verification_email(email, token)
if settings.EMAIL_HOST_USER and settings.EMAIL_HOST_PASSWORD:
messages.success(request, "Verification email sent successfully")
else:
messages.error(request, "Email settings are not configured. Unable to send verification email.")
request.session['email'] = email ## Save email in session
# Redirect to the verification page after successful registration
return redirect("verify-email-page")

View File

@@ -0,0 +1,50 @@
from django.shortcuts import render, redirect
from django.contrib import messages
from auth.models import Profile
from auth.views import AuthView
from django.contrib.auth import authenticate, login
class ResetPasswordView(AuthView):
def get(self, request,token):
if request.user.is_authenticated:
# If the user is already logged in, redirect them to the home page or another appropriate page.
return redirect("index") # Replace 'index' with the actual URL name for the home page
# Render the login page for users who are not logged in.
return super().get(request)
def post(self, request, token):
try:
profile = Profile.objects.get(forget_password_token=token)
except Profile.DoesNotExist:
messages.error(request, "Invalid or expired token.")
return redirect("forgot-password")
if request.method == "POST":
new_password = request.POST.get("password")
confirm_password = request.POST.get("confirm-password")
if not (new_password and confirm_password):
messages.error(request, "Please fill all fields.")
return render(request, "reset-password")
if new_password != confirm_password:
messages.error(request, "Passwords do not match.")
return render(request, "reset-password")
user = profile.user
user.set_password(new_password)
user.save()
# Clear the forget_password_token
profile.forget_password_token = ""
profile.save()
# Log the user in after a successful password reset
authenticated_user = authenticate(request, username=user.username, password=new_password)
if authenticated_user:
login(request, authenticated_user)
return redirect("index")
else:
messages.success(request, "Password reset successful. Please log in.")
return redirect("login")

View File

@@ -0,0 +1,59 @@
from django.urls import path
from django.contrib.auth.views import LogoutView
from .register.views import RegisterView
from .login.views import LoginView
from .forgot_password.views import ForgetPasswordView
from .reset_password.views import ResetPasswordView
from .verify_email.views import VerifyEmailTokenView , VerifyEmailView, SendVerificationView
urlpatterns = [
path(
"login/",
LoginView.as_view(template_name="auth/login.html"),
name="login",
),
path(
"logout/",
LogoutView.as_view(),
name="logout",
),
path(
"register/",
RegisterView.as_view(template_name="auth/register.html"),
name="register",
),
path(
"verify_email/",
VerifyEmailView.as_view(template_name="auth/verify_email.html"),
name="verify-email-page",
),
path(
"verify/email/<str:token>/",
VerifyEmailTokenView.as_view(),
name="verify-email",
),
path(
"send_verification/",
SendVerificationView.as_view(),
name="send-verification",
),
path(
"forgot_password/",
ForgetPasswordView.as_view(template_name="auth/forgot_password.html"),
name="forgot-password",
),
path(
"reset_password/<str:token>/",
ResetPasswordView.as_view(template_name="auth/reset_password.html"),
name="reset-password",
),
]

View File

@@ -0,0 +1,66 @@
from django.shortcuts import redirect
from django.contrib import messages
from django.conf import settings
from auth.views import AuthView
from auth.models import Profile
from auth.helpers import send_verification_email
import uuid
class VerifyEmailTokenView(AuthView):
def get(self, request, token):
try:
profile = Profile.objects.filter(email_token=token).first()
profile.is_verified = True
profile.email_token = ""
profile.save()
if not request.user.is_authenticated:
# User is not already authenticated
# Perform the email verification and any other necessary actions
messages.success(request, "Email verified successfully")
return redirect("login")
# Now, redirect to the login page
except Profile.DoesNotExist:
messages.error(request, "Invalid token, please try again")
return redirect("verify-email-page")
class VerifyEmailView(AuthView):
def get(self, request):
# Render the login page for users who are not logged in.
return super().get(request)
class SendVerificationView(AuthView):
def get(self, request):
email, message = self.get_email_and_message(request)
if email:
token = str(uuid.uuid4())
user_profile = Profile.objects.filter(email=email).first()
user_profile.email_token = token
user_profile.save()
send_verification_email(email, token)
messages.success(request, message)
else:
messages.error(request, "Email not found in session")
return redirect("verify-email-page")
def get_email_and_message(self, request):
if request.user.is_authenticated:
email = request.user.profile.email
if settings.EMAIL_HOST_USER and settings.EMAIL_HOST_PASSWORD:
message = messages.success(request, "Verification email sent successfully")
else:
message = messages.error(request, "Email settings are not configured. Unable to send verification email.")
else:
email = request.session.get('email')
if settings.EMAIL_HOST_USER and settings.EMAIL_HOST_PASSWORD:
message = "Resend verification email successfully" if email else None
else:
message = messages.error(request, "Email settings are not configured. Unable to send verification email.")
return email, message

View File

@@ -0,0 +1,26 @@
from django.views.generic import TemplateView
from web_project import TemplateLayout
from web_project.template_helpers.theme import TemplateHelper
"""
This file is a view controller for multiple pages as a module.
Here you can override the page view layout.
Refer to auth/urls.py file for more pages.
"""
class AuthView(TemplateView):
# Predefined function
def get_context_data(self, **kwargs):
# A function to init the global layout. It is defined in web_project/__init__.py file
context = TemplateLayout.init(self, super().get_context_data(**kwargs))
# Update the context
context.update(
{
"layout_path": TemplateHelper.set_layout("layout_blank.html", context),
}
)
return context