Ejemplo n.º 1
0
def ask_user_for_permission(request):
    """

    :param request:
    :param user:
    :param subacc:
    :return:
    """
    if 'device_ask_permission' in request.session:
        ask_count = int(request.session['device_ask_permission']['count'])
    else:
        ask_count = 0
    ask_count += 1

    if 'device_permission' in request.session:
        device_id = request.session['device_permission']['subacc']
        user_email = request.session['device_permission']['user']
        if settings.DEBUG:
            print("User:  "******"Device:", device_id)
            print("Ask Count:", ask_count)

        user = get_user_model().objects.get(email=user_email)
        device = Device.objects.get(pk=device_id)

    else:
        if settings.DEBUG:
            print("Not passed from Sub-account Login correctly")
        messages.error(request, "Unable to Check Permission")
        return HttpResponseRedirect(reverse("api:home"))

    # Check the number of attempts to get permission
    # DONE: Check ask_permission count against settings.
    if settings.DEVICE_PERMISSION_COUNT:
        max_count = settings.DEVICE_PERMISSION_COUNT
    else:
        # Set a default
        max_count = 3

    if max_count > 0:
        # We need to check the number of attempts
        if ask_count > max_count:
            # Set subacc as used
            # set message
            # return to api:home
            device.set_used()
            # now we can clear down the count
            request.session['device_ask_permission'] = {}

            messages.error(
                request, "Too many permission attempts. "
                "This Sub-Account is locked. "
                "The account owner will need to reset "
                "this Sub-account")
            return HttpResponseRedirect(reverse("api:home"))

    # Now to Ask for Permission

    if settings.DEBUG:
        print("Entering apps.subacc.views.Ask_User_For_Permission")
        print("request.user:"******"request.session:", request.session)

        print("user passed via session:", user)
        print("subacc passed via session:", device)

    # We need to work out the user and subacc
    # should be able to use request.session
    # DONE: Create Ask User For Permission
    # DONE: Create Form and View to get permission
    # DONE: Add view to urls.py.py
    if request.POST:
        form = Question_Form(request.POST)
        if form.is_valid():
            if Check_Answer(user, form.cleaned_data['question'],
                            form.cleaned_data['answer']):
                # True is good. False is BAD
                # Finish the login process
                # Also have to set subacc.permitted to True
                permitted_result = Device_Set_To_Permitted(device)
                # DONE: Set subacc.used = True
                used_result = device.set_used()
                if settings.DEBUG:
                    print("subacc is now permitted?:", permitted_result)
                    print("subacc in set to used:", used_result)
                User_Model = get_user_model()
                user = User_Model.objects.get(email=device.user)
                user.backend = 'django.contrib.auth.backends.ModelBackend'
                # fix for user.backend attribute

                if settings.DEBUG:
                    print("User_Model:", User_Model)
                    print("user:"******"ET":
                    # msg = PERM_MSG0 + user.email + PERM_MSG1 + subacc.subacc + PERM_MSG2
                    subject = "Device Connected to " + settings.APPLICATION_TITLE
                    if user.notify_activity in "ET":
                        send_activity_message(
                            request,
                            user,
                            subject,
                            template=
                            "accounts/messages/device_permission_email",
                            context={
                                'subacc': device.device,
                                'email_mask': email_mask(user.email)
                            },
                        )
            # Otherwise don't send a message

                django_login(request, user)
                session_set = session_device(request, device.device)
                # DONE: Record Access in DeviceAccessLog

                dal_result = Post_Device_Access(request,
                                                device,
                                                action="PERMISSION")
                if settings.DEBUG:
                    print("Post to Device Access Log:", dal_result)

                # CLEAR DOWN THE REQUEST.SESSION VARIABLE
                request.session['device_permission'] = {}
                request.session['device_ask_permission'] = {}
                if settings.DEBUG:
                    print("User:"******"Sessions:", request.session)

                return HttpResponseRedirect(reverse("api:home"))
            else:
                # Failed - Go back to Login
                messages.error(request, "Sorry - that was the wrong answer")
                Post_Device_Access(request, device, action="WRONG")
                # DONE: increment counter in request.session
                request.session['device_ask_permission'] = {'count': ask_count}

                # DONE: Record Access in DeviceAccessLog
                return HttpResponseRedirect(reverse('subaccount:device_login'))
        else:
            messages.error(request, "I am sorry = there was a problem")
            render(request, 'subacc/subaccount_permission.html', {
                'form': form,
                'question': form['question']
            })
    else:

        print("In the GET - about to render question form")

    question = Get_Question(request, user)
    print("Got from Get_Question:", question[1])
    form = Question_Form(initial={'question': question[1]})

    if settings.DEBUG:
        print("Question to ask:", question)
    return render(
        request,
        'subacc/subaccount_permission.html',
        {
            'form': form,
            'question': question,
            'subacc': device
        },
    )
Ejemplo n.º 2
0
def Subaccount_Login(request, *args, **kwargs):
    """
    Device Login
    :param request:
    :param args:
    :param kwargs:
    :return:
    """

    if request.method == 'POST':
        form = Device_AuthenticationForm(request.POST)
        if settings.DEBUG:
            print("in apps.subacc.views.Subaccount_Login POST")
        if form.is_valid():
            if settings.DEBUG:
                print("Form is Valid: Authenticating Sub-account")

            # DONE: Remove trailing spaces
            account = form.cleaned_data['account'].strip()
            Dpassword = form.cleaned_data['password'].strip()

            device = subaccount_authenticate(
                account=account,
                password=Dpassword,
            )
            # device_authenticate will check for active and not deleted
            if settings.DEBUG:
                print(
                    "subacc:",
                    device,
                )
            permission_check = False
            if device is not None:
                if device.is_active:
                    if settings.DEBUG:
                        print("Active Sub-account:", device.is_active())
                        print("Request.user:"******"Sub-account.user:"******"Sub-account used:", device.is_used())
                    # Now get the User Account
                    User_Model = get_user_model()
                    user = User_Model.objects.get(email=device.user)
                    # fix for user.backend attribute
                    user.backend = 'django.contrib.auth.backends.ModelBackend'
                    auth_rslt = django_authenticate(username=user.email,
                                                    password=user.password)
                    # DONE: Check for not subacc.used

                    if not device.used:
                        if not device.permitted:
                            # Device has not been used and we need to check permission
                            # DONE: check permission if subacc is not used before
                            # We need to Ask Permission and use a challenge question
                            # Call the ask_permission Screen
                            if settings.DEBUG:
                                print("About to ask Permission")
                            form = Question_Form()
                            args = {}
                            args['form'] = form
                            args['user'] = user.email
                            args['subacc'] = device.id

                            request.session['device_permission'] = {
                                'subacc': device.id,
                                'user': device.user.email
                            }
                            return HttpResponseRedirect(
                                reverse("subaccount:ask_permission"), args)

                        else:  # subacc.permitted

                            permission_check = True
                            if settings.DEBUG:
                                print("Sub-account Used:", device.used,
                                      " Permitted:", device.permitted)
                                # Device is permitted
                    else:  # Device has been used
                        if not device.permitted:
                            if settings.DEBUG:
                                print(
                                    "Sub-account Used and Device_Permitted NOT Set"
                                )
                                # Failed authorization checks
                                # So check if permitted
                            permission_check = False
                            messages.error(
                                request,
                                "You are not permitted access with this Sub-account"
                            )
                            Post_Device_Access(request,
                                               device,
                                               action="NOTPERMITD")
                            # DONE: Record Access in DeviceAccessLog

                            return HttpResponseRedirect(reverse("api:home"))
                        else:
                            if settings.DEBUG:
                                print("Sub-account Used:", device.used,
                                      " Permitted:", device.permitted)
                                # Authorized Check is empty - so there were no problems
                            permission_check = True
                else:
                    permission_check = False
                    messages.error(request, "Inactive Sub-account.")
                    Post_Device_Access(request, device, action="INACTIVE")
                    # DONE: Record Access in DeviceAccessLog
                    return HttpResponseRedirect(reverse('api:home'))

                # End of Insert
                # DONE: Call function to get permission

                if permission_check:
                    # We passed the checks so finish the login

                    django_login(request, user)
                    session_set = session_device(request, device.device)
                    # DONE: Record Access in DeviceAccessLog

                    dal_result = Post_Device_Access(request, device)
                    if settings.DEBUG:
                        print("Post to Device Access Log:", dal_result)

                    if settings.DEBUG:
                        print("User:"******"Django_auth result:", auth_rslt)
                        print("Sessions:", request.session)

                    return HttpResponseRedirect(reverse('api:home'))
                else:  # subacc.active = False
                    messages.error(request, "This is an inactive Sub-account.")
                    return HttpResponseRedirect(reverse('api:home'))
            else:  # Problem with account or password match
                messages.error(request, "Invalid Sub-account or password.")
                return render_to_response(
                    'subacc/subaccount_login.html',
                    {'form': Device_AuthenticationForm()},
                    RequestContext(request))
        else:  # Problem with the form
            return render_to_response('subacc/subaccount_login.html',
                                      {'form': form}, RequestContext(request))
    else:  # GET and not a POST - so setup form
        if settings.DEBUG:
            print("in Subaccount_Login. Setting up Form")
        form = Device_AuthenticationForm()

    return render_to_response('subacc/subaccount_login.html', {'form': form},
                              RequestContext(request))
Ejemplo n.º 3
0
def Subaccount_Login(request, *args, **kwargs):
    """
    Device Login
    :param request:
    :param args:
    :param kwargs:
    :return:
    """

    if request.method == 'POST':
        form = Device_AuthenticationForm(request.POST)
        if settings.DEBUG:
            print("in apps.subacc.views.Subaccount_Login POST")
        if form.is_valid():
            if settings.DEBUG:
                print("Form is Valid: Authenticating Sub-account")

            # DONE: Remove trailing spaces
            account = form.cleaned_data['account'].strip()
            Dpassword = form.cleaned_data['password'].strip()

            device = subaccount_authenticate(account=account,
                                         password=Dpassword,)
            # device_authenticate will check for active and not deleted
            if settings.DEBUG:
                print("subacc:", device,)
            permission_check = False
            if device is not None:
                if device.is_active:
                    if settings.DEBUG:
                        print("Active Sub-account:", device.is_active())
                        print("Request.user:"******"Sub-account.user:"******"Sub-account used:", device.is_used())
                    # Now get the User Account
                    User_Model = get_user_model()
                    user = User_Model.objects.get(email=device.user)
                    # fix for user.backend attribute
                    user.backend = 'django.contrib.auth.backends.ModelBackend'
                    auth_rslt = django_authenticate(username=user.email,
                                                    password=user.password)
                    # DONE: Check for not subacc.used

                    if not device.used:
                        if not device.permitted:
                            # Device has not been used and we need to check permission
                            # DONE: check permission if subacc is not used before
                            # We need to Ask Permission and use a challenge question
                            # Call the ask_permission Screen
                            if settings.DEBUG:
                                print("About to ask Permission")
                            form = Question_Form()
                            args = {}
                            args['form']   = form
                            args['user']   = user.email
                            args['subacc'] = device.id

                            request.session['device_permission'] = {'subacc':device.id,
                                                                    'user':device.user.email}
                            return HttpResponseRedirect(reverse("subaccount:ask_permission"), args)

                        else: # subacc.permitted

                            permission_check = True
                            if settings.DEBUG:
                                print("Sub-account Used:", device.used,
                                      " Permitted:", device.permitted)
                                # Device is permitted
                    else: # Device has been used
                        if not device.permitted:
                            if settings.DEBUG:
                                print("Sub-account Used and Device_Permitted NOT Set")
                                # Failed authorization checks
                                # So check if permitted
                            permission_check = False
                            messages.error(request, "You are not permitted access with this Sub-account")
                            Post_Device_Access(request, device, action="NOTPERMITD")
                            # DONE: Record Access in DeviceAccessLog

                            return HttpResponseRedirect(reverse("api:home"))
                        else:
                            if settings.DEBUG:
                                print("Sub-account Used:", device.used,
                                      " Permitted:", device.permitted)
                                # Authorized Check is empty - so there were no problems
                            permission_check = True
                else:
                    permission_check = False
                    messages.error(request,"Inactive Sub-account.")
                    Post_Device_Access(request, device, action="INACTIVE")
                    # DONE: Record Access in DeviceAccessLog
                    return HttpResponseRedirect(reverse('api:home'))

                # End of Insert
                # DONE: Call function to get permission

                if permission_check:
                    # We passed the checks so finish the login

                    django_login(request, user)
                    session_set = session_device(request, device.device)
                    # DONE: Record Access in DeviceAccessLog

                    dal_result = Post_Device_Access(request, device)
                    if settings.DEBUG:
                        print("Post to Device Access Log:", dal_result)

                    if settings.DEBUG:
                        print("User:"******"Django_auth result:", auth_rslt)
                        print("Sessions:", request.session )

                    return HttpResponseRedirect(reverse('api:home'))
                else: # subacc.active = False
                    messages.error(request, "This is an inactive Sub-account.")
                    return HttpResponseRedirect(reverse('api:home'))
            else: # Problem with account or password match
                messages.error(request, "Invalid Sub-account or password.")
                return render_to_response('subacc/subaccount_login.html',
                                          {'form': Device_AuthenticationForm()},
                                          RequestContext(request))
        else: # Problem with the form
            return render_to_response('subacc/subaccount_login.html',
                                      {'form': form},
                                      RequestContext(request))
    else: # GET and not a POST - so setup form
        if settings.DEBUG:
            print("in Subaccount_Login. Setting up Form")
        form = Device_AuthenticationForm()

    return render_to_response('subacc/subaccount_login.html', {'form': form},
                              RequestContext(request))
Ejemplo n.º 4
0
def ask_user_for_permission(request):
    """

    :param request:
    :param user:
    :param subacc:
    :return:
    """
    if 'device_ask_permission' in request.session:
        ask_count = int(request.session['device_ask_permission']['count'])
    else:
        ask_count = 0
    ask_count += 1

    if 'device_permission' in request.session:
        device_id = request.session['device_permission']['subacc']
        user_email   = request.session['device_permission']['user']
        if settings.DEBUG:
            print("User:  "******"Device:", device_id)
            print("Ask Count:", ask_count)

        user = get_user_model().objects.get(email=user_email)
        device = Device.objects.get(pk=device_id)

    else:
        if settings.DEBUG:
            print("Not passed from Sub-account Login correctly")
        messages.error(request, "Unable to Check Permission")
        return HttpResponseRedirect(reverse("api:home"))

    # Check the number of attempts to get permission
    # DONE: Check ask_permission count against settings.
    if settings.DEVICE_PERMISSION_COUNT:
        max_count = settings.DEVICE_PERMISSION_COUNT
    else:
        # Set a default
        max_count = 3

    if max_count > 0:
        # We need to check the number of attempts
        if ask_count > max_count:
            # Set subacc as used
            # set message
            # return to api:home
            device.set_used()
            # now we can clear down the count
            request.session['device_ask_permission'] = {}

            messages.error(request, "Too many permission attempts. "
                                    "This Sub-Account is locked. "
                                    "The account owner will need to reset "
                                    "this Sub-account")
            return HttpResponseRedirect(reverse("api:home"))

    # Now to Ask for Permission

    if settings.DEBUG:
        print("Entering apps.subacc.views.Ask_User_For_Permission")
        print("request.user:"******"request.session:", request.session)

        print("user passed via session:", user )
        print("subacc passed via session:", device)

    # We need to work out the user and subacc
    # should be able to use request.session
    # DONE: Create Ask User For Permission
    # DONE: Create Form and View to get permission
    # DONE: Add view to urls.py.py
    if request.POST:
        form = Question_Form(request.POST)
        if form.is_valid():
            if Check_Answer(user, form.cleaned_data['question'], form.cleaned_data['answer']):
                # True is good. False is BAD
                # Finish the login process
                # Also have to set subacc.permitted to True
                permitted_result = Device_Set_To_Permitted(device)
                # DONE: Set subacc.used = True
                used_result = device.set_used()
                if settings.DEBUG:
                    print("subacc is now permitted?:", permitted_result)
                    print("subacc in set to used:", used_result)
                User_Model = get_user_model()
                user = User_Model.objects.get(email=device.user)
                user.backend = 'django.contrib.auth.backends.ModelBackend'
                # fix for user.backend attribute

                if settings.DEBUG:
                    print("User_Model:", User_Model)
                    print("user:"******"ET":
                    # msg = PERM_MSG0 + user.email + PERM_MSG1 + subacc.subacc + PERM_MSG2
                    subject = "Device Connected to " + settings.APPLICATION_TITLE
                    if user.notify_activity in "ET":
                        send_activity_message(request,
                                              user,
                                              subject,
                                              template="accounts/messages/device_permission_email",
                                              context={'subacc':device.device,
                                                       'email_mask':email_mask(user.email)},
                                              )
              # Otherwise don't send a message

                django_login(request, user)
                session_set = session_device(request, device.device)
                # DONE: Record Access in DeviceAccessLog

                dal_result = Post_Device_Access(request, device, action="PERMISSION")
                if settings.DEBUG:
                    print("Post to Device Access Log:", dal_result)

                # CLEAR DOWN THE REQUEST.SESSION VARIABLE
                request.session['device_permission'] = {}
                request.session['device_ask_permission'] = {}
                if settings.DEBUG:
                    print("User:"******"Sessions:", request.session )

                return HttpResponseRedirect(reverse("api:home"))
            else:
                # Failed - Go back to Login
                messages.error(request, "Sorry - that was the wrong answer")
                Post_Device_Access(request, device, action="WRONG")
                # DONE: increment counter in request.session
                request.session['device_ask_permission'] = {'count': ask_count}

                # DONE: Record Access in DeviceAccessLog
                return HttpResponseRedirect(reverse('subaccount:device_login'))
        else:
            messages.error(request,"I am sorry = there was a problem")
            render(request,
                   'subacc/subaccount_permission.html',
                   {'form': form,
                    'question': form['question']})
    else:

        print("In the GET - about to render question form")

    question = Get_Question(request, user)
    print("Got from Get_Question:",question[1])
    form = Question_Form(initial={'question': question[1]})

    if settings.DEBUG:
        print("Question to ask:", question)
    return render(request,
                  'subacc/subaccount_permission.html',
                   {'form': form,
                    'question': question,
                    'subacc': device},
                    )
Ejemplo n.º 5
0
def sms_login(request, *args, **kwargs):

    # Check session variables to find information carried forward.
    access_field = settings.USERNAME_FIELD
    # This is the key field name. Probably username or email

    if access_field in request.session:
        if request.session[access_field] != "":
            access_key = request.session[access_field]
        else:
            access_key = ""
    else:
        access_key = ""
    if settings.DEBUG:
        # print(request.GET)
        print("SMS_LOGIN.GET:", access_field, ":[%s]" % (access_key))
        # print(request.POST)
        print(args)

    if request.method == 'POST':
        form = AuthenticationForm(request.POST)
        if request.POST['login'].lower() == 'resend code':
            if settings.DEBUG:
                print("Resending Code for %s" % request.POST[access_field])
            # form = SMSCodeForm(request.POST)
            # form.username = request.POST['username']
            request.session[access_field] = request.POST[access_field]
            return HttpResponseRedirect(reverse('accounts:sms_code'))
        if form.is_valid():
            print("Authenticating...")
            access_key = form.cleaned_data[access_field].lower()
            password = form.cleaned_data['password'].lower()
            sms_code = form.cleaned_data['sms_code']
            if not validate_sms(access_key=access_key, smscode=sms_code):
                messages.error(request, "Invalid Access Code.")
                return render_to_response('accounts/login.html',
                                          {'form': AuthenticationForm()},
                                          RequestContext(request))
            # DONE: Trying to handle LDAP Errors. eg. Not available
            try:
                user = authenticate(username=access_key, password=password)
            except (ldap3.LDAPBindError, ldap3.LDAPSASLPrepError,
                    ldap3.LDAPSocketOpenError):
                print("We got an LDAP Error - Bind:", dir(ldap3.LDAPBindError),
                      "\nSASL Prep:", ldap3.LDAPSASLPrepError,
                      "\nSocketOpenError:", ldap3.LDAPSocketOpenError)
                messages.error(
                    request, "We had a problem reaching the Directory Server")
                return render_to_response('accounts/login.html',
                                          RequestContext(request))

            #######

            if user is not None:

                if user.is_active:
                    django_login(request, user)

                    # DONE: Set a session variable to identify as
                    # master account and not a subacc

                    session_device(request, "True", Session="auth_master")
                    # DONE: Now Send a message on login
                    if user.notify_activity in "ET":
                        send_activity_message(request, user)
                    # Otherwise don't send a message

                    return HttpResponseRedirect(reverse('home'))
                else:

                    messages.error(request, "Your account is not active.")
                    return HttpResponseRedirect(reverse('sms_code'))
            else:
                messages.error(request, "Invalid username or password.")
                return render_to_response('accounts/login.html',
                                          {'form': AuthenticationForm()},
                                          RequestContext(request))
        else:
            print("Error with the POST form", )
            return render_to_response('accounts/login.html', {'form': form},
                                      RequestContext(request))
    else:
        if access_field in request.session:
            access_key = request.session[access_field]
        else:
            access_key = ""
        if settings.DEBUG:
            print("in sms_login. Setting up Form [", access_key, "]")
        form = AuthenticationForm(initial={
            access_field: access_key,
        })
    if settings.DEBUG:
        # print(form)
        print("Dropping to render_to_response in sms_login")
    return render_to_response('accounts/login.html', {'form': form},
                              RequestContext(request))
Ejemplo n.º 6
0
def sms_login(request, *args, **kwargs):

    # Check session variables to find information carried forward.
    access_field = settings.USERNAME_FIELD
    # This is the key field name. Probably username or email

    if access_field in request.session:
        if request.session[access_field] != "":
            access_key = request.session[access_field]
        else:
            access_key = ""
    else:
        access_key = ""
    if settings.DEBUG:
        # print(request.GET)
        print("SMS_LOGIN.GET:", access_field, ":[%s]" % (access_key))
        # print(request.POST)
        print(args)

    if request.method == 'POST':
        form = AuthenticationForm(request.POST)
        if request.POST['login'].lower() == 'resend code':
            if settings.DEBUG:
                print("Resending Code for %s" % request.POST[access_field])
            # form = SMSCodeForm(request.POST)
            # form.username = request.POST['username']
            request.session[access_field] = request.POST[access_field]
            return HttpResponseRedirect(reverse('accounts:sms_code'))
        if form.is_valid():
            print("Authenticating...")
            access_key = form.cleaned_data[access_field].lower()
            password = form.cleaned_data['password'].lower()
            sms_code = form.cleaned_data['sms_code']
            if not validate_sms(access_key=access_key, smscode=sms_code):
                messages.error(request, "Invalid Access Code.")
                return render_to_response('accounts/login.html',
                                          {'form': AuthenticationForm()},
                                          RequestContext(request))
            # DONE: Trying to handle LDAP Errors. eg. Not available
            try:
                user = authenticate(username=access_key, password=password)
            except (ldap3.LDAPBindError,
                    ldap3.LDAPSASLPrepError,
                    ldap3.LDAPSocketOpenError):
                print("We got an LDAP Error - Bind:",dir(ldap3.LDAPBindError),
                    "\nSASL Prep:", ldap3.LDAPSASLPrepError,
                    "\nSocketOpenError:",ldap3.LDAPSocketOpenError)
                messages.error(request, "We had a problem reaching the Directory Server")
                return render_to_response('accounts/login.html',
                                      RequestContext(request))

            #######

            if user is not None:

                if user.is_active:
                    django_login(request, user)

                    # DONE: Set a session variable to identify as
                    # master account and not a subacc

                    session_device(request,
                                   "True",
                                   Session="auth_master")
                    # DONE: Now Send a message on login
                    if user.notify_activity in "ET":
                        send_activity_message(request,
                                              user)
                    # Otherwise don't send a message

                    return HttpResponseRedirect(reverse('home'))
                else:

                    messages.error(request, "Your account is not active.")
                    return HttpResponseRedirect(reverse('sms_code'))
            else:
                messages.error(request, "Invalid username or password.")
                return render_to_response('accounts/login.html',
                                          {'form': AuthenticationForm()},
                                          RequestContext(request))
        else:
            print("Error with the POST form", )
            return render_to_response('accounts/login.html',
                                      {'form': form},
                                      RequestContext(request))
    else:
        if access_field in request.session:
            access_key = request.session[access_field]
        else:
            access_key = ""
        if settings.DEBUG:
            print("in sms_login. Setting up Form [", access_key, "]")
        form = AuthenticationForm(initial={access_field: access_key, })
    if settings.DEBUG:
        # print(form)
        print("Dropping to render_to_response in sms_login")
    return render_to_response('accounts/login.html', {'form': form},
                              RequestContext(request))
Ejemplo n.º 7
0
def sms_login(request, *args, **kwargs):
    if 'email' in request.session:
        if request.session['email'] != "":
            email = request.session['email']
        else:
            email = ""
    else:
        email = ""
    if settings.DEBUG:
        # print(request.GET)
        print("SMS_LOGIN.GET:email:[%s]" % (email))
        # print(request.POST)
        print(args)

    if request.method == 'POST':
        form = AuthenticationForm(request.POST)
        if request.POST['login'].lower() == 'resend code':
            if settings.DEBUG:
                print("Resending Code for %s" % request.POST['email'])
            # form = SMSCodeForm(request.POST)
            # form.email = request.POST['email']
            request.session['email'] = request.POST['email']
            return HttpResponseRedirect(reverse('accounts:sms_code'))
        if form.is_valid():
            # print("Authenticate")
            email = form.cleaned_data['email'].lower()
            password = form.cleaned_data['password'].lower()
            sms_code = form.cleaned_data['sms_code']
            if not validate_sms(username=email, smscode=sms_code):
                messages.error(request, "Invalid Access Code.")
                return render_to_response('accounts/login.html',
                                          {'form': AuthenticationForm()},
                                          RequestContext(request))
            # DONE: Trying to handle LDAP Errors. eg. Not available
            try:
                user = authenticate(username=email, password=password)
            except (ldap3.LDAPBindError,
                    ldap3.LDAPSASLPrepError,
                    ldap3.LDAPSocketOpenError):
                print("We got an LDAP Error - Bind:",dir(ldap3.LDAPBindError),
                    "\nSASL Prep:", ldap3.LDAPSASLPrepError,
                    "\nSocketOpenError:",ldap3.LDAPSocketOpenError)
                messages.error(request, "We had a problem reaching the Directory Server")
                return render_to_response('accounts/login.html',
                                      RequestContext(request))

            #######

            if user is not None:

                if user.is_active:
                    django_login(request, user)

                    # DONE: Set a session variable to identify as
                    # master account and not a subacc

                    session_device(request,
                                   "True",
                                   Session="auth_master")
                    # DONE: Now Send a message on login
                    if user.notify_activity in "ET":
                        send_activity_message(request,
                                              user)
                    # Otherwise don't send a message

                    return HttpResponseRedirect(reverse('home'))
                else:

                    messages.error(request, "Your account is not active.")
                    return HttpResponseRedirect(reverse('sms_code'))
            else:
                messages.error(request, "Invalid username or password.")
                return render_to_response('accounts/login.html',
                                          {'form': AuthenticationForm()},
                                          RequestContext(request))
        else:
            return render_to_response('accounts/login.html',
                                      {'form': form},
                                      RequestContext(request))
    else:
        if 'email' in request.session:
            email = request.session['email']
        else:
            email = ""
        if settings.DEBUG:
            print("in sms_login. Setting up Form [", email, "]")
        form = AuthenticationForm(initial={'email': email, })
    if settings.DEBUG:
        # print(form)
        print("Dropping to render_to_response in sms_login")
    return render_to_response('accounts/login.html', {'form': form},
                              RequestContext(request))