attribs - :access_token - required
 always returns a new object; check .errors? or .valid? to see how it went
484944
def authorize_token(attribs={})
      params = parse_request_params(attribs)
      parsed, creds = request(:post, url+'/authorize', params)
      if parsed[:data][:object] == 'user_token'
        UserToken.new(parsed, creds)
      else
        User.new(parsed, creds)
      end
    end
756638
def setup(*args)
      # Keep trying to get the access token
      until @access_token = self.get_access_token
        print "Try again? [Y/n] "
        return false if self.class.get_input.downcase == 'n'
      end
      # When we finally get it, record it in a dotfile
      tokens = {:default => { :token => @access_token.token, :secret => @access_token.secret }}
      save_tokens(tokens)
    end
404602
def refresh_token(self, arguments):
        

        new_access_token = None

        auth = ExistAuth(self.client_id, self.client_secret)
        resp = auth.refresh_token(self.access_token)
        if auth.token:
            new_access_token = auth.token['access_token']
            print('OAuth token refreshed: %s' % new_access_token)
            self.write_config(new_access_token)
        else:
            print('ERROR: We were unable to refresh the OAuth token | %s' % json.dumps(resp))
3894
function AccessDeniedError(message, innerMessage, model) {
    AccessDeniedError.super_.bind(this)('EACCESS', ('Access Denied' || message) , innerMessage, model);
    this.statusCode = 401;
}
65076
def get_token(params, access_token_opts={})
      params = params.merge(:parse => :json)
      access_token_opts = access_token_opts.merge({:header_format => "OAuth2 %s", :param_name => "access_token"})
      
      @token = super(params, access_token_opts)
    end
94427
def _check_token(self):
        
        need_token = (self._token_info is None or
                      self.auth_handler.is_token_expired(self._token_info))
        if need_token:
            new_token = \
                self.auth_handler.refresh_access_token(
                    self._token_info['refresh_token'])
            # skip when refresh failed
            if new_token is None:
                return

            self._token_info = new_token
            self._auth_header = {"content-type": "application/json",
                                 "Authorization": "Bearer {}".format(
                                     self._token_info.get('access_token'))}
1008536
def valid?
    @errors = (defined?(HashWithIndifferentAccess) ? HashWithIndifferentAccess : ActiveSupport::HashWithIndifferentAccess).new
    
    self.class._module.required_fields.each do |attribute|
      valid_attribute?(attribute)
    end
    
    # for rails compatibility
    def @errors.full_messages
      # After removing attributes without errors, flatten the error hash, repeating the name of the attribute before each message:
      # e.g. {'name' => ['cannot be blank', 'is too long'], 'website' => ['is not valid']}
      # will become 'name cannot be blank, name is too long, website is not valid
      self.inject([]){|memo, obj| memo.concat(obj[1].inject([]){|m, o| m << "#{obj[0].to_s.humanize} #{o}" })}
    end
    
    # Rails needs each attribute to be present in the error hash (if the attribute has no error, it has [] as a value)
    # Redefine the [] method for the errors hash to return [] instead of nil is the hash doesn't contain the key
    class << @errors
      alias :old_key_lookup :[]
      def [](key)
        old_key_lookup(key) || Array.new
      end
    end
    
    @errors.size == 0
  end
921236
def check_exists_in_object(method, obj, required_fields):
    
    missing = []
    for field in required_fields:
        if getattr(obj, field) is None:
            missing.append(field)
    if missing:
        raise PyCronofyValidationError('Method: %s. Missing auth field(s): %s' % (method, missing),
                                       method,
                                       missing
                                       )
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
1195957
def get_token
      return @token if !@token.nil?
      body =  build_auth_json

      http_client = HTTPClient.new

      p @auth_url
      p body
	
      response = http_client.post_content(@auth_url, body, 'Content-Type' => 'application/json')
      response_json_body = JSON.load(response)

      @token = response_json_body['access']['token']['id']
    end
1046241
def upgrade!
      access_token = nil
      transaction do
        access_token = OauthProviderEngine::AccessToken.create!({
          :application_id => self.application_id,
          :user_id => self.user_id,
        })
        self.destroy || raise(ActiveRecord::Rollback)
      end
      return access_token
    end
1124519
def request_access_token(self, params):
        
        return self.request(self.access_token_url, method="GET", params=params)
68774
def get_validated_token(self, raw_token):
        
        messages = []
        for AuthToken in api_settings.AUTH_TOKEN_CLASSES:
            try:
                return AuthToken(raw_token)
            except TokenError as e:
                messages.append({'token_class': AuthToken.__name__,
                                 'token_type': AuthToken.token_type,
                                 'message': e.args[0]})

        raise InvalidToken({
            'detail': _('Given token not valid for any token type'),
            'messages': messages,
        })
1102606
def get_refresh_token_params(self, scope_list=None):
        
        if self.refresh_token is None:
            raise AttributeError('No refresh token is defined.')

        params = {
            'grant_type': 'refresh_token',
            'refresh_token': self.refresh_token,
        }

        if scope_list:
            if isinstance(scope_list, list):
                scopes = '+'.join(scope_list)
            else:
                raise AttributeError('scope_list must be a list of scope.')
            params['scope'] = scopes

        return self.__prepare_token_request(params)
164938
def request_token(params)
    if scope = Util.arglist(params.delete(:scope))
      params[:scope] = Util.strlist(scope)
    end
    headers = {'content-type' => FORM_UTF8, 'accept' => JSON_UTF8,
        'authorization' => Http.basic_auth(@client_id, @client_secret) }
    reply = json_parse_reply(@key_style, *request(@token_target, :post,
        '/oauth/token', Util.encode_form(params), headers))
    raise BadResponse unless reply[jkey :token_type] && reply[jkey :access_token]
    TokenInfo.new(reply)
  end
714238
def get_access_token
      # get saved access token
      if ::File.exists?(ACCESS_TOKEN)
        @access_token = ::YAML.load_file(ACCESS_TOKEN)
      end
      # if access token is nil,
      # then get a new initial token
      if @access_token.nil?
        get_initial_token
        ::File.open(ACCESS_TOKEN, 'w') do |out|
          YAML.dump(@access_token, out)
        end
      end
    end
213739
def _verify(self, token):
        
        # Attempt to authenticate.
        url = '{}{}/'.format(self._url, 'verify')
        resp = requests.post(
            url,
            json={'token': token},
            **self._default_request_kwargs
        )
        if resp.status_code == 200:
            return resp.json().get('data', None)
        return None