Example #1
0
def login(request, internal=False, **kwargs):
    if CONFIG.get("CAS_LOGIN") and internal is False:
        return cas_login(request, **kwargs)
    else:
        return auth_login_view(
            request, authentication_form=IPAMAuthenticationForm, **kwargs
        )
Example #2
0
def login(request, internal=False, **kwargs):
    # if CONFIG.get("CAS_LOGIN") and internal is False:
    #     return cas_login(request, **kwargs)
    # else:
    return auth_login_view(request,
                           authentication_form=IPAMAuthenticationForm,
                           **kwargs)
Example #3
0
def openid(request, op_name=None):
    client = None
    request.session["next"] = request.GET["next"] if "next" in request.GET.keys() else "/"
    try:
        dyn = settings.OIDC_ALLOW_DYNAMIC_OP or False
    except:
        dyn = True

    try:
        template_name = settings.OIDC_LOGIN_TEMPLATE
    except AttributeError:
        template_name = 'djangooidc/login.html'

    # Internal login?
    if request.method == 'POST' and "internal_login" in request.POST:
        ilform = AuthenticationForm(request.POST)
        return auth_login_view(request)
    else:
        ilform = AuthenticationForm()

    # Try to find an OP client either from the form or from the op_name URL argument
    if request.method == 'GET' and op_name is not None:
        client = CLIENTS[op_name]
        request.session["op"] = op_name

    if request.method == 'POST' and dyn:
        form = DynamicProvider(request.POST)
        if form.is_valid():
            try:
                client = CLIENTS.dynamic_client(form.cleaned_data["hint"])
                request.session["op"] = client.provider_info["issuer"]
            except Exception, e:
                logger.exception("could not create OOID client")
                return render_to_response("djangooidc/error.html", {"error": e})
Example #4
0
def openid(request, op_name=None):
    client = None
    request.session[
        "next"] = request.GET["next"] if "next" in request.GET.keys() else "/"
    try:
        dyn = settings.OIDC_ALLOW_DYNAMIC_OP or False
    except:
        dyn = True

    try:
        template_name = settings.OIDC_LOGIN_TEMPLATE
    except AttributeError:
        template_name = 'djangooidc/login.html'

    # Internal login?
    if request.method == 'POST' and "internal_login" in request.POST:
        ilform = AuthenticationForm(request.POST)
        return auth_login_view(request)
    else:
        ilform = AuthenticationForm()

    # Try to find an OP client either from the form or from the op_name URL
    # argument
    if request.method == 'GET' and op_name is not None:
        try:
            client = CLIENTS[op_name]
        except KeyError as e:
            logger.info(str(e))
            raise Http404("OIDC client not found")
        request.session["op"] = op_name

    if request.method == 'POST' and dyn:
        form = DynamicProvider(request.POST)
        if form.is_valid():
            try:
                client = CLIENTS.dynamic_client(form.cleaned_data["hint"])
                request.session["op"] = client.provider_info["issuer"]
            except Exception as e:
                logger.exception("could not create OOID client")
                return view_error_handler(request, {"error": e})
    else:
        form = DynamicProvider()

    # If we were able to determine the OP client, just redirect to it with an
    # authentication request
    if client:
        try:
            return client.create_authn_request(request.session)
        except Exception as e:
            return view_error_handler(request, {"error": e})

    # Otherwise just render the list+form.
    return render(
        request, template_name, {
            "op_list": [i for i in settings.OIDC_PROVIDERS.keys() if i],
            'dynamic': dyn,
            'form': form,
            'ilform': ilform,
            "next": request.session["next"]
        })
Example #5
0
def openid(request, op_name=None):
    client = None
    request.session["next"] = request.GET["next"] if "next" in request.GET.keys() else "/"
    try:
        dyn = settings.OIDC_ALLOW_DYNAMIC_OP or False
    except:
        dyn = True

    try:
        template_name = settings.OIDC_LOGIN_TEMPLATE
    except AttributeError:
        template_name = 'djangooidc/login.html'

    # Internal login?
    if request.method == 'POST' and "internal_login" in request.POST:
        ilform = AuthenticationForm(request.POST)
        return auth_login_view(request)
    else:
        ilform = AuthenticationForm()

    # Try to find an OP client either from the form or from the op_name URL argument
    if request.method == 'GET' and op_name is not None:
        client = CLIENTS[op_name]
        request.session["op"] = op_name

    if request.method == 'POST' and dyn:
        form = DynamicProvider(request.POST)
        if form.is_valid():
            try:
                client = CLIENTS.dynamic_client(form.cleaned_data["hint"])
                request.session["op"] = client.provider_info["issuer"]
            except Exception, e:
                logger.exception("could not create OOID client")
                return render_to_response("djangooidc/error.html", {"error": e})
