<commit_before>from django import forms
from django.conf.urls.defaults import url, patterns, include
from django.contrib import messages
from django.contrib.auth import authenticate, login, views as auth_views
from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm, PasswordChangeForm
from django.contrib.auth.models import User
from django.contrib.auth.tokens import default_token_generator as password_token_generator
from django.contrib.sites.models import Site
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
from django.db import models
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.utils.http import int_to_base36, base36_to_int
from django.utils.translation import ugettext_lazy, ugettext as _
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from philo.models import MultiView, Page
from philo.contrib.waldo.forms import LOGIN_FORM_KEY, LoginForm, RegistrationForm
from philo.contrib.waldo.tokens import registration_token_generator, email_token_generator
import urlparse


ERROR_MESSAGE = ugettext_lazy("Please enter a correct username and password. Note that both fields are case-sensitive.")


def get_field_data(obj, fields):
	if fields == None:
		fields = [field.name for field in obj._meta.fields if field.editable]
	
	return dict([(field.name, field.value_from_object(obj)) for field in obj._meta.fields if field.name in fields])


class LoginMultiView(MultiView):
	"""
	Handles login, registration, and forgotten passwords. In other words, this
	multiview provides exclusively view and methods related to usernames and
	passwords.
	"""
	login_page = models.ForeignKey(Page, related_name='%(app_label)s_%(class)s_login_related')
	password_reset_page = models.ForeignKey(Page, related_name='%(app_label)s_%(class)s_password_reset_related')
	password_reset_confirmation_email = models.ForeignKey(Page, related_name='%(app_label)s_%(class)s_password_reset_confirmation_email_related')
	password_set_page = models.ForeignKey(Page, related_name='%(app_label)s_%(class)s_password_set_related')
	password_change_page = models.ForeignKey(Page, related_name='%(app_label)s_%(class)s_password_change_related', blank=True, null=True)
	register_page = models.ForeignKey(Page, related_name='%(app_label)s_%(class)s_register_related')
	register_confirmation_email = models.ForeignKey(Page, related_name='%(app_label)s_%(class)s_register_confirmation_email_related')
	
	@property
	def urlpatterns(self):
		urlpatterns = patterns('',
			url(r'^login/$', self.login, name='login'),
			url(r'^logout/$', self.logout, name='logout'),
			
			url(r'^password/reset/$', csrf_protect(self.password_reset), name='password_reset'),
			url(r'^password/reset/(?P<uidb36>\w+)/(?P<token>[^/]+)/$', self.password_reset_confirm, name='password_reset_confirm'),
			
			url(r'^register/$', csrf_protect(self.register), name='register'),
			url(r'^register/(?P<uidb36>\w+)/(?P<token>[^/]+)/$', self.register_confirm, name='register_confirm')
		)
		
		if self.password_change_page:
			urlpatterns += patterns('',
				url(r'^password/change/$', csrf_protect(self.login_required(self.password_change)), name='password_change'),
			)
		
		return urlpatterns
	
	def get_context(self, extra_dict=None):
		context = {}
		context.update(extra_dict or {})
		return context
	
	def display_login_page(self, request, message, node=None, extra_context=None):
		request.session.set_test_cookie()
		
		referrer = request.META.get('HTTP_REFERER', None)
		
		if referrer is not None:
			referrer = urlparse.urlparse(referrer)
			host = referrer[1]
			if host != request.get_host():
				referrer = None
			else:
				redirect = ''.join(referrer[2:])
		
		if referrer is None:
			redirect = node.get_absolute_url()
		
		path = request.get_full_path()
		if redirect != path:
			if redirect is None:
				redirect = '/'.join(path.split('/')[:-2])
			request.session['redirect'] = redirect
		
		if request.POST:
			form = LoginForm(request.POST)
		else:
			form = LoginForm()
		context = self.get_context({
			'message': message,
			'form': form
		})
		context.update(extra_context or {})
		return self.login_page.render_to_response(node, request, extra_context=context)
	
	def login(self, request, node=None, extra_context=None):
		"""
		Displays the login form for the given HttpRequest.
		"""
		context = self.get_context(extra_context)
		
		from django.contrib.auth.models import User
		
		# If this isn't already the login page, display it.
		if not request.POST.has_key(LOGIN_FORM_KEY):
			if request.POST:
				message = _("Please log in again, because your session has expired.")
			else:
				message = ""
			return self.display_login_page(request, message, node, context)

		# Check that the user accepts cookies.
		if not request.session.test_cookie_worked():
			message = _("Looks like your browser isn't configured to accept cookies. Please enable cookies, reload this page, and try again.")
			return self.display_login_page(request, message, node, context)
		else:
			request.session.delete_test_cookie()
		
		# Check the password.
		username = request.POST.get('username', None)
		password = request.POST.get('password', None)
		user = authenticate(username=username, password=password)
		if user is None:
			message = ERROR_MESSAGE
			if username is not None and u'@' in username:
				# Mistakenly entered e-mail address instead of username? Look it up.
				try:
					user = User.objects.get(email=username)
				except (User.DoesNotExist, User.MultipleObjectsReturned):
					message = _("Usernames cannot contain the '@' character.")
				else:
					if user.check_password(password):
						message = _("Your e-mail address is not your username."
									" Try '%s' instead.") % user.username
					else:
						message = _("Usernames cannot contain the '@' character.")
			return self.display_login_page(request, message, node, context)

		# The user data is correct; log in the user in and continue.
		else:
			if user.is_active:
				login(request, user)
				try:
					redirect = request.session.pop('redirect')
				except KeyError:
					redirect = node.get_absolute_url()
				return HttpResponseRedirect(redirect)
			else:
				return self.display_login_page(request, ERROR_MESSAGE, node, context)
	login = never_cache(login)
	
	def logout(self, request):
		return auth_views.logout(request, request.META['HTTP_REFERER'])
	
	def login_required(self, view):
		def inner(request, node=None, *args, **kwargs):
			if not request.user.is_authenticated():
				login_url = reverse('login', urlconf=self).strip('/')
				return HttpResponseRedirect('%s%s/' % (node.get_absolute_url(), login_url))
			return view(request, node=node, *args, **kwargs)
		
		return inner
	
	def send_confirmation_email(self, subject, email, page, extra_context):
		message = page.render_to_string(extra_context=extra_context)
		from_email = 'noreply@%s' % Site.objects.get_current().domain
		send_mail(subject, message, from_email, [email])
	
	def password_reset(self, request, node=None, extra_context=None, token_generator=password_token_generator):
		if request.method == 'POST':
			form = PasswordResetForm(request.POST)
			if form.is_valid():
				current_site = Site.objects.get_current()
				for user in form.users_cache:
					token = token_generator.make_token(user)
					link = 'http://%s/%s/%s/' % (current_site.domain, node.get_absolute_url().strip('/'), reverse('password_reset_confirm', urlconf=self, kwargs={'uidb36': int_to_base36(user.id), 'token': token}).strip('/'))
					context = {<commit_msg>Fixed login redirects<commit_after>from django import forms
from django.conf.urls.defaults import url, patterns, include
from django.contrib import messages
from django.contrib.auth import authenticate, login, views as auth_views
from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm, PasswordChangeForm
from django.contrib.auth.models import User
from django.contrib.auth.tokens import default_token_generator as password_token_generator
from django.contrib.sites.models import Site
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
from django.db import models
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.utils.http import int_to_base36, base36_to_int
from django.utils.translation import ugettext_lazy, ugettext as _
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from philo.models import MultiView, Page
from philo.contrib.waldo.forms import LOGIN_FORM_KEY, LoginForm, RegistrationForm
from philo.contrib.waldo.tokens import registration_token_generator, email_token_generator
import urlparse


ERROR_MESSAGE = ugettext_lazy("Please enter a correct username and password. Note that both fields are case-sensitive.")


def get_field_data(obj, fields):
	if fields == None:
		fields = [field.name for field in obj._meta.fields if field.editable]
	
	return dict([(field.name, field.value_from_object(obj)) for field in obj._meta.fields if field.name in fields])


class LoginMultiView(MultiView):
	"""
	Handles login, registration, and forgotten passwords. In other words, this
	multiview provides exclusively view and methods related to usernames and
	passwords.
	"""
	login_page = models.ForeignKey(Page, related_name='%(app_label)s_%(class)s_login_related')
	password_reset_page = models.ForeignKey(Page, related_name='%(app_label)s_%(class)s_password_reset_related')
	password_reset_confirmation_email = models.ForeignKey(Page, related_name='%(app_label)s_%(class)s_password_reset_confirmation_email_related')
	password_set_page = models.ForeignKey(Page, related_name='%(app_label)s_%(class)s_password_set_related')
	password_change_page = models.ForeignKey(Page, related_name='%(app_label)s_%(class)s_password_change_related', blank=True, null=True)
	register_page = models.ForeignKey(Page, related_name='%(app_label)s_%(class)s_register_related')
	register_confirmation_email = models.ForeignKey(Page, related_name='%(app_label)s_%(class)s_register_confirmation_email_related')
	
	@property
	def urlpatterns(self):
		urlpatterns = patterns('',
			url(r'^login/$', self.login, name='login'),
			url(r'^logout/$', self.logout, name='logout'),
			
			url(r'^password/reset/$', csrf_protect(self.password_reset), name='password_reset'),
			url(r'^password/reset/(?P<uidb36>\w+)/(?P<token>[^/]+)/$', self.password_reset_confirm, name='password_reset_confirm'),
			
			url(r'^register/$', csrf_protect(self.register), name='register'),
			url(r'^register/(?P<uidb36>\w+)/(?P<token>[^/]+)/$', self.register_confirm, name='register_confirm')
		)
		
		if self.password_change_page:
			urlpatterns += patterns('',
				url(r'^password/change/$', csrf_protect(self.login_required(self.password_change)), name='password_change'),
			)
		
		return urlpatterns
	
	def get_context(self, extra_dict=None):
		context = {}
		context.update(extra_dict or {})
		return context
	
	def display_login_page(self, request, message, node=None, extra_context=None):
		request.session.set_test_cookie()
		
		referrer = request.META.get('HTTP_REFERER', None)
		
		if referrer is not None:
			referrer = urlparse.urlparse(referrer)
			host = referrer[1]
			if host != request.get_host():
				referrer = None
			else:
				redirect = '%s?%s' % (referrer[2], referrer[4])
		
		if referrer is None:
			redirect = node.get_absolute_url()
		
		path = request.get_full_path()
		if redirect != path:
			if redirect is None:
				redirect = '/'.join(path.split('/')[:-2])
			request.session['redirect'] = redirect
		
		if request.POST:
			form = LoginForm(request.POST)
		else:
			form = LoginForm()
		context = self.get_context({
			'message': message,
			'form': form
		})
		context.update(extra_context or {})
		return self.login_page.render_to_response(node, request, extra_context=context)
	
	def login(self, request, node=None, extra_context=None):
		"""
		Displays the login form for the given HttpRequest.
		"""
		if request.user.is_authenticated():
			return HttpResponseRedirect(node.get_absolute_url())
		
		context = self.get_context(extra_context)
		
		from django.contrib.auth.models import User
		
		# If this isn't already the login page, display it.
		if not request.POST.has_key(LOGIN_FORM_KEY):
			if request.POST:
				message = _("Please log in again, because your session has expired.")
			else:
				message = ""
			return self.display_login_page(request, message, node, context)

		# Check that the user accepts cookies.
		if not request.session.test_cookie_worked():
			message = _("Looks like your browser isn't configured to accept cookies. Please enable cookies, reload this page, and try again.")
			return self.display_login_page(request, message, node, context)
		else:
			request.session.delete_test_cookie()
		
		# Check the password.
		username = request.POST.get('username', None)
		password = request.POST.get('password', None)
		user = authenticate(username=username, password=password)
		if user is None:
			message = ERROR_MESSAGE
			if username is not None and u'@' in username:
				# Mistakenly entered e-mail address instead of username? Look it up.
				try:
					user = User.objects.get(email=username)
				except (User.DoesNotExist, User.MultipleObjectsReturned):
					message = _("Usernames cannot contain the '@' character.")
				else:
					if user.check_password(password):
						message = _("Your e-mail address is not your username."
									" Try '%s' instead.") % user.username
					else:
						message = _("Usernames cannot contain the '@' character.")
			return self.display_login_page(request, message, node, context)

		# The user data is correct; log in the user in and continue.
		else:
			if user.is_active:
				login(request, user)
				try:
					redirect = request.session.pop('redirect')
				except KeyError:
					redirect = node.get_absolute_url()
				return HttpResponseRedirect(redirect)
			else:
				return self.display_login_page(request, ERROR_MESSAGE, node, context)
	login = never_cache(login)
	
	def logout(self, request):
		return auth_views.logout(request, request.META['HTTP_REFERER'])
	
	def login_required(self, view):
		def inner(request, node=None, *args, **kwargs):
			if not request.user.is_authenticated():
				login_url = reverse('login', urlconf=self).strip('/')
				return HttpResponseRedirect('%s%s/' % (node.get_absolute_url(), login_url))
			return view(request, node=node, *args, **kwargs)
		
		return inner
	
	def send_confirmation_email(self, subject, email, page, extra_context):
		message = page.render_to_string(extra_context=extra_context)
		from_email = 'noreply@%s' % Site.objects.get_current().domain
		send_mail(subject, message, from_email, [email])
	
	def password_reset(self, request, node=None, extra_context=None, token_generator=password_token_generator):
		if request.user.is_authenticated():
			return HttpResponseRedirect(node.get_absolute_url())
		
		if request.method == 'POST':
			form = PasswordResetForm(request.POST)
			if form.is_valid():
				current_site = Site.objects.get_current()
				for user in form.users_cache:
					token = token_generator.make_token(user)
					link = 'http://%s/%s/%s/' % (current_site.domain, node.get_absolute_url().strip('/'), reverse('password_reset_confirm', urlconf=self, kwargs={'uidb36': int_to_base36(user.id), 'token': token}).strip('/'))
					context = {
{'fraction_non_alphanumeric': 0.11743863943825292, 'fraction_numerical': 0.002770083102493075, 'mean_word_length': 5.1287011448874855, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5359658', 'n_tokens_mistral': 5392, 'n_tokens_neox': 4719, 'n_words': 1144}