// NewAuth returns a pointer to an initialized Auth
321893
func NewAuth(r *Robot) *Auth {
	a := &Auth{robot: r}

	c := &authConfig{}
	env.MustProcess(c)

	if c.Enabled {
		if c.Admins != "" {
			a.admins = strings.Split(c.Admins, ",")
		}

		r.Handle(
			addUserRoleHandler,
			removeUserRoleHandler,
			listUserRolesHandler,
			listAdminsHandler,
		)
	}

	return a
}
5718
func NewAuthorizer(access services.Access, identity services.UserGetter, trust services.Trust) (Authorizer, error) {
	if access == nil {
		return nil, trace.BadParameter("missing parameter access")
	}
	if identity == nil {
		return nil, trace.BadParameter("missing parameter identity")
	}
	if trust == nil {
		return nil, trace.BadParameter("missing parameter trust")
	}
	return &authorizer{access: access, identity: identity, trust: trust}, nil
}
764016
func NewOauth(context *context.Context) *Oauth {
	auth := new(Oauth)
	auth.Context = context
	return auth
}
1189917
func NewAuthMux(p Provider, a Authenticator, t Tokenizer, basepath string, l chronograf.Logger, UseIDToken bool) *AuthMux {
	return &AuthMux{
		Provider:   p,
		Auth:       a,
		Tokens:     t,
		SuccessURL: path.Join(basepath, "/"),
		FailureURL: path.Join(basepath, "/login"),
		Now:        DefaultNowTime,
		Logger:     l,
		UseIDToken: UseIDToken,
	}
}
1317570
func NewUserAuthorizer(username string, identity services.UserGetter, access services.Access) (Authorizer, error) {
	authContext, err := contextForLocalUser(username, identity, access)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return &contextAuthorizer{authContext: *authContext}, nil
}
419703
func (ra *RegistrationAuthorityImpl) NewAuthorization(ctx context.Context, request core.Authorization, regID int64) (core.Authorization, error) {
	identifier := request.Identifier
	identifier.Value = strings.ToLower(identifier.Value)

	// Check that the identifier is present and appropriate
	if err := ra.PA.WillingToIssue(identifier); err != nil {
		return core.Authorization{}, err
	}

	if err := ra.checkPendingAuthorizationLimit(ctx, regID); err != nil {
		return core.Authorization{}, err
	}

	if err := ra.checkInvalidAuthorizationLimit(ctx, regID, identifier.Value); err != nil {
		return core.Authorization{}, err
	}

	if ra.reuseValidAuthz {
		auths, err := ra.SA.GetValidAuthorizations(ctx, regID, []string{identifier.Value}, ra.clk.Now())
		if err != nil {
			outErr := berrors.InternalServerError(
				"unable to get existing validations for regID: %d, identifier: %s, %s",
				regID,
				identifier.Value,
				err,
			)
			ra.log.Warning(outErr.Error())
			return core.Authorization{}, outErr
		}

		if existingAuthz, ok := auths[identifier.Value]; ok {
			// Use the valid existing authorization's ID to find a fully populated version
			// The results from `GetValidAuthorizations` are most notably missing
			// `Challenge` values that the client expects in the result.
			populatedAuthz, err := ra.SA.GetAuthorization(ctx, existingAuthz.ID)
			if err != nil {
				outErr := berrors.InternalServerError(
					"unable to get existing authorization for auth ID: %s",
					existingAuthz.ID,
				)
				ra.log.Warningf("%s: %s", outErr.Error(), existingAuthz.ID)
				return core.Authorization{}, outErr
			}
			if ra.authzValidChallengeEnabled(&populatedAuthz) {
				// The existing authorization must not expire within the next 24 hours for
				// it to be OK for reuse
				reuseCutOff := ra.clk.Now().Add(time.Hour * 24)
				if populatedAuthz.Expires.After(reuseCutOff) {
					ra.stats.Inc("ReusedValidAuthz", 1)
					return populatedAuthz, nil
				}
			}
		}
	}

	nowishNano := ra.clk.Now().Add(time.Hour).UnixNano()
	identifierTypeString := string(identifier.Type)
	pendingAuth, err := ra.SA.GetPendingAuthorization(ctx, &sapb.GetPendingAuthorizationRequest{
		RegistrationID:  &regID,
		IdentifierType:  &identifierTypeString,
		IdentifierValue: &identifier.Value,
		ValidUntil:      &nowishNano,
	})
	if err != nil && !berrors.Is(err, berrors.NotFound) {
		return core.Authorization{}, berrors.InternalServerError(
			"unable to get pending authorization for regID: %d, identifier: %s: %s",
			regID,
			identifier.Value,
			err)
	} else if err == nil {
		return *pendingAuth, nil
	}

	v2 := features.Enabled(features.NewAuthorizationSchema)
	authzPB, err := ra.createPendingAuthz(ctx, regID, identifier, v2)
	if err != nil {
		return core.Authorization{}, err
	}

	if v2 {
		authzIDs, err := ra.SA.NewAuthorizations2(ctx, &sapb.AddPendingAuthorizationsRequest{
			Authz: []*corepb.Authorization{authzPB},
		})
		if err != nil {
			return core.Authorization{}, err
		}
		if len(authzIDs.Ids) != 1 {
			return core.Authorization{}, berrors.InternalServerError("unexpected number of authorization IDs returned from NewAuthorizations2: expected 1, got %d", len(authzIDs.Ids))
		}
		// The current internal authorization objects use a string for the ID, the new
		// storage format uses a integer ID. In order to maintain compatibility we
		// convert the integer ID to a string.
		id := fmt.Sprintf("%d", authzIDs.Ids[0])
		authzPB.Id = &id
		return bgrpc.PBToAuthz(authzPB)
	}

	authz, err := bgrpc.PBToAuthz(authzPB)
	if err != nil {
		return core.Authorization{}, err
	}
	result, err := ra.SA.NewPendingAuthorization(ctx, authz)
	if err != nil {
		// berrors.InternalServerError since the user-data was validated before being
		// passed to the SA.
		err = berrors.InternalServerError("failed to store new pending authorization: %s", err)
		return core.Authorization{}, err
	}
	return result, nil
}
454716
func newAuthenticator(ctx context.Context, credentials, actAs string, scopes []string) *auth.Authenticator {
	// TODO(vadimsh): Don't hardcode auth options here, pass them from outside
	// somehow.
	authOpts := chromeinfra.DefaultAuthOptions()
	authOpts.ServiceAccountJSONPath = credentials
	authOpts.Scopes = scopes
	authOpts.ActAsServiceAccount = actAs
	return auth.NewAuthenticator(ctx, auth.SilentLogin, authOpts)
}
119332
func NewAuthenticatedSession(user, password string) (*Client, error) {
	client, err := NewClient()
	if err != nil {
		return nil, err
	}

	if err := client.Authenticate(user, password); err != nil {
		return nil, err
	}

	return client, nil
}
1324495
func (c completedOAuthConfig) New(delegationTarget genericapiserver.DelegationTarget) (*OAuthServer, error) {
	genericServer, err := c.GenericConfig.New("openshift-oauth", delegationTarget)
	if err != nil {
		return nil, err
	}

	s := &OAuthServer{
		GenericAPIServer: genericServer,
	}

	return s, nil
}
213040
func Auth(method auth.Builder) Option {
	return func(c *CredHub) error {
		c.authBuilder = method
		return nil
	}
}
1163954
func newBypassAuthorizer(auth kauthorizer.Authorizer, paths ...string) kauthorizer.Authorizer {
	return bypassAuthorizer{paths: sets.NewString(paths...), authorizer: auth}
}
1056204
func NewAuthToken(signer Signer, tokenType string, expireIn int,
	submoduleName, version string, rh AuthTokenRefreshHandler) *AuthToken {
	clientName := fmt.Sprintf("go %s %s %s",
		submoduleName, libkb.GetPlatformString(), runtime.GOARCH)
	authToken := &AuthToken{
		signer:         signer,
		tokenType:      tokenType,
		expireIn:       expireIn,
		clientName:     clientName,
		clientVersion:  version,
		refreshHandler: rh,
	}
	return authToken
}
974747
func NewAuthServer(cfg *InitConfig, opts ...AuthServerOption) (*AuthServer, error) {
	if cfg.Trust == nil {
		cfg.Trust = local.NewCAService(cfg.Backend)
	}
	if cfg.Presence == nil {
		cfg.Presence = local.NewPresenceService(cfg.Backend)
	}
	if cfg.Provisioner == nil {
		cfg.Provisioner = local.NewProvisioningService(cfg.Backend)
	}
	if cfg.Identity == nil {
		cfg.Identity = local.NewIdentityService(cfg.Backend)
	}
	if cfg.Access == nil {
		cfg.Access = local.NewAccessService(cfg.Backend)
	}
	if cfg.ClusterConfiguration == nil {
		cfg.ClusterConfiguration = local.NewClusterConfigurationService(cfg.Backend)
	}
	if cfg.Events == nil {
		cfg.Events = local.NewEventsService(cfg.Backend)
	}
	if cfg.AuditLog == nil {
		cfg.AuditLog = events.NewDiscardAuditLog()
	}

	limiter, err := limiter.NewConnectionsLimiter(limiter.LimiterConfig{
		MaxConnections: defaults.LimiterMaxConcurrentSignatures,
	})
	if err != nil {
		return nil, trace.Wrap(err)
	}

	closeCtx, cancelFunc := context.WithCancel(context.TODO())
	as := AuthServer{
		bk:              cfg.Backend,
		limiter:         limiter,
		Authority:       cfg.Authority,
		AuthServiceName: cfg.AuthServiceName,
		oidcClients:     make(map[string]*oidcClient),
		samlProviders:   make(map[string]*samlProvider),
		githubClients:   make(map[string]*githubClient),
		cancelFunc:      cancelFunc,
		closeCtx:        closeCtx,
		AuthServices: AuthServices{
			Trust:                cfg.Trust,
			Presence:             cfg.Presence,
			Provisioner:          cfg.Provisioner,
			Identity:             cfg.Identity,
			Access:               cfg.Access,
			ClusterConfiguration: cfg.ClusterConfiguration,
			IAuditLog:            cfg.AuditLog,
			Events:               cfg.Events,
		},
	}
	for _, o := range opts {
		o(&as)
	}
	if as.clock == nil {
		as.clock = clockwork.NewRealClock()
	}

	return &as, nil
}
119882
func NewOAuthConfig(activeDirectoryEndpoint, tenantID string) (*OAuthConfig, error) {
	apiVer := "1.0"
	return NewOAuthConfigWithAPIVersion(activeDirectoryEndpoint, tenantID, &apiVer)
}
580104
func NewAuth(in interface{}, context *compiler.Context) (*Auth, error) {
	errors := make([]error, 0)
	x := &Auth{}
	m, ok := compiler.UnpackMap(in)
	if !ok {
		message := fmt.Sprintf("has unexpected value: %+v (%T)", in, in)
		errors = append(errors, compiler.NewError(context, message))
	} else {
		allowedKeys := []string{"oauth2"}
		var allowedPatterns []*regexp.Regexp
		invalidKeys := compiler.InvalidKeysInMap(m, allowedKeys, allowedPatterns)
		if len(invalidKeys) > 0 {
			message := fmt.Sprintf("has invalid %s: %+v", compiler.PluralProperties(len(invalidKeys)), strings.Join(invalidKeys, ", "))
			errors = append(errors, compiler.NewError(context, message))
		}
		// Oauth2 oauth2 = 1;
		v1 := compiler.MapValueForKey(m, "oauth2")
		if v1 != nil {
			var err error
			x.Oauth2, err = NewOauth2(v1, compiler.NewContext("oauth2", context))
			if err != nil {
				errors = append(errors, err)
			}
		}
	}
	return x, compiler.NewErrorGroupOrNil(errors)
}
1316947
func NewAuthKey(KEY [32]uint8) *AuthKey {
	m := AuthKey{}
	m.KEY = KEY
	return &m
}
95289
func newAuth(c *Connection) (Authenticator, error) {
	AuthVersion := c.AuthVersion
	if AuthVersion == 0 {
		if strings.Contains(c.AuthUrl, "v3") {
			AuthVersion = 3
		} else if strings.Contains(c.AuthUrl, "v2") {
			AuthVersion = 2
		} else if strings.Contains(c.AuthUrl, "v1") {
			AuthVersion = 1
		} else {
			return nil, newErrorf(500, "Can't find AuthVersion in AuthUrl - set explicitly")
		}
	}
	switch AuthVersion {
	case 1:
		return &v1Auth{}, nil
	case 2:
		return &v2Auth{
			// Guess as to whether using API key or
			// password it will try both eventually so
			// this is just an optimization.
			useApiKey: len(c.ApiKey) >= 32,
		}, nil
	case 3:
		return &v3Auth{}, nil
	}
	return nil, newErrorf(500, "Auth Version %d not supported", AuthVersion)
}