Example #6
0
def login_view(request):
    """Log in view.
    """
    defaults = {
        'template_name': 'accounts/login.html',
    }
    return auth_login_view(request, **defaults)
Example #7
0
def signin(q):
    context = {
        'inpirationalQuote':
        'When your mind is full of indecision, try thinking with your heart.',
    }
    tname = 'registration/signin'
    injectDefaultContext(q, tname, context)
    return auth_login_view(q, tname + '.html', extra_context=context)
Example #8
0
def openid(request, op_name=None):
    client = None
    request.session[
        "next"] = request.GET["next"] if "next" in request.GET.keys() else "/"
    try:
        dyn = settings.OIDC_ALLOW_DYNAMIC_OP or False
    except:
        dyn = True

    try:
        template_name = settings.OIDC_LOGIN_TEMPLATE
    except AttributeError:
        template_name = 'djangooidc/login.html'

    # Internal login?
    if request.method == 'POST' and "internal_login" in request.POST:
        ilform = AuthenticationForm(request.POST)
        return auth_login_view(request)
    else:
        ilform = AuthenticationForm()

    # Try to find an OP client either from the form or from the op_name URL argument
    if request.method == 'GET' and op_name is not None:
        client = CLIENTS[op_name]
        request.session["op"] = op_name

    if request.method == 'POST' and dyn:
        form = DynamicProvider(request.POST)
        if form.is_valid():
            # Bypass error handling to allow default Django exception analysis
            client = CLIENTS.dynamic_client(form.cleaned_data["hint"])
            request.session["op"] = client.provider_info["issuer"]
            # try:
            #     client = CLIENTS.dynamic_client(form.cleaned_data["hint"])
            #     request.session["op"] = client.provider_info["issuer"]
            # except Exception as e:
            #     logger.exception("could not create OOID client")
            #     return render(request, "djangooidc/error.html", {"error": e})
    else:
        form = DynamicProvider()

    # If we were able to determine the OP client, just redirect to it with an authentication request
    if client:
        # Bypass error handling to allow default Django exception analysis
        return client.create_authn_request(request.session)
        # try:
        #     return client.create_authn_request(request.session)
        # except Exception as e:
        #     return render(request, "djangooidc/error.html", {"error": e})

    return render(
        request, template_name, {
            "op_list": [i for i in settings.OIDC_PROVIDERS.keys() if i],
            'dynamic': dyn,
            'form': form,
            'ilform': ilform,
            "next": request.session["next"]
        })
Example #9
0
def bind_weibo_user(request):

    oauth_access_token = request.session.get('oauth_access_token', None)
    client = APIClient(app_key=APP_KEY,
                       app_secret=APP_SECRET,
                       redirect_uri=_get_weibo_callback_url(request))
    client.set_access_token(oauth_access_token['access_token'],
                            oauth_access_token['expires_in'])
    weibo_user = client.get.users__show(uid=oauth_access_token['uid'])
    weibo_username = weibo_user.screen_name

    template_var = {}
    template_var['weibo_username'] = weibo_username
    if request.method == 'POST':
        email = request.POST.get('email', None)
        password = request.POST.get('password', None)
        if _login(request, email, password) == True:

            #weibo信息记录
            w_user = WeiboUser()
            w_user.user = request.user

            w_user.weibo_user_id = oauth_access_token['uid']
            w_user.weibo_username = weibo_username
            w_user.oauth_access_token = oauth_access_token['access_token']
            w_user.save()

            #发微博提示
            if request.POST.get('update_msg'):
                msg = request.POST.get('bind_msg')[0:140]
                client.post.statuses__update(status=msg)

            return HttpResponseRedirect(reverse('songs.views.my_home'))
        else:

            template_var['login_failure'] = True
            template_var['input_email'] = email
            return auth_login_view(
                request,
                template_name='register/bind_weibo_user.html',
                extra_context=template_var)
    else:
        return auth_login_view(request,
                               template_name='register/bind_weibo_user.html',
                               extra_context=template_var)
