Decorator for API requests.
    Handles auth and adds the username as the first argument.
12329
def api(require_login=True, schema=None, enabled=True,
        require_admin=False, require_anonymous=False):
    
    if require_admin:
        require_login = True

    if schema is not None:
        Draft4Validator.check_schema(schema)
        validator = Draft4Validator(schema)
    else:
        validator = None

    assert not (require_login and require_anonymous), (
            "Can't both require login and require anonymous access.")

    def innerdec(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            g.auth = Auth(user=None, email=None, is_logged_in=False, is_admin=False, is_active=True)

            user_agent_str = request.headers.get('user-agent', '')
            g.user_agent = httpagentparser.detect(user_agent_str, fill_none=True)

            if not enabled:
                raise ApiException(
                    requests.codes.bad_request,
                    "This endpoint is not enabled."
                    )

            if validator is not None:
                try:
                    validator.validate(request.get_json(cache=True))
                except ValidationError as ex:
                    raise ApiException(requests.codes.bad_request, ex.message)

            auth = request.headers.get(AUTHORIZATION_HEADER)
            g.auth_header = auth
            if auth is None:
                if not require_anonymous:
                    if require_login or not ALLOW_ANONYMOUS_ACCESS:
                        raise ApiException(requests.codes.unauthorized, "Not logged in")
            else:
                # try to validate new auth
                token = auth
                # for compatibility with old clients
                if token.startswith("Bearer "):
                    token = token[7:]

                try:
                    user = verify_token_string(token)
                except AuthException:
                    raise ApiException(requests.codes.unauthorized, "Token invalid.")

                g.user = user
                g.auth = Auth(user=user.name,
                              email=user.email,
                              is_logged_in=True,
                              is_admin=user.is_admin,
                              is_active=user.is_active)

                g.auth_token = token

                if not g.auth.is_active:
                    raise ApiException(
                        requests.codes.forbidden,
                        "Account is inactive. Must have an active account."
                        )

            if require_admin and not g.auth.is_admin:
                raise ApiException(
                    requests.codes.forbidden,
                    "Must be authenticated as an admin to use this endpoint."
                    )

            return f(*args, **kwargs)
        return wrapper
    return innerdec
281165
def make_request(self, url, params, auth=None):
        
        req = urllib2.Request(url + urllib.urlencode(params))

        if auth:
            req.add_header('AUTHORIZATION', 'Basic ' + auth)

        return urllib2.urlopen(req)
647394
def authenticated_users(func):
    
    is_object_permission = "has_object" in func.__name__

    @wraps(func)
    def func_wrapper(*args, **kwargs):
        request = args[0]
        # use second parameter if object permission
        if is_object_permission:
            request = args[1]

        if not(request.user and request.user.is_authenticated):
            return False

        return func(*args, **kwargs)

    return func_wrapper
883990
def _apply_auth(self, view_func):
        
        @functools.wraps(view_func)
        def decorated(*args, **kwargs):
            if not self.auth:
                return view_func(*args, **kwargs)

            auth_data = self.auth.get_authorization()

            if auth_data is None:
                return self._handle_authentication_error()

            if not self._authentication_callback or not self._authentication_callback(auth_data):
                return self._handle_authentication_error()

            return view_func(*args, **kwargs)

        return decorated
557406
def auth(username, password):
    
    def middleware(conn):
        conn.login(username, password)
    return middleware
1111664
def handleRequestForUser(self, username, url):
        
        attempt = self.newAttemptForUser(username)
        account = self.accountByAddress(username)
        if account is None:
            # do we want to disclose this to the user?
            return
        email = self.getExternalEmail(account)
        if email is not None:
            self.sendEmail(url, attempt, email)
201713
def auth(context, request):
    

    if ploneapi.user.is_anonymous():
        request.response.setStatus(401)
        request.response.setHeader('WWW-Authenticate',
                                   'basic realm="JSONAPI AUTH"', 1)

    logger.info("*** BASIC AUTHENTICATE ***")
    return {}
803340
def argument_request_user(obj, func_name):
    """"""
    func = getattr(obj, func_name)
    request = threadlocals.request()
    if request:
        return func(request.user)
957388
function(name) {
                console.log('oauthInterface.user.username');

                var params = corbel.utils.extend(this.params, {});
                params.url = this._buildUri('username/' + name);
                params.method = corbel.request.method.GET;

                return this.request(params);
            }
723673
def create_user(self, username, first_name=None, last_name=None):
		
		
		url = api_url+'users/'
		payload = {
			'username':username
		}
		if first_name:
			payload['first_name'] = first_name
		if last_name:
			payload['last_name'] = last_name
		r = requests.post(url, data=json.dumps(payload), headers=self.headers)
		print(request_status(r))
		r.raise_for_status()
		return User(r.json())
940393
def requires_auth(func):
    """"""
    @wraps(func)
    def wrapper(self, *args, **kwargs):
        if self.token is None or self.token_expired:
            self.login()
        elif self.token_needs_refresh:
            self.refresh_token()
        return func(self, *args, **kwargs)
    return wrapper
1118121
def authorized_handler(self, f):
        
        @wraps(f)
        def decorated(*args, **kwargs):
            if 'code' in request.args:
                data = self._handle_response()
            else:
                data = self._handle_invalid_response()
            return f(*((data,) + args), **kwargs)
        return decorated
26596
def register(self, username, password, email, full_name):
        
        if all([username, password, email, full_name]):
            r = requests.post(self._base + 'user/register', params={
                'username': username,
                'password_1': password,
                'password_2': password,
                'email': email,
                'fullname': full_name
            })
            r.raise_for_status()
        else:
            raise Exception('None of the arguments may be "None"')
169975
def requires_auth(self, func):
        '''
        
        '''
        @wraps(func)
        def decorated(*args, **kwargs):
            ''' Wrapper '''
            auth = request.authorization
            if not auth or not self.check_auth(auth.username, auth.password):
                return self.authenticate()
            return func(*args, **kwargs)
        return decorated
544988
def requires_basic_auth(func):
    
    @wraps(func)
    def auth_wrapper(self, *args, **kwargs):
        if hasattr(self, '_session') and self._session.auth:
            return func(self, *args, **kwargs)
        else:
            from .models import GitHubError
            # Mock a 401 response
            r = generate_fake_error_response(
                '{"message": "Requires username/password authentication"}'
            )
            raise GitHubError(r)
    return auth_wrapper
1264756
def require_auth(request: Request, exceptions: bool=True) -> User:
    
    if not request.user or not request.user.is_authenticated:
        if exceptions:
            raise NotAuthenticated()
        return None
    return request.user
618161
def basic_auth_handler(url, method, timeout, headers, data, username=None, password=None):
    """"""

    def handle():
        """Handler that implements HTTP Basic Auth.
        """
        if username is not None and password is not None:
            auth_value = '{0}:{1}'.format(username, password).encode('utf-8')
            auth_token = base64.b64encode(auth_value)
            auth_header = b'Basic ' + auth_token
            headers.append(['Authorization', auth_header])
        default_handler(url, method, timeout, headers, data)()

    return handle