Forwards to CAS login URL or verifies CAS ticket

    :param: request RequestObj
    :param: next_page Next page to redirect after login
    :param: required
    :param: gateway Gatewayed response
168333
def login(request, next_page=None, required=False, gateway=False):
    

    if not next_page:
        next_page = _redirect_url(request)

    try:
        # use callable for pre-django 2.0
        is_authenticated = request.user.is_authenticated()
    except TypeError:
        is_authenticated = request.user.is_authenticated

    if is_authenticated:
        return HttpResponseRedirect(next_page)

    ticket = request.GET.get('ticket')

    if gateway:
        service = _service_url(request, next_page, True)
    else:
        service = _service_url(request, next_page, False)

    if ticket:
        user = auth.authenticate(ticket=ticket, service=service)

        if user is not None:

            auth.login(request, user)

            if settings.CAS_PROXY_CALLBACK:
                proxy_callback(request)

            return HttpResponseRedirect(next_page)
        elif settings.CAS_RETRY_LOGIN or required:
            if gateway:
                return HttpResponseRedirect(_login_url(service, ticket, True))
            else:
                return HttpResponseRedirect(_login_url(service, ticket, False))
        else:
            logger.warning('User has a valid ticket but not a valid session')
            # Has ticket, not session

            if gateway:
                # Gatewayed responses should nto redirect.
                return False

            if getattr(settings, 'CAS_CUSTOM_FORBIDDEN'):
                return HttpResponseRedirect(reverse(settings.CAS_CUSTOM_FORBIDDEN) + "?" + request.META['QUERY_STRING'])
            else:
                error = "<h1>Forbidden</h1><p>Login failed.</p>"
                return HttpResponseForbidden(error)
    else:
        if gateway:
            return HttpResponseRedirect(_login_url(service, ticket, True))
        else:
            return HttpResponseRedirect(_login_url(service, ticket, False))
1045154
def _login_url(service, ticket='ST', gateway=False):
    

    LOGINS = {'ST': 'login',
              'PT': 'proxyValidate'}
    if gateway:
        params = {'service': service, 'gateway': 'true'}
    else:
        params = {'service': service}

    if settings.CAS_EXTRA_LOGIN_PARAMS:
        params.update(settings.CAS_EXTRA_LOGIN_PARAMS)

    if not ticket:
        ticket = 'ST'

    login_type = LOGINS.get(ticket[:2], 'login')

    return urlparse.urljoin(settings.CAS_SERVER_URL, login_type) + '?' + urlencode(params)
462605
def next_redirect(request, fallback, **get_kwargs):
    
    next = request.POST.get('next')
    if not is_safe_url(url=next, allowed_hosts=request.get_host()):
        next = resolve_url(fallback)

    if get_kwargs:
        if '#' in next:
            tmp = next.rsplit('#', 1)
            next = tmp[0]
            anchor = '#' + tmp[1]
        else:
            anchor = ''

        joiner = ('?' in next) and '&' or '?'
        next += joiner + urlencode(get_kwargs) + anchor
    return HttpResponseRedirect(next)
1322350
def gateway():
    

    if settings.CAS_GATEWAY == False:
        raise ImproperlyConfigured('CAS_GATEWAY must be set to True')

    def wrap(func):
        def wrapped_f(*args):

            from cas.views import login
            request = args[0]

            try:
                # use callable for pre-django 2.0
                is_authenticated = request.user.is_authenticated()
            except TypeError:
                is_authenticated = request.user.is_authenticated

            if is_authenticated:
                # Is Authed, fine
                pass
            else:
                path_with_params = request.path + '?' + urlencode(request.GET.copy())
                if request.GET.get('ticket'):
                    # Not Authed, but have a ticket!
                    # Try to authenticate
                    response = login(request, path_with_params, False, True)
                    if isinstance(response, HttpResponseRedirect):
                        # For certain instances where a forbidden occurs, we need to pass instead of return a response.
                        return response
                else:
                    #Not Authed, but no ticket
                    gatewayed = request.GET.get('gatewayed')
                    if gatewayed == 'true':
                        pass
                    else:
                        # Not Authed, try to authenticate
                        response = login(request, path_with_params, False, True)
                        if isinstance(response, HttpResponseRedirect):
                            return response

            return func(*args)
        return wrapped_f
    return wrap
