// UpdateProfile attempts to update the root password used by a user to log
// into Torus which also allows them to access their stored and encrypted
// secrets.
760906
func (s *Session) UpdateProfile(ctx context.Context, newEmail, newName, newPassword string) (envelope.UserInf, error) {
	if s.engine.session.Type() != apitypes.UserSession {
		return nil, &apitypes.Error{
			Type: apitypes.BadRequestError,
			Err:  []string{"You must be a logged in user to change your password!"},
		}
	}

	// Convert the auth portion of the session to a UserInf interface
	// Note: the auth and identity sections for a user are the same
	user, ok := s.engine.session.Self().Auth.(envelope.UserInf)
	if !ok {
		log.Printf("Could not convert to UserInf during update profile")
		return nil, &apitypes.Error{
			Type: apitypes.InternalServerError,
			Err:  []string{"Could not convert to user interface"},
		}
	}

	if user.StructVersion() != 2 {
		return nil, &apitypes.Error{
			Type: apitypes.BadRequestError,
			Err: []string{fmt.Sprintf(
				"User schema must be v2 to perform password change: %d",
				user.StructVersion()),
			},
		}
	}

	payload := &updateProfile{}
	if newEmail != "" {
		payload.Email = newEmail
	}

	if newName != "" {
		payload.Name = newName
	}

	if newPassword != "" {
		pw, master, keypair, err := s.engine.crypto.ChangePassword(ctx, newPassword)
		if err != nil {
			log.Printf("Could not re-encrypt master key: %s", err)
			return nil, &apitypes.Error{
				Type: apitypes.InternalServerError,
				Err:  []string{"Could not re-encrypt master key"},
			}
		}

		payload.Password = pw
		payload.Master = master
		payload.PublicKey = keypair
	}

	updatedUser, err := s.engine.client.Users.Update(ctx, payload)
	if err != nil {
		log.Printf("Could not update password on server due to err: %s", err)
		return nil, err
	}

	s.engine.session.SetIdentity(apitypes.UserSession, updatedUser, updatedUser)
	return updatedUser, nil
}
1201221
func (ac *APIController) AppProfileUpdate(oldProf, newProf *contivModel.AppProfile) error {
	log.Infof("Received AppProfileUpdate: %+v, newProf: %+v", oldProf, newProf)

	// handle any epg addition
	for _, epg := range newProf.EndpointGroups {
		epgKey := newProf.TenantName + ":" + epg
		log.Infof("Add %s to %s", epgKey, newProf.AppProfileName)
		epgObj := contivModel.FindEndpointGroup(epgKey)
		if epgObj == nil {
			return core.Errorf("EndpointGroup %s not found", epgKey)
		}
		modeldb.AddLinkSet(&newProf.LinkSets.EndpointGroups, epgObj)

		// workaround for objdb update problem
		modeldb.AddLinkSet(&oldProf.LinkSets.EndpointGroups, epgObj)

		modeldb.AddLink(&epgObj.Links.AppProfile, newProf)
		err := epgObj.Write()
		if err != nil {
			log.Errorf("Error updating epg state(%+v). Err: %v", epgObj, err)
			return err
		}
	}

	// handle any epg removal
	for _, epg := range oldProf.EndpointGroups {
		if !stringInSlice(epg, newProf.EndpointGroups) {
			epgKey := newProf.TenantName + ":" + epg
			log.Infof("Remove %s from %s", epgKey, newProf.AppProfileName)
			epgObj := contivModel.FindEndpointGroup(epgKey)
			if epgObj == nil {
				return core.Errorf("EndpointGroup %s not found", epgKey)
			}
			modeldb.RemoveLink(&epgObj.Links.AppProfile, oldProf)
			err := epgObj.Write()
			if err != nil {
				log.Errorf("Error updating epg state(%+v). Err: %v",
					epgObj, err)
				return err
			}

			// workaround for objdb update problem
			modeldb.RemoveLinkSet(&oldProf.LinkSets.EndpointGroups, epgObj)
		}
	}

	// workaround for objdb update problem -- should fix model
	oldProf.EndpointGroups = newProf.EndpointGroups

	// update the app nw
	DeleteAppNw(oldProf)
	lErr := CreateAppNw(oldProf)
	return lErr
}
1111173
func NewProfiler() (prof *Profiler, err error) {
	p, err := info.NewProfiler()
	if err != nil {
		return nil, err
	}
	return &Profiler{Profiler: p}, nil
}
570408
func UpdateDeviceProfile(db sqlx.Execer, dp *DeviceProfile) error {
	dp.UpdatedAt = time.Now()

	res, err := db.Exec(`
        update device_profile set
            updated_at = $2,

            supports_class_b = $3,
            class_b_timeout = $4,
            ping_slot_period = $5,
            ping_slot_dr = $6,
            ping_slot_freq = $7,
            supports_class_c = $8,
            class_c_timeout = $9,
            mac_version = $10,
            reg_params_revision = $11,
            rx_delay_1 = $12,
            rx_dr_offset_1 = $13,
            rx_data_rate_2 = $14,
            rx_freq_2 = $15,
            factory_preset_freqs = $16,
            max_eirp = $17,
            max_duty_cycle = $18,
            supports_join = $19,
            rf_region = $20,
            supports_32bit_fcnt = $21
        where
            device_profile_id = $1`,
		dp.ID,
		dp.UpdatedAt,
		dp.SupportsClassB,
		dp.ClassBTimeout,
		dp.PingSlotPeriod,
		dp.PingSlotDR,
		dp.PingSlotFreq,
		dp.SupportsClassC,
		dp.ClassCTimeout,
		dp.MACVersion,
		dp.RegParamsRevision,
		dp.RXDelay1,
		dp.RXDROffset1,
		dp.RXDataRate2,
		dp.RXFreq2,
		pq.Array(dp.FactoryPresetFreqs),
		dp.MaxEIRP,
		dp.MaxDutyCycle,
		dp.SupportsJoin,
		dp.RFRegion,
		dp.Supports32bitFCnt,
	)
	if err != nil {
		return handlePSQLError(err, "update error")
	}
	ra, err := res.RowsAffected()
	if err != nil {
		return handlePSQLError(err, "get rows affected error")
	}
	if ra == 0 {
		return ErrDoesNotExist
	}

	log.WithField("id", dp.ID).Info("device-profile updated")
	return nil
}
708110
func validateProfile(profile string, loadedProfiles map[string]bool) error {
	if err := ValidateProfileFormat(profile); err != nil {
		return err
	}

	if strings.HasPrefix(profile, ProfileNamePrefix) {
		profileName := strings.TrimPrefix(profile, ProfileNamePrefix)
		if !loadedProfiles[profileName] {
			return fmt.Errorf("profile %q is not loaded", profileName)
		}
	}

	return nil
}
887537
func (s *Server) ReplaceOrAddContainerProfile(name, oldProfile, newProfile string) error {
	container, eTag, err := s.GetContainer(name)
	if err != nil {
		return errors.Trace(errors.Annotatef(err, "failed to get container %q", name))
	}
	profiles := addRemoveReplaceProfileName(container.Profiles, oldProfile, newProfile)

	container.Profiles = profiles
	resp, err := s.UpdateContainer(name, container.Writable(), eTag)
	if err != nil {
		return errors.Trace(errors.Annotatef(err, "failed to updated container %q", name))
	}

	op := resp.Get()
	logger.Debugf("updated container, waiting on %s", op.Description)
	err = resp.Wait()
	if err != nil {
		logger.Tracef("updating container failed on %q", err)
	}
	return errors.Trace(err)
}
1037695
func (s *AacSettings) SetProfile(v string) *AacSettings {
	s.Profile = &v
	return s
}
945202
func (s *GetProfileOutput) SetProfile(v *Profile) *GetProfileOutput {
	s.Profile = v
	return s
}
201400
func NewProfiler() (prof *Profiler, err error) {
	p, err := util.NewProfiler()
	if err != nil {
		return nil, err
	}
	return &Profiler{Profiler: p}, nil
}
286223
func (s *RoomData) SetProfileArn(v string) *RoomData {
	s.ProfileArn = &v
	return s
}
574374
func (s *witServiceImpl) UpdateUser(ctx context.Context, updatePayload *app.UpdateUsersPayload, identityID string) error {
	// Using the UpdateUserPayload because it also describes which attribtues are being updated and which are not.
	updateUserPayload := &witservice.UpdateUserAsServiceAccountUsersPayload{
		Data: &witservice.UpdateUserData{
			Attributes: &witservice.UpdateIdentityDataAttributes{
				Bio:                   updatePayload.Data.Attributes.Bio,
				Company:               updatePayload.Data.Attributes.Company,
				ContextInformation:    updatePayload.Data.Attributes.ContextInformation,
				Email:                 updatePayload.Data.Attributes.Email,
				FullName:              updatePayload.Data.Attributes.FullName,
				ImageURL:              updatePayload.Data.Attributes.ImageURL,
				RegistrationCompleted: updatePayload.Data.Attributes.RegistrationCompleted,
				URL:                   updatePayload.Data.Attributes.URL,
				Username:              updatePayload.Data.Attributes.Username,
			},
			Type: updatePayload.Data.Type,
		},
	}

	remoteWITService, err := s.createClientWithContextSigner(ctx)

	if err != nil {
		return err
	}

	remoteUpdateUserAPIPath := witservice.UpdateUserAsServiceAccountUsersPath(identityID)
	res, err := remoteWITService.UpdateUserAsServiceAccountUsers(goasupport.ForwardContextRequestID(ctx), remoteUpdateUserAPIPath, updateUserPayload)
	if err != nil {
		return err
	}
	defer rest.CloseResponse(res)
	bodyString := rest.ReadBody(res.Body) // To prevent FDs leaks
	if res.StatusCode != http.StatusOK {
		log.Error(ctx, map[string]interface{}{
			"identity_id":     identityID,
			"username":        updatePayload.Data.Attributes.Username,
			"response_status": res.Status,
			"response_body":   bodyString,
		}, "unable to update user in WIT")
		return errors.Errorf("unable to update user in WIT. Response status: %s. Response body: %s", res.Status, bodyString)
	}
	return nil
}
737872
func (o *Enterprise) IKEEncryptionprofiles(info *bambou.FetchingInfo) (IKEEncryptionprofilesList, *bambou.Error) {

	var list IKEEncryptionprofilesList
	err := bambou.CurrentSession().FetchChildren(o, IKEEncryptionprofileIdentity, &list, info)
	return list, err
}
899340
func (b *BigIP) HttpProfiles() (*HttpProfiles, error) {
	var httpProfiles HttpProfiles
	err, _ := b.getForEntity(&httpProfiles, uriLtm, uriProfile, uriHttp)
	if err != nil {
		return nil, err
	}

	return &httpProfiles, nil
}
221877
func NewProfiler() (prof *Profiler, err error) {
	p, err := mem.NewProfiler()
	if err != nil {
		return nil, err
	}
	return &Profiler{Profiler: p}, nil
}
622081
func (b *BigIP) ModifyHttpProfile(name string, config *HttpProfile) error {
	return b.put(config, uriLtm, uriProfile, uriHttp, name)
}
899440
func readProfile(profileDir string, profileName string) (*ProfileStatus, error) {
	var err error

	// Read in the profile for this proxy.
	profile, err := ProfileFromFile(filepath.Join(profileDir, profileName))
	if err != nil {
		return nil, trace.Wrap(err)
	}

	// Read in the SSH certificate for the user logged into this proxy.
	store, err := NewFSLocalKeyStore(profileDir)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	keys, err := store.GetKey(profile.Name(), profile.Username)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	publicKey, _, _, _, err := ssh.ParseAuthorizedKey(keys.Cert)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	cert, ok := publicKey.(*ssh.Certificate)
	if !ok {
		return nil, trace.BadParameter("no certificate found")
	}

	// Extract from the certificate how much longer it will be valid for.
	validUntil := time.Unix(int64(cert.ValidBefore), 0)

	// Extract roles from certificate. Note, if the certificate is in old format,
	// this will be empty.
	var roles []string
	rawRoles, ok := cert.Extensions[teleport.CertExtensionTeleportRoles]
	if ok {
		roles, err = services.UnmarshalCertRoles(rawRoles)
		if err != nil {
			return nil, trace.Wrap(err)
		}
	}
	sort.Strings(roles)

	// Extract extensions from certificate. This lists the abilities of the
	// certificate (like can the user request a PTY, port forwarding, etc.)
	var extensions []string
	for ext, _ := range cert.Extensions {
		if ext == teleport.CertExtensionTeleportRoles {
			continue
		}
		extensions = append(extensions, ext)
	}
	sort.Strings(extensions)

	return &ProfileStatus{
		ProxyURL: url.URL{
			Scheme: "https",
			Host:   profile.WebProxyAddr,
		},
		Username:   profile.Username,
		Logins:     cert.ValidPrincipals,
		ValidUntil: validUntil,
		Extensions: extensions,
		Roles:      roles,
		Cluster:    profile.Name(),
	}, nil
}
1142538
func (e Endpoints) PutProfile(ctx context.Context, id string, p Profile) error {
	request := putProfileRequest{ID: id, Profile: p}
	response, err := e.PutProfileEndpoint(ctx, request)
	if err != nil {
		return err
	}
	resp := response.(putProfileResponse)
	return resp.Err
}