// NewPendingAuthorization retrieves a pending authorization for
// authz.Identifier if one exists, or creates a new one otherwise.
426902
func (ssa *SQLStorageAuthority) NewPendingAuthorization(ctx context.Context, authz core.Authorization) (core.Authorization, error) {
	var output core.Authorization

	tx, err := ssa.dbMap.Begin()
	if err != nil {
		return output, err
	}
	txWithCtx := tx.WithContext(ctx)

	// Create a random ID and check that it doesn't exist already
	authz.ID = core.NewToken()
	for existingPending(txWithCtx, authz.ID) ||
		existingFinal(txWithCtx, authz.ID) {
		authz.ID = core.NewToken()
	}

	// Insert a stub row in pending
	pendingAuthz := pendingauthzModel{Authorization: authz}
	err = txWithCtx.Insert(&pendingAuthz)
	if err != nil {
		err = Rollback(tx, err)
		return output, err
	}

	for i, c := range authz.Challenges {
		challModel, err := challengeToModel(&c, pendingAuthz.ID)
		if err != nil {
			err = Rollback(tx, err)
			return output, err
		}
		// Magic happens here: Gorp will modify challModel, setting challModel.ID
		// to the auto-increment primary key. This is important because we want
		// the challenge objects inside the Authorization we return to know their
		// IDs, so they can have proper URLs.
		// See https://godoc.org/github.com/coopernurse/gorp#DbMap.Insert
		err = txWithCtx.Insert(challModel)
		if err != nil {
			err = Rollback(tx, err)
			return output, err
		}
		challenge, err := modelToChallenge(challModel)
		if err != nil {
			err = Rollback(tx, err)
			return output, err
		}
		authz.Challenges[i] = challenge
	}

	err = tx.Commit()
	output = pendingAuthz.Authorization
	output.Challenges = authz.Challenges
	return output, err
}
631197
func NewBasicAuthorizer(userName, password string) *BasicAuthorizer {
	return &BasicAuthorizer{
		userName: userName,
		password: password,
	}
}
654722
func (s *AuthorizationService) CreateAuthorization(ctx context.Context, authorization *platform.Authorization) error {
	return s.CreateAuthorizationFn(ctx, authorization)
}
1163954
func newBypassAuthorizer(auth kauthorizer.Authorizer, paths ...string) kauthorizer.Authorizer {
	return bypassAuthorizer{paths: sets.NewString(paths...), authorizer: auth}
}
954243
func NewAuthorizationHandler(b *AuthorizationBackend) *AuthorizationHandler {
	h := &AuthorizationHandler{
		Router: NewRouter(),
		Logger: b.Logger,

		AuthorizationService: b.AuthorizationService,
		OrganizationService:  b.OrganizationService,
		UserService:          b.UserService,
		LookupService:        b.LookupService,
	}

	h.HandlerFunc("POST", "/api/v2/authorizations", h.handlePostAuthorization)
	h.HandlerFunc("GET", "/api/v2/authorizations", h.handleGetAuthorizations)
	h.HandlerFunc("GET", "/api/v2/authorizations/:id", h.handleGetAuthorization)
	h.HandlerFunc("PATCH", "/api/v2/authorizations/:id", h.handleUpdateAuthorization)
	h.HandlerFunc("DELETE", "/api/v2/authorizations/:id", h.handleDeleteAuthorization)
	return h
}
4537
func (api UsersAPI) UpdateAuthorization(w http.ResponseWriter, r *http.Request) {
	username := mux.Vars(r)["username"]
	grantedTo := mux.Vars(r)["grantedTo"]

	authorization := &user.Authorization{}

	if err := json.NewDecoder(r.Body).Decode(authorization); err != nil {
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}
	userMgr := user.NewManager(r)
	userobj, err := userMgr.GetByName(username)
	if handleServerError(w, "getting user by name", err) {
		return
	}
	verifiedEmails := []user.EmailAddress{}
	if len(authorization.OwnerOf.EmailAddresses) != 0 || len(authorization.ValidatedEmailAddresses) > 0 {
		verifiedEmails, err = api.getValidatedEmails(r, *userobj)
		if handleServerError(w, "getting verified emails", err) {
			return
		}
	}

	verifiedPhones := []user.Phonenumber{}
	if len(authorization.ValidatedPhonenumbers) > 0 {
		verifiedPhones, err = api.getValidatedPhones(r, *userobj)
		if handleServerError(w, "getting verified phone numbers", err) {
			return
		}
	}

	authorization.Username = username
	authorization.GrantedTo = grantedTo
	authorization.Addresses = FilterAuthorizationMaps(authorization.Addresses)
	authorization.EmailAddresses = FilterAuthorizationMaps(authorization.EmailAddresses)
	authorization.ValidatedEmailAddresses = FilterValidatedEmails(FilterAuthorizationMaps(authorization.ValidatedEmailAddresses), verifiedEmails)
	authorization.Phonenumbers = FilterAuthorizationMaps(authorization.Phonenumbers)
	authorization.ValidatedPhonenumbers = FilterValidatedPhones(FilterAuthorizationMaps(authorization.ValidatedPhonenumbers), verifiedPhones)
	authorization.BankAccounts = FilterAuthorizationMaps(authorization.BankAccounts)
	authorization.PublicKeys = FilterAuthorizationMaps(authorization.PublicKeys)
	authorization.DigitalWallet = FilterDigitalWallet(authorization.DigitalWallet)
	authorization.OwnerOf = FilterOwnerOf(authorization.OwnerOf, verifiedEmails)
	authorization.Avatars = FilterAuthorizationMaps(authorization.Avatars)

	existingAuth, err := userMgr.GetAuthorization(username, grantedTo)
	if handleServerError(w, "getting existing authorization", err) {
		return
	}
	if existingAuth != nil {
		// Merge authorizations
		authorization.Merge(existingAuth)
	}

	err = userMgr.UpdateAuthorization(authorization)
	if handleServerError(w, "updating authorization", err) {
		return
	}
	w.Header().Set("Content-type", "application/json")
	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(authorization)
}
320585
func (s *GetRouteOutput) SetAuthorizationType(v string) *GetRouteOutput {
	s.AuthorizationType = &v
	return s
}
884071
func (ssa *SQLStorageAuthority) GetPendingAuthorization2(ctx context.Context, req *sapb.GetPendingAuthorizationRequest) (*corepb.Authorization, error) {
	var am authz2Model
	err := ssa.dbMap.WithContext(ctx).SelectOne(
		&am,
		fmt.Sprintf(`SELECT %s FROM authz2 WHERE
			registrationID = :regID AND
			identifierValue = :ident AND
			status = :status AND
			expires > :validUntil
			ORDER BY expires ASC
			LIMIT 1 `, authz2Fields),
		map[string]interface{}{
			"regID":      *req.RegistrationID,
			"ident":      *req.IdentifierValue,
			"status":     statusUint(core.StatusPending),
			"validUntil": time.Unix(0, *req.ValidUntil),
		},
	)
	if err != nil {
		if err == sql.ErrNoRows {
			// there may be an old style pending authorization so look for that
			authz, err := ssa.GetPendingAuthorization(ctx, req)
			if err != nil {
				return nil, err
			}
			return bgrpc.AuthzToPB(*authz)
		}
		return nil, err
	}
	return modelToAuthzPB(&am)
}
576156
func (m *Manager) UpdateAuthorization(authorization *Authorization) (err error) {
	_, err = m.getAuthorizationCollection().Upsert(bson.M{"username": authorization.Username, "grantedto": authorization.GrantedTo}, authorization)
	return
}
12790
func (s *SecurityGroupService) NewAuthorizeSecurityGroupEgressParams() *AuthorizeSecurityGroupEgressParams {
	p := &AuthorizeSecurityGroupEgressParams{}
	p.p = make(map[string]interface{})
	return p
}
802114
func (s *UpdateRouteInput) SetAuthorizerId(v string) *UpdateRouteInput {
	s.AuthorizerId = &v
	return s
}
378629
func NewAuthorizer(alwaysAllowPaths []string) (authorizer.Authorizer, error) {
	var prefixes []string
	paths := sets.NewString()
	for _, p := range alwaysAllowPaths {
		p = strings.TrimPrefix(p, "/")
		if len(p) == 0 {
			// matches "/"
			paths.Insert(p)
			continue
		}
		if strings.ContainsRune(p[:len(p)-1], '*') {
			return nil, fmt.Errorf("only trailing * allowed in %q", p)
		}
		if strings.HasSuffix(p, "*") {
			prefixes = append(prefixes, p[:len(p)-1])
		} else {
			paths.Insert(p)
		}
	}

	return authorizer.AuthorizerFunc(func(a authorizer.Attributes) (authorizer.Decision, string, error) {
		if a.IsResourceRequest() {
			return authorizer.DecisionNoOpinion, "", nil
		}

		pth := strings.TrimPrefix(a.GetPath(), "/")
		if paths.Has(pth) {
			return authorizer.DecisionAllow, "", nil
		}

		for _, prefix := range prefixes {
			if strings.HasPrefix(pth, prefix) {
				return authorizer.DecisionAllow, "", nil
			}
		}

		return authorizer.DecisionNoOpinion, "", nil
	}), nil
}
1268641
func NewAuthorizer(client *http.Client, f func(string) (string, string, error)) Authorizer {
	if client == nil {
		client = http.DefaultClient
	}
	return &dockerAuthorizer{
		credentials: f,
		client:      client,
		auth:        map[string]string{},
	}
}
981396
func (s *UpdateRouteInput) SetAuthorizationType(v string) *UpdateRouteInput {
	s.AuthorizationType = &v
	return s
}
438758
func (s *Service) UpdateAuthorization(ctx context.Context, id platform.ID, upd *platform.AuthorizationUpdate) (*platform.Authorization, error) {
	op := OpPrefix + platform.OpUpdateAuthorization
	a, err := s.FindAuthorizationByID(ctx, id)
	if err != nil {
		return nil, &platform.Error{
			Err: err,
			Op:  op,
		}
	}

	if upd.Status != nil {
		status := *upd.Status
		switch status {
		case platform.Active, platform.Inactive:
		default:
			return nil, &platform.Error{
				Code: platform.EInvalid,
				Msg:  "unknown authorization status",
				Op:   op,
			}
		}
		a.Status = status
	}

	if upd.Description != nil {
		a.Description = *upd.Description
	}

	return a, s.PutAuthorization(ctx, a)
}
163885
func New(config *Config, authorizer Authorizer) (*NodeAuthorizer, error) {
	utils.Logger.Info("starting the node authorization service",
		zap.String("listen", config.Listen),
		zap.String("version", Version))

	if authorizer == nil {
		return nil, errors.New("no authorizer")
	}

	if err := config.IsValid(); err != nil {
		return nil, fmt.Errorf("configuration error: %s", err)
	}

	return &NodeAuthorizer{
		authorizer: authorizer,
		config:     config,
	}, nil
}
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
}