From 759e8b6ddb774c932f7a931a16acce2407e40f0a Mon Sep 17 00:00:00 2001 From: Omer Habib Date: Tue, 15 Jan 2019 18:49:13 +0500 Subject: [PATCH 1/3] Added accounts app and models --- DonationApp/settings.py | 1 + accounts/__init__.py | 0 accounts/admin.py | 5 +++ accounts/apps.py | 5 +++ accounts/migrations/0001_initial.py | 54 +++++++++++++++++++++++++++++ accounts/migrations/__init__.py | 0 accounts/models.py | 52 +++++++++++++++++++++++++++ accounts/tests.py | 3 ++ accounts/views.py | 3 ++ 9 files changed, 123 insertions(+) create mode 100644 accounts/__init__.py create mode 100644 accounts/admin.py create mode 100644 accounts/apps.py create mode 100644 accounts/migrations/0001_initial.py create mode 100644 accounts/migrations/__init__.py create mode 100644 accounts/models.py create mode 100644 accounts/tests.py create mode 100644 accounts/views.py diff --git a/DonationApp/settings.py b/DonationApp/settings.py index 08f9f97..d07aebb 100644 --- a/DonationApp/settings.py +++ b/DonationApp/settings.py @@ -31,6 +31,7 @@ # Application definition INSTALLED_APPS = [ + 'accounts.apps.AccountsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', diff --git a/accounts/__init__.py b/accounts/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/accounts/admin.py b/accounts/admin.py new file mode 100644 index 0000000..fd8e5a1 --- /dev/null +++ b/accounts/admin.py @@ -0,0 +1,5 @@ +from django.contrib import admin +from .models import Financer, Consumer + +admin.site.register(Financer) +admin.site.register(Consumer) diff --git a/accounts/apps.py b/accounts/apps.py new file mode 100644 index 0000000..9b3fc5a --- /dev/null +++ b/accounts/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class AccountsConfig(AppConfig): + name = 'accounts' diff --git a/accounts/migrations/0001_initial.py b/accounts/migrations/0001_initial.py new file mode 100644 index 0000000..b7373dc --- /dev/null +++ b/accounts/migrations/0001_initial.py @@ -0,0 +1,54 @@ +# Generated by Django 2.1.3 on 2019-01-15 12:09 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Consumer', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('first_name', models.CharField(max_length=100)), + ('last_name', models.CharField(max_length=100)), + ('gender', models.CharField(choices=[('M', 'Male'), ('F', 'Female')], max_length=10)), + ('occupation', models.CharField(max_length=255, null=True)), + ('profile_pic', models.ImageField(null=True, upload_to='images/')), + ('username', models.EmailField(max_length=50, unique=True)), + ('email', models.EmailField(max_length=100, unique=True)), + ('date_of_birth', models.DateField(default='2000-01-01')), + ('mobile', models.CharField(default=0, max_length=11)), + ('address', models.CharField(max_length=255)), + ('created_on', models.DateTimeField(auto_now_add=True)), + ], + ), + migrations.CreateModel( + name='Financer', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('first_name', models.CharField(max_length=100)), + ('last_name', models.CharField(max_length=100)), + ('gender', models.CharField(choices=[('M', 'Male'), ('F', 'Female')], max_length=10)), + ('profile_pic', models.ImageField(upload_to='images/')), + ('username', models.EmailField(max_length=50, unique=True)), + ('email', models.EmailField(max_length=100, unique=True)), + ('date_of_birth', models.DateField(default='2000-01-01')), + ('mobile', models.CharField(default=0, max_length=11)), + ('address', models.CharField(max_length=255)), + ('created_on', models.DateTimeField(auto_now_add=True)), + ('account_balance', models.BigIntegerField()), + ], + ), + migrations.AddField( + model_name='consumer', + name='financer', + field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='accounts.Financer'), + ), + ] diff --git a/accounts/migrations/__init__.py b/accounts/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/accounts/models.py b/accounts/models.py new file mode 100644 index 0000000..9021e86 --- /dev/null +++ b/accounts/models.py @@ -0,0 +1,52 @@ +from django.db import models + + +GENDER_TYPES = ( + ('M', 'Male'), + ('F', 'Female'), +) + + +class Financer(models.Model): + + first_name = models.CharField(max_length=100) + last_name = models.CharField(max_length=100) + gender = models.CharField(choices=GENDER_TYPES, max_length=10) + profile_pic = models.ImageField(upload_to='images/') + username = models.EmailField(max_length=50, unique=True) + email = models.EmailField(max_length=100, unique=True) + date_of_birth = models.DateField(default='2000-01-01') + mobile = models.CharField(max_length=11, default=0) + address = models.CharField(max_length=255) + created_on = models.DateTimeField(auto_now_add=True) + account_balance = models.BigIntegerField() + + def __str__(self): + return self.username + + def get_full_name(self): + return self.first_name + ' ' + self.last_name + + +class Consumer(models.Model): + + first_name = models.CharField(max_length=100) + last_name = models.CharField(max_length=100) + gender = models.CharField(choices=GENDER_TYPES, max_length=10) + occupation = models.CharField(max_length=255, null=True) + profile_pic = models.ImageField(upload_to='images/', null=True) + username = models.EmailField(max_length=50, unique=True) + email = models.EmailField(max_length=100, unique=True) + date_of_birth = models.DateField(default='2000-01-01') + mobile = models.CharField(max_length=11, default=0) + address = models.CharField(max_length=255) + created_on = models.DateTimeField(auto_now_add=True) + financer = models.ForeignKey(Financer, on_delete=models.CASCADE, null=True) + + def __str__(self): + return self.username + + def get_full_name(self): + return self.first_name + ' ' + self.last_name + + diff --git a/accounts/tests.py b/accounts/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/accounts/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/accounts/views.py b/accounts/views.py new file mode 100644 index 0000000..91ea44a --- /dev/null +++ b/accounts/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. From 43c597ffcc50f050769d3de38c7323c486cff6b5 Mon Sep 17 00:00:00 2001 From: Omer Habib Date: Thu, 24 Jan 2019 20:06:38 +0500 Subject: [PATCH 2/3] Create Custom Authentication for user --- DonationApp/__init__.py | 0 DonationApp/settings.py | 9 ++- DonationApp/templates/base.html | 71 +++++++++++++++++++ DonationApp/urls.py | 7 +- accounts/__init__.py | 0 accounts/admin.py | 1 + accounts/backends.py | 21 ++++++ accounts/forms.py | 64 +++++++++++++++++ accounts/migrations/0001_initial.py | 47 +++++++++---- accounts/models.py | 66 ++++++++++++++++-- accounts/templates/accounts/index.html | 10 +++ accounts/templates/accounts/login.html | 25 +++++++ accounts/templates/accounts/signup.html | 89 ++++++++++++++++++++++++ accounts/urls.py | 11 +++ accounts/views.py | 92 ++++++++++++++++++++++++- 15 files changed, 486 insertions(+), 27 deletions(-) delete mode 100644 DonationApp/__init__.py create mode 100644 DonationApp/templates/base.html delete mode 100644 accounts/__init__.py create mode 100644 accounts/backends.py create mode 100644 accounts/forms.py create mode 100644 accounts/templates/accounts/index.html create mode 100644 accounts/templates/accounts/login.html create mode 100644 accounts/templates/accounts/signup.html create mode 100644 accounts/urls.py diff --git a/DonationApp/__init__.py b/DonationApp/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/DonationApp/settings.py b/DonationApp/settings.py index d07aebb..81a114e 100644 --- a/DonationApp/settings.py +++ b/DonationApp/settings.py @@ -52,10 +52,14 @@ ROOT_URLCONF = 'DonationApp.urls' +AUTH_USER_MODEL = 'accounts.Financer' +# AUTHENTICATION_BACKENDS = ('accounts.backends.FinancerAuth',) +AUTHENTICATION_BACKENDS = ('accounts.backends.FinancerAuth', 'django.contrib.auth.backends.ModelBackend',) + TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'DIRS': [], + 'DIRS': ['DonationApp/templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ @@ -119,3 +123,6 @@ # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' + +MEDIA_ROOT = os.path.join(BASE_DIR, 'media') +MEDIA_URL = '/media/' \ No newline at end of file diff --git a/DonationApp/templates/base.html b/DonationApp/templates/base.html new file mode 100644 index 0000000..b15e341 --- /dev/null +++ b/DonationApp/templates/base.html @@ -0,0 +1,71 @@ + + + + + + + + + + Donation App + + + + + + + + + +
+ +
+ +
+ {% block content %} + + {% endblock %} +
+ +
+
+