Example #10
0
def newUser(request):
	newUserForm = UserCreationForm(request.POST)

	if not newUserForm.is_valid():
		request.method = "GET"
		return auth_login_view(request, template_name='auth/login.html', extra_context={"newUserForm": newUserForm})

	username = newUserForm.clean_username()
	password = newUserForm.clean_password2()
	newUserForm.save()
	user = authenticate(username=username, password=password)
	auth_login(request, user)
	return redirect("/")
Example #11
0
def login(request, **kwargs):
    if get_user_model().objects.count() == 0:
        return redirect('first-run')
    else:
        # tries to authenticate without credentials (with AutologinBackend)
        u = authenticate()
        if u is not None:
            auth_login(request, u)
            redirect_to = request.REQUEST.get(kwargs.get('redirect_field_name', REDIRECT_FIELD_NAME), '')
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)
            return HttpResponseRedirect(redirect_to)
        else:
            return auth_login_view(request, **kwargs)
Example #12
0
def bind_weibo_user(request):

    oauth_access_token = request.session.get('oauth_access_token', None)
    client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=_get_weibo_callback_url(request))
    client.set_access_token(oauth_access_token['access_token'], oauth_access_token['expires_in'])
    weibo_user = client.get.users__show(uid=oauth_access_token['uid'])
    weibo_username = weibo_user.screen_name

    template_var = {}
    template_var['weibo_username'] = weibo_username
    if request.method == 'POST':
        email = request.POST.get('email', None)
        password = request.POST.get('password', None)
        if _login(request, email, password) == True:

            #weibo信息记录
            w_user = WeiboUser()
            w_user.user = request.user

            w_user.weibo_user_id = oauth_access_token['uid']
            w_user.weibo_username = weibo_username
            w_user.oauth_access_token = oauth_access_token['access_token']
            w_user.save()

            #发微博提示
            if request.POST.get('update_msg'):
                msg = request.POST.get('bind_msg')[0:140]
                client.post.statuses__update(status=msg)

            return HttpResponseRedirect(reverse('songs.views.my_home'))
        else:

            template_var['login_failure'] = True
            template_var['input_email'] = email
            return auth_login_view(request, template_name='register/bind_weibo_user.html', extra_context=template_var)
    else:
        return auth_login_view(request, template_name='register/bind_weibo_user.html', extra_context=template_var)
Example #13
0
def openid(request, op_name=None):
    client = None
    request.session["next"] = request.GET["next"] if "next" in request.GET.keys() else "/"
    try:
        dyn = settings.OIDC_ALLOW_DYNAMIC_OP or False
    except:
        dyn = True

    try:
        template_name = settings.OIDC_LOGIN_TEMPLATE
    except AttributeError:
        template_name = 'openid/login.html'

    # Internal login?
    if request.method == 'POST' and "internal_login" in request.POST:
        ilform = AuthenticationForm(request.POST)
        return auth_login_view(request)
    else:
        ilform = AuthenticationForm()

    # Try to find an OP client either from the form or from the op_name URL argument
    if request.method == 'GET' and op_name is not None:
        client = CLIENTS[op_name]
        request.session["op"] = op_name

    if request.method == 'POST' and dyn:
        form = DynamicProvider(request.POST)
        if form.is_valid():
            try:
                client = CLIENTS.dynamic_client(form.cleaned_data["hint"])
                request.session["op"] = client.provider_info["issuer"]
            except Exception as e:
                logger.exception("could not create OOID client")
                return render_to_response("openid/error.html", {"error": e})
    else:
        form = DynamicProvider()

    # If we were able to determine the OP client, just redirect to it with an authentication request
    if client:
        try:
            return client.create_authn_request(request.session)
        except Exception as e:
            return render_to_response("openid/error.html", {"error": e})

    # Otherwise just render the list+form.
    return render_to_response(template_name,
                              {"op_list": [i for i in settings.OIDC_PROVIDERS.keys() if i], 'dynamic': dyn,
                               'form': form, 'ilform': ilform, "next": request.session["next"]},
                              context_instance=RequestContext(request))
