User Role Permission & Authentication — Django101

pertama-tama buat template user.html

{%  extends 'accounts/main.html' %}
{% block content %}
{% include 'accounts/status.html' %}

<h3>User Profile</h3>

{% endblock content %}

buat def userPage (views.py)

def userPage(request):
context = {}
return render(request, 'accounts/user.html', context)

tambahkan route /user (urls.py)

path('user/', views.userPage, name="user-page"),

buat file decorators.py

from django.http import HttpResponse
from django.shortcuts import redirect

def unauthenticated_user(view_func):
def wrapper_func(request, *args, **kwargs):
if request.user.is_authenticated:
return redirect('home')
else:
return view_func(request, *args, **kwargs)

return wrapper_func

def allowed_users(allowed_roles=[]):
def decorator(view_func):
def wrapper_func(request, *args, **kwargs):

group = None
if request.user.groups.exists():
group = request.user.groups.all()[0].name

if group in allowed_roles:
return view_func(request, *args, **kwargs)
else:
return HttpResponse('You are not authorized to view this page')
return wrapper_func
return decorator

def admin_only(view_func):
def wrapper_function(request, *args, **kwargs):
group = None
if request.user.groups.exists():
group = request.user.groups.all()[0].name

if group == 'customer':
return redirect('user-page')

if group == 'admin':
return view_func(request, *args, **kwargs)

return wrapper_function

hapus request_is_invalid di setiap fungsi dan tambahkan annotations

@unauthenticated_user
def registerPage(request):
if request.user.is_authenticated:
return redirect('')
else:

form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
user = form.cleaned_data.get('username')
messages.success(request, 'Account was created for ' + user)
return redirect('dashboard')
context = {'form': form}
return render(request, 'accounts/register.html', context)

views.py

from django.shortcuts import render, redirect 
from django.http import HttpResponse
from django.forms import inlineformset_factory
from django.contrib.auth.forms import UserCreationForm

from django.contrib.auth import authenticate, login, logout

from django.contrib import messages

from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group

# Create your views here.
from .models import *
from .forms import OrderForm, CreateUserForm
from .filters import OrderFilter
from .decorators import unauthenticated_user, allowed_users, admin_only

@unauthenticated_user
def registerPage(request):

form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
user = form.save()
username = form.cleaned_data.get('username')

group = Group.objects.get(name='customer')
user.groups.add(group)

messages.success(request, 'Account was created for ' + username)

return redirect('login')


context = {'form':form}
return render(request, 'accounts/register.html', context)

@unauthenticated_user
def loginPage(request):

if request.method == 'POST':
username = request.POST.get('username')
password =request.POST.get('password')

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

if user is not None:
login(request, user)
return redirect('home')
else:
messages.info(request, 'Username OR password is incorrect')

context = {}
return render(request, 'accounts/login.html', context)

def logoutUser(request):
logout(request)
return redirect('login')

@login_required(login_url='login')
@admin_only
def home(request):
orders = Order.objects.all()
customers = Customer.objects.all()

total_customers = customers.count()

total_orders = orders.count()
delivered = orders.filter(status='Delivered').count()
pending = orders.filter(status='Pending').count()

context = {'orders':orders, 'customers':customers,
'total_orders':total_orders,'delivered':delivered,
'pending':pending }

return render(request, 'accounts/dashboard.html', context)

def userPage(request):
context = {}
return render(request, 'accounts/user.html', context)


@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def products(request):
products = Product.objects.all()

return render(request, 'accounts/products.html', {'products':products})

@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def customer(request, pk_test):
customer = Customer.objects.get(id=pk_test)

orders = customer.order_set.all()
order_count = orders.count()

myFilter = OrderFilter(request.GET, queryset=orders)
orders = myFilter.qs

