Middleware that exposes the user's profile as well as login/logout URLs to any templates. These are available as `profile`, `login`, and `logout`.
190092
function addTemplateVariables (req, res, next) {
  res.locals.profile = req.user;
  res.locals.login = '/auth/login?return=' +
    encodeURIComponent(req.originalUrl);
  res.locals.logout = '/auth/logout?return=' +
    encodeURIComponent(req.originalUrl);
  next();
}
1094331
def logout_path(user = current_user, app = main_app)
      path = security.logout_path
      path ||=
        if defined? ::Devise
          scope = ::Devise::Mapping.find_scope! user
          "destroy_#{scope}_session_path"
        end
      ModuleUtils.try_to app, path
    end
353366
def profileit(path=None):
    

    def inner(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            prof = cProfile.Profile()
            retval = prof.runcall(func, *args, **kwargs)
            if path is not None:
                print prof.print_stats()
                prof.dump_stats(os.path.expanduser(path))
            else:
                print prof.print_stats()
            return retval
        return wrapper
    return inner
305117
function loginCallback(options) {
  return async function loginCallbackHandler(ctx) {
    let referer;
    // customize how to get redirect target
    if (options.getRedirectTarget) {
      referer = options.getRedirectTarget(ctx);
    }
    if (!referer) referer = ctx.session.userauthLoginReferer || options.rootPath;

    debug('loginReferer in session: %j', ctx.session.userauthLoginReferer);
    // cleanup the userauthLoginReferer on session
    ctx.session.userauthLoginReferer = undefined;
    let user = ctx.session[options.userField];
    if (user) {
      // already login
      return redirect(ctx, referer);
    }
    user = await options.getUser(ctx);
    if (!user) {
      return redirect(ctx, referer);
    }

    const res = await options.loginCallback(ctx, user);
    const loginUser = res[0];
    const redirectURL = res[1];
    ctx.session[options.userField] = loginUser;
    if (redirectURL) {
      referer = redirectURL;
    }
    redirect(ctx, referer);
  };
}
1129938
def get_new_profile_template(self):
        
        uri = '{}/new-profile-template'.format(self.data["uri"])
        return self._helper.do_get(uri)
201077
def logout(request, template_name=None,
           next_page=None,
           redirect_field_name=REDIRECT_FIELD_NAME,
           current_app=None, extra_context=None):
    
    auth_logout(request)

    if next_page is not None:
        next_page = resolve_url(next_page)

    if (redirect_field_name in request.POST or
            redirect_field_name in request.GET):
        next_page = request.POST.get(redirect_field_name,
                                     request.GET.get(redirect_field_name))
        # Security check -- don't allow redirection to a different host.
        if not is_safe_url(url=next_page, host=request.get_host()):
            next_page = request.path

    if next_page:
        # Redirect to this page until the session has been cleared.
        return HttpResponseRedirect(next_page)

    current_site = get_current_site(request)
    context = {
        'site': current_site,
        'site_name': current_site.name,
        'title': _('Logged out')
    }
    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)
53875
def manage_profile_requests_view(request):
    '''  '''
    page_name = "Admin - Manage Profile Requests"
    profile_requests = ProfileRequest.objects.all()
    return render_to_response('manage_profile_requests.html', {
        'page_name': page_name,
        'choices': UserProfile.STATUS_CHOICES,
        'profile_requests': profile_requests
        }, context_instance=RequestContext(request))
642175
def logout_user(f):
    

    @functools.wraps(f)
    def deco(*a, **kw):
        signals.user_logout(lambda: flask_login.current_user)
        flask_login.logout_user()
        return f(*a, **kw)

    return deco
555099
def logout(self, request, extra_context=None):
        
        from django.contrib.auth.views import logout
        defaults = {
            'extra_context': extra_context or {},
            'template_name': 'cms/logged_out.html',
        }
        if self.logout_template is not None:
            defaults['template_name'] = self.logout_template
        return logout(request, **defaults)
1328898
def redirect_profile(request):
    '''
    
    '''
    if request.user.is_authenticated:
        return HttpResponseRedirect(reverse('wafer_user_profile',
                                            args=(request.user.username,)))
    else:
        return redirect_to_login(next=reverse(redirect_profile))