Example #14
0
def newUser(request):
    newUserForm = UserCreationForm(request.POST)

    if not newUserForm.is_valid():
        request.method = "GET"
        return auth_login_view(request,
                               template_name='auth/login.html',
                               extra_context={"newUserForm": newUserForm})

    username = newUserForm.clean_username()
    password = newUserForm.clean_password2()
    newUserForm.save()
    user = authenticate(username=username, password=password)
    auth_login(request, user)
    return redirect("/")
Example #15
0
def login(request, **kwargs):
    if get_user_model().objects.count() == 0:
        return redirect('first-run')
    else:
        # tries to authenticate without credentials (with AutologinBackend)
        u = authenticate()
        if u is not None:
            auth_login(request, u)
            redirect_to = request.REQUEST.get(
                kwargs.get('redirect_field_name', REDIRECT_FIELD_NAME), '')
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)
            return HttpResponseRedirect(redirect_to)
        else:
            return auth_login_view(request, **kwargs)
Example #16
0
def hx_login(request, template_name='hxauth/login.html',
        redirect_field_name=REDIRECT_FIELD_NAME,
        authentication_form=HXAuthenticationForm,
        current_app=None, extra_context=None, test_func=lambda u: u.is_authenticated()):
    """ 登录失败,返回错误的form(或错误信息)
        登录成功,跳转到首页或上一次页面。
    """
    # 如果用于已经登录,则跳转到主页
    if test_func(request.user):
        return HttpResponseRedirect('/')

    return auth_login_view(request, template_name=template_name,
            redirect_field_name=REDIRECT_FIELD_NAME,
            authentication_form=HXAuthenticationForm,
            current_app=current_app, extra_context=extra_context)
Example #17
0
def default_login(request):
 
    if request.method == 'GET':
        extra_context = {}
        context = RequestContext(request)
        for key, value in extra_context.items():
            context[key] = callable(value) and value() or value
        return render_to_response('registration/login.html',
                            {'form': AuthenticationForm, 'next': request.GET.get('next', '/')},
                            context_instance=context)
    else:
        if settings.SITE_NAME_SHORT == "Stanford":
            return auth_login_view(request)
        else:
            return ldap_login(request, '', '')
Example #18
0
def login(request, *args, **kwargs):

    from django.contrib.auth.views import login as auth_login_view
    ret = auth_login_view(request, *args, **kwargs)

    if request.method == 'POST' and request.user.is_authenticated():

        ip = request.META['REMOTE_ADDR']

        if Session.objects.filter(src=ip, dt_finish=None).count():
            if Session.objects.filter(user=request.user, src=ip, dt_finish=None).count():
                messages.success(request, 'Интернет уже включен для %s.' % ip)
            else:
                messages.warning(request, 'Интернет для адреса %s был включен другим пользователем, отключаем его.' % ip)
                session = Session.objects.get(src=ip, dt_finish=None)
                session.dt_finish = datetime.now()
                session.save()
        else:
            Session(user=request.user, src=ip).save()
            messages.success(request, 'Интернет включен для адреса %s.' % ip)

    return ret
Example #19
0
def login(request):
    newUserForm = UserCreationForm()
    return auth_login_view(request,
                           template_name='auth/login.html',
                           extra_context={"newUserForm": newUserForm})
