first push

This commit is contained in:
2025-05-23 14:44:12 +08:00
commit abefd1b19b
817 changed files with 580289 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
default_app_config = 'authentication.apps.AuthenticationConfig'
+10
View File
@@ -0,0 +1,10 @@
from django.contrib import admin
from .models import User
# Register your models here.
@admin.register(User)
class SupportAdmin(admin.ModelAdmin):
list_display = ['full_name', 'email', 'role',
'organization', 'is_active', 'is_deleted', 'created_at']
+9
View File
@@ -0,0 +1,9 @@
from django.apps import AppConfig
class AuthenticationConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'authentication'
def ready(self):
import authentication.signals
+11
View File
@@ -0,0 +1,11 @@
from django.contrib.auth import authenticate
from django.contrib import messages
from django.shortcuts import redirect
def unauthenticated_user(view_func):
def wrapper(request,*args,**kwargs):
if request.user.is_authenticated:
return redirect('/')
else:
return view_func(request,*args,**kwargs)
return wrapper
+200
View File
@@ -0,0 +1,200 @@
from django import forms
from .models import User
from dashboard.models import Organization, Location
from django.contrib.auth.forms import UserCreationForm, PasswordChangeForm, PasswordResetForm, SetPasswordForm
from smart_selects.form_fields import ChainedModelChoiceField
from django.forms import URLField
from django.core.exceptions import ValidationError
class UserRegisterForm(UserCreationForm):
full_name = forms.CharField(required=True, widget=forms.TextInput(
attrs={'autocomplete': 'off', 'class': 'form-control form-control-xl', 'placeholder': 'Full name', 'autofocus': True}))
email = forms.EmailField(max_length=30, widget=forms.EmailInput(
attrs={'autocomplete': 'off', 'class': 'form-control form-control-xl', 'placeholder': 'Email'}))
username = forms.CharField(required=True, widget=forms.TextInput(
attrs={'autocomplete': 'off', 'class': 'form-control form-control-xl', 'placeholder': 'Username'}))
phone = forms.IntegerField(required=True, widget=forms.NumberInput(
attrs={'autocomplete': 'off', 'class': 'form-control form-control-xl', 'placeholder': 'Phone'}))
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['password1'].widget.attrs.update(
{'autocomplete': 'off', 'class': 'form-control form-control-xl', 'placeholder': 'Password'})
self.fields['password2'].widget.attrs.update(
{'autocomplete': 'off', 'class': 'form-control form-control-xl', 'placeholder': 'Confirm password'})
def clean_email(self):
email = self.cleaned_data.get('email')
if User.objects.filter(email=email).exists():
raise forms.ValidationError('Email already registered with us')
return email.lower()
def clean_username(self):
username = self.cleaned_data.get('username')
return username.lower()
def clean_username(self):
username = self.cleaned_data.get('username')
if User.objects.filter(username=username).exists():
raise forms.ValidationError('Username already taken')
return username
def clean_full_name(self):
full_name = self.cleaned_data.get('full_name')
return full_name.title()
class Meta:
model = User
fields = ['full_name', 'email', 'username',
'phone', 'password1', 'password2']
class OrganizationForm(forms.ModelForm):
name = forms.CharField(required=True, widget=forms.TextInput(
attrs={'autocomplete': 'off', 'class': 'form-control form-control-xl', 'placeholder': 'Company Name'}))
website = forms.CharField(required=True, widget=forms.TextInput(
attrs={'autocomplete': 'off', 'class': 'form-control form-control-xl', 'placeholder': 'Company Website'}))
def clean_name(self):
name = self.cleaned_data.get('name')
return name.title()
def clean_website(self):
url = self.cleaned_data.get('website')
url_form_field = URLField()
try:
url = url_form_field.clean(url)
except ValidationError:
raise forms.ValidationError(
'This is not a valid website name.')
return url.lower()
class Meta:
model = Organization
fields = ['name', 'website']
class UserLoginForm(forms.Form):
email = forms.EmailField(required=True, widget=forms.EmailInput(
attrs={'autocomplete': 'off', 'class': 'form-control form-control-xl', 'placeholder': 'Email'}))
password = forms.CharField(required=True, widget=forms.PasswordInput(
attrs={'autocomplete': 'off', 'class': 'form-control form-control-xl', 'placeholder': 'Password'}))
def clean_email(self):
email = self.cleaned_data.get('email')
return email.lower()
class UserPasswordChangeForm(PasswordChangeForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['old_password'].widget.attrs.update(
{'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'Old password'})
self.fields['new_password1'].widget.attrs.update(
{'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'New password'})
self.fields['new_password2'].widget.attrs.update(
{'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'Confirm password'})
class UserPasswordResetRequestForm(PasswordResetForm):
def __init__(self, *args, **kwargs):
super(UserPasswordResetRequestForm, self).__init__(*args, **kwargs)
email = forms.EmailField(required=True, widget=forms.EmailInput(
attrs={'autocomplete': 'off', 'class': 'form-control form-control-xl', 'placeholder': 'Email'}))
def clean_email(self):
email = self.cleaned_data.get('email')
if not User.objects.filter(email=email.lower(), is_active=True).exists():
raise forms.ValidationError(
'There is no user registered with the specified email address!')
return email.lower()
class UserPasswordResetForm(SetPasswordForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['new_password1'].widget.attrs.update(
{'autocomplete': 'off', 'class': 'form-control form-control-xl', 'placeholder': 'New password'})
self.fields['new_password2'].widget.attrs.update(
{'autocomplete': 'off', 'class': 'form-control form-control-xl', 'placeholder': 'Confirm password'})
class UserUpdateForm(forms.ModelForm):
full_name = forms.CharField(required=True, widget=forms.TextInput(
attrs={'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'Full name', 'autofocus': True}))
email = forms.EmailField(max_length=30, widget=forms.EmailInput(
attrs={'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'Email'}))
phone = forms.IntegerField(required=True, widget=forms.NumberInput(
attrs={'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'Phone'}))
profile_pic = forms.ImageField(
required=False,
widget=forms.FileInput(
attrs={'class': 'form-control', 'id': 'inputFile'}
))
def clean_email(self):
email = self.cleaned_data.get('email')
return email.lower()
def clean_full_name(self):
full_name = self.cleaned_data.get('full_name')
return full_name.title()
class Meta:
model = User
fields = ['full_name', 'email', 'phone', 'profile_pic']
class OrganizationUpdateForm(forms.ModelForm):
name = forms.CharField(required=True, widget=forms.TextInput(
attrs={'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'Company Name'}))
website = forms.CharField(required=True, widget=forms.TextInput(
attrs={'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'Company Website'}))
email = forms.EmailField(required=False, max_length=30, widget=forms.EmailInput(
attrs={'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'Company Email'}))
phone = forms.IntegerField(required=False, widget=forms.NumberInput(
attrs={'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'Company Phone'}))
currency = forms.CharField(required=False, widget=forms.TextInput(
attrs={'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'Company Currency'}))
date_format = forms.CharField(required=False, widget=forms.TextInput(
attrs={'autocomplete': 'off', 'class': 'form-control', 'placeholder': 'Date Format'}))
logo = forms.ImageField(required=False, widget=forms.FileInput(
attrs={'autocomplete': 'off', 'class': 'form-control', 'id': 'inputFile'}))
def clean_name(self):
name = self.cleaned_data.get('name')
return name.title()
def clean_email(self):
email = self.cleaned_data.get('email')
return email.lower()
def clean_currency(self):
currency = self.cleaned_data.get('currency')
return currency.upper()
def clean_website(self):
url = self.cleaned_data.get('website')
url_form_field = URLField()
try:
url = url_form_field.clean(url)
except ValidationError:
raise forms.ValidationError(
'This is not a valid website.')
return url.lower()
class Meta:
model = Organization
fields = ['name', 'website', 'email', 'phone',
'currency', 'date_format', 'logo']
+73
View File
@@ -0,0 +1,73 @@
# Generated by Django 3.2 on 2022-05-27 06:01
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('dashboard', '0001_initial'),
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('email', models.EmailField(max_length=255, unique=True)),
('full_name', models.CharField(blank=True, max_length=255, null=True)),
('phone', models.CharField(blank=True, max_length=255, null=True)),
('profile_pic', models.ImageField(blank=True, null=True, upload_to='profile_pics')),
('employee_id', models.CharField(blank=True, max_length=45, null=True)),
('is_active', models.BooleanField(default=True)),
('is_staff', models.BooleanField(default=False)),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('location', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='dashboard.location')),
('organization', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='dashboard.organization')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Role',
fields=[
('status', models.IntegerField(default=1)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('created_by', models.IntegerField()),
('updated_by', models.IntegerField()),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('name', models.CharField(blank=True, max_length=255, null=True)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='UserRole',
fields=[
('status', models.IntegerField(default=1)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('created_by', models.IntegerField()),
('updated_by', models.IntegerField()),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('role', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='authentication.role')),
('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
]
@@ -0,0 +1,24 @@
# Generated by Django 3.2 on 2022-06-17 06:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Register',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=30)),
('email', models.EmailField(max_length=50)),
('username', models.CharField(max_length=30)),
('pass1', models.CharField(max_length=30)),
('pass2', models.CharField(max_length=30)),
],
),
]
@@ -0,0 +1,21 @@
# Generated by Django 3.2 on 2022-06-21 13:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0002_register'),
]
operations = [
migrations.DeleteModel(
name='Register',
),
migrations.AddField(
model_name='user',
name='username',
field=models.CharField(blank=True, max_length=255, null=True),
),
]
@@ -0,0 +1,33 @@
# Generated by Django 3.2 on 2022-06-21 13:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0003_auto_20220621_1344'),
]
operations = [
migrations.AlterField(
model_name='role',
name='created_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='role',
name='updated_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='userrole',
name='created_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='userrole',
name='updated_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2022-07-02 18:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0004_auto_20220621_1350'),
]
operations = [
migrations.AlterField(
model_name='user',
name='is_active',
field=models.BooleanField(default=False),
),
]
@@ -0,0 +1,21 @@
# Generated by Django 3.2 on 2022-07-05 18:59
from django.db import migrations
import django.db.models.deletion
import smart_selects.db_fields
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0005_alter_organization_logo'),
('authentication', '0005_alter_user_is_active'),
]
operations = [
migrations.AlterField(
model_name='user',
name='location',
field=smart_selects.db_fields.ChainedForeignKey(auto_choose=True, blank=True, chained_field='organization', chained_model_field='organization', null=True, on_delete=django.db.models.deletion.CASCADE, to='dashboard.location'),
),
]
@@ -0,0 +1,21 @@
# Generated by Django 3.2 on 2022-07-05 19:10
from django.db import migrations
import django.db.models.deletion
import smart_selects.db_fields
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0005_alter_organization_logo'),
('authentication', '0006_alter_user_location'),
]
operations = [
migrations.AlterField(
model_name='user',
name='location',
field=smart_selects.db_fields.ChainedForeignKey(auto_choose=True, blank=True, chained_field='organization', chained_model_field='name', null=True, on_delete=django.db.models.deletion.CASCADE, to='dashboard.location'),
),
]
@@ -0,0 +1,20 @@
# Generated by Django 3.2 on 2022-07-05 19:46
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0005_alter_organization_logo'),
('authentication', '0007_alter_user_location'),
]
operations = [
migrations.AlterField(
model_name='user',
name='location',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='dashboard.location'),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2022-09-26 06:34
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('authentication', '0008_alter_user_location'),
]
operations = [
migrations.RenameField(
model_name='user',
old_name='profile_pic',
new_name='profile_picture',
),
]
@@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2022-09-26 06:55
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('authentication', '0009_rename_profile_pic_user_profile_picture'),
]
operations = [
migrations.RenameField(
model_name='user',
old_name='profile_picture',
new_name='profile_pic',
),
]
@@ -0,0 +1,51 @@
# Generated by Django 3.2 on 2022-10-17 11:11
import authentication.models
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0015_delete_employee'),
('roles', '0001_initial'),
('authentication', '0010_rename_profile_picture_user_profile_pic'),
]
operations = [
migrations.RemoveField(
model_name='userrole',
name='role',
),
migrations.RemoveField(
model_name='userrole',
name='user',
),
migrations.AddField(
model_name='user',
name='access_level',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AddField(
model_name='user',
name='department',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='dashboard.department'),
),
migrations.AddField(
model_name='user',
name='role',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='role', to='roles.role'),
),
migrations.AlterField(
model_name='user',
name='profile_pic',
field=models.ImageField(blank=True, null=True, upload_to=authentication.models.path_and_rename),
),
migrations.DeleteModel(
name='Role',
),
migrations.DeleteModel(
name='UserRole',
),
]
@@ -0,0 +1,24 @@
# Generated by Django 3.2 on 2022-10-18 10:15
import authentication.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0011_auto_20221017_1111'),
]
operations = [
migrations.AlterField(
model_name='user',
name='access_level',
field=models.BooleanField(default=False),
),
migrations.AlterField(
model_name='user',
name='profile_pic',
field=models.ImageField(blank=True, default='profile_pics/default.jpg', null=True, upload_to=authentication.models.path_and_rename),
),
]
@@ -0,0 +1,19 @@
# Generated by Django 3.2 on 2022-10-18 10:22
import authentication.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0012_auto_20221018_1015'),
]
operations = [
migrations.AlterField(
model_name='user',
name='profile_pic',
field=models.ImageField(blank=True, null=True, upload_to=authentication.models.path_and_rename),
),
]
@@ -0,0 +1,40 @@
# Generated by Django 3.2 on 2022-10-18 10:30
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('authentication', '0013_alter_user_profile_pic'),
]
operations = [
migrations.AddField(
model_name='user',
name='created_at',
field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AddField(
model_name='user',
name='created_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AddField(
model_name='user',
name='status',
field=models.IntegerField(default=1),
),
migrations.AddField(
model_name='user',
name='updated_at',
field=models.DateTimeField(auto_now=True),
),
migrations.AddField(
model_name='user',
name='updated_by',
field=models.CharField(blank=True, max_length=255, null=True),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2022-10-19 09:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0014_auto_20221018_1030'),
]
operations = [
migrations.AlterField(
model_name='user',
name='access_level',
field=models.BooleanField(choices=[(False, 'Only Assigned'), (True, 'All')]),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2022-10-20 06:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0015_alter_user_access_level'),
]
operations = [
migrations.AddField(
model_name='user',
name='is_deleted',
field=models.BooleanField(default=False),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2022-11-02 06:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0016_user_is_deleted'),
]
operations = [
migrations.AlterField(
model_name='user',
name='access_level',
field=models.BooleanField(choices=[(False, 'Only Assigned'), (True, 'All')], default=False),
),
]
@@ -0,0 +1,20 @@
# Generated by Django 3.2 on 2022-12-09 07:36
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0015_delete_employee'),
('authentication', '0017_alter_user_access_level'),
]
operations = [
migrations.AddField(
model_name='user',
name='address',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='dashboard.address'),
),
]
@@ -0,0 +1,20 @@
# Generated by Django 3.2 on 2022-12-13 07:50
import authentication.models
from django.db import migrations
import django_resized.forms
class Migration(migrations.Migration):
dependencies = [
('authentication', '0018_user_address'),
]
operations = [
migrations.AlterField(
model_name='user',
name='profile_pic',
field=django_resized.forms.ResizedImageField(blank=True, crop=None, force_format='JPEG', keep_meta=True, null=True, quality=75, scale=None, size=[1024, 768], upload_to=authentication.models.path_and_rename),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 3.2 on 2023-01-04 09:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0019_alter_user_profile_pic'),
]
operations = [
migrations.AlterField(
model_name='user',
name='status',
field=models.BooleanField(default=True),
),
]
@@ -0,0 +1,60 @@
# Generated by Django 3.2 on 2023-01-05 06:54
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import simple_history.models
import uuid
class Migration(migrations.Migration):
dependencies = [
('roles', '0003_alter_role_status'),
('dashboard', '0018_auto_20230104_1455'),
('authentication', '0020_alter_user_status'),
]
operations = [
migrations.CreateModel(
name='HistoricalUser',
fields=[
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('status', models.BooleanField(default=True)),
('created_at', models.DateTimeField(blank=True, editable=False)),
('updated_at', models.DateTimeField(blank=True, editable=False)),
('created_by', models.CharField(blank=True, max_length=255, null=True)),
('updated_by', models.CharField(blank=True, max_length=255, null=True)),
('is_deleted', models.BooleanField(default=False)),
('id', models.UUIDField(db_index=True, default=uuid.uuid4, editable=False)),
('email', models.EmailField(db_index=True, max_length=255)),
('username', models.CharField(blank=True, max_length=255, null=True)),
('full_name', models.CharField(blank=True, max_length=255, null=True)),
('phone', models.CharField(blank=True, max_length=255, null=True)),
('profile_pic', models.TextField(blank=True, max_length=100, null=True)),
('employee_id', models.CharField(blank=True, max_length=45, null=True)),
('is_active', models.BooleanField(default=False)),
('is_staff', models.BooleanField(default=False)),
('access_level', models.BooleanField(choices=[(False, 'Only Assigned'), (True, 'All')], default=False)),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField(db_index=True)),
('history_change_reason', models.CharField(max_length=100, null=True)),
('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)),
('address', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='dashboard.address')),
('department', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='dashboard.department')),
('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
('location', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='dashboard.location')),
('organization', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='dashboard.organization')),
('role', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='roles.role')),
],
options={
'verbose_name': 'historical user',
'verbose_name_plural': 'historical users',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': ('history_date', 'history_id'),
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
]
+91
View File
@@ -0,0 +1,91 @@
import uuid
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin, Permission
from django.contrib.contenttypes.models import ContentType
from dashboard.models import Organization, Location, Address, Department, TimeStampModel, SoftDeleteModel
from django.conf import settings
from roles.models import Role
import os
from uuid import uuid4
from django_resized import ResizedImageField
from simple_history.models import HistoricalRecords
def path_and_rename(instance, filename):
upload_to = 'profile/'
ext = filename.split('.')[-1]
if instance.pk:
filename = '{}.{}'.format(instance.pk, ext)
else:
filename = '{}.{}'.format(uuid4().hex, ext)
return os.path.join(upload_to, filename)
class UserManager(BaseUserManager):
def create_user(self, email, full_name, username, phone, password, **extra_fields):
if not email:
raise ValueError('Users must have an email address.')
user = self.model(email=self.normalize_email(email), full_name=full_name,username=username, phone=phone, **extra_fields)
user.set_password(password)
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
def create_superuser(self, email, full_name, username, phone, password, **extra_fields):
user = self.create_user(email, full_name, username, phone, password, is_active = True, access_level=True, **extra_fields)
# Create or get the Superuser default
organization = Organization.objects.filter(name='DjangoSuperUserOrganization').first()
if not organization:
organization = Organization.objects.create(name='DjangoSuperUserOrganization')
role = Role.objects.filter(related_name='Superuser', organization=organization).first()
if not role:
role = Role.objects.create(
name = "all_permissions",
related_name='Superuser',
organization=organization
)
if role.permissions.count() == 0:
all_permisisons = Permission.objects.all()
for permission in all_permisisons:
role.permissions.add(permission)
role.save()
user.role = role
user.save(using=self._db)
return user
BOOL_CHOICES = ((False, 'Only Assigned'), (True, 'All'))
class User(AbstractBaseUser, PermissionsMixin, TimeStampModel, SoftDeleteModel):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
email = models.EmailField(max_length=255, unique=True)
username = models.CharField(max_length=255 , blank=True, null=True)
full_name = models.CharField(max_length=255, blank=True, null=True)
phone = models.CharField(max_length=255, blank=True, null=True)
profile_pic = ResizedImageField(upload_to=path_and_rename, blank=True, null=True)
employee_id = models.CharField(max_length=45, blank=True, null=True)
is_active = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
organization = models.ForeignKey(Organization, models.DO_NOTHING, blank=True, null=True)
address = models.ForeignKey(Address, models.DO_NOTHING, blank=True, null=True)
location = models.ForeignKey(Location, models.DO_NOTHING, blank=True, null=True)
department = models.ForeignKey(Department, models.DO_NOTHING, blank=True, null=True)
access_level = models.BooleanField(choices=BOOL_CHOICES,default=False)
role = models.ForeignKey(Role, models.DO_NOTHING, related_name='role', blank=True, null=True)
objects = UserManager()
history = HistoricalRecords()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['full_name', 'phone', 'username']
def __str__(self):
return f'{self.full_name} ({self.role})'
+66
View File
@@ -0,0 +1,66 @@
from django.db.models.signals import post_save, post_init
from django.dispatch import receiver
from django.conf import settings
from django.template.loader import render_to_string
from django.utils.http import urlsafe_base64_encode
from django.utils.encoding import force_bytes
from django.core.mail import send_mail
from authentication.token import account_activation_token
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def send_verification_mail(sender, instance, created, **kwargs):
if created and not instance.is_active:
url = settings.LOCALHOST_URL if settings.DEBUG else settings.DEV_URL
subject = 'Account activation mail for Asset Management'
message_html = render_to_string('auth/verification/account_activation_email.html', {
'user': instance,
'url': url,
'uid': urlsafe_base64_encode(force_bytes(instance.pk)),
'token': account_activation_token.make_token(instance)
})
send_mail(
subject,
'User activation email',
'Asset Management <noreply@assetmanagement.com>',
[instance.email],
html_message=message_html,
fail_silently=False,
)
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def post_save(sender, instance, created, **kwargs):
if instance.previous_email != instance.email and not created:
sender.objects.filter(pk=instance.pk).update(is_active=False)
user = sender.objects.get(pk=instance.pk)
url = settings.LOCALHOST_URL if settings.DEBUG else settings.DEV_URL
subject = 'Account re-activation mail for Asset Management'
message_html = render_to_string('auth/verification/account_re_activation_email.html', {
'user': instance,
'url': url,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user)
})
send_mail(
subject,
'User activation email',
'Asset Management <noreply@assetmanagement.com>',
[user.email],
html_message=message_html,
fail_silently=False,
)
@receiver(post_init, sender=settings.AUTH_USER_MODEL)
def remember_state(sender, instance, **kwargs):
instance.previous_email = instance.email
+237
View File
@@ -0,0 +1,237 @@
from django.test import TestCase
from django.contrib.auth import get_user_model
from dashboard.models import Organization,Address,Location,Department
from roles.models import Role
from authentication.models import User
from vendors.models import Vendor
import uuid
# Create your tests here.
class User_Test(TestCase):
def setUp(self):
self.user_organization = Organization.objects.create(
name="Organization 1",
website="asseto.com",
phone="1234567890",
email="asseto@asseto.com",
currency="INR",
date_format="dd-mm-yyyy",
logo = "logo.png"
)
self.user_address=Address.objects.create(
country = "India",
state = "Rajasthan",
address_line_one = "testline 1",
address_line_two = "testline 2",
city = "Jaipur",
pin_code = "302001"
)
self.user_role=Role.objects.create(
related_name= "Role 1",
organization=self.user_organization,
)
self.user_location=Location.objects.create(
office_name = "Office 1",
address = self.user_address,
contact_person_name = "Person 1",
contact_person_email = "person1@asseto.com",
contact_person_phone = "1234567890",
organization = self.user_organization
)
self.user_department=Department.objects.create(
name="Department 1",
organization=self.user_organization,
contact_person_name = "Person 1",
contact_person_email = "person1@asseto.com",
contact_person_phone = "1234567890",
)
self.user=User.objects.create(
email = "mail@gmail.com",
username = 'usertest',
full_name = 'test',
phone = '1234567890',
role = self.user_role,
organization = self.user_organization,
address= self.user_address,
location=self.user_location,
department=self.user_department,
profile_pic="test.jpg",
employee_id="1234",
is_active=True,
is_staff=True,
access_level=1
)
self.edit_user_organization = Organization.objects.create(
name="Organization 2",
website="asseto2.com",
phone="123456789",
email="asseto@asseto2.com",
currency="INR2",
date_format="dd-mm-yyyy",
logo = "logo2.png"
)
self.edit_user_address=Address.objects.create(
country = "India",
state = "West Bengal",
address_line_one = "testline 11",
address_line_two = "testline 21",
city = "Kolkata",
pin_code = "700018"
)
# self.edit_user_role=Role.objects.create(
# related_name= "Role 2",
# organization=self.edit_user_organization,
# )
self.edit_user_location=Location.objects.create(
office_name = "Office 2",
address = self.edit_user_address,
contact_person_name = "Person 2",
contact_person_email = "person2@asseto.com",
contact_person_phone = "1234567899",
organization = self.edit_user_organization
)
self.edit_user_department=Department.objects.create(
name="Department 2",
organization=self.edit_user_organization,
contact_person_name = "Person 2",
contact_person_email = "person2@asseto.com",
contact_person_phone = "1234567899",
)
self.edit_user=User.objects.create(
email = "mail2@gmail.com",
username = 'usertest2',
full_name = 'test2',
phone = '1234567899',
role = self.user_role,
organization = self.edit_user_organization,
address= self.edit_user_address,
location= self.edit_user_location,
department= self.edit_user_department,
profile_pic="test2.jpg",
employee_id="12342",
is_active=True,
is_staff=True,
access_level=0
)
def test_user(self):
print("User Testing Start")
# self.user = User.objects.get(email = "mail@gmail.com")
self.assertEqual(self.user.full_name, "test")
self.assertEqual(self.user.username, "usertest")
self.assertEqual(self.user.profile_pic, "test.jpg")
self.assertEqual(self.user.phone, "1234567890")
self.assertEqual(self.user.employee_id, "1234")
self.assertEqual(self.user.is_active, True)
self.assertEqual(self.user.is_staff, True)
self.assertEqual(self.user.access_level, 1)
self.assertEqual(self.user.address.address_line_one, "testline 1")
self.assertEqual(self.user.address.address_line_two, "testline 2")
self.assertEqual(self.user.address.city, "Jaipur")
self.assertEqual(self.user.address.pin_code, "302001")
self.assertEqual(self.user.address.state, "Rajasthan")
self.assertEqual(self.user.address.country, "India")
self.assertEqual(self.user.location.office_name, "Office 1")
# self.assertEqual(user.location.contact_person_name, "Person 1")
# self.assertEqual(user.location.contact_person_email, "person1@asseto.com")
# self.assertEqual(user.location.contact_person_phone, "1234567890")
self.assertEqual(self.user.role.related_name, "Role 1")
self.assertEqual(self.user.department.name, "Department 1")
self.assertEqual(self.user.department.contact_person_name, "Person 1")
self.assertEqual(self.user.department.contact_person_email, "person1@asseto.com")
self.assertEqual(self.user.department.contact_person_phone, "1234567890")
self.assertEqual(self.user.organization.name, "Organization 1")
self.assertEqual(self.user.organization.website, "asseto.com")
self.assertEqual(self.user.organization.phone, "1234567890")
self.assertEqual(self.user.organization.email, "asseto@asseto.com")
self.assertEqual(self.user.organization.currency, "INR")
self.assertEqual(self.user.organization.date_format, "dd-mm-yyyy")
self.assertEqual(self.user.organization.logo, "logo.png")
print("User Testing Successful\n")
def test_edit_user(self):
# user = User.objects.get(email="mail2@gmail.com")
print("User Edit Testing Start")
self.user.username = "usertest2"
self.user.full_name = "test2"
self.user.phone = "1234567890"
self.user.profile_pic = "test2.jpg"
self.user.employee_id = "12342"
self.user.is_active = True
self.user.is_staff = True
self.user.access_level = 0
self.user.organization.name = "Organization 2"
self.user.organization.website = "asseto2.com"
self.user.organization.phone = "123456789"
self.user.organization.email = "asseto@asseto2.com"
self.user.organization.currency = "INR2"
self.user.organization.date_format = "dd-mm-yyyy"
self.user.organization.logo = "logo2.png"
self.user.address.country = "India"
self.user.address.state = "West Bengal"
self.user.address.address_line_one = "testline 11"
self.user.address.address_line_two = "testline 21"
self.user.address.city = "Kolkata"
self.user.address.pin_code = "700018"
self.user.location.office_name = "Office 2"
self.user.location.contact_person_name = "Person 2"
self.user.location.contact_person_email = "person2@asseto.com"
self.user.location.contact_person_phone = "1234567890"
self.user.department.name = "Department 2"
self.user.department.contact_person_name = "Person 2"
self.user.department.contact_person_email = "person2@asseto.com"
self.user.department.contact_person_phone = "1234567890"
self.user.save()
self.assertEqual(self.user.username, "usertest2")
self.assertEqual(self.user.full_name, "test2")
self.assertEqual(self.user.phone, "1234567890")
self.assertEqual(self.user.profile_pic, "test2.jpg")
self.assertEqual(self.user.employee_id, "12342")
self.assertEqual(self.user.is_active, True)
self.assertEqual(self.user.is_staff, True)
self.assertEqual(self.user.access_level, 0)
self.assertEqual(self.user.organization.name, "Organization 2")
self.assertEqual(self.user.organization.website, "asseto2.com")
self.assertEqual(self.user.organization.phone, "123456789")
self.assertEqual(self.user.organization.email, "asseto@asseto2.com")
self.assertEqual(self.user.organization.currency, "INR2")
self.assertEqual(self.user.organization.date_format, "dd-mm-yyyy")
self.assertEqual(self.user.organization.logo, "logo2.png")
self.assertEqual(self.user.address.country, "India")
self.assertEqual(self.user.address.state, "West Bengal")
self.assertEqual(self.user.address.address_line_one, "testline 11")
self.assertEqual(self.user.address.address_line_two, "testline 21")
self.assertEqual(self.user.address.city, "Kolkata")
self.assertEqual(self.user.address.pin_code, "700018")
self.assertEqual(self.user.location.office_name, "Office 2")
self.assertEqual(self.user.location.contact_person_name, "Person 2")
self.assertEqual(self.user.location.contact_person_email, "person2@asseto.com")
self.assertEqual(self.user.location.contact_person_phone, "1234567890")
self.assertEqual(self.user.department.name, "Department 2")
self.assertEqual(self.user.department.contact_person_name, "Person 2")
self.assertEqual(self.user.department.contact_person_email, "person2@asseto.com")
self.assertEqual(self.user.department.contact_person_phone, "1234567890")
print('User Edit Testing Successfuol\n')
def delete_user(self):
print("User Delete Testing Start")
self.user.delete()
# Check if the vendor object is deleted from the database
with self.assertRaises(User.DoesNotExist):
User.objects.get(id=self.product.id)
# Check if the address and organization objects are not affected
address=Address.objects.get(id=self.user.address.id)
location=Location.objects.get(id=self.user.location.id)
organization = Organization.objects.get(name=self.user.organization.id)
department=Department.objects.get(id=self.user.department.id)
role=Role.objects.get(related_name=self.user.role.related_name)
self.assertIsNotNone(location)
self.assertIsNotNone(address)
self.assertIsNotNone(department)
self.assertIsNotNone(organization)
self.assertIsNotNone(role)
print("User Delete Testing Successful\n")
+12
View File
@@ -0,0 +1,12 @@
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from six import text_type
class AccountActivationTokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self, user, timestamp):
return(
text_type(user.pk) + text_type(timestamp) + text_type(user.is_active)
)
account_activation_token = AccountActivationTokenGenerator()
+16
View File
@@ -0,0 +1,16 @@
from django.urls import path
from authentication import views
from django.contrib.auth import views as auth_views
app_name = 'authentication'
urlpatterns = [
path('', views.index, name = 'index'),
path('login', views.user_login, name = 'login'),
path('register', views.user_register, name = 'register'),
path('activate/<uidb64>/<token>', views.activate, name='activate'),
path('profile', views.profile, name='profile'),
path('logout', auth_views.LogoutView.as_view(next_page='authentication:login'), name='logout'),
path('profile-basic-information/update', views.profile_basic_info_update, name='profile_basic_info_update'),
path('organization-information/update', views.organization_info_update, name='organization_info_update'),
]
+226
View File
@@ -0,0 +1,226 @@
from django.contrib.auth.decorators import user_passes_test
from django.contrib.auth import logout
from django.shortcuts import get_object_or_404
from datetime import datetime, timedelta
from asyncio.log import logger
from django.shortcuts import redirect
from django.shortcuts import render, HttpResponse
from django.contrib import messages
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from authentication.forms import (
UserRegisterForm, OrganizationForm, UserPasswordChangeForm, UserLoginForm, UserUpdateForm, OrganizationUpdateForm)
from authentication.decorators import unauthenticated_user
from django.utils.encoding import force_bytes, force_str
from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode
from authentication.token import account_activation_token
from django.contrib.auth.models import User
from dashboard.forms import LocationForm, AddressForm
from dashboard.models import Location, Address
from django.contrib.auth import get_user_model
from products.models import Product
from vendors.models import Vendor
from assets.models import *
User = get_user_model()
@login_required
def index(request):
all_asset_cost = 0
today = datetime.now()
time_threshold = datetime.now() + timedelta(days=30)
expiring_assets = Asset.undeleted_objects.filter(organization=request.user.organization, warranty_expiry_date__lt=time_threshold).exclude(
warranty_expiry_date__lt=today).order_by('warranty_expiry_date')
all_asset_list = Asset.undeleted_objects.filter(
organization=request.user.organization)
asset_count = all_asset_list.count()
for asset in all_asset_list:
all_asset_cost = all_asset_cost + asset.price
all_product_list = Product.undeleted_objects.filter(
organization=request.user.organization)
latest_product_list = Product.undeleted_objects.filter(
organization=request.user.organization).order_by('created_at').reverse()[0:5]
product_count = all_product_list.count()
all_vendor_list = Vendor.undeleted_objects.filter(
organization=request.user.organization)
latest_vendor_list = Vendor.undeleted_objects.filter(
organization=request.user.organization).order_by('created_at').reverse()[0:5]
vendor_count = all_vendor_list.count()
location_list = Location.undeleted_objects.filter(
organization=request.user.organization)
all_location_list = Location.undeleted_objects.filter(
organization=request.user.organization).order_by('created_at').reverse()[0:5]
location_count = location_list.count()
assign_assets = AssignAsset.objects.filter(
asset__organization=request.user.organization)
assign_assets_counts = assign_assets.count()
unassign_assets_count = asset_count - assign_assets_counts
users_list = User.undeleted_objects.filter(
organization=request.user.organization).exclude(is_superuser=True)
latest_users_list = User.undeleted_objects.filter(organization=request.user.organization).exclude(
is_superuser=True).order_by('created_at').reverse()[0:5]
users_count = users_list.count()
context = {
'sidebar': 'index',
'product_count': product_count,
'vendor_count': vendor_count,
'asset_count': asset_count,
'location_count': location_count,
'all_asset_cost': all_asset_cost,
'latest_vendor_list': latest_vendor_list,
'latest_product_list': latest_product_list,
'all_location_list': all_location_list,
'assign_assets_counts': assign_assets_counts,
'unassign_assets_count': unassign_assets_count,
'latest_users_list': latest_users_list,
'users_count': users_count,
'expiring_assets': expiring_assets,
'title': 'Dashboard'
}
return render(request, 'index.html', context=context)
@unauthenticated_user
def user_login(request):
form = UserLoginForm()
if request.method == 'POST':
form = UserLoginForm(request.POST)
if form.is_valid():
email = form.cleaned_data['email']
password = form.cleaned_data['password']
user = authenticate(email=email, password=password)
if user is not None:
login(request, user)
messages.success(request, f'Welcome, {user.full_name}')
# redirecting to the requested url
if request.GET.get('next'):
return redirect(request.GET.get('next'))
return redirect('/')
else:
messages.error(request, 'Invalid credentials!')
return render(request, 'auth/login.html', context={'form': form})
@unauthenticated_user
def user_register(request):
u_form = UserRegisterForm()
o_form = OrganizationForm()
if request.method == "POST":
o_form = OrganizationForm(request.POST)
u_form = UserRegisterForm(request.POST)
if o_form.is_valid() and u_form.is_valid():
organization = o_form.save()
user = u_form.save(commit=False)
user.organization = organization
user.is_superuser = True
user.access_level = True
user.save()
messages.success(
request, f'Account for {user.full_name} created successfully. Please verify your email to continue.')
return redirect('authentication:login')
else:
messages.error(request, 'Please correct the below errors.')
return render(request, 'auth/register.html', context={'u_form': u_form, 'o_form': o_form})
@unauthenticated_user
def activate(request, uidb64, token):
User = get_user_model()
try:
uid = force_str(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=uid)
except (TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
if user is not None and account_activation_token.check_token(user, token):
user.is_active = True
user.save()
messages.success(
request, 'Your account verified successfully. You can login now.')
return redirect('authentication:login')
else:
messages.error(request, 'Invalid token.')
return redirect('authentication:login')
@login_required
def profile(request):
context = {'profile': True, 'title': 'Profile'}
return render(request, 'auth/profile.html', context=context)
@login_required
def profile_basic_info_update(request):
user = request.user
old_email = user.email
form = UserUpdateForm(instance=user)
address_form = None
if not user.is_superuser:
address = get_object_or_404(Address, pk=user.address.id)
address_form = AddressForm(request.POST or None, instance=address)
if request.method == "POST":
form = UserUpdateForm(request.POST, request.FILES, instance=user)
if user.is_superuser:
if form.is_valid():
new_email = form.cleaned_data['email']
form.save()
if (old_email) != (new_email):
logout(request)
messages.success(
request, 'Profile updated successfully. and verification mail has been sent to the new email address.')
else:
messages.success(request, 'Profile updated successfully')
return HttpResponse(status=204)
else:
if form.is_valid() and address_form.is_valid():
new_email = form.cleaned_data['email']
form.save()
address_form.save()
if (old_email) != (new_email):
logout(request)
messages.success(
request, 'Profile updated successfully. and verification mail has been sent to the new email address.')
else:
messages.success(request, 'Profile updated successfully')
return HttpResponse(status=204)
context = {'form': form, 'address_form': address_form}
return render(request, 'auth/profile_basic_info_update.html', context=context)
@login_required
@user_passes_test(lambda u: u.is_superuser)
def organization_info_update(request):
organization = request.user.organization
organization_form = OrganizationUpdateForm(instance=organization)
if request.method == "POST":
organization_form = OrganizationUpdateForm(
request.POST, request.FILES, instance=organization)
if organization_form.is_valid():
organization_form.save()
messages.success(
request, 'Organization details updated successfully')
return HttpResponse(status=204)
context = {'organization_form': organization_form,
'organization': organization}
return render(request, 'auth/organization_info_update.html', context=context)