711317
def verify_proxy_ticket(ticket, service):
    

    params = {'ticket': ticket, 'service': service}

    url = (urljoin(settings.CAS_SERVER_URL, 'proxyValidate') + '?' +
           urlencode(params))

    page = urlopen(url)

    try:
        response = page.read()
        tree = ElementTree.fromstring(response)
        if tree[0].tag.endswith('authenticationSuccess'):
            username = tree[0][0].text
            proxies = []
            if len(tree[0]) > 1:
                for element in tree[0][1]:
                    proxies.append(element.text)
            return {"username": username, "proxies": proxies}
        else:
            return None
    finally:
        page.close()
1286423
def post_registration_redirect(self, request, user):
        
        next_url = "/registration/register/complete/"
        if "next" in request.GET or "next" in request.POST:
            next_url = request.GET.get("next", None) or request.POST.get("next", None) or "/"
            
        return (next_url, (), {})
1254239
def login_required(fn):
    

    async def wrapped(request, **kwargs):
        session = await get_session(request)

        if 'token' not in session:
            return web.HTTPFound(cfg.oauth_redirect_path)

        client = GoogleClient(
            client_id=cfg.client_id,
            client_secret=cfg.client_secret,
            access_token=session['token']
        )

        try:
            user, info = await client.user_info()
        except Exception:
            return web.HTTPFound(cfg.oauth_redirect_path)

        return await fn(request, user, **kwargs)

    return wrapped
437499
def login_url(service_url=request.url)
      url = URI(Rails.application.cas_server_url)
      url.path = "/login"
      url.query = "service=#{service_url || request.url}"
      url.to_s
    end
1328704
def init_post(self, request):
        
        self.request = request
        self.service = request.POST.get('service')
        self.renew = bool(request.POST.get('renew') and request.POST['renew'] != "False")
        self.gateway = request.POST.get('gateway')
        self.method = request.POST.get('method')
        self.ajax = settings.CAS_ENABLE_AJAX_AUTH and 'HTTP_X_AJAX' in request.META
        if request.POST.get('warned') and request.POST['warned'] != "False":
            self.warned = True
        self.warn = request.POST.get('warn')
        if settings.CAS_FEDERATE:
            self.username = request.POST.get('username')
            # in federated mode, the valdated indentity provider CAS ticket is used as password
            self.ticket = request.POST.get('password')
676057
def _get_redirect_url(self, request):
        
        if 'next' in request.session:
            next_url = request.session['next']
            del request.session['next']
        elif 'next' in request.GET:
            next_url = request.GET.get('next')
        elif 'next' in request.POST:
            next_url = request.POST.get('next')
        else:
            next_url = request.user.get_absolute_url()
        if not next_url:
            next_url = '/'
        return next_url
411631
def get_service_url(request, redirect_to=None):
    """"""
    if hasattr(django_settings, 'CAS_ROOT_PROXIED_AS'):
        service = django_settings.CAS_ROOT_PROXIED_AS + request.path
    else:
        protocol = get_protocol(request)
        host = request.get_host()
        service = urllib_parse.urlunparse(
            (protocol, host, request.path, '', '', ''),
        )
    if not django_settings.CAS_STORE_NEXT:
        if '?' in service:
            service += '&'
        else:
            service += '?'
        service += urllib_parse.urlencode({
            REDIRECT_FIELD_NAME: redirect_to or get_redirect_url(request)
        })
    return service
700776
def login(request):
    """"""
    email = verify_login(request)
    request.response.headers.extend(remember(request, email))
    return {'redirect': request.POST.get('came_from', '/'), 'success': True}
