// handleAuthorizationCode exchange `code` for user ID token and user profile.
972002
func handleAuthorizationCode(c context.Context, cfg *Settings, code string) (uid string, u *auth.User, err error) {
	if cfg.ClientID == "" || cfg.ClientSecret == "" || cfg.RedirectURI == "" {
		return "", nil, ErrNotConfigured
	}

	// Validate the discover doc has necessary fields to proceed.
	discovery, err := fetchDiscoveryDoc(c, cfg.DiscoveryURL)
	switch {
	case err != nil:
		return "", nil, err
	case discovery.TokenEndpoint == "":
		return "", nil, errors.New("openid: bad discovery doc, empty token_endpoint")
	}

	// Prepare a request to exchange authorization code for the ID token.
	v := url.Values{}
	v.Set("code", code)
	v.Set("client_id", cfg.ClientID)
	v.Set("client_secret", cfg.ClientSecret)
	v.Set("redirect_uri", cfg.RedirectURI)
	v.Set("grant_type", "authorization_code")
	payload := v.Encode()

	// Send POST to the token endpoint with URL-encoded parameters to get back the
	// ID token. There's more stuff in the reply, we don't need it.
	var token struct {
		IDToken string `json:"id_token"`
	}
	req := internal.Request{
		Method: "POST",
		URL:    discovery.TokenEndpoint,
		Body:   []byte(payload),
		Headers: map[string]string{
			"Content-Type": "application/x-www-form-urlencoded",
		},
		Out: &token,
	}
	if err := req.Do(c); err != nil {
		return "", nil, err
	}

	// Unpack the ID token to grab the user information from it.
	return userFromIDToken(c, token.IDToken, cfg, discovery)
}
210692
func (s *authenticationProviderServiceImpl) ExchangeCodeWithProvider(ctx context.Context, code string, redirectURL string) (*oauth2.Token, error) {

	// Exchange the code for an access token
	provider := s.Factories().IdentityProviderFactory().NewIdentityProvider(ctx, s.config)
	provider.SetRedirectURL(redirectURL)
	token, err := provider.Exchange(ctx, code)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"code":         code,
			"err":          err,
			"redirect_url": redirectURL,
		}, "oauth exchange operation failed")
		return nil, autherrors.NewUnauthorizedError(err.Error())
	}

	log.Debug(ctx, map[string]interface{}{
		"code": code,
	}, "exchanged code to access token")

	return token, nil
}
1211924
func (c Client) Exchange(code string) (*oauth2.Token, error) {
	jwt := NewClientJWT(c.ISS, c.AUD)
	clientAssertion, err := SignJWT(jwt, c.PrivateKey)
	if err != nil {
		return nil, err
	}
	values := url.Values{"client_assertion": {clientAssertion},
		"client_assertion_type": {"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"},
		"client_id":             {c.ISS}, "grant_type": {"authorization_code"},
		"code": {code}}
	resp, err := http.PostForm(c.Endpoint.TokenURL, values)
	if err != nil {
		return nil, errors.Annotate(err, "Couldn't connect to the token endpoint")
	}
	defer resp.Body.Close()
	decoder := json.NewDecoder(resp.Body)
	token := &oauth2.Token{}
	err = decoder.Decode(token)
	if err != nil {
		return nil, errors.Annotate(err, "Couldn't decode the token")
	}
	return token, nil
}
722987
func (h *protocolHandler) handleGetOAuthToken(req *rpcs.GetOAuthTokenRequest) (*rpcs.GetOAuthTokenResponse, error) {
	// Validate the request.
	if err := req.Validate(); err != nil {
		return nil, &protocolError{
			Status:  400,
			Message: fmt.Sprintf("Bad request: %s.", err.Error()),
		}
	}
	if subtle.ConstantTimeCompare(h.secret, req.Secret) != 1 {
		return nil, &protocolError{
			Status:  403,
			Message: "Invalid secret.",
		}
	}
	generator := h.tokens[req.AccountID]
	if generator == nil {
		return nil, &protocolError{
			Status:  404,
			Message: fmt.Sprintf("Unrecognized account ID %q.", req.AccountID),
		}
	}

	// Dedup and sort scopes.
	scopes := stringset.New(len(req.Scopes))
	for _, s := range req.Scopes {
		scopes.Add(s)
	}
	sortedScopes := scopes.ToSlice()
	sort.Strings(sortedScopes)

	// Ask the token provider for the token. This may produce ErrorWithCode.
	tok, err := generator.GenerateToken(h.ctx, sortedScopes, minTokenLifetime)
	if err != nil {
		return nil, err
	}
	return &rpcs.GetOAuthTokenResponse{
		AccessToken: tok.AccessToken,
		Expiry:      tok.Expiry.Unix(),
	}, nil
}
75445
func (h *AuthorizationHandler) handleDeleteAuthorization(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	req, err := decodeDeleteAuthorizationRequest(ctx, r)
	if err != nil {
		h.Logger.Info("failed to decode request", zap.String("handler", "deleteAuthorization"), zap.Error(err))
		EncodeError(ctx, err, w)
		return
	}

	if err := h.AuthorizationService.DeleteAuthorization(ctx, req.ID); err != nil {
		// Don't log here, it should already be handled by the service
		EncodeError(ctx, err, w)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}
451168
func (ctx *Context) QueryAuthCode(authCode string) (*AuthBaseInfo, error) {
	cat, err := ctx.GetComponentAccessToken()
	if err != nil {
		return nil, err
	}

	req := map[string]string{
		"component_appid":    ctx.AppID,
		"authorization_code": authCode,
	}
	uri := fmt.Sprintf(queryAuthURL, cat)
	body, err := util.PostJSON(uri, req)
	if err != nil {
		return nil, err
	}

	var ret struct {
		Info *AuthBaseInfo `json:"authorization_info"`
	}

	if err := json.Unmarshal(body, &ret); err != nil {
		return nil, err
	}

	return ret.Info, nil
}
277967
func (c *UserConfig) GetAccessToken(token string, verifier string, service *Service, client *http.Client) error {
	// This code used to error out if RequestTokenKey were empty, but
	// in the interest of being able to operate in a stateless manner this
	// has been removed.  If you want to make sure that the request token
	// is validated against what is being returned, populate the UserConfig
	// with a request token stored server-side somewhere, accessed by the
	// user's session.
	if c.RequestTokenKey != "" && c.RequestTokenKey != token {
		return fmt.Errorf("Returned token did not match request token")
	}
	c.Verifier = verifier
	data := url.Values{}
	if service.ClientConfig.CallbackURL != "" {
		data.Set("oauth_verifier", verifier)
	}
	body := strings.NewReader(data.Encode())
	request, err := http.NewRequest("POST", service.AccessURL, body)
	if err != nil {
		return err
	}
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	response, err := c.send(request, service, client)
	if err != nil {
		return err
	}
	err = c.parseAccessToken(response)
	return err
}
1006793
func (oauth *Oauth) GetUserAccessToken(code string) (result ResAccessToken, err error) {
	urlStr := fmt.Sprintf(accessTokenURL, oauth.AppID, oauth.AppSecret, code)
	var response []byte
	response, err = util.HTTPGet(urlStr)
	if err != nil {
		return
	}
	err = json.Unmarshal(response, &result)
	if err != nil {
		return
	}
	if result.ErrCode != 0 {
		err = fmt.Errorf("GetUserAccessToken error : errcode=%v , errmsg=%v", result.ErrCode, result.ErrMsg)
		return
	}
	return
}
992781
func (m *MockAuthorizeCodeStrategy) GenerateAuthorizeCode(arg0 context.Context, arg1 fosite.Requester) (string, string, error) {
	ret := m.ctrl.Call(m, "GenerateAuthorizeCode", arg0, arg1)
	ret0, _ := ret[0].(string)
	ret1, _ := ret[1].(string)
	ret2, _ := ret[2].(error)
	return ret0, ret1, ret2
}
1110323
func (r *rest) AppAuthorize(c *gin.Context) {
	resp := r.server.NewResponse()
	defer resp.Close()
	if ar := r.server.HandleAuthorizeRequest(resp, c.Request); ar != nil {
		userId, ok := handleLoginPage(r, ar, c)
		if !ok {
			return
		}
		ar.UserData = userId
		ar.Authorized = true
		r.server.FinishAuthorizeRequest(resp, c.Request, ar)
	}
	if resp.IsError && resp.InternalError != nil {
		log.Printf("ERROR: %s\n", resp.InternalError)
	}
	if !resp.IsError {
		//resp.Output["custom_parameter"] = 42
	}
	osin.OutputJSON(resp, c.Writer, c.Request)
}
558627
func AccessCodeFlow(authorizationURL, tokenURL string) {
	if current, ok := dslengine.CurrentDefinition().(*design.SecuritySchemeDefinition); ok {
		if current.Kind == design.OAuth2SecurityKind {
			current.Flow = "accessCode"
			current.AuthorizationURL = authorizationURL
			current.TokenURL = tokenURL
			return
		}
	}
	dslengine.IncompatibleDSL()
}
246748
func (u UAA) Exchange(authCode string) (Token, error) {
	return u.ExchangeCommand(u, authCode)
}
1124408
func (c *UsersController) SendEmailVerificationCode(ctx *app.SendEmailVerificationCodeUsersContext) error {
	identity, err := c.app.UserService().LoadContextIdentityAndUser(ctx)
	if err != nil {
		log.Error(ctx, map[string]interface{}{"err": err}, "unable to load identity or user")
		return jsonapi.JSONErrorResponse(ctx, err)
	}

	_, err = c.EmailVerificationService.SendVerificationCode(ctx, ctx.RequestData, *identity)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"err":         err,
			"identity_id": identity.ID.String(),
			"username":    identity.Username,
			"email":       identity.User.Email,
		}, "failed to send verification email for update on email")
		return jsonapi.JSONErrorResponse(ctx, err)
	}
	return ctx.NoContent()
}
15024
func handleAccountOrigin(h goa.Handler) goa.Handler {

	return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
		origin := req.Header.Get("Origin")
		if origin == "" {
			// Not a CORS request
			return h(ctx, rw, req)
		}
		if cors.MatchOrigin(origin, "http://swagger.goa.design") {
			ctx = goa.WithLogContext(ctx, "origin", origin)
			rw.Header().Set("Access-Control-Allow-Origin", origin)
			rw.Header().Set("Vary", "Origin")
			rw.Header().Set("Access-Control-Max-Age", "600")
			rw.Header().Set("Access-Control-Allow-Credentials", "true")
			if acrm := req.Header.Get("Access-Control-Request-Method"); acrm != "" {
				// We are handling a preflight request
				rw.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE")
			}
			return h(ctx, rw, req)
		}

		return h(ctx, rw, req)
	}
}
1132479
func (p *ecrTokenGetter) GetAuthorizationToken(input *ecr.GetAuthorizationTokenInput) (*ecr.GetAuthorizationTokenOutput, error) {
	return p.svc.GetAuthorizationToken(input)
}
99613
func (r *ExchangeAuthorizationError) Error() string {
	return fmt.Sprintf("%v %v: %v %v",
		r.HttpResponse.Request.Method, r.HttpResponse.Request.URL,
		r.ErrorCode, r.ErrorDescription)
}
1208727
func (r *InspectOAuthTokenGrantRPC) InspectOAuthTokenGrant(c context.Context, req *admin.InspectOAuthTokenGrantRequest) (*admin.InspectOAuthTokenGrantResponse, error) {
	inspection, err := InspectGrant(c, r.Signer, req.Token)
	if err != nil {
		return nil, status.Errorf(codes.Internal, err.Error())
	}

	resp := &admin.InspectOAuthTokenGrantResponse{
		Valid:            inspection.Signed && inspection.NonExpired,
		Signed:           inspection.Signed,
		NonExpired:       inspection.NonExpired,
		InvalidityReason: inspection.InvalidityReason,
	}

	addInvalidityReason := func(msg string, args ...interface{}) {
		reason := fmt.Sprintf(msg, args...)
		resp.Valid = false
		if resp.InvalidityReason == "" {
			resp.InvalidityReason = reason
		} else {
			resp.InvalidityReason += "; " + reason
		}
	}

	if env, _ := inspection.Envelope.(*tokenserver.OAuthTokenGrantEnvelope); env != nil {
		resp.SigningKeyId = env.KeyId
	}

	// Examine the body, even if the token is expired or unsigned. This helps to
	// debug expired or unsigned tokens...
	resp.TokenBody, _ = inspection.Body.(*tokenserver.OAuthTokenGrantBody)
	if resp.TokenBody != nil {
		rules, err := r.Rules(c)
		if err != nil {
			return nil, status.Errorf(codes.Internal, "failed to load service accounts rules")
		}

		// Always return the rule that matches the service account, even if the
		// token itself is not allowed by it (we check it separately below).
		rule, err := rules.Rule(c, resp.TokenBody.ServiceAccount, "")
		switch {
		case status.Code(err) == codes.PermissionDenied:
			s, _ := status.FromError(err)
			addInvalidityReason("%s", s.Message())
			return resp, nil
		case err != nil: // usually codes.Internal
			return nil, err
		default:
			resp.MatchingRule = rule.Rule
		}

		q := &RulesQuery{
			ServiceAccount: resp.TokenBody.ServiceAccount,
			Rule:           rule,
			Proxy:          identity.Identity(resp.TokenBody.Proxy),
			EndUser:        identity.Identity(resp.TokenBody.EndUser),
		}
		switch _, err = rules.Check(c, q); {
		case err == nil:
			resp.AllowedByRules = true
		case status.Code(err) == codes.Internal:
			return nil, err // a transient error when checking rules
		default: // fatal gRPC error => the rules forbid the token
			addInvalidityReason("not allowed by the rules (rev %s)", rules.ConfigRevision())
		}
	}

	return resp, nil
}