// RegisterAuth registers a new authentication scheme.
770241
func RegisterAuth(name string, ctor AuthConfigParser) {
	if _, dup := authConstructor[name]; dup {
		panic("Dup registration of auth mode " + name)
	}
	authConstructor[name] = ctor
}
298595
func (r *Reference) Auth(token string) *Reference {
	r.token = token

	return r
}
544843
func (process *TeleportProcess) registerWithAuthServer(role teleport.Role, eventName string) {
	serviceName := strings.ToLower(role.String())
	process.RegisterCriticalFunc(fmt.Sprintf("register.%v", serviceName), func() error {
		connector, err := process.reconnectToAuthService(role)
		if err != nil {
			return trace.Wrap(err)
		}
		process.onExit(fmt.Sprintf("auth.client.%v", serviceName), func(interface{}) {
			process.Debugf("Closed client for %v.", role)
			err := connector.Client.Close()
			if err != nil {
				process.Debugf("Failed to close client: %v", err)
			}
		})
		process.BroadcastEvent(Event{Name: eventName, Payload: connector})
		return nil
	})
}
522257
func RegisterRoutes(e *gin.Engine, config map[string][]gin.HandlerFunc, dal DataAccessLayer, serverConfig Config) {

	switch serverConfig.Auth.Method {
	case auth.AuthTypeNone:
		// do nothing
	case auth.AuthTypeOIDC:
		// Set up sessions so we can keep track of the logged in user
		store := sessions.NewCookieStore([]byte(serverConfig.Auth.SessionSecret))
		e.Use(sessions.Sessions("mysession", store))
		// The OIDCAuthenticationHandler is set up before the IndexHandler in the handler function
		// chain. It will check to see if the user is logged in based on their session. If they are not
		// the user will be redirected to the authentication endpoint at the OP.
		oauthConfig := oauth2.Config{ClientID: serverConfig.Auth.ClientID,
			ClientSecret: serverConfig.Auth.ClientSecret,
			Endpoint: oauth2.Endpoint{AuthURL: serverConfig.Auth.AuthorizationURL,
				TokenURL: serverConfig.Auth.TokenURL},
		}
		oidcHandler := auth.OIDCAuthenticationHandler(oauthConfig)
		oauthHandler := auth.OAuthIntrospectionHandler(serverConfig.Auth.ClientID,
			serverConfig.Auth.ClientSecret, serverConfig.Auth.IntrospectionURL)
		e.Use(func(c *gin.Context) {
			if c.Request.Header.Get("Authorization") != "" {
				oauthHandler(c)
			} else {
				oidcHandler(c)
			}
		})
		// This handler is to take the redirect from the OP when the user logs in. It will
		// then fetch information about the user by hitting the user info endpoint and put
		// that in the session. Lastly, this handler is set up to redirect the user back
		// to the root.
		e.GET("/redirect", auth.RedirectHandler(oauthConfig, serverConfig.ServerURL,
			serverConfig.Auth.UserInfoURL))
		e.GET("/logout", heart.LogoutHandler)

	case auth.AuthTypeHEART:
		heart.SetUpRoutes(serverConfig.Auth.JWKPath, serverConfig.Auth.ClientID, serverConfig.Auth.OPURL,
			serverConfig.ServerURL, serverConfig.Auth.SessionSecret, e)

	}

	// Batch Support
	batch := NewBatchController(dal)
	batchHandlers := make([]gin.HandlerFunc, len(config["Batch"]))
	copy(batchHandlers, config["Batch"])
	batchHandlers = append(batchHandlers, batch.Post)
	e.POST("/", batchHandlers...)

	// Resources

	RegisterController("Account", e, config["Account"], dal, serverConfig)
	RegisterController("AllergyIntolerance", e, config["AllergyIntolerance"], dal, serverConfig)
	RegisterController("Appointment", e, config["Appointment"], dal, serverConfig)
	RegisterController("AppointmentResponse", e, config["AppointmentResponse"], dal, serverConfig)
	RegisterController("AuditEvent", e, config["AuditEvent"], dal, serverConfig)
	RegisterController("Basic", e, config["Basic"], dal, serverConfig)
	RegisterController("Binary", e, config["Binary"], dal, serverConfig)
	RegisterController("BodySite", e, config["BodySite"], dal, serverConfig)
	RegisterController("Bundle", e, config["Bundle"], dal, serverConfig)
	RegisterController("CarePlan", e, config["CarePlan"], dal, serverConfig)
	RegisterController("Claim", e, config["Claim"], dal, serverConfig)
	RegisterController("ClaimResponse", e, config["ClaimResponse"], dal, serverConfig)
	RegisterController("ClinicalImpression", e, config["ClinicalImpression"], dal, serverConfig)
	RegisterController("Communication", e, config["Communication"], dal, serverConfig)
	RegisterController("CommunicationRequest", e, config["CommunicationRequest"], dal, serverConfig)
	RegisterController("Composition", e, config["Composition"], dal, serverConfig)
	RegisterController("ConceptMap", e, config["ConceptMap"], dal, serverConfig)
	RegisterController("Condition", e, config["Condition"], dal, serverConfig)
	RegisterController("Conformance", e, config["Conformance"], dal, serverConfig)
	RegisterController("Contract", e, config["Contract"], dal, serverConfig)
	RegisterController("Coverage", e, config["Coverage"], dal, serverConfig)
	RegisterController("DataElement", e, config["DataElement"], dal, serverConfig)
	RegisterController("DetectedIssue", e, config["DetectedIssue"], dal, serverConfig)
	RegisterController("Device", e, config["Device"], dal, serverConfig)
	RegisterController("DeviceComponent", e, config["DeviceComponent"], dal, serverConfig)
	RegisterController("DeviceMetric", e, config["DeviceMetric"], dal, serverConfig)
	RegisterController("DeviceUseRequest", e, config["DeviceUseRequest"], dal, serverConfig)
	RegisterController("DeviceUseStatement", e, config["DeviceUseStatement"], dal, serverConfig)
	RegisterController("DiagnosticOrder", e, config["DiagnosticOrder"], dal, serverConfig)
	RegisterController("DiagnosticReport", e, config["DiagnosticReport"], dal, serverConfig)
	RegisterController("DocumentManifest", e, config["DocumentManifest"], dal, serverConfig)
	RegisterController("DocumentReference", e, config["DocumentReference"], dal, serverConfig)
	RegisterController("EligibilityRequest", e, config["EligibilityRequest"], dal, serverConfig)
	RegisterController("EligibilityResponse", e, config["EligibilityResponse"], dal, serverConfig)
	RegisterController("Encounter", e, config["Encounter"], dal, serverConfig)
	RegisterController("EnrollmentRequest", e, config["EnrollmentRequest"], dal, serverConfig)
	RegisterController("EnrollmentResponse", e, config["EnrollmentResponse"], dal, serverConfig)
	RegisterController("EpisodeOfCare", e, config["EpisodeOfCare"], dal, serverConfig)
	RegisterController("ExplanationOfBenefit", e, config["ExplanationOfBenefit"], dal, serverConfig)
	RegisterController("FamilyMemberHistory", e, config["FamilyMemberHistory"], dal, serverConfig)
	RegisterController("Flag", e, config["Flag"], dal, serverConfig)
	RegisterController("Goal", e, config["Goal"], dal, serverConfig)
	RegisterController("Group", e, config["Group"], dal, serverConfig)
	RegisterController("HealthcareService", e, config["HealthcareService"], dal, serverConfig)
	RegisterController("ImagingObjectSelection", e, config["ImagingObjectSelection"], dal, serverConfig)
	RegisterController("ImagingStudy", e, config["ImagingStudy"], dal, serverConfig)
	RegisterController("Immunization", e, config["Immunization"], dal, serverConfig)
	RegisterController("ImmunizationRecommendation", e, config["ImmunizationRecommendation"], dal, serverConfig)
	RegisterController("ImplementationGuide", e, config["ImplementationGuide"], dal, serverConfig)
	RegisterController("List", e, config["List"], dal, serverConfig)
	RegisterController("Location", e, config["Location"], dal, serverConfig)
	RegisterController("Media", e, config["Media"], dal, serverConfig)
	RegisterController("Medication", e, config["Medication"], dal, serverConfig)
	RegisterController("MedicationAdministration", e, config["MedicationAdministration"], dal, serverConfig)
	RegisterController("MedicationDispense", e, config["MedicationDispense"], dal, serverConfig)
	RegisterController("MedicationOrder", e, config["MedicationOrder"], dal, serverConfig)
	RegisterController("MedicationStatement", e, config["MedicationStatement"], dal, serverConfig)
	RegisterController("MessageHeader", e, config["MessageHeader"], dal, serverConfig)
	RegisterController("NamingSystem", e, config["NamingSystem"], dal, serverConfig)
	RegisterController("NutritionOrder", e, config["NutritionOrder"], dal, serverConfig)
	RegisterController("Observation", e, config["Observation"], dal, serverConfig)
	RegisterController("OperationDefinition", e, config["OperationDefinition"], dal, serverConfig)
	RegisterController("OperationOutcome", e, config["OperationOutcome"], dal, serverConfig)
	RegisterController("Order", e, config["Order"], dal, serverConfig)
	RegisterController("OrderResponse", e, config["OrderResponse"], dal, serverConfig)
	RegisterController("Organization", e, config["Organization"], dal, serverConfig)
	RegisterController("Patient", e, config["Patient"], dal, serverConfig)
	RegisterController("PaymentNotice", e, config["PaymentNotice"], dal, serverConfig)
	RegisterController("PaymentReconciliation", e, config["PaymentReconciliation"], dal, serverConfig)
	RegisterController("Person", e, config["Person"], dal, serverConfig)
	RegisterController("Practitioner", e, config["Practitioner"], dal, serverConfig)
	RegisterController("Procedure", e, config["Procedure"], dal, serverConfig)
	RegisterController("ProcedureRequest", e, config["ProcedureRequest"], dal, serverConfig)
	RegisterController("ProcessRequest", e, config["ProcessRequest"], dal, serverConfig)
	RegisterController("ProcessResponse", e, config["ProcessResponse"], dal, serverConfig)
	RegisterController("Provenance", e, config["Provenance"], dal, serverConfig)
	RegisterController("Questionnaire", e, config["Questionnaire"], dal, serverConfig)
	RegisterController("QuestionnaireResponse", e, config["QuestionnaireResponse"], dal, serverConfig)
	RegisterController("ReferralRequest", e, config["ReferralRequest"], dal, serverConfig)
	RegisterController("RelatedPerson", e, config["RelatedPerson"], dal, serverConfig)
	RegisterController("RiskAssessment", e, config["RiskAssessment"], dal, serverConfig)
	RegisterController("Schedule", e, config["Schedule"], dal, serverConfig)
	RegisterController("SearchParameter", e, config["SearchParameter"], dal, serverConfig)
	RegisterController("Slot", e, config["Slot"], dal, serverConfig)
	RegisterController("Specimen", e, config["Specimen"], dal, serverConfig)
	RegisterController("StructureDefinition", e, config["StructureDefinition"], dal, serverConfig)
	RegisterController("Subscription", e, config["Subscription"], dal, serverConfig)
	RegisterController("Substance", e, config["Substance"], dal, serverConfig)
	RegisterController("SupplyDelivery", e, config["SupplyDelivery"], dal, serverConfig)
	RegisterController("SupplyRequest", e, config["SupplyRequest"], dal, serverConfig)
	RegisterController("TestScript", e, config["TestScript"], dal, serverConfig)
	RegisterController("ValueSet", e, config["ValueSet"], dal, serverConfig)
	RegisterController("VisionPrescription", e, config["VisionPrescription"], dal, serverConfig)

}
499020
func (s *Server) registerAccount(acc *Account) {
	if acc.sl == nil {
		acc.sl = NewSublist()
	}
	if acc.maxnae == 0 {
		acc.maxnae = DEFAULT_MAX_ACCOUNT_AE_RESPONSE_MAPS
	}
	if acc.maxaettl == 0 {
		acc.maxaettl = DEFAULT_TTL_AE_RESPONSE_MAP
	}
	if acc.clients == nil {
		acc.clients = make(map[*client]*client)
	}
	// If we are capable of routing we will track subscription
	// information for efficient interest propagation.
	// During config reload, it is possible that account was
	// already created (global account), so use locking and
	// make sure we create only if needed.
	acc.mu.Lock()
	// TODO(dlc)- Double check that we need this for GWs.
	if acc.rm == nil && s.opts != nil && s.shouldTrackSubscriptions() {
		acc.rm = make(map[string]int32)
	}
	acc.srv = s
	acc.mu.Unlock()
	s.accounts.Store(acc.Name, acc)
	s.enableAccountTracking(acc)
}
675997
func registerThroughAuth(token string, params RegisterParams) (*Identity, error) {
	log.Debugf("Attempting to register through auth server.")

	var client *Client
	var err error

	// Build a client to the Auth Server. If a CA pin is specified require the
	// Auth Server is validated. Otherwise attempt to use the CA file on disk
	// but if it's not available connect without validating the Auth Server CA.
	switch {
	case params.CAPin != "":
		client, err = pinRegisterClient(params)
	default:
		client, err = insecureRegisterClient(params)
	}
	if err != nil {
		return nil, trace.Wrap(err)
	}
	defer client.Close()

	// Get the SSH and X509 certificates for a node.
	keys, err := client.RegisterUsingToken(RegisterUsingTokenRequest{
		Token:                token,
		HostID:               params.ID.HostUUID,
		NodeName:             params.ID.NodeName,
		Role:                 params.ID.Role,
		AdditionalPrincipals: params.AdditionalPrincipals,
		DNSNames:             params.DNSNames,
		PublicTLSKey:         params.PublicTLSKey,
		PublicSSHKey:         params.PublicSSHKey,
	})
	if err != nil {
		return nil, trace.Wrap(err)
	}
	keys.Key = params.PrivateKey

	return ReadIdentityFromKeyPair(keys)
}
1345247
func (l *RateLimiter) RegisterRequest(token string) error {
	l.Lock()
	defer l.Unlock()

	bucketSetI, exists := l.rateLimits.Get(token)
	var bucketSet *ratelimit.TokenBucketSet

	if exists {
		bucketSet = bucketSetI.(*ratelimit.TokenBucketSet)
		bucketSet.Update(l.rates)
	} else {
		bucketSet = ratelimit.NewTokenBucketSet(l.rates, l.clock)
		// We set ttl as 10 times rate period. E.g. if rate is 100 requests/second per client ip
		// the counters for this ip will expire after 10 seconds of inactivity
		err := l.rateLimits.Set(token, bucketSet, int(bucketSet.GetMaxPeriod()/time.Second)*10+1)
		if err != nil {
			return trace.Wrap(err)
		}
	}
	delay, err := bucketSet.Consume(1)
	if err != nil {
		return err
	}
	if delay > 0 {
		return &ratelimit.MaxRateError{}
	}
	return nil
}
580411
func registerSTSRouter(router *mux.Router) {
	// Initialize STS.
	sts := &stsAPIHandlers{}

	// STS Router
	stsRouter := router.NewRoute().PathPrefix("/").Subrouter()

	// Assume roles with no JWT, handles AssumeRole.
	stsRouter.Methods("POST").MatcherFunc(func(r *http.Request, rm *mux.RouteMatch) bool {
		ctypeOk := wildcard.MatchSimple("application/x-www-form-urlencoded*", r.Header.Get("Content-Type"))
		authOk := wildcard.MatchSimple("AWS4-HMAC-SHA256*", r.Header.Get("Authorization"))
		noQueries := len(r.URL.Query()) == 0
		return ctypeOk && authOk && noQueries
	}).HandlerFunc(httpTraceAll(sts.AssumeRole))

	// Assume roles with JWT handler, handles both ClientGrants and WebIdentity.
	stsRouter.Methods("POST").MatcherFunc(func(r *http.Request, rm *mux.RouteMatch) bool {
		ctypeOk := wildcard.MatchSimple("application/x-www-form-urlencoded*", r.Header.Get("Content-Type"))
		noQueries := len(r.URL.Query()) == 0
		return ctypeOk && noQueries
	}).HandlerFunc(httpTraceAll(sts.AssumeRoleWithJWT))

	// AssumeRoleWithClientGrants
	stsRouter.Methods("POST").HandlerFunc(httpTraceAll(sts.AssumeRoleWithClientGrants)).
		Queries("Action", clientGrants).
		Queries("Version", stsAPIVersion).
		Queries("Token", "{Token:.*}")

	// AssumeRoleWithWebIdentity
	stsRouter.Methods("POST").HandlerFunc(httpTraceAll(sts.AssumeRoleWithWebIdentity)).
		Queries("Action", webIdentity).
		Queries("Version", stsAPIVersion).
		Queries("WebIdentityToken", "{Token:.*}")

}
1165423
func (a Authorizer) Register(rw http.ResponseWriter, req *http.Request, user UserData, password string) error {
	if user.Username == "" {
		return mkerror("no username given")
	}
	if user.Email == "" {
		return mkerror("no email given")
	}
	if user.Hash != nil {
		return mkerror("hash will be overwritten")
	}
	if password == "" {
		return mkerror("no password given")
	}

	// Validate username
	_, err := a.backend.User(user.Username)
	if err == nil {
		a.addMessage(rw, req, "Username has been taken.")
		return mkerror("user already exists")
	} else if err != ErrMissingUser {
		if err != nil {
			return mkerror(err.Error())
		}
		return nil
	}

	// Generate and save hash
	hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return mkerror("couldn't save password: " + err.Error())
	}
	user.Hash = hash

	// Validate role
	if user.Role == "" {
		user.Role = a.defaultRole
	} else {
		if _, ok := a.roles[user.Role]; !ok {
			return mkerror("nonexistent role")
		}
	}

	err = a.backend.SaveUser(user)
	if err != nil {
		a.addMessage(rw, req, err.Error())
		return mkerror(err.Error())
	}
	return nil
}
820152
func (api UsersAPI) RegisterNewDigitalAssetAddress(w http.ResponseWriter, r *http.Request) {
	username := mux.Vars(r)["username"]
	userMgr := user.NewManager(r)

	currency := user.DigitalAssetAddress{}

	if err := json.NewDecoder(r.Body).Decode(&currency); err != nil {
		log.Debug("Error while decoding the body: ", err)
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	if !currency.Validate() {
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	u, err := userMgr.GetByName(username)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		return
	}

	//Check if this label is already used
	_, err = u.GetDigitalAssetAddressByLabel(currency.Label)
	if err == nil {
		http.Error(w, http.StatusText(http.StatusConflict), http.StatusConflict)
		return
	}

	if err := userMgr.SaveVirtualCurrency(username, currency); err != nil {
		log.Error("ERROR while saving virtual currency:\n", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	// respond with created digital wallet.
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusCreated)

	json.NewEncoder(w).Encode(&currency)
}
331156
func Register(name string, auth handleFunc) {
	authTex.Lock()
	authenticators[name] = auth
	authTex.Unlock()
}
1042210
func (cmd *UpdateAccountCommand) RegisterFlags(cc *cobra.Command, c *client.Client) {
	cc.Flags().StringVar(&cmd.Payload, "payload", "", "Request body encoded in JSON")
	cc.Flags().StringVar(&cmd.ContentType, "content", "", "Request content type override, e.g. 'application/x-www-form-urlencoded'")
	var accountID int
	cc.Flags().IntVar(&cmd.AccountID, "accountID", accountID, `Account ID`)
}
532160
func (mgr *MockCAClient) Register(request *api.RegistrationRequest) (string, error) {
	return "", errors.New("not implemented")
}
948597
func Register(servicer Servicer, botToken string) {
	//jobs.Config.Db.Address="192.168.1.101:6379"

	service := servicer.Service()
	if service.DefaultOAuth1 != nil {
		if service.DefaultOAuth1.AccessTokenReceiver == nil {
			err := errors.New("OAuth1 need an AccessTokenReceiver func to be specified\n")
			panic(err.Error())
		}
		service.DefaultBaseURL = *URLMustParse(service.DefaultOAuth1.AccessTokenURL)

		//mongoSession.DB(mongo.Database).C("users").EnsureIndex(mgo.Index{Key: []string{"settings." + service.Name + ".oauth_redirect_token"}})
	} else if service.DefaultOAuth2 != nil {
		service.DefaultBaseURL = *URLMustParse(service.DefaultOAuth2.Endpoint.AuthURL)
	}
	service.DefaultBaseURL.Path = ""
	service.DefaultBaseURL.RawPath = ""
	service.DefaultBaseURL.RawQuery = ""

	services[service.Name] = service

	if len(service.Jobs) > 0 || service.OAuthSuccessful != nil {
		if service.JobsPool == 0 {
			service.JobsPool = 1
		}
		pool, err := jobs.NewPool(&jobs.PoolConfig{
			Key:        "_" + service.Name,
			NumWorkers: service.JobsPool,
			BatchSize:  Config.TGPoolBatchSize,
		})
		if err != nil {
			log.Panicf("Can't create jobs pool: %v\n", err)
		} else {
			pool.SetMiddleware(beforeJob)
			pool.SetAfterFunc(afterJob)
		}

		//log.Infof("%s: workers pool [%d] is ready", service.Name, service.JobsPool)

		jobsPerService[service.Name] = make(map[string]*jobs.Type)

		if service.OAuthSuccessful != nil {
			service.Jobs = append(service.Jobs, Job{
				service.OAuthSuccessful, 10, JobRetryFibonacci,
			})
		}

		if len(service.Modules) > 0 {
			for _, module := range service.Modules {
				service.Actions = append(service.Actions, module.Actions...)
				service.Jobs = append(service.Jobs, module.Jobs...)
			}
		}

		for _, job := range service.Jobs {
			handlerType := reflect.TypeOf(job.HandlerFunc)
			m := make([]interface{}, handlerType.NumIn())

			for i := 0; i < handlerType.NumIn(); i++ {
				argType := handlerType.In(i)
				if argType.Kind() == reflect.Ptr {
					//argType = argType.Elem()
				}

				if argType.Kind() == reflect.Interface {
					gob.Register(reflect.Zero(argType))
				} else {
					gob.Register(reflect.Zero(argType).Interface())
				}
				m[i] = reflect.Zero(argType)
			}
			gob.Register(m)

			jobName := service.getShortFuncPath(job.HandlerFunc)

			jobType, err := jobs.RegisterTypeWithPoolKey(jobName, "_"+service.Name, job.Retries, job.HandlerFunc)
			if err != nil {
				fmt.Errorf("RegisterTypeWithPoolKey '%s', for %s: %s", jobName, service.Name, err.Error() )
			} else {
				jobsPerService[service.Name][jobName] = jobType
			}

		}

		rootPackagePath := reflect.TypeOf(servicer).PkgPath()
		service.rootPackagePath = rootPackagePath

		log.Debugf("RootPackagePath of %s is %s", service.Name, rootPackagePath)

		go func(pool *jobs.Pool, service *Service) {
			time.Sleep(time.Second * 5)

			err = pool.Start()

			if err != nil {
				log.Panicf("Can't start jobs pool: %v\n", err)
			}
			log.Infof("%s service: workers pool [%d] started", service.Name, service.JobsPool)

		}(pool, service)

	}

	if len(service.Actions) > 0 {
		for _, actionFunc := range service.Actions {
			actionFuncType := reflect.TypeOf(actionFunc)
			m := make([]interface{}, actionFuncType.NumIn())

			for i := 0; i < actionFuncType.NumIn(); i++ {
				argType := actionFuncType.In(i)
				if argType.Kind() == reflect.Ptr {
					//argType = argType.Elem()
				}

				gob.Register(reflect.Zero(argType).Interface())
			}
			gob.Register(m)
			actionFuncs[service.getShortFuncPath(actionFunc)] = actionFunc
		}
	}
	if botToken == "" {
		return
	}

	err := service.registerBot(botToken)
	if err != nil {
		log.WithError(err).WithField("token", botToken).Panic("Can't register the bot")
	}

	if service.Worker != nil {
		go SeviceWorkerAutorespawnGoroutine(service)
	}
	// todo: here is possible bug if service just want to use inline keyboard callbacks via setCallbackAction
	if service.TGNewMessageHandler == nil && service.TGInlineQueryHandler == nil {
		return
	}

}
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
}
603895
func (s *tokenServiceImpl) RegisterToken(ctx context.Context, identityID uuid.UUID, tokenString string, tokenType string,
	privileges []tokenrepo.TokenPrivilege) (*tokenrepo.Token, error) {

	// Parse the claims from the provided token string
	tokenClaims, err := s.tokenManager.ParseToken(ctx, tokenString)
	if err != nil {
		log.Error(ctx, map[string]interface{}{"error": err}, "invalid token string could not be parsed")
		return nil, errors.NewBadParameterErrorFromString("tokenString", tokenString,
			"invalid token string could not be parsed")
	}

	// Extract the id from the refresh token
	tokenID, err := uuid.FromString(tokenClaims.Id)
	if err != nil {
		log.Error(ctx, map[string]interface{}{"error": err}, "could not extract token ID from token string")
		return nil, errors.NewBadParameterErrorFromString("tokenString", tokenString,
			"could not extract token ID from token string")
	}

	expiryTime := time.Unix(tokenClaims.ExpiresAt, 0)

	tkn := &tokenrepo.Token{
		TokenID:    tokenID,
		IdentityID: identityID,
		Status:     0,
		TokenType:  tokenType,
		ExpiryTime: expiryTime,
	}

	// Persist the token record to the database
	err = s.ExecuteInTransaction(func() error {
		err = s.Repositories().TokenRepository().Create(ctx, tkn)
		if err != nil {
			return err
		}

		// If the access token is an RPT, register its permissions also
		if privileges != nil && len(privileges) > 0 {
			// Assign privileges to the token record, and persist them to the database
			for _, tokenPriv := range privileges {
				tokenPriv.TokenID = tokenID
				err = s.Repositories().TokenRepository().CreatePrivilege(ctx, &tokenPriv)
				if err != nil {
					return err
				}
			}
		}

		return nil
	})

	if err != nil {
		return nil, errors.NewInternalError(ctx, err)
	}

	return tkn, nil
}
602001
func RegisterCredentials(
	ctx *cmd.Context,
	store jujuclient.CredentialStore,
	provider environs.EnvironProvider,
	args modelcmd.RegisterCredentialsParams,
) error {
	credentials, err := modelcmd.RegisterCredentials(provider, args)
	switch {
	case errors.IsNotFound(err):
		return nil
	case err != nil:
		return errors.Trace(err)
	case credentials == nil:
		return nil
	}

	ctx.Verbosef("updating credential store")

	for name, credential := range credentials {
		if err := store.UpdateCredential(name, *credential); err != nil {
			return errors.Trace(err)
		}
	}
	return nil
}