CopyRight Omer Habib {% now "Y" %}

+
+
+ + + + + diff --git a/DonationApp/urls.py b/DonationApp/urls.py index e755dde..a06f8ea 100644 --- a/DonationApp/urls.py +++ b/DonationApp/urls.py @@ -14,8 +14,11 @@ 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin -from django.urls import path +from django.urls import path, include +from django.conf import settings +from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), -] + path('', include('accounts.urls')), +] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) diff --git a/accounts/__init__.py b/accounts/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/accounts/admin.py b/accounts/admin.py index fd8e5a1..a8146af 100644 --- a/accounts/admin.py +++ b/accounts/admin.py @@ -1,4 +1,5 @@ from django.contrib import admin + from .models import Financer, Consumer admin.site.register(Financer) diff --git a/accounts/backends.py b/accounts/backends.py new file mode 100644 index 0000000..4e3df2c --- /dev/null +++ b/accounts/backends.py @@ -0,0 +1,21 @@ +from .models import Financer + + +class FinancerAuth(object): + + def authenticate(self, request, email=None, password=None): + try: + user = Financer.objects.get(email=email) + if user.check_password(password): + return user + except Financer.DoesNotExist: + return None + + def get_user(self, user_id): + try: + user = Financer.objects.get(email=user_id) + if user.is_active: + return user + return None + except Financer.DoesNotExist: + return None diff --git a/accounts/forms.py b/accounts/forms.py new file mode 100644 index 0000000..9b8cefa --- /dev/null +++ b/accounts/forms.py @@ -0,0 +1,64 @@ +from django import forms +from django.forms import ModelForm +from django.core.exceptions import NON_FIELD_ERRORS +from .models import Financer, Consumer +from django.contrib.auth import authenticate + + +GENDER_TYPES = ( + ('M', 'Male'), + ('F', 'Female'), +) + + +class FinancerForm(ModelForm): + class Meta: + model = Financer + fields = ['first_name', 'last_name', 'gender', 'password', 'profile_pic', 'username', 'email', 'date_of_birth', + 'mobile', 'address', 'city', 'state', 'country'] + error_messages = { + NON_FIELD_ERRORS: { + 'unique_together': "%(model_name)s's %(field_labels)s are not unique.", + } + } + + def save(self, commit=True): + user = super(FinancerForm, self).save(commit=False) + user.set_password(user.password) # set password properly before commit + if commit: + user.save() + return user + + +class ConsumerForm(ModelForm): + class Meta: + model = Consumer + fields = ['first_name', 'last_name', 'gender', 'password', 'profile_pic', 'username', 'email', 'date_of_birth', + 'mobile', 'address', 'city', 'state', 'country'] + error_messages = { + NON_FIELD_ERRORS: { + 'unique_together': "%(model_name)s's %(field_labels)s are not unique.", + } + } + + +class SignUp(forms.Form): + + username = forms.CharField(label="Username", max_length=100) + email = forms.EmailField() + password = forms.CharField(widget=forms.PasswordInput()) + first_name = forms.CharField(max_length=100) + last_name = forms.CharField(max_length=100) + gender = forms.ChoiceField() + date_of_birth = forms.DateField() + mobile = forms.CharField(max_length=11) + address = forms.CharField(max_length=255) + city = forms.CharField(max_length=100) + state = forms.CharField(max_length=100) + country = forms.CharField(max_length=100) + + +class LoginForm(forms.Form): + email = forms.EmailField(label="Email", max_length=100) + password = forms.CharField(label="Password", widget=forms.PasswordInput()) + diff --git a/accounts/migrations/0001_initial.py b/accounts/migrations/0001_initial.py index b7373dc..49fa79b 100644 --- a/accounts/migrations/0001_initial.py +++ b/accounts/migrations/0001_initial.py @@ -1,5 +1,7 @@ -# Generated by Django 2.1.3 on 2019-01-15 12:09 +# Generated by Django 2.1.3 on 2019-01-24 14:24 +import datetime +from django.conf import settings from django.db import migrations, models import django.db.models.deletion @@ -9,46 +11,61 @@ class Migration(migrations.Migration): initial = True dependencies = [ + ('auth', '0009_alter_user_last_name_max_length'), ] operations = [ migrations.CreateModel( - name='Consumer', + name='Financer', fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('first_name', models.CharField(max_length=100)), ('last_name', models.CharField(max_length=100)), ('gender', models.CharField(choices=[('M', 'Male'), ('F', 'Female')], max_length=10)), - ('occupation', models.CharField(max_length=255, null=True)), + ('password', models.CharField(max_length=31)), ('profile_pic', models.ImageField(null=True, upload_to='images/')), - ('username', models.EmailField(max_length=50, unique=True)), - ('email', models.EmailField(max_length=100, unique=True)), + ('username', models.CharField(max_length=50, unique=True)), + ('email', models.EmailField(max_length=100, primary_key=True, serialize=False, unique=True)), ('date_of_birth', models.DateField(default='2000-01-01')), ('mobile', models.CharField(default=0, max_length=11)), ('address', models.CharField(max_length=255)), + ('city', models.CharField(max_length=100)), + ('state', models.CharField(max_length=100)), + ('country', models.CharField(max_length=100)), ('created_on', models.DateTimeField(auto_now_add=True)), + ('account_balance', models.BigIntegerField(default=0)), + ('date_joined', models.DateTimeField(default=datetime.datetime.now, verbose_name='date joined')), + ('is_active', models.BooleanField(default=True)), + ('is_admin', models.BooleanField(default=False)), + ('is_staff', models.BooleanField(default=False)), + ('is_superuser', 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')), + ('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='Financer', + name='Consumer', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(max_length=100)), ('last_name', models.CharField(max_length=100)), ('gender', models.CharField(choices=[('M', 'Male'), ('F', 'Female')], max_length=10)), - ('profile_pic', models.ImageField(upload_to='images/')), - ('username', models.EmailField(max_length=50, unique=True)), + ('password', models.CharField(max_length=31)), + ('occupation', models.CharField(max_length=255, null=True)), + ('profile_pic', models.ImageField(null=True, upload_to='images/')), + ('username', models.CharField(max_length=50, unique=True)), ('email', models.EmailField(max_length=100, unique=True)), ('date_of_birth', models.DateField(default='2000-01-01')), ('mobile', models.CharField(default=0, max_length=11)), ('address', models.CharField(max_length=255)), + ('city', models.CharField(max_length=100)), + ('state', models.CharField(max_length=100)), + ('country', models.CharField(max_length=100)), ('created_on', models.DateTimeField(auto_now_add=True)), - ('account_balance', models.BigIntegerField()), + ('financer', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), - migrations.AddField( - model_name='consumer', - name='financer', - field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='accounts.Financer'), - ), ] diff --git a/accounts/models.py b/accounts/models.py index 9021e86..3aa8423 100644 --- a/accounts/models.py +++ b/accounts/models.py @@ -1,4 +1,8 @@ from django.db import models +from django.contrib.auth.models import PermissionsMixin +from django.contrib.auth.models import AbstractBaseUser, BaseUserManager +from datetime import datetime +from django.utils.translation import ugettext_lazy as _ GENDER_TYPES = ( @@ -7,25 +11,69 @@ ) -class Financer(models.Model): +class CustomUserManager(BaseUserManager): + def _create_user(self, username, password, is_staff, is_superuser, is_admin, **extra_fields): + now = datetime.now() + + user = self.model(username=username, + is_staff=is_staff, is_active=True, + is_superuser=is_superuser, last_login=now, + date_joined=now, **extra_fields) + user.is_admin = is_admin + user.set_password(password) + user.save(using=self._db) + return user + + def create_user(self, username, password=None, **extra_fields): + return self._create_user(username, password, False, False, False, **extra_fields) + + def create_superuser(self, username, password=None, **extra_fields): + return self._create_user(username, password, True, True, True, **extra_fields) + + +class Financer(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) gender = models.CharField(choices=GENDER_TYPES, max_length=10) - profile_pic = models.ImageField(upload_to='images/') - username = models.EmailField(max_length=50, unique=True) - email = models.EmailField(max_length=100, unique=True) + password = models.CharField(max_length=31) + profile_pic = models.ImageField(upload_to='images/', null=True) + username = models.CharField(max_length=50, unique=True) + email = models.EmailField(max_length=100, primary_key=True, unique=True) date_of_birth = models.DateField(default='2000-01-01') mobile = models.CharField(max_length=11, default=0) address = models.CharField(max_length=255) + city = models.CharField(max_length=100) + state = models.CharField(max_length=100) + country = models.CharField(max_length=100) created_on = models.DateTimeField(auto_now_add=True) - account_balance = models.BigIntegerField() + account_balance = models.BigIntegerField(default=0) + + date_joined = models.DateTimeField(_('date joined'), default=datetime.now) + is_active = models.BooleanField(default=True) + is_admin = models.BooleanField(default=False) + is_staff = models.BooleanField(default=False) + is_superuser = models.BooleanField(default=False) + + USERNAME_FIELD = 'username' + REQUIRED_FIELDS = ['first_name', 'last_name', 'email'] + + objects = CustomUserManager() def __str__(self): return self.username def get_full_name(self): - return self.first_name + ' ' + self.last_name + full_name = '%s %s' % (self.first_name, self.last_name) + return full_name.strip() + + # this methods are require to login super user from admin panel + def has_perm(self, perm, obj=None): + return self.is_admin + + # this methods are require to login super user from admin panel + def has_module_perms(self, app_label): + return self.is_admin class Consumer(models.Model): @@ -33,13 +81,17 @@ class Consumer(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) gender = models.CharField(choices=GENDER_TYPES, max_length=10) + password = models.CharField(max_length=31) occupation = models.CharField(max_length=255, null=True) profile_pic = models.ImageField(upload_to='images/', null=True) - username = models.EmailField(max_length=50, unique=True) + username = models.CharField(max_length=50, unique=True) email = models.EmailField(max_length=100, unique=True) date_of_birth = models.DateField(default='2000-01-01') mobile = models.CharField(max_length=11, default=0) address = models.CharField(max_length=255) + city = models.CharField(max_length=100) + state = models.CharField(max_length=100) + country = models.CharField(max_length=100) created_on = models.DateTimeField(auto_now_add=True) financer = models.ForeignKey(Financer, on_delete=models.CASCADE, null=True) diff --git a/accounts/templates/accounts/index.html b/accounts/templates/accounts/index.html new file mode 100644 index 0000000..c2d5649 --- /dev/null +++ b/accounts/templates/accounts/index.html @@ -0,0 +1,10 @@ +{% extends 'base.html' %} + +{% block content %} +