context = {'customer':customer, 'orders':orders, 'order_count':order_count,
'myFilter':myFilter}
return render(request, 'accounts/customer.html',context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def createOrder(request, pk):
OrderFormSet = inlineformset_factory(Customer, Order, fields=('product', 'status'), extra=10 )
customer = Customer.objects.get(id=pk)
formset = OrderFormSet(queryset=Order.objects.none(),instance=customer)
#form = OrderForm(initial={'customer':customer})
if request.method == 'POST':
#print('Printing POST:', request.POST)
form = OrderForm(request.POST)
formset = OrderFormSet(request.POST, instance=customer)
if formset.is_valid():
formset.save()
return redirect('/')

context = {'form':formset}
return render(request, 'accounts/order_form.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def updateOrder(request, pk):

order = Order.objects.get(id=pk)
form = OrderForm(instance=order)

if request.method == 'POST':
form = OrderForm(request.POST, instance=order)
if form.is_valid():
form.save()
return redirect('/')

context = {'form':form}
return render(request, 'accounts/order_form.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def deleteOrder(request, pk):
order = Order.objects.get(id=pk)
if request.method == "POST":
order.delete()
return redirect('/')

context = {'item':order}
return render(request, 'accounts/delete.html', context)

tambahkan group pada saat register

@unauthenticated_user
def registerPage(request):

form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
user = form.save()
username = form.cleaned_data.get('username')

group = Group.objects.get(name='customer')
user.groups.add(group)


messages.success(request, 'Account was created for ' + username)

return redirect('login')


context = {'form':form}
return render(request, 'accounts/register.html', context)

keseluruhan views.py

from django.contrib.auth.decorators import login_required
from django.forms import inlineformset_factory
from django.shortcuts import render, redirect

from .decorators import unauthenticated_user, admin_only, allowed_users
from .forms import OrderForm, CreateUserForm
from .models import *
from .filters import OrderFilter
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages

from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group


@unauthenticated_user
def registerPage(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
user = form.cleaned_data.get('username')
messages.success(request, 'Account was created for ' + user)
return redirect('dashboard')
context = {'form': form}
return render(request, 'accounts/register.html', context)


@unauthenticated_user
def loginPage(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')

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

if user is not None:
login(request, user)
return redirect('dashboard')
else:
messages.info(request, 'Username OR password is incorrect')

context = {}
return render(request, 'accounts/login.html', context)


def logoutUser(request):
logout(request)
return redirect('login')


# Create your views here.
def home(request):
return render(request, 'accounts/home.html')


@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def products(request):
products = Product.objects.all()
return render(request, 'accounts/products.html', {'products': products})


@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def customer(request, pk_test):
customer = Customer.objects.get(id=pk_test) # ambil customer berdasarkan id
orders = customer.order_set.all() # ambil order berdasarkan customer
order_count = orders.count() # menghitung jumlah orderan tiap customer

myFilter = OrderFilter(request.GET, queryset=orders)
orders = myFilter.qs
context = {'customer': customer, 'orders': orders, 'order_count': order_count,
'myFilter': myFilter
}
return render(request, 'accounts/customer.html', context)


@login_required(login_url='login')
@admin_only
def dashboard(request):
customers = Customer.objects.all()
total_customer = customers.count()
orders = Order.objects.all()
total_orders = orders.count()
delivered = Order.objects.filter(status='Delivered').count()
pending = Order.objects.filter(status='Pending').count()

context = {
'customers': customers,
'orders': orders,
'total_orders': total_orders,
'total_customer': total_customer,
'delivered': delivered,
'pending': pending
}
return render(request, 'accounts/dashboard.html', context)


@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def createOrder(request, pk):
OrderFormSet = inlineformset_factory(Customer, Order, fields=('product', 'status'), extra=10)
customer = Customer.objects.get(id=pk)
formset = OrderFormSet(queryset=Order.objects.none(), instance=customer)

if request.method == 'POST':
# print('Printing POST:', request.POST)
formset = OrderFormSet(request.POST, instance=customer)
if formset.is_valid():
formset.save()
return redirect('/')

context = {'form': formset}
return render(request, 'accounts/order_form.html', context)


@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def updateOrder(request, pk):
order = Order.objects.get(id=pk)
form = OrderForm(instance=order)

if request.method == 'POST':
form = OrderForm(request.POST, instance=order)
if form.is_valid():
form.save()
return redirect('/')

context = {'form': form}
return render(request, 'accounts/order_form.html', context)


@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def delete_order(request, pk):
order = Order.objects.get(id=pk)
if request.method == 'POST':
order.delete()
return redirect('/')

context = {'item': order}
return render(request, 'accounts/delete.html', context)


def userPage(request):
context = {}
return render(request, 'accounts/user.html', context)

full source code :