Example #20
0
def login(
    request,
    template_name="login.html",
    authentication_form=AuthenticationForm,
    login_url=None,
    current_app=None,
    extra_context={},
):
    if request.user.is_superuser:
        return redirect(reverse("super_login"))
    elif request.user.is_authenticated():
        return redirect(reverse("home"))

    # Log the login attempt.
    ip_address = get_ip(request)
    if ip_address:
        LoginAttempt.objects.create(ip_address=ip_address)

    half_day_ago = datetime.now() - timedelta(hours=12)
    login_attempts = (
        LoginAttempt.objects.all().filter(ip_address=ip_address).filter(attempt_datetime__gt=half_day_ago).count()
    )

    extra_context.update(
        {
            "show_captcha": (login_attempts >= 10),
            "invalid_captcha": False,
            "RECAPTCHA_PUBLIC_KEY": s.RECAPTCHA_PUBLIC_KEY,
        }
    )

    form = authentication_form(data=request.POST)
    if not form.is_valid():
        if re.search(m.not_activated, str(form.errors)):
            extra_context.update({"show_resend_activation_email_form": True})
        else:
            extra_context.update({"show_resend_activation_email_form": False})

    if request.method == "POST" and login_attempts > 10:
        captcha_params = urllib.urlencode(
            {
                "privatekey": s.RECAPTCHA_PRIVATE_KEY,
                "remoteip": ip_address,
                "challenge": request.POST.get("recaptcha_challenge_field", ""),
                "response": request.POST.get("recaptcha_response_field", ""),
            }
        )
        captcha_req = urllib2.Request(
            url="http://www.google.com/recaptcha/api/verify",
            data=captcha_params,
            headers={"Content-type": "application/x-www-form-urlencoded", "User-agent": "reCAPTCHA Umeqo"},
        )
        captcha_resp = urllib2.urlopen(captcha_req)
        return_values = captcha_resp.read().splitlines()
        captcha_resp.close()

        if return_values[0] != "true":
            form = authentication_form(data=request.POST)
            current_site = get_current_site(request)

            context = extra_context
            context.update(
                {"invalid_captcha": True, "form": form, "site": current_site, "site_name": current_site.name}
            )
            return context
    response = auth_login_view(
        request,
        template_name=template_name,
        authentication_form=AuthenticationForm,
        current_app=current_app,
        extra_context=extra_context,
    )
    if request.user.is_staff:
        return redirect(reverse("super_login"))
    else:
        us_user_logged_in.send(sender=request.user.__class__, request=request, user=request.user)
        return response
Example #21
0
def login(request):
    extra_context = []
    return auth_login_view(request, extra_context=extra_context, authentication_form=AuthenticationForm)
Example #22
0
def login(request):
	newUserForm = UserCreationForm()
	return auth_login_view(request, template_name='auth/login.html', extra_context={"newUserForm": newUserForm})
Example #23
0
def login_with_username(request):
    defaults = {"template_name": "admin/login.html", "authentication_form": AuthenticationForm}
    return auth_login_view(request, **defaults)
Example #24
0
def login(request,
          template_name="login.html",
          authentication_form=AuthenticationForm,
          login_url=None,
          current_app=None,
          extra_context={}):
    if request.user.is_superuser:
        return redirect(reverse('super_login'))
    elif request.user.is_authenticated():
        return redirect(reverse('home'))

    # Log the login attempt.
    ip_address = get_ip(request)
    if ip_address:
        LoginAttempt.objects.create(ip_address=ip_address)

    half_day_ago = datetime.now() - timedelta(hours=12)
    login_attempts = LoginAttempt.objects.all().filter(
        ip_address=ip_address).filter(
            attempt_datetime__gt=half_day_ago).count()

    extra_context.update({
        'show_captcha': (login_attempts >= 10),
        'invalid_captcha': False,
        'RECAPTCHA_PUBLIC_KEY': s.RECAPTCHA_PUBLIC_KEY,
    })

    form = authentication_form(data=request.POST)
    if not form.is_valid():
        if re.search(m.not_activated, str(form.errors)):
            extra_context.update({'show_resend_activation_email_form': True})
        else:
            extra_context.update({'show_resend_activation_email_form': False})

    if request.method == 'POST' and login_attempts > 10:
        captcha_params = urllib.urlencode({
            'privatekey':
            s.RECAPTCHA_PRIVATE_KEY,
            'remoteip':
            ip_address,
            'challenge':
            request.POST.get('recaptcha_challenge_field', ''),
            'response':
            request.POST.get('recaptcha_response_field', '')
        })
        captcha_req = urllib2.Request(
            url="http://www.google.com/recaptcha/api/verify",
            data=captcha_params,
            headers={
                "Content-type": "application/x-www-form-urlencoded",
                "User-agent": "reCAPTCHA Umeqo"
            })
        captcha_resp = urllib2.urlopen(captcha_req)
        return_values = captcha_resp.read().splitlines()
        captcha_resp.close()

        if return_values[0] != 'true':
            form = authentication_form(data=request.POST)
            current_site = get_current_site(request)

            context = extra_context
            context.update({
                'invalid_captcha': True,
                'form': form,
                'site': current_site,
                'site_name': current_site.name,
            })
            return context
    response = auth_login_view(request,
                               template_name=template_name,
                               authentication_form=AuthenticationForm,
                               current_app=current_app,
                               extra_context=extra_context)
    if request.user.is_staff:
        return redirect(reverse('super_login'))
    else:
        us_user_logged_in.send(sender=request.user.__class__,
                               request=request,
                               user=request.user)
        return response