Welcome

+{% csrf_token %} + {% if user.is_authenticated %} +

{{ user.get_full_name }}

+

User is Authenticated

+{% endif %} +{% endblock %} diff --git a/accounts/templates/accounts/login.html b/accounts/templates/accounts/login.html new file mode 100644 index 0000000..fc26419 --- /dev/null +++ b/accounts/templates/accounts/login.html @@ -0,0 +1,25 @@ + + + + + Login + {% extends 'base.html' %} + + +{% block content %} +

Login

+ +{% if form.errors %} + Invalid Login Details {{ form.errors.as_data}} +{% endif %} +
+ + {% csrf_token %} + + {{ form.as_p }} + +
+ +{% endblock %} + + \ No newline at end of file diff --git a/accounts/templates/accounts/signup.html b/accounts/templates/accounts/signup.html new file mode 100644 index 0000000..98a8520 --- /dev/null +++ b/accounts/templates/accounts/signup.html @@ -0,0 +1,89 @@ + + + + + Sign Up + {% extends 'base.html' %} + + + +{% block content %} +

Sign Up

+ +{% if error %} +
{{ error }}
+
+{% endif %} +
+ + {% csrf_token %} + Select Account Type: +
+ Financer + Consumer +
+ Username: +
+ +
+ Email: +
+ +
+ Password: +
+ +
+ Confirm Password: +
+ +
+ Profile Pic +
+ +
+ First Name: +
+ +
+ Last Name: +
+ +
+ Gender: +
+ Male + Female +
+ Date of Birth: +
+ +
+ Mobile No: +
+ +
+ Address: +
+ +
+ City: +
+ +
+ State: +
+ +
+ Country: +
+ +
+
+
+ +
+ +{% endblock %} + + \ No newline at end of file diff --git a/accounts/urls.py b/accounts/urls.py new file mode 100644 index 0000000..1bbf284 --- /dev/null +++ b/accounts/urls.py @@ -0,0 +1,11 @@ +from django.urls import path +from . import views + +app_name = 'accounts' + +urlpatterns = [ + path('', views.index, name='index'), + path('login/', views.login, name='login'), + path('logout/', views.logout, name='logout'), + path('signup/', views.signup, name='signup'), +] \ No newline at end of file diff --git a/accounts/views.py b/accounts/views.py index 91ea44a..e1dd6b2 100644 --- a/accounts/views.py +++ b/accounts/views.py @@ -1,3 +1,91 @@ -from django.shortcuts import render +from django.http import HttpResponse +from django.shortcuts import render, redirect +from .models import Financer, Consumer +from django.utils import timezone +from .forms import SignUp, LoginForm, FinancerForm, ConsumerForm +from django.contrib import auth +from django.contrib.auth import authenticate -# Create your views here. + +def index(request): + return render(request, 'accounts/index.html') + + +def signup(request): + if request.method == 'POST': + form = SignUp(request.POST) + + # if form.is_valid(): + # return redirect('accounts:index') + + if request.POST['password'] == request.POST['password2']: + if request.POST['type'] == 'financer': + try: + financer = Financer.objects.get(username=request.POST['username']) + return render(request, 'accounts/signup.html', {'error': 'Username has already been taken'}) + except Financer.DoesNotExist: + try: + financer = Financer.objects.get(email=request.POST['email']) + return render(request, 'accounts/signup.html', + {'error': 'Email is already associated with another account'}) + except Financer.DoesNotExist: + financer = FinancerForm(request.POST, files=request.FILES) + + if financer.is_valid(): + user = financer.save(commit=False) + user.set_password(request.POST['password']) + user.save() + return redirect('accounts:index') + else: + return render(request, 'accounts/signup.html', {'form': form}) + + elif request.POST['type'] == 'consumer': + try: + consumer = Consumer.objects.get(username=request.POST['username']) + return render(request, 'accounts/signup.html', {'error': 'Username has already been taken'}) + except Consumer.DoesNotExist: + try: + consumer = Consumer.objects.get(email=request.POST['email']) + return render(request, 'accounts/signup.html', + {'error': 'Email is already associated with another account'}) + except Consumer.DoesNotExist: + consumer = ConsumerForm(request.POST, files=request.FILES) + + if consumer.is_valid(): + consumer.save() + return redirect('accounts:index') + else: + return render(request, 'accounts/signup.html', {'form': form}) + else: + return render(request, 'accounts/signup.html', {'error': 'Password does not matched'}) + else: + return render(request, 'accounts/signup.html', ) + + +def login(request): + form = LoginForm(request.POST or None) + if form.is_valid(): + # # + # user = Financer.objects.get(email=form.cleaned_data.get('email')) + # user.check_password(form.cleaned_data['password']) + # user = authenticate(email=form.cleaned_data['email'], password=form.cleaned_data['password']) + email = form.cleaned_data.get('email') + password = form.cleaned_data.get('password') + user = auth.authenticate(email=email, password=password) + + if user is not None: + auth.login(request, user) + if user.is_authenticated: + return redirect('accounts:index',) + else: + return HttpResponse('Login Failed') + else: + return render(request, 'accounts/login.html', {'form': form}) + else: + return render(request, 'accounts/login.html', {'form': form}) + + +def logout(request): + if request.method == 'POST': + auth.logout(request) + return redirect('accounts:index') From ef75b1d062feeca1db2406fb24e77dc0976bd57a Mon Sep 17 00:00:00 2001 From: omer Date: Fri, 8 Feb 2019 18:13:25 +0500 Subject: [PATCH 3/3] Custom Authentications and custom admin form --- DonationApp/settings.py | 10 +- accounts/admin.py | 89 +++++++++++- accounts/backends.py | 16 +- accounts/forms.py | 79 ++++++---- accounts/migrations/0001_initial.py | 64 +++----- accounts/models.py | 186 ++++++++++++++---------- accounts/templates/accounts/index.html | 3 +- accounts/templates/accounts/signup.html | 67 +-------- accounts/views.py | 77 ++++------ 9 files changed, 312 insertions(+), 279 deletions(-) diff --git a/DonationApp/settings.py b/DonationApp/settings.py index 81a114e..a00d91c 100644 --- a/DonationApp/settings.py +++ b/DonationApp/settings.py @@ -51,10 +51,10 @@ ] ROOT_URLCONF = 'DonationApp.urls' - -AUTH_USER_MODEL = 'accounts.Financer' -# AUTHENTICATION_BACKENDS = ('accounts.backends.FinancerAuth',) -AUTHENTICATION_BACKENDS = ('accounts.backends.FinancerAuth', 'django.contrib.auth.backends.ModelBackend',) +# +AUTH_USER_MODEL = 'accounts.User' +# # AUTHENTICATION_BACKENDS = ('accounts.backends.FinancerAuth',) +AUTHENTICATION_BACKENDS = ('accounts.backends.CustomAccountAuth',) TEMPLATES = [ { @@ -125,4 +125,4 @@ STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') -MEDIA_URL = '/media/' \ No newline at end of file +MEDIA_URL = '/media/' diff --git a/accounts/admin.py b/accounts/admin.py index a8146af..731c70b 100644 --- a/accounts/admin.py +++ b/accounts/admin.py @@ -1,6 +1,89 @@ +from django import forms from django.contrib import admin +from django.contrib.auth.admin import UserAdmin as BaseUserAdmin +from django.contrib.auth.forms import ReadOnlyPasswordHashField +from django.contrib.auth.models import Group -from .models import Financer, Consumer +from accounts.forms import CustomUserCreationForm +from .models import User -admin.site.register(Financer) -admin.site.register(Consumer) +GENDER_TYPES = ( + ('M', 'Male'), + ('F', 'Female'), +) + +USER_ROLES = ( + ('financer', 'Financer'), + ('consumer', 'Consumer'), +) + + +class UserChangeForm(forms.ModelForm): + """A form for updating users. Includes all the fields on + the user, but replaces the password field with admin's + password hash display field. + """ + username = forms.CharField(max_length=50) + email = forms.EmailField(max_length=255) + first_name = forms.CharField(max_length=100) + last_name = forms.CharField(max_length=100) + gender = forms.ChoiceField(choices=GENDER_TYPES, widget=forms.Select()) + user_roles = forms.ChoiceField(choices=USER_ROLES, widget=forms.Select()) + date_of_birth = forms.DateField(initial='2000-01-01') + is_active = forms.BooleanField(initial=True) + is_staff = forms.BooleanField(initial=True) + is_admin = forms.BooleanField(initial=False) + country = forms.CharField(max_length=50) + state = forms.CharField(max_length=50) + district = forms.CharField(max_length=50) + city = forms.CharField(max_length=50) + area = forms.CharField(max_length=150) + mobile = forms.CharField(max_length=10, initial='0') + password = ReadOnlyPasswordHashField() + + class Meta: + model = User + fields = ('username', 'email', 'first_name', 'last_name', 'gender', 'user_roles', 'date_of_birth', + 'is_active', 'is_staff', 'is_admin', 'country', 'state', 'district', 'city', 'area', 'mobile') + + def clean_password(self): + # Regardless of what the user provides, return the initial value. + # This is done here, rather than on the field, because the + # field does not have access to the initial value + return self.initial["password"] + + +class UserAdmin(BaseUserAdmin): + # The forms to add and change user instances + change_form = UserChangeForm + creation_form = CustomUserCreationForm + + # The fields to be used in displaying the User model. + # These override the definitions on the base UserAdmin + # that reference specific fields on auth.User. + list_display = ('email', 'date_of_birth', 'is_admin') + list_filter = ('is_admin',) + fieldsets = ( + (None, {'fields': ('email', 'password')}), + ('Personal info', {'fields': ('first_name', 'last_name', 'gender', 'user_roles', 'date_of_birth', 'mobile',)}), + ('Address', {'fields': ('country', 'state', 'district', 'city', 'area',)}), + ('Permissions', {'fields': ('financer', 'consumer', 'is_admin', 'is_active', 'is_staff',)}), + ) + # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin + # overrides get_fieldsets to use this attribute when creating a user. + add_fieldsets = ( + (None, { + 'classes': ('wide',), + 'fields': ('username', 'email', 'first_name', 'last_name', 'gender', 'user_roles', 'date_of_birth', + 'financer', 'consumer', 'is_active', 'is_staff', 'is_admin', 'country', 'state', 'district', + 'city', 'area', + 'mobile', 'password1', 'password2')} + ), + ) + search_fields = ('email',) + ordering = ('email',) + filter_horizontal = () + + +admin.site.register(User, UserAdmin) +admin.site.unregister(Group) diff --git a/accounts/backends.py b/accounts/backends.py index 4e3df2c..c804408 100644 --- a/accounts/backends.py +++ b/accounts/backends.py @@ -1,21 +1,21 @@ -from .models import Financer +from .models import User -class FinancerAuth(object): +class CustomAccountAuth(object): - def authenticate(self, request, email=None, password=None): + def authenticate(self, request, username=None, password=None): try: - user = Financer.objects.get(email=email) + user = User.objects.get(username=username) if user.check_password(password): return user - except Financer.DoesNotExist: + except User.DoesNotExist: return None - def get_user(self, user_id): + def get_user(self, username): try: - user = Financer.objects.get(email=user_id) + user = User.objects.get(username=username) if user.is_active: return user return None - except Financer.DoesNotExist: + except User.DoesNotExist: return None diff --git a/accounts/forms.py b/accounts/forms.py index 9b8cefa..4dcdbc4 100644 --- a/accounts/forms.py +++ b/accounts/forms.py @@ -1,49 +1,69 @@ from django import forms -from django.forms import ModelForm -from django.core.exceptions import NON_FIELD_ERRORS -from .models import Financer, Consumer -from django.contrib.auth import authenticate +from django.contrib.auth.forms import UserCreationForm +from .models import User GENDER_TYPES = ( ('M', 'Male'), ('F', 'Female'), ) +USER_ROLES = ( + ('financer', 'Financer'), + ('consumer', 'Consumer'), +) + + +class CustomUserCreationForm(UserCreationForm): + username = forms.CharField(max_length=50) + email = forms.EmailField(max_length=255) + first_name = forms.CharField(max_length=100) + last_name = forms.CharField(max_length=100) + gender = forms.ChoiceField(choices=GENDER_TYPES, widget=forms.Select()) + user_roles = forms.ChoiceField(choices=USER_ROLES, widget=forms.Select()) + date_of_birth = forms.DateField(initial='2000-01-01') + country = forms.CharField(max_length=50) + state = forms.CharField(max_length=50) + district = forms.CharField(max_length=50) + city = forms.CharField(max_length=50) + area = forms.CharField(max_length=150) + mobile = forms.CharField(max_length=10, initial='0') + financer = forms.ModelChoiceField(queryset=User.objects.filter(user_roles='financer'), widget=forms.HiddenInput(), + required=False) + consumer = forms.ModelChoiceField(queryset=User.objects.filter(user_roles='financer'), + widget=forms.HiddenInput(), + initial=None, + required=False) + password1 = forms.CharField(label='Password', widget=forms.PasswordInput) + password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) -class FinancerForm(ModelForm): class Meta: - model = Financer - fields = ['first_name', 'last_name', 'gender', 'password', 'profile_pic', 'username', 'email', 'date_of_birth', - 'mobile', 'address', 'city', 'state', 'country'] - error_messages = { - NON_FIELD_ERRORS: { - 'unique_together': "%(model_name)s's %(field_labels)s are not unique.", - } - } + model = User + fields = ('username', 'email', 'first_name', 'last_name', 'gender', 'user_roles', 'date_of_birth', + 'country', 'state', 'district', 'city', 'area', 'mobile') + + def __init__(self, *args, **kwargs): + super(CustomUserCreationForm, self).__init__(*args, **kwargs) + self.fields['financer'].required = False + + def clean_password2(self): + # Check that the two password entries match + password1 = self.cleaned_data.get("password1") + password2 = self.cleaned_data.get("password2") + if password1 and password2 and password1 != password2: + raise forms.ValidationError("Passwords don't match") + return password2 def save(self, commit=True): - user = super(FinancerForm, self).save(commit=False) - user.set_password(user.password) # set password properly before commit + # Save the provided password in hashed format + user = super().save(commit=False) + user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user -class ConsumerForm(ModelForm): - class Meta: - model = Consumer - fields = ['first_name', 'last_name', 'gender', 'password', 'profile_pic', 'username', 'email', 'date_of_birth', - 'mobile', 'address', 'city', 'state', 'country'] - error_messages = { - NON_FIELD_ERRORS: { - 'unique_together': "%(model_name)s's %(field_labels)s are not unique.", - } - } - - class SignUp(forms.Form): - username = forms.CharField(label="Username", max_length=100) email = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput()) @@ -59,6 +79,5 @@ class SignUp(forms.Form): class LoginForm(forms.Form): - email = forms.EmailField(label="Email", max_length=100) + username = forms.CharField(label="Username", max_length=100) password = forms.CharField(label="Password", widget=forms.PasswordInput()) - diff --git a/accounts/migrations/0001_initial.py b/accounts/migrations/0001_initial.py index 49fa79b..5b4f321 100644 --- a/accounts/migrations/0001_initial.py +++ b/accounts/migrations/0001_initial.py @@ -1,6 +1,6 @@ -# Generated by Django 2.1.3 on 2019-01-24 14:24 +# Generated by Django 2.1.3 on 2019-02-08 13:09 -import datetime +import accounts.models from django.conf import settings from django.db import migrations, models import django.db.models.deletion @@ -16,29 +16,33 @@ class Migration(migrations.Migration): operations = [ migrations.CreateModel( - name='Financer', + 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')), + ('username', models.CharField(max_length=50, primary_key=True, serialize=False, unique=True)), + ('email', models.EmailField(max_length=255, unique=True)), ('first_name', models.CharField(max_length=100)), - ('last_name', models.CharField(max_length=100)), + ('last_name', models.CharField(max_length=100, null=True)), ('gender', models.CharField(choices=[('M', 'Male'), ('F', 'Female')], max_length=10)), - ('password', models.CharField(max_length=31)), - ('profile_pic', models.ImageField(null=True, upload_to='images/')), - ('username', models.CharField(max_length=50, unique=True)), - ('email', models.EmailField(max_length=100, primary_key=True, serialize=False, unique=True)), - ('date_of_birth', models.DateField(default='2000-01-01')), - ('mobile', models.CharField(default=0, max_length=11)), - ('address', models.CharField(max_length=255)), - ('city', models.CharField(max_length=100)), - ('state', models.CharField(max_length=100)), - ('country', models.CharField(max_length=100)), - ('created_on', models.DateTimeField(auto_now_add=True)), - ('account_balance', models.BigIntegerField(default=0)), - ('date_joined', models.DateTimeField(default=datetime.datetime.now, verbose_name='date joined')), + ('user_roles', + models.CharField(choices=[('financer', 'Financer'), ('consumer', 'Consumer')], max_length=20)), + ('date_of_birth', models.DateField(default='2000-01-01', null=True)), ('is_active', models.BooleanField(default=True)), + ('is_staff', models.BooleanField(default=True)), ('is_admin', models.BooleanField(default=False)), - ('is_staff', models.BooleanField(default=False)), - ('is_superuser', models.BooleanField(default=False)), + ('country', models.CharField(max_length=50, null=True)), + ('state', models.CharField(max_length=50, null=True)), + ('district', models.CharField(max_length=50, null=True)), + ('city', models.CharField(max_length=50, null=True)), + ('area', models.CharField(max_length=150, null=True)), + ('mobile', models.CharField(blank=True, default='0', max_length=10, null=True)), + ('consumer', accounts.models.ListField(blank=True, default=None, null=True, token=',')), + ('financer', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, + to=settings.AUTH_USER_MODEL)), ('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')), ('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')), ], @@ -46,26 +50,4 @@ class Migration(migrations.Migration): 'abstract': False, }, ), - migrations.CreateModel( - name='Consumer', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('first_name', models.CharField(max_length=100)), - ('last_name', models.CharField(max_length=100)), - ('gender', models.CharField(choices=[('M', 'Male'), ('F', 'Female')], max_length=10)), - ('password', models.CharField(max_length=31)), - ('occupation', models.CharField(max_length=255, null=True)), - ('profile_pic', models.ImageField(null=True, upload_to='images/')), - ('username', models.CharField(max_length=50, unique=True)), - ('email', models.EmailField(max_length=100, unique=True)), - ('date_of_birth', models.DateField(default='2000-01-01')), - ('mobile', models.CharField(default=0, max_length=11)), - ('address', models.CharField(max_length=255)), - ('city', models.CharField(max_length=100)), - ('state', models.CharField(max_length=100)), - ('country', models.CharField(max_length=100)), - ('created_on', models.DateTimeField(auto_now_add=True)), - ('financer', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), - ], - ), ] diff --git a/accounts/models.py b/accounts/models.py index 3aa8423..48f405c 100644 --- a/accounts/models.py +++ b/accounts/models.py @@ -1,8 +1,53 @@ -from django.db import models +from typing import Iterable + +from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.contrib.auth.models import PermissionsMixin -from django.contrib.auth.models import AbstractBaseUser, BaseUserManager -from datetime import datetime -from django.utils.translation import ugettext_lazy as _ +from django.core.exceptions import ObjectDoesNotExist +from django.db import models + + +class ListField(models.TextField): + """ + A custom Django field to represent lists as comma separated strings + """ + + def __init__(self, *args, **kwargs): + self.token = kwargs.pop('token', ',') + super().__init__(*args, **kwargs) + + def deconstruct(self): + name, path, args, kwargs = super().deconstruct() + kwargs['token'] = self.token + return name, path, args, kwargs + + def to_python(self, value): + + class SubList(list): + def __init__(self, token, *args): + self.token = token + super().__init__(*args) + + def __str__(self): + return self.token.join(self) + + if isinstance(value, list): + return value + if value is None: + return SubList(self.token) + return SubList(self.token, value.split(self.token)) + + def from_db_value(self, value, expression, connection): + return self.to_python(value) + + def get_prep_value(self, value): + if not value: + return + assert (isinstance(value, Iterable)) + return self.token.join(value) + + def value_to_string(self, obj): + value = self.value_from_object(obj) + return self.get_prep_value(value) GENDER_TYPES = ( @@ -10,95 +55,90 @@ ('F', 'Female'), ) +USER_ROLES = ( + ('financer', 'Financer'), + ('consumer', 'Consumer'), +) + -class CustomUserManager(BaseUserManager): - def _create_user(self, username, password, is_staff, is_superuser, is_admin, **extra_fields): +class UserManager(BaseUserManager): - now = datetime.now() + def create_user(self, username, email, password=None): + if not username: + raise ValueError('Users must have an username') - user = self.model(username=username, - is_staff=is_staff, is_active=True, - is_superuser=is_superuser, last_login=now, - date_joined=now, **extra_fields) - user.is_admin = is_admin + # Save the user + user = self.model(username=username) user.set_password(password) - user.save(using=self._db) + user.email = email + user.is_staff = True + user.save() return user - def create_user(self, username, password=None, **extra_fields): - return self._create_user(username, password, False, False, False, **extra_fields) - - def create_superuser(self, username, password=None, **extra_fields): - return self._create_user(username, password, True, True, True, **extra_fields) + def create_superuser(self, username, password): + user = self.create_user(username=username, email="", password=password) + user.is_admin = True + user.is_active = True + user.is_staff = True + user.save() + return user -class Financer(AbstractBaseUser, PermissionsMixin): +class User(AbstractBaseUser, PermissionsMixin): + username = models.CharField(max_length=50, primary_key=True, unique=True) + email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=100) - last_name = models.CharField(max_length=100) + last_name = models.CharField(max_length=100, null=True) gender = models.CharField(choices=GENDER_TYPES, max_length=10) - password = models.CharField(max_length=31) - profile_pic = models.ImageField(upload_to='images/', null=True) - username = models.CharField(max_length=50, unique=True) - email = models.EmailField(max_length=100, primary_key=True, unique=True) - date_of_birth = models.DateField(default='2000-01-01') - mobile = models.CharField(max_length=11, default=0) - address = models.CharField(max_length=255) - city = models.CharField(max_length=100) - state = models.CharField(max_length=100) - country = models.CharField(max_length=100) - created_on = models.DateTimeField(auto_now_add=True) - account_balance = models.BigIntegerField(default=0) - - date_joined = models.DateTimeField(_('date joined'), default=datetime.now) + user_roles = models.CharField(choices=USER_ROLES, max_length=20) + date_of_birth = models.DateField(default='2000-01-01', null=True) is_active = models.BooleanField(default=True) + is_staff = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) - is_staff = models.BooleanField(default=False) - is_superuser = models.BooleanField(default=False) + country = models.CharField(max_length=50, null=True) + state = models.CharField(max_length=50, null=True) + district = models.CharField(max_length=50, null=True) + city = models.CharField(max_length=50, null=True) + area = models.CharField(max_length=150, null=True) + mobile = models.CharField(max_length=10, default='0', blank=True, null=True) + financer = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) + consumer = ListField(default=None, blank=True, null=True) - USERNAME_FIELD = 'username' - REQUIRED_FIELDS = ['first_name', 'last_name', 'email'] + objects = UserManager() - objects = CustomUserManager() + USERNAME_FIELD = 'username' def __str__(self): return self.username - def get_full_name(self): - full_name = '%s %s' % (self.first_name, self.last_name) - return full_name.strip() + def __unicode__(self): + return self.username - # this methods are require to login super user from admin panel def has_perm(self, perm, obj=None): - return self.is_admin - - # this methods are require to login super user from admin panel - def has_module_perms(self, app_label): - return self.is_admin - - -class Consumer(models.Model): - - first_name = models.CharField(max_length=100) - last_name = models.CharField(max_length=100) - gender = models.CharField(choices=GENDER_TYPES, max_length=10) - password = models.CharField(max_length=31) - occupation = models.CharField(max_length=255, null=True) - profile_pic = models.ImageField(upload_to='images/', null=True) - username = models.CharField(max_length=50, unique=True) - email = models.EmailField(max_length=100, unique=True) - date_of_birth = models.DateField(default='2000-01-01') - mobile = models.CharField(max_length=11, default=0) - address = models.CharField(max_length=255) - city = models.CharField(max_length=100) - state = models.CharField(max_length=100) - country = models.CharField(max_length=100) - created_on = models.DateTimeField(auto_now_add=True) - financer = models.ForeignKey(Financer, on_delete=models.CASCADE, null=True) - - def __str__(self): - return self.username + if self.is_active and self.is_admin: + return True + # return _user_has_perm(self, perm, obj) + else: + try: + user_perm = self.user_permissions.get(codename=perm) + except ObjectDoesNotExist: + user_perm = False + + return bool(user_perm) + + def has_module_perms(self, perm, obj=None): + if self.is_active and self.is_admin: + return True + # return _user_has_perm(self, perm, obj) + else: + try: + user_perm = self.user_permissions.get(codename=perm) + except ObjectDoesNotExist: + user_perm = False + + return bool(user_perm) def get_full_name(self): - return self.first_name + ' ' + self.last_name - + full_name = '%s %s' % (self.first_name, self.last_name) + return full_name.strip() diff --git a/accounts/templates/accounts/index.html b/accounts/templates/accounts/index.html index c2d5649..2e22209 100644 --- a/accounts/templates/accounts/index.html +++ b/accounts/templates/accounts/index.html @@ -3,8 +3,7 @@ {% block content %}

