//const RegistryURL = "http://localhost:8082/servicecontroller/registerService"
/*
RegisterService handles service registartion with Piazza for external services.
*/
10676
func RegisterService(m ResourceMetadata) error {
	data, err := json.Marshal(m)
	if err != nil {
		return errors.New("Error marshaling ResourceMetadata")
	}

	response, err := http.Post(
		RegistryURL, ContentTypeJSON, bytes.NewBuffer(data),
	)
	if err != nil {
		return errors.New("Error posting ResourceMetadata to registerService")
	}

	if response.Body == nil {
		return errors.New("No JSON body returned from registerService")
	}

	b, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return errors.New("Error reading JSON body returned from registerService")
	}

	// Throw 400 if we cannot unmarshal the body as a valid InputMsg.
	var rm RegisterServiceMsg
	if err := json.Unmarshal(b, &rm); err != nil {
		return errors.New("Error unmarshaling RegisterServiceMsg")
	}
	log.Println("RegisterService received resourceId=" + rm.ResourceID)

	return nil
}
124067
func Registry() (c *RegistryController) {
	return &RegistryController{
		List:   registryList,
		Create: registryCreate,
		Delete: registryDelete,
		Update: registryUpdate,
	}
}
624601
func extractRegistryURL(imagePath string) (string, error) {
	imageNamed, err := reference.ParseNormalizedNamed(imagePath)
	if err != nil {
		return "", errors.Annotate(err, "extracting registry from path")
	}
	return reference.Domain(imageNamed), nil
}
968544
func RegisterService(m ResourceMetadata) error {
	data, err := json.Marshal(m)
	if err != nil {
		return errors.New("Error marshaling ResourceMetadata")
	}

	str := fmt.Sprintf("{\"apiKey\":\"my-api-key-38n987\",\"jobType\":{\"type\":\"register-service\",\"data\":%s}}", bytes.NewBuffer(data))
	fmt.Println(str)

	var buffer bytes.Buffer
	w := multipart.NewWriter(&buffer)
	err = w.WriteField("body", str)
	if err != nil {
		return errors.New("Error writing body")
	}
	err = w.Close()
	if err != nil {
		return errors.New("Error closing writer")
	}

	req, err := http.NewRequest("POST", GatewayJobURL, &buffer)
	if err != nil {
		return errors.New("Error creating request")
	}
	req.Header.Add("Content-Type", w.FormDataContentType())

	client := &http.Client{}
	response, err := client.Do(req)
	if err != nil {
		return errors.New("Error performing request")
	}

	if response.Body == nil {
		return errors.New("No JSON body returned from gateway")
	}
	defer response.Body.Close()

	b, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return errors.New("Error reading JSON body returned from gateway")
	}

	var rm JobMsg
	if err := json.Unmarshal(b, &rm); err != nil {
		return errors.New("Error unmarshaling JobMsg")
	}
	log.Println("Gateway received type " + rm.Type + ", jobId " + rm.JobID)

	return nil
}
739769
func RegisterServer(s *grpc.Server, m throttler.Manager) {
	throttlerservicepb.RegisterThrottlerServer(s, NewServer(m))
}
463457
func (r *Registry) RegisterParameterParser(paramType string, parser ParameterParser) {
	r.parsersLock.Lock()
	defer r.parsersLock.Unlock()
	r.parsers[paramType] = parser
}
1323242
func (service *Service) ProcessRegistrationForm(w http.ResponseWriter, r *http.Request) {
	response := struct {
		Redirecturl string `json:"redirecturl"`
		Error       string `json:"error"`
	}{}
	values := struct {
		Firstname       string `json:"firstname"`
		Lastname        string `json:"lastname"`
		Email           string `json:"email"`
		Phonenumber     string `json:"phonenumber"`
		PhonenumberCode string `json:"phonenumbercode"`
		Password        string `json:"password"`
		RedirectParams  string `json:"redirectparams"`
		LangKey         string `json:"langkey"`
	}{}
	if err := json.NewDecoder(r.Body).Decode(&values); err != nil {
		log.Debug("Error decoding the registration request:", err)
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	registrationSession, err := service.GetSession(r, SessionForRegistration, "registrationdetails")
	if err != nil {
		log.Error("Failed to retrieve registration session: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	if registrationSession.IsNew {
		sessions.Save(r, w)
		log.Debug("Registration session expired")
		http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
		return
	}

	sessionKey, _ := registrationSession.Values["sessionkey"].(string)
	if sessionKey == "" {
		log.Debug("Tried to finalize registration but no session key is present")
		sessions.Save(r, w)
		http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
		return
	}

	rMgr := registration.NewManager(r)
	registeringUser, err := rMgr.GetRegisteringUserBySessionKey(sessionKey)
	if err != nil {
		log.Error("Failed to get registration object: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	logMgr := persistentlog.NewManager(r)

	// check if phone number is validated or sms code is provided to validate phone
	phonevalidationkey := registeringUser.PhoneValidationKey

	if isConfirmed, _ := service.phonenumberValidationService.IsConfirmed(r, phonevalidationkey); !isConfirmed {

		logMgr.SaveLog(persistentlog.New(sessionKey, persistentlog.RegistrationFlow, "User tried to register without validated phone"))

		smscode := values.PhonenumberCode
		if smscode == "" {
			log.Debug("no sms code provided and phone not confirmed yet")
			http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
			return
		}

		err = service.phonenumberValidationService.ConfirmRegistrationValidation(r, phonevalidationkey, smscode)
		if err == validation.ErrInvalidCode {
			w.WriteHeader(http.StatusUnprocessableEntity)
			response.Error = "invalid_sms_code"
			json.NewEncoder(w).Encode(&response)
			return
		}
		if err == validation.ErrInvalidOrExpiredKey {
			sessions.Save(r, w)
			http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
			json.NewEncoder(w).Encode(&response)
			return
		}
		if err != nil {
			log.Error("Error while trying to validate phone number in regsitration flow: ", err)
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}

		logMgr.SaveLog(persistentlog.New(sessionKey, persistentlog.RegistrationFlow, "User confirmed phone number in final registration step"))

	}

	emailvalidationkey := registeringUser.EmailValidationKey
	emailConfirmed, _ := service.emailaddressValidationService.IsConfirmed(r, emailvalidationkey)
	if !emailConfirmed {
		logMgr.SaveLog(persistentlog.New(sessionKey, persistentlog.RegistrationFlow, "User tried to register without validated email"))
		log.Debug("Email not confirmed yet")
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	// We know that the phone number and email address are confirmed. So lets create the actual user
	userMgr := user.NewManager(r)

	// First get the username from the firstname and lastname
	username, err := generateUsername(r, registeringUser.Firstname, registeringUser.Lastname)
	if err != nil {
		log.Error("Failed to generate username: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	// Create the user object
	log.Debug("Creating new user with username ", username)
	userObj := &user.User{
		Username:       username,
		Firstname:      registeringUser.Firstname,
		Lastname:       registeringUser.Lastname,
		EmailAddresses: []user.EmailAddress{{Label: "main", EmailAddress: registeringUser.Email}},
		Phonenumbers:   []user.Phonenumber{{Label: "main", Phonenumber: registeringUser.Phonenumber}},
	}

	err = userMgr.Save(userObj)
	if err != nil {
		log.Error("Failed to create new user: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	// Also give this user a password
	log.Debug("Saving user password")
	passwdMgr := password.NewManager(r)
	err = passwdMgr.Save(username, values.Password)
	if err != nil {
		log.Error("Error while saving the users password: ", err)
		if err.Error() != "internal_error" {
			writeErrorResponse(w, "invalid_password", http.StatusUnprocessableEntity)
		} else {
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		}
		return
	}

	// Add correct validated phone number and validated email address
	valMgr := validationdb.NewManager(r)
	p := valMgr.NewValidatedPhonenumber(username, registeringUser.Phonenumber)
	if err = valMgr.SaveValidatedPhonenumber(p); err != nil {
		log.Error("Failed to add validated phone number of new user: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	e := valMgr.NewValidatedEmailAddress(username, registeringUser.Email)
	if err = valMgr.SaveValidatedEmailAddress(e); err != nil {
		log.Error("Failed to add validated email address of new user: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	logMgr.SaveLog(persistentlog.New(sessionKey, persistentlog.RegistrationFlow, "Registration finished, user created"))
	log.Debug("Finished saving new user information")

	// Ideally, we would remove the registration session here as registration is completed.
	// However the login handler checks the existence of this session because it needs the
	// redirectparams as part of the logic to move the user to the requested authenticated page.
	// But this means that if the user immediatly goes back to the registration screen, the old
	// user data is modified as there is already data in the session such as a username. Since we can't
	// remove the session, just empty out al the keys to mimic this process, and then only set the
	// redirectparams

	// Clear registration session
	for key := range registrationSession.Values {
		delete(registrationSession.Values, key)
	}

	// Now set the redirectparams
	registrationSession.Values["redirectparams"] = values.RedirectParams

	sessions.Save(r, w)
	service.loginUser(w, r, username)
}
563183
func (c *CAClientImpl) Register(request *api.RegistrationRequest) (string, error) {
	if c.adapter == nil {
		return "", fmt.Errorf("no CAs configured for organization: %s", c.orgName)
	}
	if c.registrar.EnrollID == "" {
		return "", api.ErrCARegistrarNotFound
	}
	// Validate registration request
	if request == nil {
		return "", errors.New("registration request is required")
	}
	if request.Name == "" {
		return "", errors.New("request.Name is required")
	}

	registrar, err := c.getRegistrar(c.registrar.EnrollID, c.registrar.EnrollSecret)
	if err != nil {
		return "", err
	}

	secret, err := c.adapter.Register(registrar.PrivateKey(), registrar.EnrollmentCertificate(), request)
	if err != nil {
		return "", errors.Wrap(err, "failed to register user")
	}

	return secret, nil
}
59968
func (p *ExtensionManagerClient) RegisterExtension(ctx context.Context, info *InternalExtensionInfo, registry ExtensionRegistry) (r *ExtensionStatus, err error) {
  var _args25 ExtensionManagerRegisterExtensionArgs
  _args25.Info = info
  _args25.Registry = registry
  var _result26 ExtensionManagerRegisterExtensionResult
  if err = p.Client_().Call(ctx, "registerExtension", &_args25, &_result26); err != nil {
    return
  }
  return _result26.GetSuccess(), nil
}
899339
func (a *Agent) vetServiceRegister(token string, service *structs.NodeService) error {
	// Resolve the token and bail if ACLs aren't enabled.
	rule, err := a.resolveToken(token)
	if err != nil {
		return err
	}
	if rule == nil {
		return nil
	}

	// Vet the service itself.
	if !rule.ServiceWrite(service.Service, nil) {
		return acl.ErrPermissionDenied
	}

	// Vet any service that might be getting overwritten.
	services := a.State.Services()
	if existing, ok := services[service.ID]; ok {
		if !rule.ServiceWrite(existing.Service, nil) {
			return acl.ErrPermissionDenied
		}
	}

	// If the service is a proxy, ensure that it has write on the destination too
	// since it can be discovered as an instance of that service.
	if service.Kind == structs.ServiceKindConnectProxy {
		if !rule.ServiceWrite(service.Proxy.DestinationServiceName, nil) {
			return acl.ErrPermissionDenied
		}
	}

	return nil
}
1136951
func (s ServiceInfo) Url() string {
	url := fmt.Sprintf("%s://%s:%v", s.Protocol, s.Host, s.Port)
	return url
}
227456
func (i *Infrastructure) RegisterService(name string, s Service) error {
	i.Lock.RLock()
	if _, ok := i.Services[name]; ok {
		i.Lock.RUnlock()
		return ErrServiceExists
	}
	i.Lock.RUnlock()
	i.Lock.Lock()
	if s.Name == "" {
		s.Name = name
	}
	i.Services[name] = &s
	i.Lock.Unlock()

	return nil
}
707883
func (_m *API) RegisterHost(_a0 []byte) error {
	ret := _m.Called(_a0)

	var r0 error
	if rf, ok := ret.Get(0).(func([]byte) error); ok {
		r0 = rf(_a0)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}
1289082
func (i Name) Registry() string {
	switch i.Domain {
	case "", oldDockerHubHost:
		return dockerHubHost
	default:
		return i.Domain
	}
}
857638
func (c *Client) Register(request *RegistrationRequest) (string, error) {
	ca, err := newCAClient(c.ctx, c.orgName)
	if err != nil {
		return "", err
	}

	var a []mspapi.Attribute
	for i := range request.Attributes {
		a = append(a, mspapi.Attribute{Name: request.Attributes[i].Name, Value: request.Attributes[i].Value, ECert: request.Attributes[i].ECert})
	}

	r := mspapi.RegistrationRequest{
		Name:           request.Name,
		Type:           request.Type,
		MaxEnrollments: request.MaxEnrollments,
		Affiliation:    request.Affiliation,
		Attributes:     a,
		CAName:         request.CAName,
		Secret:         request.Secret,
	}
	return ca.Register(&r)
}
440137
func (a *Agent) ServiceRegister(service *AgentServiceRegistration) error {
	r := a.c.newRequest("PUT", "/v1/agent/service/register")
	r.obj = service
	_, resp, err := requireOK(a.c.doRequest(r))
	if err != nil {
		return err
	}
	resp.Body.Close()
	return nil
}
1015908
func Services(s map[string][]*registry.Service) registry.Option {
	return func(o *registry.Options) {
		if o.Context == nil {
			o.Context = context.Background()
		}
		o.Context = context.WithValue(o.Context, servicesKey{}, s)
	}
}