1093597
protected void prepareForLoginPage(final RequestContext context) {
        val currentService = WebUtils.getService(context);
        val service = authenticationRequestServiceSelectionStrategies.resolveService(currentService, WebApplicationService.class);

        val request = WebUtils.getHttpServletRequestFromExternalWebflowContext(context);
        val response = WebUtils.getHttpServletResponseFromExternalWebflowContext(context);
        val webContext = new J2EContext(request, response, this.sessionStore);

        val urls = new LinkedHashSet<ProviderLoginPageConfiguration>();
        this.clients
            .findAllClients()
            .stream()
            .filter(client -> client instanceof IndirectClient && isDelegatedClientAuthorizedForService(client, service))
            .map(IndirectClient.class::cast)
            .forEach(client -> {
                try {
                    val provider = buildProviderConfiguration(client, webContext, currentService);
                    provider.ifPresent(p -> {
                        urls.add(p);
                        if (p.isAutoRedirect()) {
                            WebUtils.putDelegatedAuthenticationProviderPrimary(context, p);
                        }
                    });
                } catch (final Exception e) {
                    LOGGER.error("Cannot process client [{}]", client, e);
                }
            });

        if (!urls.isEmpty()) {
            context.getFlowScope().put(FLOW_ATTRIBUTE_PROVIDER_URLS, urls);
        } else if (response.getStatus() != HttpStatus.UNAUTHORIZED.value()) {
            LOGGER.warn("No delegated authentication providers could be determined based on the provided configuration. "
                + "Either no clients are configured, or the current access strategy rules prohibit CAS from using authentication providers for this request.");
        }
    }
1259524
def get(self, request, *args, **kwargs):
        
        logger.info("logout requested")
        # initialize the class attributes
        self.init_get(request)
        # if CAS federation mode is enable, bakup the provider before flushing the sessions
        if settings.CAS_FEDERATE:
            try:
                user = FederatedUser.get_from_federated_username(
                    self.request.session.get("username")
                )
                auth = CASFederateValidateUser(user.provider, service_url="")
            except FederatedUser.DoesNotExist:
                auth = None
        session_nb = self.logout(self.request.GET.get("all"))
        # if CAS federation mode is enable, redirect to user CAS logout page, appending the
        # current querystring
        if settings.CAS_FEDERATE:
            if auth is not None:
                params = utils.copy_params(request.GET, ignore={"forget_provider"})
                url = auth.get_logout_url()
                response = HttpResponseRedirect(utils.update_url(url, params))
                if request.GET.get("forget_provider"):
                    response.delete_cookie("remember_provider")
                return response
        # if service is set, redirect to service after logout
        if self.service:
            list(messages.get_messages(request))  # clean messages before leaving the django app
            return HttpResponseRedirect(self.service)
        # if service is not set but url is set, redirect to url after logout
        elif self.url:
            list(messages.get_messages(request))  # clean messages before leaving the django app
            return HttpResponseRedirect(self.url)
        else:
            # build logout message depending of the number of sessions the user logs out
            if session_nb == 1:
                logout_msg = mark_safe(_(
                    "<h3>Logout successful</h3>"
                    "You have successfully logged out from the Central Authentication Service. "
                    "For security reasons, close your web browser."
                ))
            elif session_nb > 1:
                logout_msg = mark_safe(_(
                    "<h3>Logout successful</h3>"
                    "You have successfully logged out from %d sessions of the Central "
                    "Authentication Service. "
                    "For security reasons, close your web browser."
                ) % session_nb)
            else:
                logout_msg = mark_safe(_(
                    "<h3>Logout successful</h3>"
                    "You were already logged out from the Central Authentication Service. "
                    "For security reasons, close your web browser."
                ))

            # depending of settings, redirect to the login page with a logout message or display
            # the logout page. The default is to display tge logout page.
            if settings.CAS_REDIRECT_TO_LOGIN_AFTER_LOGOUT:
                messages.add_message(request, messages.SUCCESS, logout_msg)
                if self.ajax:
                    url = reverse("cas_server:login")
                    data = {
                        'status': 'success',
                        'detail': 'logout',
                        'url': url,
                        'session_nb': session_nb
                    }
                    return json_response(request, data)
                else:
                    return redirect("cas_server:login")
            else:
                if self.ajax:
                    data = {'status': 'success', 'detail': 'logout', 'session_nb': session_nb}
                    return json_response(request, data)
                else:
                    return render(
                        request,
                        settings.CAS_LOGOUT_TEMPLATE,
                        utils.context({'logout_msg': logout_msg})
                    )