Welcome

{% csrf_token %} - {% if user.is_authenticated %} +{% if user.is_authenticated %}

{{ user.get_full_name }}

-

User is Authenticated

{% endif %} {% endblock %} diff --git a/accounts/templates/accounts/signup.html b/accounts/templates/accounts/signup.html index 98a8520..e7421b8 100644 --- a/accounts/templates/accounts/signup.html +++ b/accounts/templates/accounts/signup.html @@ -14,73 +14,10 @@

Sign Up

{{ error }}

{% endif %} -
+ {% csrf_token %} - Select Account Type: -
- Financer - Consumer -
- Username: -
- -
- Email: -
- -
- Password: -
- -
- Confirm Password: -
- -
- Profile Pic -
- -
- First Name: -
- -
- Last Name: -
- -
- Gender: -
- Male - Female -
- Date of Birth: -
- -
- Mobile No: -
- -
- Address: -
- -
- City: -
- -
- State: -
- -
- Country: -
- -
-
-
+ {{ form.as_p }}
diff --git a/accounts/views.py b/accounts/views.py index e1dd6b2..0a7c775 100644 --- a/accounts/views.py +++ b/accounts/views.py @@ -1,8 +1,7 @@ +from .models import User from django.http import HttpResponse from django.shortcuts import render, redirect -from .models import Financer, Consumer -from django.utils import timezone -from .forms import SignUp, LoginForm, FinancerForm, ConsumerForm +from .forms import CustomUserCreationForm, LoginForm from django.contrib import auth from django.contrib.auth import authenticate @@ -12,54 +11,28 @@ def index(request): def signup(request): - if request.method == 'POST': - form = SignUp(request.POST) - - # if form.is_valid(): - # return redirect('accounts:index') - - if request.POST['password'] == request.POST['password2']: - if request.POST['type'] == 'financer': - try: - financer = Financer.objects.get(username=request.POST['username']) - return render(request, 'accounts/signup.html', {'error': 'Username has already been taken'}) - except Financer.DoesNotExist: - try: - financer = Financer.objects.get(email=request.POST['email']) - return render(request, 'accounts/signup.html', - {'error': 'Email is already associated with another account'}) - except Financer.DoesNotExist: - financer = FinancerForm(request.POST, files=request.FILES) - - if financer.is_valid(): - user = financer.save(commit=False) - user.set_password(request.POST['password']) - user.save() - return redirect('accounts:index') - else: - return render(request, 'accounts/signup.html', {'form': form}) - - elif request.POST['type'] == 'consumer': - try: - consumer = Consumer.objects.get(username=request.POST['username']) - return render(request, 'accounts/signup.html', {'error': 'Username has already been taken'}) - except Consumer.DoesNotExist: - try: - consumer = Consumer.objects.get(email=request.POST['email']) - return render(request, 'accounts/signup.html', - {'error': 'Email is already associated with another account'}) - except Consumer.DoesNotExist: - consumer = ConsumerForm(request.POST, files=request.FILES) - - if consumer.is_valid(): - consumer.save() - return redirect('accounts:index') - else: - return render(request, 'accounts/signup.html', {'form': form}) - else: - return render(request, 'accounts/signup.html', {'error': 'Password does not matched'}) + form = CustomUserCreationForm(request.POST or None) + if form.is_valid(): + try: + user = User.objects.get(username=form.cleaned_data.get('username')) + return render(request, 'accounts/signup.html', {'form': form}) + except User.DoesNotExist: + try: + user = User.objects.get(email=form.cleaned_data.get('email')) + return render(request, 'accounts/signup.html', + {'form': form}) + except User.DoesNotExist: + new_user = form.save(commit=False) + new_user.save() + new_user = authenticate(username=form.cleaned_data.get('username'), + password=form.cleaned_data.get('password1')) + auth.login(request, new_user) + if new_user.is_authenticated: + return redirect('accounts:index', ) + else: + return HttpResponse('Login Failed') else: - return render(request, 'accounts/signup.html', ) + return render(request, 'accounts/signup.html', {'form': form}) def login(request): @@ -69,9 +42,9 @@ def login(request): # user = Financer.objects.get(email=form.cleaned_data.get('email')) # user.check_password(form.cleaned_data['password']) # user = authenticate(email=form.cleaned_data['email'], password=form.cleaned_data['password']) - email = form.cleaned_data.get('email') + username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') - user = auth.authenticate(email=email, password=password) + user = authenticate(username=username, password=password) if user is not None: auth.login(request, user)