Speed up development with full-stack environments for every branch.

Learn More

Users and Authentication [Python, Django and HTTPRequest]

466 Runs 939 Views 446 Copies
Saved

Saved

bhawani0915 49

bhawani0915
published 3 years ago

from django.http import HttpResponse
from django.shortcuts import render
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from django.contrib.auth import login as auth_login
from django.contrib.auth import logout as auth_logout

def index(request):
  # create a default user in the database, so that it can be used elsewhere
  #user = User.objects.create_user('admin', '[email protected]', 'admin')
	context = {}
	populateContext(request, context)
	return render(request, 'index.html', context)

def login(request):
	context = {}
	try:
		username = request.GET['username']
		password = request.GET['password']
		user = authenticate(username=username, password=password)
		if user is not None:
			if user.is_active:
				auth_login(request, user)
			else:
				context['error'] = 'Non active user'
		else:
			context['error'] = 'Wrong username or password'
	except:
		context['error'] = ''
	
	populateContext(request, context)
	return render(request, 'index.html', context)

def logout(request):
	context = {}
	try:
		auth_logout(request)
	except:
		context['error'] = 'Some error occured.'
	
	populateContext(request, context)
	return render(request, 'index.html', context)

def populateContext(request, context):
	context['authenticated'] = request.user.is_authenticated()
	if context['authenticated'] == True:
		context['username'] = request.user.username
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).