Skip to content

Commit

Permalink
authentication features completed except forgot password and deactivate
Browse files Browse the repository at this point in the history
  • Loading branch information
arya-oss committed Apr 14, 2016
1 parent 19dbd0c commit a7e0635
Show file tree
Hide file tree
Showing 14 changed files with 644 additions and 64 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,7 @@ media/
# django setting file

todos/settings.py

# db file

arya.sqlite3
Binary file modified db.sqlite3
Binary file not shown.
32 changes: 32 additions & 0 deletions mauth/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from django import forms
from django.forms import widgets
from django.forms import ModelForm
from django.contrib.auth.models import User
from mauth.models import UserProfile

class UserForm(forms.ModelForm ):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ('first_name', 'last_name', 'username', 'email',)

class UserProfileForm(forms.ModelForm):
"""form for extended auth User model"""
class Meta:
model = UserProfile
fields = ('phone','birthdate','gender')

class UserImageForm(forms.ModelForm):
class Meta:
model=UserProfile
fields=('picture',)

class ProfileUpdateForm(forms.Form):
first_name = forms.CharField(required=True, max_length=50, label='First Name')
last_name = forms.CharField(max_length=50, label='Last Name', required=False)
birthdate = forms.DateField(required=True, label='Date of Birth')
email = forms.EmailField(required=True, max_length=50, label='Email')
phone = forms.CharField(max_length=11, required=True, label='Phone Number')
gender = forms.CharField(max_length=1, required=True, label='Gender')
def __unicode__(self):
return self.first_name
32 changes: 32 additions & 0 deletions mauth/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-04-14 03:33
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import mauth.models


class Migration(migrations.Migration):

initial = True

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]