817746
function (request, response, next) {
                if (!next) {
                    next = makeDefaultNext(request, response);
                }
                try {
                    var url = request.url;
                    var questionIndex = url.indexOf("?");
                    var querystring = "";
                    if (questionIndex !== -1) {
                        // if there is a querystring, we'll just chop that part off
                        // it's still preserved in request.url, and should be handled
                        // by other middleware.
                        querystring = url.substring(questionIndex);
                        url = url.substring(0, questionIndex);
                    }
                    
                    var now = +new Date();
                    if (cacheExpirationTime < now) {
                        // time to reset the dynamic cache cache
                        
                        // Object.create(null) is used instead of {} so it doesn't have a prototype of Object.prototype
                        dynamicRouteCache = Object.create(null);
                        redirectCache = Object.create(null);
                        cacheExpirationTime = now + CACHE_CLEAR_TIME;
                    }
                    
                    var actualUrl = url;
                    var cachedResult = redirectCache[actualUrl];
                    if (cachedResult) {
                        movedPermanently(response, cachedResult + querystring);
                        return;
                    }
                    
                    var lowerMethod = request.method.toLowerCase();
                    if (url.length > 1 && url[url.length - 1] === "/") {
                        url = trimEndingSlashes(url);
                    }
                    var lowerUrl = url.toLowerCase();
                    var staticRoute = staticRoutes[lowerUrl];
                    var params;
                    var callback;
                    var descriptor;
                    var properUrl;
                    
                    if (staticRoute) {
                        properUrl = staticRoute.route;
                        if (properUrl !== actualUrl) {
                            redirectCache[actualUrl] = properUrl;
                            movedPermanently(response, properUrl + querystring);
                            return;
                        }
                        
                        descriptor = staticRoute.descriptor;
                        
                        // we found a static route
                        callback = descriptor[lowerMethod];
                        
                        if (!callback) {
                            // the URL exists, but does not have the provided method defined for it
                            methodNotAllowedHandler(request, response, next);
                            return;
                        }

                        params = emptyParams;
                    } else {
                        cachedResult = dynamicRouteCache[actualUrl];
                        if (cachedResult) {
                            descriptor = cachedResult.descriptor;
                            callback = descriptor[lowerMethod];
                            if (!callback) {
                                // the URL exists, but does not have the provided method defined for it
                                methodNotAllowedHandler(request, response, next);
                                return;
                            }
                            params = cachedResult.params;
                        } else {
                            searchDynamicRoutes:
                            for (var i = 0, len = dynamicRoutes.length; i < len; i += 1) {
                                var dynamicRoute = dynamicRoutes[i];
                                var prefix = dynamicRoute.prefix;
                            
                                if (prefix !== "/" && !startsWith(lowerUrl, prefix)) {
                                    continue;
                                }
                            
                                var routes = dynamicRoute.routes;
                                searchWithinPrefix:
                                for (var j = 0, lenJ = routes.length; j < lenJ; j += 1) {
                                    var route = routes[j];
                                    var match = route.regex.exec(url);
                                    if (!match) {
                                        continue;
                                    }
                                
                                    descriptor = route.descriptor;
                                    callback = descriptor[lowerMethod];
                                    if (!callback) {
                                        // the URL exists, but does not have the provided method defined for it
                                        methodNotAllowedHandler(request, response, next);
                                        return;
                                    }
                                
                                    var literals = route.literals;
                                    properUrl = literals[0];
                                    var argumentNames = route.argumentNames;
                                    var converters = route.converters;
                                    params = {};
                                    for (var k = 0, lenK = argumentNames.length; k < lenK; k += 1) {
                                        var unconvertedValue = match[k * 2 + 2];
                                        var convertedValue;
                                        try {
                                            convertedValue = converters[k](unconvertedValue);
                                        } catch (ex) {
                                            if (ex instanceof escort.ValidationError) {
                                                // if the converter explicitly throws a ValidationError, the route doesn't match.
                                                // thus, we need to keep searching for the correct route.
                                                callback = undefined;
                                                continue searchWithinPrefix;
                                            } else if (ex instanceof escort.CasingError) {
                                                unconvertedValue = ex.expectedCasing;
                                                convertedValue = converters[k](unconvertedValue); // guaranteed not to error
                                            } else {
                                                throw ex;
                                            }
                                        }
                                        properUrl += unconvertedValue;
                                        properUrl += literals[k + 1] || "";
                                        params[argumentNames[k]] = convertedValue;
                                    }
                                    if (route.hasEndingSlash) {
                                        properUrl += "/";
                                    }
                            
                                    if (actualUrl !== properUrl) {
                                        redirectCache[actualUrl] = properUrl;
                                        movedPermanently(response, properUrl + querystring);
                                        return;
                                    }
                                    
                                    // params needs to be frozen since it will be potentially used in later requests through the dynamic route caching system
                                    freeze(params);
                                    dynamicRouteCache[actualUrl] = {
                                        descriptor: descriptor,
                                        params: params
                                    };
                                    
                                    // we're done, so we need to break out of the outer for loop
                                    break searchDynamicRoutes;
                                }
                            }
                        }
                    }
                    
                    if (!callback) {
                        // route was unable to be located
                        if (notFoundHandler) {
                            notFoundHandler(request, response, next);
                        } else {
                            next();
                        }
                        return;
                    }
                    
                    // set params on request as well as pass it into the callback.
                    request.params = params;
                    // the descriptor is passed in as "this" so that the user can do this.post(request, response) from their get callback.
                    callback.call(descriptor, request, response, params, !notFoundHandler ? next : function (err) {
                        if (err) {
                            next(err);
                        } else {
                            notFoundHandler(request, response, next);
                        }
                    });
                } catch (err) {
                    next(err);
                }
            }
