// GenerateUnsignedUserAccessTokenForAPIClient generates an unsigned OAuth2 user access token for the api_client based on the Keycloak token
499855
func (m *tokenManager) GenerateUnsignedUserAccessTokenForAPIClient(ctx context.Context, providerAccessToken string) (*jwt.Token, error) {
	kcClaims, err := m.ParseToken(ctx, providerAccessToken)
	if err != nil {
		return nil, errors.WithStack(err)
	}

	return m.GenerateUnsignedUserAccessTokenFromClaimsForAPIClient(ctx, kcClaims)
}
1319918
func (web *webAPIHandlers) PresignedGet(r *http.Request, args *PresignedGetArgs, reply *PresignedGetRep) error {
	claims, owner, authErr := webRequestAuthenticate(r)
	if authErr != nil {
		return toJSONError(authErr)
	}
	var creds auth.Credentials
	if !owner {
		var ok bool
		creds, ok = globalIAMSys.GetUser(claims.Subject)
		if !ok {
			return toJSONError(errInvalidAccessKeyID)
		}
	} else {
		creds = globalServerConfig.GetCredential()
	}

	region := globalServerConfig.GetRegion()
	if args.BucketName == "" || args.ObjectName == "" {
		return &json2.Error{
			Message: "Bucket and Object are mandatory arguments.",
		}
	}

	// Check if bucket is a reserved bucket name or invalid.
	if isReservedOrInvalidBucket(args.BucketName, false) {
		return toJSONError(errInvalidBucketName)
	}

	reply.UIVersion = browser.UIVersion
	reply.URL = presignedGet(args.HostName, args.BucketName, args.ObjectName, args.Expiry, creds, region)
	return nil
}
1158494
func (client *Client) verifyAccessToken() error {
	if len(client.AccessToken) > 0 {
		return nil
	} else {
		return fmt.Errorf("missing access token")
	}
}
1272123
func newAuthenticatorFromClientCAFile(clientCAFile string) (authenticator.Request, error) {
	opts := x509request.DefaultVerifyOptions()

	// If at custom CA bundle is provided, load it (otherwise just use system roots)
	if len(clientCAFile) > 0 {
		if caData, err := ioutil.ReadFile(clientCAFile); err != nil {
			return nil, err
		} else if len(caData) > 0 {
			roots := x509.NewCertPool()
			if !roots.AppendCertsFromPEM(caData) {
				return nil, fmt.Errorf("no valid certs found in %s", clientCAFile)
			}
			opts.Roots = roots
		}
	}

	return x509request.New(opts, x509request.CommonNameUserConversion), nil
}
374229
func (m *tokenManager) GenerateUnsignedUserAccessTokenFromRefreshToken(ctx context.Context, refreshTokenString string, identity *repository.Identity) (*jwt.Token, error) {
	token := jwt.New(jwt.SigningMethodRS256)
	token.Header["kid"] = m.userAccountPrivateKey.KeyID

	req := goa.ContextRequest(ctx)
	if req == nil {
		return nil, errors.New("missing request in context")
	}

	authOpenshiftIO := rest.AbsoluteURL(req, "", m.config)
	openshiftIO, err := rest.ReplaceDomainPrefixInAbsoluteURL(req, "", "", m.config)
	if err != nil {
		return nil, errors.WithStack(err)
	}

	refreshTokenClaims, err := m.ParseToken(ctx, refreshTokenString)
	if err != nil {
		return nil, errors.WithStack(err)
	}

	claims := token.Claims.(jwt.MapClaims)
	claims["jti"] = uuid.NewV4().String()
	iat := time.Now().Unix()
	claims["exp"] = iat + m.config.GetAccessTokenExpiresIn()
	claims["nbf"] = 0
	claims["iat"] = iat
	claims["iss"] = authOpenshiftIO
	claims["aud"] = openshiftIO
	claims["typ"] = "Bearer"
	claims["auth_time"] = iat // TODO should use the time when user actually logged-in the last time. Will need to get this time from the RHD token
	claims["allowed-origins"] = []string{
		authOpenshiftIO,
		openshiftIO,
	}
	claims["approved"] = identity != nil && !identity.User.Banned
	if identity != nil {
		claims["sub"] = identity.ID.String()
		claims["email_verified"] = identity.User.EmailVerified
		claims["name"] = identity.User.FullName
		claims["preferred_username"] = identity.Username
		firstName, lastName := account.SplitFullName(identity.User.FullName)
		claims["given_name"] = firstName
		claims["family_name"] = lastName
		claims["email"] = identity.User.Email
		claims["company"] = identity.User.Company
	} else {
		claims["sub"] = refreshTokenClaims.Subject

		// refresh token should have all following claims included only for api_client(e.g. vscode analytics) who don't have identity in auth db
		claims["email_verified"] = refreshTokenClaims.EmailVerified
		claims["name"] = refreshTokenClaims.Name
		claims["preferred_username"] = refreshTokenClaims.Username
		claims["given_name"] = refreshTokenClaims.GivenName
		claims["family_name"] = refreshTokenClaims.FamilyName
		claims["email"] = refreshTokenClaims.Email
		claims["company"] = refreshTokenClaims.Company
	}

	claims["azp"] = refreshTokenClaims.Audience
	claims["session_state"] = refreshTokenClaims.SessionState
	claims["acr"] = "0"

	realmAccess := make(map[string]interface{})
	realmAccess["roles"] = []string{"uma_authorization"}
	claims["realm_access"] = realmAccess

	resourceAccess := make(map[string]interface{})
	broker := make(map[string]interface{})
	broker["roles"] = []string{"read-token"}
	resourceAccess["broker"] = broker

	account := make(map[string]interface{})
	account["roles"] = []string{"manage-account", "manage-account-links", "view-profile"}
	resourceAccess["account"] = account

	claims["resource_access"] = resourceAccess

	return token, nil
}
1217608
func (m *tokenManager) GenerateUserTokenUsingRefreshToken(ctx context.Context, refreshTokenString string,
	identity *repository.Identity, permissions []Permissions) (*oauth2.Token, error) {

	nowTime := time.Now().Unix()
	unsignedAccessToken, err := m.GenerateUnsignedUserAccessTokenFromRefreshToken(ctx, refreshTokenString, identity)
	if err != nil {
		return nil, errors.WithStack(err)
	}

	if permissions != nil && len(permissions) > 0 {
		claims := unsignedAccessToken.Claims.(jwt.MapClaims)
		claims["permissions"] = permissions
	}

	accessToken, err := unsignedAccessToken.SignedString(m.userAccountPrivateKey.Key)
	if err != nil {
		return nil, errors.WithStack(err)
	}
	unsignedRefreshToken, err := m.GenerateUnsignedUserRefreshToken(ctx, refreshTokenString, identity)
	if err != nil {
		return nil, errors.WithStack(err)
	}
	refreshToken, err := unsignedRefreshToken.SignedString(m.userAccountPrivateKey.Key)
	if err != nil {
		return nil, errors.WithStack(err)
	}

	var nbf int64

	token := &oauth2.Token{
		AccessToken:  accessToken,
		RefreshToken: refreshToken,
		Expiry:       time.Unix(nowTime+m.config.GetAccessTokenExpiresIn(), 0),
		TokenType:    "Bearer",
	}

	// Derivative OAuth2 claims "expires_in" and "refresh_expires_in"
	extra := make(map[string]interface{})
	extra["expires_in"] = m.config.GetAccessTokenExpiresIn()
	extra["refresh_expires_in"] = m.config.GetRefreshTokenExpiresIn()
	extra["not_before_policy"] = nbf

	token = token.WithExtra(extra)

	return token, nil
}
767001
func (c *FlickrClient) ApiSign() {
	c.Args.Set("api_key", c.ApiKey)
	// the "api_sig" param must not be included in the signing process
	c.Args.Del("api_sig")
	c.Args.Set("api_sig", c.getApiSignature(c.ApiSecret))
}
1044023
func (self *OpenIdProvider) GetAuthenticatedUser(w http.ResponseWriter, r *http.Request) (User, Token, error) {

	// Parse the url parameters
	params := r.URL.Query()

	// Check to see if the user successfully authenticated
	if params.Get("openid.mode") == "cancel" {
		return nil, nil, ErrAuthDeclined
	}

	// Get the user details from the URL parameters
	lastName := params.Get("openid.ext1.value.lastname")
	firstName := params.Get("openid.ext1.value.firstname")
	fullName := fmt.Sprintf("%s %s", firstName, lastName)
	email := params.Get("openid.ext1.value.email")

	// Return the User data
	// TODO for now we are re-using the Google User
	user := user{id: email, email: email, name: fullName, provider: self.endpoint }
	return &user, nil, nil
}
1203861
func (g *Generator) generateUserTypes(outdir string, api *design.APIDefinition) error {
	var modelname, filename string
	err := GormaDesign.IterateStores(func(store *RelationalStoreDefinition) error {
		err := store.IterateModels(func(model *RelationalModelDefinition) error {
			modelname = strings.ToLower(codegen.Goify(model.ModelName, false))

			filename = fmt.Sprintf("%s.go", modelname)
			utFile := filepath.Join(outdir, filename)
			err := os.RemoveAll(utFile)
			if err != nil {
				fmt.Println(err)
			}
			utWr, err := NewUserTypesWriter(utFile)
			if err != nil {
				panic(err) // bug
			}
			title := fmt.Sprintf("%s: Models", api.Context())
			imports := []*codegen.ImportSpec{
				codegen.SimpleImport(g.appPkgPath),
				codegen.SimpleImport("context"),
				codegen.SimpleImport("time"),
				codegen.SimpleImport("github.com/goadesign/goa"),
				codegen.SimpleImport("github.com/jinzhu/gorm"),
				codegen.SimpleImport("github.com/gofrs/uuid"),
			}

			if model.Cached {
				imp := codegen.NewImport("cache", "github.com/patrickmn/go-cache")
				imports = append(imports, imp)
				imp = codegen.SimpleImport("strconv")
				imports = append(imports, imp)
			}
			utWr.WriteHeader(title, g.target, imports)
			data := &UserTypeTemplateData{
				APIDefinition: api,
				UserType:      model,
				DefaultPkg:    g.target,
				AppPkg:        g.appPkgPath,
			}
			err = utWr.Execute(data)
			g.genfiles = append(g.genfiles, utFile)
			if err != nil {
				fmt.Println(err)
				return err
			}
			err = utWr.FormatCode()
			if err != nil {
				fmt.Println(err)
			}
			return err
		})
		return err
	})
	return err
}
1343441
func NewUserAuthTokenProvider(ctx context.Context, clientID, clientSecret string, scopes []string) (TokenProvider, error) {
	return &userAuthTokenProvider{
		config: &oauth2.Config{
			ClientID:     clientID,
			ClientSecret: clientSecret,
			Endpoint: oauth2.Endpoint{
				AuthURL:  "https://accounts.google.com/o/oauth2/auth",
				TokenURL: "https://accounts.google.com/o/oauth2/token",
			},
			RedirectURL: "urn:ietf:wg:oauth:2.0:oob",
			Scopes:      scopes,
		},
		cacheKey: CacheKey{
			Key:    fmt.Sprintf("user/%s", clientID),
			Scopes: scopes,
		},
	}, nil
}
244020
func (m *tokenManager) GenerateUnsignedUserAccessTokenFromClaimsForAPIClient(ctx context.Context, tokenClaims *TokenClaims) (*jwt.Token, error) {
	token := jwt.New(jwt.SigningMethodRS256)
	token.Header["kid"] = m.userAccountPrivateKey.KeyID

	req := goa.ContextRequest(ctx)
	if req == nil {
		return nil, errors.New("missing request in context")
	}

	authOpenshiftIO := rest.AbsoluteURL(req, "", m.config)
	openshiftIO, err := rest.ReplaceDomainPrefixInAbsoluteURL(req, "", "", m.config)
	if err != nil {
		return nil, errors.WithStack(err)
	}

	claims := token.Claims.(jwt.MapClaims)
	claims["jti"] = uuid.NewV4().String()

	iat := time.Now().Unix()
	claims["exp"] = iat + m.config.GetAccessTokenExpiresIn()
	claims["nbf"] = 0
	claims["iat"] = iat
	claims["iss"] = authOpenshiftIO
	claims["aud"] = openshiftIO
	claims["typ"] = "Bearer"
	claims["auth_time"] = iat
	claims["typ"] = "Bearer"
	claims["approved"] = tokenClaims.Approved

	claims["sub"] = tokenClaims.Subject
	claims["email_verified"] = tokenClaims.EmailVerified
	claims["name"] = tokenClaims.Name
	claims["preferred_username"] = tokenClaims.Username
	claims["given_name"] = tokenClaims.GivenName
	claims["family_name"] = tokenClaims.FamilyName
	claims["email"] = tokenClaims.Email

	claims["allowed-origins"] = []string{
		authOpenshiftIO,
		openshiftIO,
	}

	claims["azp"] = tokenClaims.Audience
	claims["session_state"] = tokenClaims.SessionState
	claims["acr"] = "0"

	realmAccess := make(map[string]interface{})
	realmAccess["roles"] = []string{"uma_authorization"}
	claims["realm_access"] = realmAccess

	resourceAccess := make(map[string]interface{})
	broker := make(map[string]interface{})
	broker["roles"] = []string{"read-token"}
	resourceAccess["broker"] = broker

	account := make(map[string]interface{})
	account["roles"] = []string{"manage-account", "manage-account-links", "view-profile"}
	resourceAccess["account"] = account

	claims["resource_access"] = resourceAccess

	return token, nil
}
1239215
func (p pAdapter) authorizationIDFromToken(ctx context.Context, token string) (platform.ID, error) {
	authorizer, err := icontext.GetAuthorizer(ctx)
	if err != nil {
		return 0, err
	}

	if token == "" {
		// No explicit token. Use the authorization ID from the context's authorizer.
		k := authorizer.Kind()
		if k != platform.AuthorizationKind {
			return 0, fmt.Errorf("unable to create task using authorization of kind %s", k)
		}

		return authorizer.Identifier(), nil
	}

	// Token was explicitly provided. Look it up.
	a, err := p.as.FindAuthorizationByToken(ctx, token)
	if err != nil {
		// TODO(mr): log the actual error.
		return 0, errTokenUnreadable
	}

	// It's a valid token. Is it our token?
	if a.GetUserID() != authorizer.GetUserID() {
		// The auth token isn't ours. Ensure we're allowed to read it.
		p, err := platform.NewPermissionAtID(a.ID, platform.ReadAction, platform.AuthorizationsResourceType, a.OrgID)
		if err != nil {
			// TODO(mr): log the actual error.
			return 0, errTokenUnreadable
		}
		if !authorizer.Allowed(*p) {
			return 0, errTokenUnreadable
		}
	}

	return a.ID, nil
}
873049
func (r User_Customer_OpenIdConnect) AddApiAuthenticationKey() (resp string, err error) {
	err = r.Session.DoRequest("SoftLayer_User_Customer_OpenIdConnect", "addApiAuthenticationKey", nil, &r.Options, &resp)
	return
}
827338
func newAuthenticatorFromOIDCIssuerURL(opts oidc.Options) (authenticator.Token, error) {
	const noUsernamePrefix = "-"

	if opts.UsernamePrefix == "" && opts.UsernameClaim != "email" {
		// Old behavior. If a usernamePrefix isn't provided, prefix all claims other than "email"
		// with the issuerURL.
		//
		// See https://github.com/kubernetes/kubernetes/issues/31380
		opts.UsernamePrefix = opts.IssuerURL + "#"
	}

	if opts.UsernamePrefix == noUsernamePrefix {
		// Special value indicating usernames shouldn't be prefixed.
		opts.UsernamePrefix = ""
	}

	tokenAuthenticator, err := oidc.New(opts)
	if err != nil {
		return nil, err
	}

	return tokenAuthenticator, nil
}
177828
func NewAPIClientFromFlags(opts *cliflags.CommonOptions, configFile *configfile.ConfigFile) (client.APIClient, error) {
	store := &ContextStoreWithDefault{
		Store: store.New(cliconfig.ContextStoreDir(), defaultContextStoreConfig()),
		Resolver: func() (*DefaultContext, error) {
			return resolveDefaultContext(opts, configFile, ioutil.Discard)
		},
	}
	contextName, err := resolveContextName(opts, configFile, store)
	if err != nil {
		return nil, err
	}
	endpoint, err := resolveDockerEndpoint(store, contextName)
	if err != nil {
		return nil, errors.Wrap(err, "unable to resolve docker endpoint")
	}
	return newAPIClientFromEndpoint(endpoint, configFile)
}
561991
func UserFromKey(c *deis.Client, fingerprint string) (api.UserApps, error) {
	res, reqErr := c.Request("GET", fmt.Sprintf("/v2/hooks/key/%s", fingerprint), nil)
	if reqErr != nil && !deis.IsErrAPIMismatch(reqErr) {
		return api.UserApps{}, reqErr
	}

	defer res.Body.Close()

	resUser := api.UserApps{}
	if err := json.NewDecoder(res.Body).Decode(&resUser); err != nil {
		return api.UserApps{}, err
	}

	return resUser, reqErr
}
213380
func (t *tokenAccessor) CreateSynPacketToken(context *pucontext.PUContext, auth *connection.AuthInfo) (token []byte, err error) {

	token, serviceContext, err := context.GetCachedTokenAndServiceContext()
	if err == nil && bytes.Equal(auth.LocalServiceContext, serviceContext) {
		// Randomize the nonce and send it
		err = t.getToken().Randomize(token, auth.LocalContext)
		if err == nil {
			return token, nil
		}
		// If there is an error, let's try to create a new one
	}

	claims := &tokens.ConnectionClaims{
		T:  context.Identity(),
		EK: auth.LocalServiceContext,
	}

	if token, err = t.getToken().CreateAndSign(false, claims, auth.LocalContext, claimsheader.NewClaimsHeader()); err != nil {
		return []byte{}, nil
	}

	context.UpdateCachedTokenAndServiceContext(token, auth.LocalServiceContext)

	return token, nil
}