Perform OAuth code exchange to retrieve a token.
        :param code: OAuth grant code.
        :param user: User who will own token.
        :return: :class:`esi.models.Token`
168697
def create_from_code(self, code, user=None):
        

        # perform code exchange
        logger.debug("Creating new token from code {0}".format(code[:-5]))
        oauth = OAuth2Session(app_settings.ESI_SSO_CLIENT_ID, redirect_uri=app_settings.ESI_SSO_CALLBACK_URL)
        token = oauth.fetch_token(app_settings.ESI_TOKEN_URL, client_secret=app_settings.ESI_SSO_CLIENT_SECRET,
                                  code=code)
        r = oauth.request('get', app_settings.ESI_TOKEN_VERIFY_URL)
        r.raise_for_status()
        token_data = r.json()
        logger.debug(token_data)

        # translate returned data to a model
        model = self.create(
            character_id=token_data['CharacterID'],
            character_name=token_data['CharacterName'],
            character_owner_hash=token_data['CharacterOwnerHash'],
            access_token=token['access_token'],
            refresh_token=token['refresh_token'],
            token_type=token_data['TokenType'],
            user=user,
        )

        # parse scopes
        if 'Scopes' in token_data:
            from esi.models import Scope
            for s in token_data['Scopes'].split():
                try:
                    scope = Scope.objects.get(name=s)
                    model.scopes.add(scope)
                except Scope.DoesNotExist:
                    # This scope isn't included in a data migration. Create a placeholder until it updates.
                    try:
                        help_text = s.split('.')[1].replace('_', ' ').capitalize()
                    except IndexError:
                        # Unusual scope name, missing periods.
                        help_text = s.replace('_', ' ').capitalize()
                    scope = Scope.objects.create(name=s, help_text=help_text)
                    model.scopes.add(scope)
            logger.debug("Added {0} scopes to new token.".format(model.scopes.all().count()))

        if not app_settings.ESI_ALWAYS_CREATE_TOKEN:
            # see if we already have a token for this character and scope combination
            # if so, we don't need a new one
            queryset = self.get_queryset().equivalent_to(model)
            if queryset.exists():
                logger.debug(
                    "Identified {0} tokens equivalent to new token. Updating access and refresh tokens.".format(
                        queryset.count()))
                queryset.update(
                    access_token=model.access_token,
                    refresh_token=model.refresh_token,
                    created=model.created,
                )
                if queryset.filter(user=model.user).exists():
                    logger.debug("Equivalent token with same user exists. Deleting new token.")
                    model.delete()
                    model = queryset.filter(user=model.user)[0]  # pick one at random

        logger.debug("Successfully created {0} for user {1}".format(repr(model), user))
        return model
1370302
def get_access_token(self, code=None, **params):
        
        if self._access_token is None:
            if code is None:
                raise ValueError(_('Invalid code.'))
            
            self.access_token_dict = self._get_access_token(code, **params)
            try:
                self._access_token = self.access_token_dict['access_token']
            except KeyError, e:
                raise OAuthError("Credentials could not be validated, the provider returned no access token.")
                
        return self._access_token
325687
async def generate_access_token(self, user):
        
        payload = await self._get_payload(user)
        secret = self._get_secret(True)
        algorithm = self._get_algorithm()

        return jwt.encode(payload, secret, algorithm=algorithm).decode("utf-8")
863396
def get_token(self, user_id):
        
        if not self.jwt_implementation:
            return self.default_token_implementation(user_id)

        try:
            implementation = import_string(self.jwt_implementation)
        except ImportError:
            msg = 'Failed to import custom JWT implementation. '
            msg += 'Check that configured module exists [{}]'
            raise x.ConfigurationException(msg.format(self.jwt_implementation))

        # return custom token
        return implementation(user_id)
1262843
def request_access_token(self, access_code):
        ""
        token_response = request_session.post(
            "https://github.com/login/oauth/access_token",
            data={
                "client_id": self.oauth_client_id,
                "client_secret": self.oauth_client_secret,
                "code": access_code
            },
            headers={"Accept": "application/json"},
        )
        return helper_request_access_token(token_response.json())
332445
def get_user(self, user):
        
        self.project_service.set_auth(self._token_project)
        return self.project_service.get_user(user)
1201489
def request_access_token(self, code, redirect_uri=None):
        '''
        
        '''
        r = self._mixin.request_access_token(code, redirect_uri)
        self._access_token = r.access_token
        return r