485159
def login(request, template_name=None,
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm,
          current_app=None, extra_context=None):
    
    redirect_to = request.POST.get(
        redirect_field_name,
        request.GET.get(redirect_field_name, '')
    )

    def get_redirect_to():
        # Ensure the user-originating redirection url is safe.
        if not is_safe_url(url=redirect_to, host=request.get_host()):
            return resolve_url(settings.LOGIN_REDIRECT_URL)
        return redirect_to

    if request.user.is_authenticated:
        return HttpResponseRedirect(get_redirect_to())

    if request.method == "POST":
        form = authentication_form(request=request, data=request.POST)
        if form.is_valid():

            # Okay, security check complete. Log the user in.
            auth_login(request, form.get_user())

            return HttpResponseRedirect(get_redirect_to())
    else:
        form = authentication_form(request=request)

    current_site = get_current_site(request)

    context = {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    }
    if extra_context is not None:
        context.update(extra_context)

    if current_app is not None:
        request.current_app = current_app

    return TemplateResponse(request, template_name, context)
730105
function authenticateUser (req, res, next) {
  // Check for verified access token
  if (req.claims && req.claims.sub) {
    User.get(req.claims.sub, function (err, user) {
      if (err) {
        return next(err)
      }

      if (!user) {
        return next(new UnauthorizedError({
          realm: 'user',
          error: 'unknown_user',
          error_description: 'Unknown user',
          statusCode: 401
        }))
      }

      req.user = user
      next()
    })

  // User is not authenticated.
  } else if (!req.user) {
    next(new UnauthorizedError({
      statusCode: 401
    }))

  // User is authenticated.
  } else {
    next()
  }
}