0

I wrote a custom auth script and it is giving me an Internal Server error, not quite sure what is causing this or how to get detailed error reporting.

allowed_hosts is set to [] but DEBUG is set to True so that shouldn't matter. I'm accessing the site directly via IP address.

This is for a Startup Weekend so quick assistance would be the best! THANK YOU! Using Django 1.5.5

import uuid, datetime, pickle
import project.models as models
from django.contrib import auth

from django.template import Context

from django.template.loader import get_template
from django.http import HttpResponse, Http404, HttpResponseRedirect, HttpResponseServerError, HttpResponseRedirect
from django.shortcuts import render_to_response, redirect

class user(object):
    userName        = str()
    userID          = uuid.UUID(int=0)

    _exists         = False
    _authenticated  = False

    def is_authenticated(self):
        return self._authenticated

    def __str__(self):
        return str(self.__dict__.copy())

    def __getstate__(self):
        return self.__dict__.copy()

    def __setstate__(self, dict):
        self.__dict__ = dict

    def __init__(self, username=None):
        if username:
            self.initialize(username)

    def initialize(self, username):
        self.userName = username
        model = models.User.objects.filter(userName=self.userName).all()
        if len(model) == 1:
            model = model[0]
            self.data = model
            self._exists = True
            self.userID = model.id          
        else:
            self._exists = False

    def authenticate(self, password):
        self._authenticated = False
        if self._exists:
            import hashlib
            hash = hashlib.md5('%s%s' % (str(password), self.data.pwSalt)).hexdigest()
            if hash == self.data.pwHash:
                self._authenticated = True
                return True
        return False

    def updateUser(self):
        self.initialize(models.User.objects.filter(id=self.userID).get().userName)

    def mkContext(self, context):
        c = context
        c['user'] = self
        return c

class userMiddleWare(object):

    def authenticated(self, request):
        if (request.session.get('user', False)):
            request.user = request.session["user"]
            return True
        return False

    def authenticate(self, request):
        if (request.method == 'POST' and ('username' in request.POST) and ('password' in request.POST)):
            u = user(str(request.POST['username']))
            if (u.authenticate(str(request.POST['password']))):
                request.session['user'] = u
                request.user = u
                try:
                    request.session.save()
                except:
                    e = "Session wasn't saved or something?"
                return True
        request.user = user()
        return False

    def authorize(self, request):
        return True

    def process_request(self, request):

        next = False

        if request.method == 'POST':
            if request.POST.get('username', False) and request.POST.get('password', False):
                next = request.POST.get('next', False)
                if not self.authenticated(request):
                    self.authenticate(request)
                    if request.session.has_key('user'):
                        if not request.session['user']._authenticated:
                            return redirect('project.views.main')
                    else:
                        return redirect('project.views.main')

        # context = Context(request)

        if request.session.has_key('user'):
            request.user = request.session['user']
            if next:
                return redirect(next)
        else:
            request.user = user()

    def process_response(self, request, response):
        try:
            if hasattr(request, 'session'):
                request.session.save()
        except:
            e = "Session wasn't saved or something?"    
        return response

    def process_exception(self, request, exception):
        return

        # import settings
        # # if getattr(settings, 'DEBUG', False):
        # #     return

        # import traceback

        # timestamp = str(datetime.datetime.now())
        # if exception == 'process_request' or exception=='process_response':
        #   errtype = exception
        # else:
        #   errtype = 'Application Error'

        # if hasattr(exception, 'args'):
        #   message = getattr(exception, 'args')
        # else:
        #   message = 'Unknown'

        # if hasattr(request, 'path'):
        #   path = getattr(request, 'path', None)
        # else:
        #   path = 'Unknown'

        # if (hasattr(request, 'session') and getattr(request, 'session').get('user', None)):
        #   user = request.session['user'].userName

        # try:
        #   tb = ''
        #   for l in traceback.format_stack():
        #       tb += l
        #   trace = tb
        # except:
        #   trace = []

        # context = Context({'errtype':errtype, 'message':message, 'path':path, 'trace':trace, 'user':user, 'client':client})

        # return HttpResponseServerError(get_template('error.html').render(context))
Timmy O'Mahony
  • 53,000
  • 18
  • 155
  • 177
MatthewKremer
  • 1,549
  • 1
  • 14
  • 25
  • 2
    If you are getting an `Internal Service Error` it's likely you aren't in debug mode. What is the actual error in the logs? – Timmy O'Mahony Nov 02 '13 at 21:32
  • Which log am I looking at? I apologize, I'm not usually the server guy, and he happened to leave an hour ago. – MatthewKremer Nov 02 '13 at 21:36
  • if DEBUG=TEMPLATE_DEBUG=True in settings, lots of useful traces and metadata are displayed in case of error https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-DEBUG, https://docs.djangoproject.com/en/dev/ref/settings/#template-debug – alko Nov 02 '13 at 21:41
  • btw, misconfigured allowed_hosts can lead to 400 bad request, not 500 internal error – alko Nov 02 '13 at 21:42
  • Not getting any logs what so ever, both are set to True. – MatthewKremer Nov 02 '13 at 21:47
  • If it is internal server error and you are in debug mode (DEBUG=True in your settings.py file) you should be able to see full stack trace on your web page. If you are not in DEBUG mode and using default logging you will get mail (admin mail set in settings.py) with full stack trace. please check http://stackoverflow.com/questions/238081/how-do-you-log-server-errors-on-django-sites Also try your testcase in Django1.4 as it may be a bug in Django1.5 – Gaurav Nov 02 '13 at 21:55

0 Answers0