614474
def get_token(authed_user: hug.directives.user):
    
    user_model = Query()
    user = db.search(user_model.username == authed_user)[0]

    if user:
        out = {
            'user': user['username'],
            'api_key': user['api_key']
        }
    else:
        # this should never happen
        out = {
            'error': 'User {0} does not exist'.format(authed_user)
        }

    return out
87148
def exchange_token(self, code):
        """"""
        url = '%s%s/oauth2/token' % (self.scheme, self.host)
        options = {
            'grant_type': 'authorization_code',
            'redirect_uri': self._redirect_uri(),
            'client_id': self.options.get('client_id'),
            'client_secret': self.options.get('client_secret'),
            'code': code,
        }
        options.update({
            'verify_ssl': self.options.get('verify_ssl', True),
            'proxies': self.options.get('proxies', None)
        })
        self.token = wrapped_resource(
            make_request('post', url, options))
        self.access_token = self.token.access_token
        return self.token
732413
public OAuthSession exchangeCode(String code, HttpUrl redirectUrl) throws IOException {
    HttpUrl url = baseUrl.newBuilder("oauth.access")
        .addQueryParameter("client_id", clientId)
        .addQueryParameter("client_secret", clientSecret)
        .addQueryParameter("code", code)
        .addQueryParameter("redirect_uri", redirectUrl.toString())
        .build();
    Request request = new Request.Builder()
        .url(url)
        .build();
    Call call = httpClient.newCall(request);
    try (Response response = call.execute()) {
      JsonAdapter<OAuthSession> jsonAdapter = moshi.adapter(OAuthSession.class);
      return jsonAdapter.fromJson(response.body().source());
    }
  }
667390
private String token(final String code) throws IOException {
        return new JdkRequest(
            new Href(this.gauth).path("o").path("oauth2").path("token")
                .toString()
        ).body()
            .formParam("client_id", this.app)
            .formParam("redirect_uri", this.redir)
            .formParam("client_secret", this.key)
            .formParam("grant_type", "authorization_code")
            .formParam(PsGoogle.CODE, code)
            .back()
            .header("Content-Type", "application/x-www-form-urlencoded")
            .method(com.jcabi.http.Request.POST)
            .fetch().as(RestResponse.class)
            .assertStatus(HttpURLConnection.HTTP_OK)
            .as(JsonResponse.class).json()
            .readObject()
            .getString(PsGoogle.ACCESS_TOKEN);
    }
1051383
def get_auth_token(self, user_payload):
        
        token = user_payload.get('token') or None
        if not token:
            raise ValueError('`user_payload` must provide api token')

        return '{auth_header_prefix} {token}'.format(
            auth_header_prefix=self.auth_header_prefix, token=token)
260538
def fetch_by_code(self, code):
        
        code_data = self.read(code)

        if code_data is None:
            raise AuthCodeNotFound

        return AuthorizationCode(**code_data)
896007
function authorizationCodeGrant (code, done) {
  var endpoint = this.endpoints.token
  var provider = this.provider
  var client = this.client
  var url = endpoint.url
  var method = endpoint.method && endpoint.method.toLowerCase()
  var auth = endpoint.auth
  var parser = endpoint.parser
  var accept = endpoint.accept || 'application/json'
  var params = {}

  // required token parameters
  params.grant_type = 'authorization_code'
  params.code = code
  params.redirect_uri = provider.redirect_uri

  // start building the request
  var req = request[method || 'post'](url)

  // Authenticate the client with HTTP Basic
  if (auth === 'client_secret_basic') {
    req.set('Authorization', 'Basic ' + this.base64credentials())
  }

  // Authenticate the client with POST params
  if (auth === 'client_secret_post') {
    params.client_id = client.client_id
    params.client_secret = client.client_secret
  }

  // Add request body params and set other headers
  req.send(qs.stringify(params))
  req.set('accept', accept)
  req.set('user-agent', agent)

  // Execute the request
  return req.end(function (err, res) {
    if (err) { return done(err) }
    var response = (parser === 'x-www-form-urlencoded')
      ? qs.parse(res.text)
      : res.body

    if (res.statusCode !== 200) {
      return done(response)
    }

    done(null, response)
  })
}
144705
def get_user_by_action_token(action, token):
    
    data = utils.unsign_url_safe(token,
                                 secret_key=get_jwt_secret(),
                                 salt=action)
    if data is None:
        raise exceptions.AuthError("Invalid Token")
    return get_user_by_id(int(data))
448295
def fetch_by_code(self, code):
        
        code_data = self.mc.get(self._generate_cache_key(code))

        if code_data is None:
            raise AuthCodeNotFound

        return AuthorizationCode(**code_data)
536160
def token(self, token):
        
        self._token = token
        if token:
            self.current_user = self.query_login_user()