operations = [
migrations.CreateModel(
name='UserProfile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('phone', models.CharField(blank=True, max_length=11)),
('birthdate', models.DateField(null=True)),
('gender', models.CharField(max_length=1)),
('picture', models.ImageField(blank=True, upload_to=mauth.models.upload_profile)),
('ipAddress', models.CharField(blank=True, max_length=20)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
15 changes: 14 additions & 1 deletion mauth/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
from __future__ import unicode_literals

from django.db import models
from django.contrib.auth.models import User
# Authorization models

# Create your models here.
def upload_profile(instance, filename):
return 'profile/%s.jpg'%instance.user.username

class UserProfile(models.Model):
user = models.OneToOneField(User)
phone = models.CharField(max_length=11, blank=True)
birthdate = models.DateField(null=True)
gender = models.CharField(max_length=1)
picture = models.ImageField(upload_to=upload_profile, blank=True)
ipAddress = models.CharField(max_length=20, blank=True)
def __unicode__(self):
return self.user.first_name
16 changes: 13 additions & 3 deletions mauth/urls.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
'''
Authentication urls for ToDos Users
Author: Rajmani Arya
'''
from django.conf.urls import url
from . import views
# Auth urls

# Authentiction urls

urlpatterns = [
url(r'^$', views.index, name='auth_index'),
url(r'^login/', views.login, name='auth_login')
url(r'^login/', views._login),
url(r'^signup/', views._register),
url(r'^change_password', views._changePassword),
url(r'^logout', views._logout),
url(r'^upload', views._upload),
url(r'^profile', views._profile),
]
143 changes: 138 additions & 5 deletions mauth/views.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,142 @@
from django.shortcuts import render
from django.http import HttpResponse
from mauth.forms import UserForm, UserProfileForm, UserImageForm, ProfileUpdateForm
from django.utils import timezone
from django.http import HttpResponseRedirect
from django.contrib.auth import authenticate,login,logout
from .models import UserProfile

from django.contrib.auth.models import User

from django.contrib.auth.decorators import login_required
from django.contrib import messages
# Create your views here.

def index(req):
return HttpResponse(req, 'You wanna go to Auth home ?')
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip


def _login(request):
title = "Login"
redirect_url="/"
if request.method == "GET":
if request.GET.get('next') != None and len(request.GET.get('next')) != 0:
redirect_url = request.GET['next']
print redirect_url

if request.method=="POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
user.last_login=timezone.now()
user.save()
if not request.POST.get('remember', None):
request.session.set_expiry(0)
messages.info(request,'Welcome '+user.username)
return HttpResponseRedirect(redirect_url)
else:
messages.info(request,'Your account is inactive, Contact webmaster.')
return HttpResponseRedirect('/')
else:
messages.error(request,'Invalid Username or Password')
return HttpResponseRedirect('/auth/login')
return render(request, 'auth/login.html', {'title':title})

def _logout(request):
logout(request)
return HttpResponseRedirect('/')

def _register(request):
registered = False
user_form = UserForm()
profile_form = UserProfileForm()
if request.method == "POST":
password = request.POST.get('password')

user_form = UserForm(data=request.POST)
profile_form = UserProfileForm(data=request.POST)

if len(password) < 6:
messages.error(request, 'Password length must be greater than 6')
elif user_form.is_valid() and profile_form.is_valid():
user = user_form.save(commit=False)
user.set_password(password)
user.date_joined = timezone.now()
user.is_active=True
user.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.ipAddress=get_client_ip(request)
profile.save()
registered = True
messages.success(request, "Successfully Registered !!")
else:
messages.info(request, 'Error in form !')
return render(request,'auth/register.html',{'title':'Sign Up', 'user_form':user_form,'profile_form':profile_form,'registered':registered})

@login_required(login_url='/auth/login')
def _changePassword(request):
title='Change Password'
if request.method == "POST":
old_pass = request.POST.get('old')
new = request.POST.get('new')
new_confirm = request.POST.get('new_confirm')
user = authenticate(username=request.user.username, password=old_pass)
if new != new_confirm:
messages.error(request, 'Password do not match !')
elif user is not None:
user.set_password(new)
messages.success(request, 'Password Successfully Changed !')
logout(request)
return HttpResponseRedirect('/')
else:
messages.info(request, 'Please Enter correct password.')

return render(request, 'auth/changePassword.html', {'title':title})

@login_required(login_url='/auth/login/')
def _upload(request):
uploaded=False
user_profile = UserProfile.objects.get(user=request.user)
image_form = UserImageForm()
if request.method == "POST":
image_form = UserImageForm(request.POST, request.FILES)
if(image_form.is_valid()):
user_profile.picture = image_form.cleaned_data['picture']
user_profile.save()
uploaded=True
else:
print str(image_form.errors)
messages.info(request, 'Image is not supported !')
return render(request, 'auth/upload.html', {'title':'Upload Avatar','userprofile': user_profile, 'image_form':image_form, 'uploaded':uploaded})


def login(req):
return render(req, 'auth/login.html', {'title':'Auth | Login', 'author': 'Rajmani Arya'})
@login_required(login_url='/auth/login')
def _profile(request):
profile_update = ProfileUpdateForm()
if request.method == 'POST':
profile_update = ProfileUpdateForm(data=request.POST)
if profile_update.is_valid():
user = User.objects.get(username=request.user.username)
user.first_name = profile_update.data['first_name']
user.last_name = profile_update.data['last_name']
user.email = profile_update.data['email']
user.save()
user_profile = UserProfile.objects.get(user=request.user)
user_profile.gender = profile_update.data['gender']
user_profile.birthdate = profile_update.data['birthdate']
user_profile.phone = profile_update.data['phone']
user_profile.save()
#print requestuest.user.username, requestuest.user.password
messages.success(request, 'profile updated Successfully')
else:
messages.error(request, 'form is not valid !')

return render(request, 'auth/profile.html', {'title':'Profile', 'profile_update':profile_update})
61 changes: 61 additions & 0 deletions templates/auth/changePassword.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
{% extends 'layout/header.html'%}
{%block content%}

<div class="container">
<div class="section no-pad-bot">
<div class="row">
<div class="col s12 m6 offset-m3">
<div class="card-panel">
<h3 class="blue-text center-align">Change Password</h3>
{% if messages %}{%for message in messages %}
<div class="chip {{message.tags}}">
{{ message|safe }}
<i class="material-icons">close</i>
</div>
{%endfor%}{%endif%}
<form action='/auth/change_password/' method='post'>
{%csrf_token%}
<div class="row">
<div class="input-field col s12">
<i class='material-icons prefix'>lock</i>
<input type="password" name="old" id="old" class="validate">
<label for="old">Old Password </label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">lock</i>
<input type="password" name="new" id="new" class="validate">
<label for="new">New Password</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">lock</i>
<input type="password" name="new_confirm" id="new_confirm" class="validate">
<label for="new_confirm">New Password Confirm</label>
</div>
</div>
<div class="row">
<div class="col s6 m6 l6">
<button class="btn waves-effect waves-light blue" type="submit">Change Password</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>

{%endblock%}
{%block foots%}
<script>
(function($){
$('.dropdown-button').dropdown({
constrain_width: true, // Does not change width of dropdown to that of the activator
});
$('.button-collapse').sideNav();
})(jQuery);
</script>
{%endblock%}
61 changes: 60 additions & 1 deletion templates/auth/login.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,63 @@
{% extends 'layout/header.html'%}
{%block content%}
<h2>{{author}}</h2>
<div class="container">
<div class="section no-pad-bot">
<div class="row">
<div class="col s12 m6 l6 offset-l3">
<div class="card-panel">
<h3 class="blue-text center-align">Login Portal</h3>
{% if messages %}{%for message in messages %}
<div class="chip {{message.tags}}">
{{ message|safe }}
<i class="material-icons">close</i>
</div>
{%endfor%}{%endif%}
<p>Enter the information to Sign In</p>
<form action='/auth/login/' method='post'>
{%csrf_token%}
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">account_circle</i>
<input id="username" type="text" name="username" class="validate">
<label for="username">Username</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">lock</i>
<input id="password" type="password" name="password" class="validate">
<label for="password">Password</label>
</div>
</div>
<div class="row">
<div class="col s12">
<input type="checkbox" id="remember" name="remember" />
<label for="remember">Remember Me</label>
</div>
</div>
<div class="row">
<div class="col s6">
<button class="waves-effect waves-light btn">Sign In <i class='material-icons right'>perm_identity</i></button>
</div>
<div class="col s6">
<a href="/auth/forgotPassword"><p class="right-align">Forgot Password ?</p></a>
</div>
</div>
</form>
<p class="center-align"><a href="/auth/signup">Create an Account</a></p>
</div>
</div>
</div>
</div>
</div>
{%endblock%}
{%block foots%}
<script>
(function($){
$('.dropdown-button').dropdown({
constrain_width: true, // Does not change width of dropdown to that of the activator
});
$('.button-collapse').sideNav();
})(jQuery);
</script>
{%endblock%}
Loading

0 comments on commit a7e0635

Please sign in to comment.