// Callback returns a redirect URL after callback from an external oauth2 resource provider such as GitHub during user's account linking
15986
func (s *linkServiceImpl) Callback(ctx context.Context, req *goa.RequestData, state string, code string) (string, error) {
	// validate known state
	knownReferrer, _, err := s.Services().AuthenticationProviderService().LoadReferrerAndResponseMode(ctx, state)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"state": state,
			"err":   err,
		}, "can't load referrer by state")
		return "", err
	}

	referrerURL, err := url.Parse(knownReferrer)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"code":           code,
			"state":          state,
			"known_referrer": knownReferrer,
			"err":            err,
		}, "failed to parse referrer")
		return "", err
	}

	identityID := referrerURL.Query().Get(identityIDParam)
	identityUUID, err := uuid.FromString(identityID)
	if err != nil {
		return "", err
	}

	forResource := referrerURL.Query().Get(forParam)

	oauthProvider, err := s.Factories().LinkingProviderFactory().NewLinkingProvider(ctx, identityUUID, rest.AbsoluteURL(req, "", nil), forResource)
	if err != nil {
		return "", err
	}

	providerToken, err := oauthProvider.Exchange(ctx, code)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"state": state,
			"code":  code,
			"err":   err,
		}, "exchange operation failed")
		return "", err
	}
	if providerToken.AccessToken == "" {
		log.Error(ctx, map[string]interface{}{
			"state":       state,
			"code":        code,
			"provider_id": oauthProvider.ID(),
		}, "access token return by provider is empty")
		return "", errors.New("access token return by provider is empty")
	}

	userProfile, err := oauthProvider.Profile(ctx, *providerToken)
	if err != nil {
		return "", err
	}
	err = s.ExecuteInTransaction(func() error {
		tokens, err := s.Repositories().ExternalTokens().LoadByProviderIDAndIdentityID(ctx, oauthProvider.ID(), identityUUID)
		if err != nil {
			return err
		}
		if len(tokens) > 0 {
			// It was re-linking. Overwrite the existing link.
			externalToken := tokens[0]
			externalToken.Token = providerToken.AccessToken
			externalToken.Username = userProfile.Username
			err = s.Repositories().ExternalTokens().Save(ctx, &externalToken)
			if err == nil {
				log.Info(ctx, map[string]interface{}{
					"provider_id":       oauthProvider.ID(),
					"identity_id":       identityID,
					"external_token_id": externalToken.ID,
				}, "An existing token found. Account re-linked & new token saved.")
			}
			return err
		}
		externalToken := token.ExternalToken{
			Token:      providerToken.AccessToken,
			IdentityID: identityUUID,
			Scope:      oauthProvider.Scopes(),
			ProviderID: oauthProvider.ID(),
			Username:   userProfile.Username,
		}
		err = s.Repositories().ExternalTokens().Create(ctx, &externalToken)
		if err == nil {
			log.Info(ctx, map[string]interface{}{
				"provider_id":       oauthProvider.ID(),
				"identity_id":       identityID,
				"external_token_id": externalToken.ID,
			}, "No old token found. Account linked & new token saved.")
		}
		return err
	})
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"state":       state,
			"code":        code,
			"provider_id": oauthProvider.ID(),
			"identity_id": identityID,
		}, "failed to save token")
		return "", err
	}

	nextResource := referrerURL.Query().Get(nextParam)
	if nextResource != "" {
		return s.ProviderLocation(ctx, req, identityID, nextResource, knownReferrer)
	}

	return knownReferrer, nil
}
630533
func afterCreateCallback(scope *Scope) {
	if !scope.HasError() {
		scope.CallMethod("AfterCreate")
	}
	if !scope.HasError() {
		scope.CallMethod("AfterSave")
	}
}
756934
func (s *service) Redirect(ctx context.Context, hostname string) (string, error) {
	resource, err := s.resourceRepo.FindByHostname(ctx, hostname)
	if err != nil {
		return "", err
	}
	return resource.RedirectURL, nil
}
605160
func (a *App) GetExternalURL() string {
	if a == nil || a.ExternalURL == nil {
		return ""
	}
	return *a.ExternalURL
}
183737
func (r *Response) GetRedirectUrl() (string, error) {
	if r.Type != REDIRECT {
		return "", errors.New("Not a redirect response")
	}

	u, err := url.Parse(r.URL)
	if err != nil {
		return "", err
	}

	var q url.Values
	if r.RedirectInFragment {
		// start with empty set for fragment
		q = url.Values{}
	} else {
		// add parameters to existing query
		q = u.Query()
	}

	// add parameters
	for n, v := range r.Output {
		q.Set(n, fmt.Sprint(v))
	}

	// https://tools.ietf.org/html/rfc6749#section-4.2.2
	// Fragment should be encoded as application/x-www-form-urlencoded (%-escaped, spaces are represented as '+')
	// The stdlib URL#String() doesn't make that easy to accomplish, so build this ourselves
	if r.RedirectInFragment {
		u.Fragment = ""
		redirectURI := u.String() + "#" + q.Encode()
		return redirectURI, nil
	}

	// Otherwise, update the query and encode normally
	u.RawQuery = q.Encode()
	u.Fragment = ""
	return u.String(), nil
}
281169
func closeCallback(conn C.virConnectPtr, reason ConnectCloseReason, goCallbackId int) {
	callbackFunc := getCallbackId(goCallbackId)
	callback, ok := callbackFunc.(CloseCallback)
	if !ok {
		panic("Inappropriate callback type called")
	}
	callback(&Connect{ptr: conn}, reason)
}
161636
func (dc *DispatcherClient) CallTimeout(funcName string, request interface{}, timeout time.Duration) (response interface{}, err error) {
	req := dc.getRequest(funcName, request)
	resp, err := dc.c.CallTimeout(req, timeout)
	return getResponse(resp, err)
}
505952
func webTokenCallback(jwtToken *jwtgo.Token) (interface{}, error) {
	if _, ok := jwtToken.Method.(*jwtgo.SigningMethodHMAC); !ok {
		return nil, fmt.Errorf("Unexpected signing method: %v", jwtToken.Header["alg"])
	}

	if err := jwtToken.Claims.Valid(); err != nil {
		return nil, errAuthentication
	}

	if claims, ok := jwtToken.Claims.(*jwtgo.StandardClaims); ok {
		if claims.Subject == globalServerConfig.GetCredential().AccessKey {
			return []byte(globalServerConfig.GetCredential().SecretKey), nil
		}
		if globalIAMSys == nil {
			return nil, errInvalidAccessKeyID
		}
		cred, ok := globalIAMSys.GetUser(claims.Subject)
		if !ok {
			return nil, errInvalidAccessKeyID
		}
		return []byte(cred.SecretKey), nil
	}

	return nil, errAuthentication
}
1101946
func (oauth *Oauth) GetWebAppRedirectURL(redirectURI, scope, state string) (string, error) {
	urlStr := url.QueryEscape(redirectURI)
	return fmt.Sprintf(webAppRedirectOauthURL, oauth.AppID, urlStr, scope, state), nil
}
874876
func (m *callback) HandleCallback(s connector.Scopes, r *http.Request) (connector.Identity, error) {
	remoteUser := r.Header.Get("X-Remote-User")
	if remoteUser == "" {
		return connector.Identity{}, fmt.Errorf("required HTTP header X-Remote-User is not set")
	}
	// TODO: add support for X-Remote-Group, see
	// https://kubernetes.io/docs/admin/authentication/#authenticating-proxy
	return connector.Identity{
		UserID:        remoteUser, // TODO: figure out if this is a bad ID value.
		Email:         remoteUser,
		EmailVerified: true,
	}, nil
}
679340
func (m *AuthMethod) callbackHandler(ctx *router.Context) {
	c, rw, r := ctx.Context, ctx.Writer, ctx.Request

	// This code path is hit when user clicks "Deny" on consent page.
	q := r.URL.Query()
	errorMsg := q.Get("error")
	if errorMsg != "" {
		replyError(c, rw, errors.New("login error"), "OpenID login error: %s", errorMsg)
		return
	}

	// Validate inputs.
	code := q.Get("code")
	if code == "" {
		replyError(c, rw, errors.New("login error"), "Missing 'code' parameter")
		return
	}
	stateTok := q.Get("state")
	if stateTok == "" {
		replyError(c, rw, errors.New("login error"), "Missing 'state' parameter")
		return
	}
	state, err := validateStateToken(c, stateTok)
	if err != nil {
		replyError(c, rw, err, "Failed to validate 'state' token")
		return
	}

	// Revalidate "dest_url". It was already validate in loginHandler when
	// generating state token, but just in case.
	dest, err := normalizeURL(state["dest_url"])
	if err != nil {
		replyError(c, rw, err, "Bad redirect URI (%q) - %s", dest, err)
		return
	}

	// Callback URI is hardcoded in OAuth2 client config and must always point
	// to default version on GAE. Yet we want to support logging to non-default
	// versions that have different hostnames. Do some redirect dance here to pass
	// control to required version if necessary (so that it can set cookie on
	// non-default version domain). Same handler with same params, just with
	// different hostname. For most common case of signing in into default version
	// this code path is not triggered.
	if state["host_url"] != r.Host {
		// There's no Scheme in r.URL. Append one, otherwise url.String() returns
		// relative (broken) URL. And replace the hostname with desired one.
		url := *r.URL
		if m.Insecure {
			url.Scheme = "http"
		} else {
			url.Scheme = "https"
		}
		url.Host = state["host_url"]
		logging.Warningf(c, "Redirecting to callback URI on another host %q", url.Host)
		http.Redirect(rw, r, url.String(), http.StatusFound)
		return
	}

	// Use authorization code to grab user profile.
	cfg, err := fetchCachedSettings(c)
	if err != nil {
		replyError(c, rw, err, "Can't load OpenID settings - %s", err)
		return
	}
	uid, user, err := handleAuthorizationCode(c, cfg, code)
	if err != nil {
		replyError(c, rw, err, "Error when fetching user profile - %s", err)
		return
	}

	// Grab previous session from the cookie to close it once new one is created.
	prevSid, err := decodeSessionCookie(c, r)
	if err != nil {
		replyError(c, rw, err, "Error when decoding session cookie - %s", err)
		return
	}

	// Create session in the session store.
	expTime := clock.Now(c).Add(sessionCookieToken.Expiration)
	sid, err := m.SessionStore.OpenSession(c, uid, user, expTime)
	if err != nil {
		replyError(c, rw, err, "Error when creating the session - %s", err)
		return
	}
	(logging.Fields{"sid": sid}).Infof(c, "Opened a new session")

	// Kill previous session now that new one is successfully created.
	if prevSid != "" {
		(logging.Fields{"sid": prevSid}).Infof(c, "Closing the previous session")
		if err = m.SessionStore.CloseSession(c, prevSid); err != nil {
			replyError(c, rw, err, "Error when closing the session - %s", err)
			return
		}
	}

	// Set the cookies.
	cookie, err := makeSessionCookie(c, sid, !m.Insecure)
	if err != nil {
		replyError(c, rw, err, "Can't make session cookie - %s", err)
		return
	}
	http.SetCookie(rw, cookie)
	m.removeIncompatibleCookies(rw, r)

	// Redirect to the final destination page.
	logging.Infof(c, "Redirecting to %s", dest)
	http.Redirect(rw, r, dest, http.StatusFound)
}
863999
func errorCallback(a *C.utp_callback_arguments) C.uint64 {
	err := errorForCode(a.error_code())
	if logCallbacks {
		log.Printf("error callback: socket %p: %s", a.socket, err)
	}
	libContextToSocket[a.context].conns[a.socket].onError(err)
	return 0
}
68325
func (c *Context) Redirect(url string, code int) error {
	if code < http.StatusMultipleChoices || code > http.StatusTemporaryRedirect {
		return errors.New("invalid redirect code")
	}
	http.Redirect(c.response, c.request, url, code)
	return nil
}
304399
func (im imp) CallbackURLParameters(acctRef blob.Ref) url.Values {
	return url.Values{}
}
1211286
func (s *State) Callbacks() []Callback {
	s.mu.RLock()
	defer s.mu.RUnlock()

	return append([]Callback{}, s.callbacks...)
}
312478
func (o *Oauth2TokenParams) WithRedirectURI(redirectURI *string) *Oauth2TokenParams {
	o.SetRedirectURI(redirectURI)
	return o
}
1052533
func (user *User) OauthRedirectURL() string {
	providerID := user.ctx.OAuthProvider().internalID()
	if providerID == user.ctx.ServiceName {
		return fmt.Sprintf("%s/auth/%s", Config.BaseURL, user.ctx.ServiceName)
	}

	return fmt.Sprintf("%s/auth/%s/%s", Config.BaseURL, user.ctx.ServiceName, providerID)
}