14685
function middlewareStrategy(metadata, dataAdapter, opts) {
    opts.filter = opts.filter || defaultFilter;
    const { filter } = opts;
    return async function magic(ctx, next) {
        const { name, key } = opts.filter.call(null, ctx);
        const obj = metadata[name];
        const { routeSwitch = {} } = obj;

        let middleware;
        if (routeSwitch[key] === true) {
            const { pres, posts } = getHooks(obj, key);
            const route = routes[key];
            middleware = route.call(null, name, dataAdapter, opts, pres, posts);
        }

        try {
            if (typeof middleware === 'function') {
                await middleware.call(null, ctx, next);
            } else {
                await next();
            }
        } catch (err) {
            throw err;
        }
    }
}
1187258
def auth_middleware(policy):
    
    assert isinstance(policy, AbstractAuthentication)

    async def _auth_middleware_factory(app, handler):

        async def _middleware_handler(request):
            # Save the policy in the request
            request[POLICY_KEY] = policy

            # Call the next handler in the chain
            response = await handler(request)

            # Give the policy a chance to handle the response
            await policy.process_response(request, response)

            return response

        return _middleware_handler

    return _auth_middleware_factory
48876
def POST(self, *args, **kwargs):
        
        if self.user_manager.session_logged_in():
            if not self.user_manager.session_username() and not self.__class__.__name__ == "ProfilePage":
                raise web.seeother("/preferences/profile")

            if not self.is_lti_page and self.user_manager.session_lti_info() is not None:  # lti session
                self.user_manager.disconnect_user()
                return self.template_helper.get_renderer().auth(self.user_manager.get_auth_methods_fields(), False)

            return self.POST_AUTH(*args, **kwargs)
        else:
            user_input = web.input()
            if "login" in user_input and "password" in user_input:
                if self.user_manager.auth_user(user_input["login"].strip(), user_input["password"]) is not None:
                    return self.GET_AUTH(*args, **kwargs)
                else:
                    return self.template_helper.get_renderer().auth(self.user_manager.get_auth_methods(), True)
            else:
                return self.template_helper.get_renderer().auth(self.user_manager.get_auth_methods(), False)
372760
def user_loggedin(sender, **kwargs):
    
    values = {
        'value': 1,
        'path': kwargs['request'].path,
        'user_id': str(kwargs['user'].pk),
        'username': kwargs['user'].username,
    }
    write('user_logins', values=values)
1166017
function authDetectionMiddleware(req, res, next) {
    logger.debug('Running Auth Detection Middleware...', req.body);

    if (req.headers['token']) {
      try {
        req.user = encryption.decode(req.headers['token'], config.secret);
        req.session = { user: req.user };
      } catch (ex) {
        logger.logError('Unexpectedly could not decode a token.', ex);
        res.status(401).send();
        // ensure no user is authenticated.
        req.user = null;
        req.session = { user: null };
      }
      if (!req.user.id) throw 'AUTH FAILED:USER HAS NO MEMBER: id';
      if (!req.user.tokenExpiry || req.user.tokenExpiry <= new Date().getTime()) {
        logger.log('Expired Token:', req.user);
        res.status(401).send({errorCode: 'expired token'});
      }
      else {
        logger.log('Authenticated User:', req.user.id);
        next();
      }
    } else {
      //logger.debug('Checking permissions to ', req.path);
      //if (config.routesNotRequiringAuthentication[req.path]) next();
      //else if (m.isPublicRoute(req.path)) next();
      //else {
      //  logger.debug('Disallowing request to:', req.path);
      //  res.status(401).send();
      //}
      if (config.authenticatedRoutes[req.path] || !m.isPublicRoute(req.path))
        res.status(401).send();
      else
        next();
    }
  }
105441
def login_view(request):
    '''  '''
    ANONYMOUS_SESSION = request.session.get('ANONYMOUS_SESSION', False)
    page_name = "Login Page"
    redirect_to = request.GET.get('next', reverse('homepage'))
    if (request.user.is_authenticated() and not ANONYMOUS_SESSION) or (ANONYMOUS_SESSION and request.user.username != ANONYMOUS_USERNAME):
        return HttpResponseRedirect(redirect_to)
    form = LoginForm(request.POST or None)
    if form.is_valid():
        user = form.save()
        login(request, user)
        if ANONYMOUS_SESSION:
            request.session['ANONYMOUS_SESSION'] = True
        return HttpResponseRedirect(redirect_to)
    elif request.method == "POST":
        reset_url = request.build_absolute_uri(reverse('reset_pw'))
        messages.add_message(request, messages.INFO,
                             MESSAGES['RESET_MESSAGE'].format(reset_url=reset_url))

    return render_to_response('login.html', {
        'page_name': page_name,
        'form': form,
        'oauth_providers': _get_oauth_providers(),
        'redirect_to': redirect_to,
        }, context_instance=RequestContext(request))
374310
def profile_url(obj, profile_app_name, profile_model_name):
    
    try:
        content_type = ContentType.objects.get(
            app_label=profile_app_name,
            model=profile_model_name.lower()
        )
        profile = content_type.get_object_for_this_type(user=obj.user)
        return profile.get_absolute_url()
    except ContentType.DoesNotExist:
        return ""
    except AttributeError:
        return ""