// SetupOrFail creates a new user, bucket, org, and auth token. Fail on error.
554745
func (tl *TestLauncher) SetupOrFail(tb testing.TB) {
	results := tl.OnBoardOrFail(tb, &platform.OnboardingRequest{
		User:     "USER",
		Password: "PASSWORD",
		Org:      "ORG",
		Bucket:   "BUCKET",
	})

	tl.User = results.User
	tl.Org = results.Org
	tl.Bucket = results.Bucket
	tl.Auth = results.Auth
}
1182758
func (s *RemoteEnforcer) setupEnforcer(payload *rpcwrapper.InitRequestPayload) error {

	var err error

	s.secrets, err = secrets.NewSecrets(payload.Secrets)
	if err != nil {
		return err
	}

	if s.enforcer, err = createEnforcer(
		payload.MutualAuth,
		payload.FqConfig,
		s.collector,
		s.service,
		s.secrets,
		payload.ServerID,
		payload.Validity,
		constants.RemoteContainer,
		s.procMountPoint,
		payload.ExternalIPCacheTimeout,
		payload.PacketLogs,
		payload.Configuration,
	); err != nil || s.enforcer == nil {
		return fmt.Errorf("Error while initializing remote enforcer, %s", err)
	}

	return nil
}
944792
func (b *awsElasticBlockStoreMounter) SetUpAt(dir string, fsGroup *int64) error {
	// TODO: handle failed mounts here.
	notMnt, err := b.mounter.IsLikelyNotMountPoint(dir)
	klog.V(4).Infof("PersistentDisk set up: %s %v %v", dir, !notMnt, err)
	if err != nil && !os.IsNotExist(err) {
		klog.Errorf("cannot validate mount point: %s %v", dir, err)
		return err
	}
	if !notMnt {
		return nil
	}

	globalPDPath := makeGlobalPDPath(b.plugin.host, b.volumeID)

	if err := os.MkdirAll(dir, 0750); err != nil {
		return err
	}

	// Perform a bind mount to the full path to allow duplicate mounts of the same PD.
	options := []string{"bind"}
	if b.readOnly {
		options = append(options, "ro")
	}
	mountOptions := util.JoinMountOptions(options, b.mountOptions)
	err = b.mounter.Mount(globalPDPath, dir, "", mountOptions)
	if err != nil {
		notMnt, mntErr := b.mounter.IsLikelyNotMountPoint(dir)
		if mntErr != nil {
			klog.Errorf("IsLikelyNotMountPoint check failed for %s: %v", dir, mntErr)
			return err
		}
		if !notMnt {
			if mntErr = b.mounter.Unmount(dir); mntErr != nil {
				klog.Errorf("failed to unmount %s: %v", dir, mntErr)
				return err
			}
			notMnt, mntErr := b.mounter.IsLikelyNotMountPoint(dir)
			if mntErr != nil {
				klog.Errorf("IsLikelyNotMountPoint check failed for %s: %v", dir, mntErr)
				return err
			}
			if !notMnt {
				// This is very odd, we don't expect it.  We'll try again next sync loop.
				klog.Errorf("%s is still mounted, despite call to unmount().  Will try again next sync loop.", dir)
				return err
			}
		}
		os.Remove(dir)
		klog.Errorf("Mount of disk %s failed: %v", dir, err)
		return err
	}

	if !b.readOnly {
		volume.SetVolumeOwnership(b, fsGroup)
	}

	klog.V(4).Infof("Successfully mounted %s", dir)
	return nil
}
536541
func (s *CreateAuthorizerInput) SetAuthorizerUri(v string) *CreateAuthorizerInput {
	s.AuthorizerUri = &v
	return s
}
1045262
func (s *ListMultipartUploadsOutput) SetUploadsList(v []*UploadListElement) *ListMultipartUploadsOutput {
	s.UploadsList = v
	return s
}
170206
func setupUser(config *initConfig) error {
	// Set up defaults.
	defaultExecUser := user.ExecUser{
		Uid:  0,
		Gid:  0,
		Home: "/",
	}

	passwdPath, err := user.GetPasswdPath()
	if err != nil {
		return err
	}

	groupPath, err := user.GetGroupPath()
	if err != nil {
		return err
	}

	execUser, err := user.GetExecUserPath(config.User, &defaultExecUser, passwdPath, groupPath)
	if err != nil {
		return err
	}

	var addGroups []int
	if len(config.AdditionalGroups) > 0 {
		addGroups, err = user.GetAdditionalGroupsPath(config.AdditionalGroups, groupPath)
		if err != nil {
			return err
		}
	}

	// Rather than just erroring out later in setuid(2) and setgid(2), check
	// that the user is mapped here.
	if _, err := config.Config.HostUID(execUser.Uid); err != nil {
		return fmt.Errorf("cannot set uid to unmapped user in user namespace")
	}
	if _, err := config.Config.HostGID(execUser.Gid); err != nil {
		return fmt.Errorf("cannot set gid to unmapped user in user namespace")
	}

	if config.RootlessEUID {
		// We cannot set any additional groups in a rootless container and thus
		// we bail if the user asked us to do so. TODO: We currently can't do
		// this check earlier, but if libcontainer.Process.User was typesafe
		// this might work.
		if len(addGroups) > 0 {
			return fmt.Errorf("cannot set any additional groups in a rootless container")
		}
	}

	// Before we change to the container's user make sure that the processes
	// STDIO is correctly owned by the user that we are switching to.
	if err := fixStdioPermissions(config, execUser); err != nil {
		return err
	}

	setgroups, err := ioutil.ReadFile("/proc/self/setgroups")
	if err != nil && !os.IsNotExist(err) {
		return err
	}

	// This isn't allowed in an unprivileged user namespace since Linux 3.19.
	// There's nothing we can do about /etc/group entries, so we silently
	// ignore setting groups here (since the user didn't explicitly ask us to
	// set the group).
	allowSupGroups := !config.RootlessEUID && strings.TrimSpace(string(setgroups)) != "deny"

	if allowSupGroups {
		suppGroups := append(execUser.Sgids, addGroups...)
		if err := unix.Setgroups(suppGroups); err != nil {
			return err
		}
	}

	if err := system.Setgid(execUser.Gid); err != nil {
		return err
	}
	if err := system.Setuid(execUser.Uid); err != nil {
		return err
	}

	// if we didn't get HOME already, set it based on the user's HOME
	if envHome := os.Getenv("HOME"); envHome == "" {
		if err := os.Setenv("HOME", execUser.Home); err != nil {
			return err
		}
	}
	return nil
}
260015
func (s *Server) configureAuthorization() {
	if s.opts == nil {
		return
	}

	// Snapshot server options.
	opts := s.getOpts()

	// Check for multiple users first
	// This just checks and sets up the user map if we have multiple users.
	if opts.CustomClientAuthentication != nil {
		s.info.AuthRequired = true
	} else if len(s.trustedKeys) > 0 {
		s.info.AuthRequired = true
	} else if opts.Nkeys != nil || opts.Users != nil {
		// Support both at the same time.
		if opts.Nkeys != nil {
			s.nkeys = make(map[string]*NkeyUser)
			for _, u := range opts.Nkeys {
				copy := u.clone()
				if u.Account != nil {
					if v, ok := s.accounts.Load(u.Account.Name); ok {
						copy.Account = v.(*Account)
					}
				}
				s.nkeys[u.Nkey] = copy
			}
		}
		if opts.Users != nil {
			s.users = make(map[string]*User)
			for _, u := range opts.Users {
				copy := u.clone()
				if u.Account != nil {
					if v, ok := s.accounts.Load(u.Account.Name); ok {
						copy.Account = v.(*Account)
					}
				}
				s.users[u.Username] = copy
			}
		}
		s.assignGlobalAccountToOrphanUsers()
		s.info.AuthRequired = true
	} else if opts.Username != "" || opts.Authorization != "" {
		s.info.AuthRequired = true
	} else {
		s.users = nil
		s.info.AuthRequired = false
	}
}
158058
func (api UsersAPI) SetupTOTP(w http.ResponseWriter, r *http.Request) {
	username := mux.Vars(r)["username"]
	values := struct {
		TotpSecret string `json:"totpsecret"`
		TotpCode   string `json:"totpcode"`
	}{}

	if err := json.NewDecoder(r.Body).Decode(&values); err != nil {
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}
	totpMgr := totp.NewManager(r)
	err := totpMgr.Save(username, values.TotpSecret)
	if err != nil {
		log.Error(err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	valid, err := totpMgr.Validate(username, values.TotpCode)
	if err != nil {
		log.Error(err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	if !valid {
		err := totpMgr.Remove(username)
		if err != nil {
			log.Error(err)
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}
		w.WriteHeader(422)
	} else {
		userMgr := user.NewManager(r)
		userMgr.RemoveExpireDate(username)
		w.WriteHeader(http.StatusNoContent)
	}
}
197015
func setup(c *caddy.Controller) error {
	configs, err := gzipParse(c)
	if err != nil {
		return err
	}

	httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
		return Gzip{Next: next, Configs: configs}
	})

	return nil
}
1251468
func (s *UsersService) SetupTOTP(username string, body TOTPSecret, headers, queryParams map[string]interface{}) (*http.Response, error) {
	var err error

	resp, err := s.client.doReqWithBody("POST", s.client.BaseURI+"/users/"+username+"/totp", &body, headers, queryParams)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	return resp, err
}
1353719
func createAuthorizer(name string, config *server.Config) (server.Authorizer, error) {
	switch name {
	case "alwaysallow":
		return alwaysallow.NewAuthorizer()
	case "aws":
		return aws.NewAuthorizer(config)
	}

	return nil, errors.New("unknown authorizer")
}
140096
func (s *Server) setupRaft() error {
	// If we have an unclean exit then attempt to close the Raft store.
	defer func() {
		if s.raft == nil && s.raftStore != nil {
			if err := s.raftStore.Close(); err != nil {
				s.logger.Error("failed to close Raft store", "error", err)
			}
		}
	}()

	// Create the FSM
	fsmConfig := &FSMConfig{
		EvalBroker: s.evalBroker,
		Periodic:   s.periodicDispatcher,
		Blocked:    s.blockedEvals,
		Logger:     s.logger,
		Region:     s.Region(),
	}
	var err error
	s.fsm, err = NewFSM(fsmConfig)
	if err != nil {
		return err
	}

	// Create a transport layer
	trans := raft.NewNetworkTransport(s.raftLayer, 3, s.config.RaftTimeout,
		s.config.LogOutput)
	s.raftTransport = trans

	// Make sure we set the Logger.
	logger := s.logger.StandardLogger(&log.StandardLoggerOptions{InferLevels: true})
	s.config.RaftConfig.Logger = logger
	s.config.RaftConfig.LogOutput = nil

	// Our version of Raft protocol requires the LocalID to match the network
	// address of the transport.
	s.config.RaftConfig.LocalID = raft.ServerID(trans.LocalAddr())
	if s.config.RaftConfig.ProtocolVersion >= 3 {
		s.config.RaftConfig.LocalID = raft.ServerID(s.config.NodeID)
	}

	// Build an all in-memory setup for dev mode, otherwise prepare a full
	// disk-based setup.
	var log raft.LogStore
	var stable raft.StableStore
	var snap raft.SnapshotStore
	if s.config.DevMode {
		store := raft.NewInmemStore()
		s.raftInmem = store
		stable = store
		log = store
		snap = raft.NewDiscardSnapshotStore()

	} else {
		// Create the base raft path
		path := filepath.Join(s.config.DataDir, raftState)
		if err := ensurePath(path, true); err != nil {
			return err
		}

		// Create the BoltDB backend
		store, err := raftboltdb.NewBoltStore(filepath.Join(path, "raft.db"))
		if err != nil {
			return err
		}
		s.raftStore = store
		stable = store

		// Wrap the store in a LogCache to improve performance
		cacheStore, err := raft.NewLogCache(raftLogCacheSize, store)
		if err != nil {
			store.Close()
			return err
		}
		log = cacheStore

		// Create the snapshot store
		snapshots, err := raft.NewFileSnapshotStore(path, snapshotsRetained, s.config.LogOutput)
		if err != nil {
			if s.raftStore != nil {
				s.raftStore.Close()
			}
			return err
		}
		snap = snapshots

		// For an existing cluster being upgraded to the new version of
		// Raft, we almost never want to run recovery based on the old
		// peers.json file. We create a peers.info file with a helpful
		// note about where peers.json went, and use that as a sentinel
		// to avoid ingesting the old one that first time (if we have to
		// create the peers.info file because it's not there, we also
		// blow away any existing peers.json file).
		peersFile := filepath.Join(path, "peers.json")
		peersInfoFile := filepath.Join(path, "peers.info")
		if _, err := os.Stat(peersInfoFile); os.IsNotExist(err) {
			if err := ioutil.WriteFile(peersInfoFile, []byte(peersInfoContent), 0755); err != nil {
				return fmt.Errorf("failed to write peers.info file: %v", err)
			}

			// Blow away the peers.json file if present, since the
			// peers.info sentinel wasn't there.
			if _, err := os.Stat(peersFile); err == nil {
				if err := os.Remove(peersFile); err != nil {
					return fmt.Errorf("failed to delete peers.json, please delete manually (see peers.info for details): %v", err)
				}
				s.logger.Info("deleted peers.json file (see peers.info for details)")
			}
		} else if _, err := os.Stat(peersFile); err == nil {
			s.logger.Info("found peers.json file, recovering Raft configuration...")
			configuration, err := raft.ReadPeersJSON(peersFile)
			if err != nil {
				return fmt.Errorf("recovery failed to parse peers.json: %v", err)
			}
			tmpFsm, err := NewFSM(fsmConfig)
			if err != nil {
				return fmt.Errorf("recovery failed to make temp FSM: %v", err)
			}
			if err := raft.RecoverCluster(s.config.RaftConfig, tmpFsm,
				log, stable, snap, trans, configuration); err != nil {
				return fmt.Errorf("recovery failed: %v", err)
			}
			if err := os.Remove(peersFile); err != nil {
				return fmt.Errorf("recovery failed to delete peers.json, please delete manually (see peers.info for details): %v", err)
			}
			s.logger.Info("deleted peers.json file after successful recovery")
		}
	}

	// If we are in bootstrap or dev mode and the state is clean then we can
	// bootstrap now.
	if s.config.Bootstrap || s.config.DevMode {
		hasState, err := raft.HasExistingState(log, stable, snap)
		if err != nil {
			return err
		}
		if !hasState {
			configuration := raft.Configuration{
				Servers: []raft.Server{
					{
						ID:      s.config.RaftConfig.LocalID,
						Address: trans.LocalAddr(),
					},
				},
			}
			if err := raft.BootstrapCluster(s.config.RaftConfig,
				log, stable, snap, trans, configuration); err != nil {
				return err
			}
		}
	}

	// Setup the leader channel
	leaderCh := make(chan bool, 1)
	s.config.RaftConfig.NotifyCh = leaderCh
	s.leaderCh = leaderCh

	// Setup the Raft store
	s.raft, err = raft.NewRaft(s.config.RaftConfig, s.fsm, log, stable, snap, trans)
	if err != nil {
		return err
	}
	return nil
}
1339669
func SetupWidget(Admin *admin.Admin) {
	if Widgets != nil {
		return
	}
	Widgets = widget.New(&widget.Config{DB: db.DB})
	Widgets.WidgetSettingResource = Admin.NewResource(&QorWidgetSetting{})

	Widgets.RegisterScope(&widget.Scope{
		Name: "From Google",
		Visible: func(context *widget.Context) bool {
			if request, ok := context.Get("Request"); ok {
				_, ok := request.(*http.Request).URL.Query()["from_google"]
				return ok
			}
			return false
		},
	})

	Admin.AddResource(Widgets, &admin.Config{Menu: []string{"Pages Management"}, Priority: 3})

	// Top Banner
	type bannerArgument struct {
		Title           string
		ButtonTitle     string
		Link            string
		BackgroundImage oss.OSS
		Logo            oss.OSS
	}

	Widgets.RegisterWidget(&widget.Widget{
		Name:        "NormalBanner",
		Templates:   []string{"banner", "banner2"},
		PreviewIcon: "/images/Widget-NormalBanner.png",
		Group:       "Banners",
		Setting:     Admin.NewResource(&bannerArgument{}),
		Context: func(context *widget.Context, setting interface{}) *widget.Context {
			context.Options["Setting"] = setting
			return context
		},
	})

	// Banner Editor
	type bannerEditorArgument struct {
		Value string
	}
	type subHeaderSetting struct {
		Text  string
		Color string
	}
	type headerSetting struct {
		Text  string
		Color string
	}
	type textsSetting struct {
		Text  string
		Color string
	}
	type buttonSetting struct {
		Text string
		Link string
	}

	type modelBuyLinkSetting struct {
		ProductName string
		Price       string
		ButtonName  string
		Link        string
	}

	type imageSetting struct {
		Image oss.OSS
	}

	headerRes := Admin.NewResource(&headerSetting{})
	headerRes.Meta(&admin.Meta{Name: "Text"})
	headerRes.Meta(&admin.Meta{Name: "Color"})

	modelBuyLink := Admin.NewResource(&modelBuyLinkSetting{})
	modelBuyLink.Meta(&admin.Meta{Name: "ProductName"})
	modelBuyLink.Meta(&admin.Meta{Name: "Price"})
	modelBuyLink.Meta(&admin.Meta{Name: "ButtonName"})
	modelBuyLink.Meta(&admin.Meta{Name: "Link"})

	subHeaderRes := Admin.NewResource(&subHeaderSetting{})
	subHeaderRes.Meta(&admin.Meta{Name: "Text"})
	subHeaderRes.Meta(&admin.Meta{Name: "Color"})

	textsRes := Admin.NewResource(&textsSetting{})
	textsRes.Meta(&admin.Meta{Name: "Text"})
	textsRes.Meta(&admin.Meta{Name: "Color"})

	buttonRes := Admin.NewResource(&buttonSetting{})
	buttonRes.Meta(&admin.Meta{Name: "Text"})
	buttonRes.Meta(&admin.Meta{Name: "Link"})

	imageRes := Admin.NewResource(&imageSetting{})
	imageRes.Meta(&admin.Meta{Name: "Image"})

	banner_editor.RegisterViewPath("github.com/qor/qor-example/app/views/banner_editor")
	banner_editor.RegisterElement(&banner_editor.Element{
		Icon:     "<i class=material-icons>short_text</i>",
		Name:     "Add Header",
		Template: "header",
		Resource: headerRes,
		Context: func(c *admin.Context, r interface{}) interface{} {
			return r.(banner_editor.QorBannerEditorSettingInterface).GetSerializableArgument(r.(banner_editor.QorBannerEditorSettingInterface))
		},
	})
	banner_editor.RegisterElement(&banner_editor.Element{
		Icon:     "<i class=material-icons>format_list_bulleted</i>",
		Name:     "Add model buy block",
		Template: "model_buy_link",
		Resource: modelBuyLink,
		Context: func(c *admin.Context, r interface{}) interface{} {
			return r.(banner_editor.QorBannerEditorSettingInterface).GetSerializableArgument(r.(banner_editor.QorBannerEditorSettingInterface))
		},
	})
	banner_editor.RegisterElement(&banner_editor.Element{
		Icon:     "<i class=material-icons>format_align_justify</i>",
		Name:     "Add Text",
		Template: "text",
		Resource: textsRes,
		Context: func(c *admin.Context, r interface{}) interface{} {
			return r.(banner_editor.QorBannerEditorSettingInterface).GetSerializableArgument(r.(banner_editor.QorBannerEditorSettingInterface))
		},
	})
	banner_editor.RegisterElement(&banner_editor.Element{
		Icon:     "<i class=material-icons>dehaze</i>",
		Name:     "Add Sub Header",
		Template: "sub_header",
		Resource: subHeaderRes,
		Context: func(c *admin.Context, r interface{}) interface{} {
			return r.(banner_editor.QorBannerEditorSettingInterface).GetSerializableArgument(r.(banner_editor.QorBannerEditorSettingInterface))
		},
	})
	banner_editor.RegisterElement(&banner_editor.Element{
		Icon:     "<i class=material-icons>view_stream</i>",
		Name:     "Add Button",
		Template: "button",
		Resource: buttonRes,
		Context: func(c *admin.Context, r interface{}) interface{} {
			return r.(banner_editor.QorBannerEditorSettingInterface).GetSerializableArgument(r.(banner_editor.QorBannerEditorSettingInterface))
		},
	})

	banner_editor.RegisterElement(&banner_editor.Element{
		Icon:     "<i class=material-icons>image</i>",
		Name:     "Add Image",
		Template: "image",
		Resource: imageRes,
		Context: func(c *admin.Context, r interface{}) interface{} {
			return r.(banner_editor.QorBannerEditorSettingInterface).GetSerializableArgument(r.(banner_editor.QorBannerEditorSettingInterface))
		},
	})

	banner_editor.RegisterExternalStylePath("//fonts.googleapis.com/css?family=Lato|Playfair+Display|Raleway")
	banner_editor.RegisterExternalStylePath("/dist/qor.css")
	banner_editor.RegisterExternalStylePath("/dist/home_banner.css")

	bannerEditorResource := Admin.NewResource(&bannerEditorArgument{})
	bannerEditorResource.Meta(&admin.Meta{Name: "Value", Config: &banner_editor.BannerEditorConfig{
		MediaLibrary: Admin.GetResource("MediaLibrary"),
		Platforms: []banner_editor.Platform{
			{
				Name:     "Laptop",
				SafeArea: banner_editor.Size{Width: 0, Height: 0},
			},
			{
				Name:     "Mobile",
				SafeArea: banner_editor.Size{Width: 0, Height: 300},
			},
		},
	}})

	// normal banner editor
	Widgets.RegisterWidget(&widget.Widget{
		Name:        "BannerEditor",
		Templates:   []string{"banner_editor"},
		PreviewIcon: "/images/Widget-BannerEditor.png",
		Setting:     bannerEditorResource,
		Context: func(context *widget.Context, setting interface{}) *widget.Context {
			context.Options["Value"] = template.HTML(setting.(*bannerEditorArgument).Value)
			return context
		},
	})

	// full width banner editor
	fullwidthBannerEditorResource := Admin.NewResource(&bannerEditorArgument{})
	fullwidthBannerEditorResource.Meta(&admin.Meta{Name: "Value", Config: &banner_editor.BannerEditorConfig{
		MediaLibrary: Admin.GetResource("MediaLibrary"),
		Platforms: []banner_editor.Platform{
			{
				Name:     "Laptop",
				SafeArea: banner_editor.Size{Width: 0, Height: 0},
			},
			{
				Name:     "Mobile",
				SafeArea: banner_editor.Size{Width: 0, Height: 300},
			},
		},
	}})

	Widgets.RegisterWidget(&widget.Widget{
		Name:        "FullWidthBannerEditor",
		Templates:   []string{"fullwidth_banner_editor"},
		PreviewIcon: "/images/Widget-FullWidthBannerEditor.png",
		Setting:     fullwidthBannerEditorResource,
		Context: func(context *widget.Context, setting interface{}) *widget.Context {
			context.Options["Value"] = template.HTML(setting.(*bannerEditorArgument).Value)
			return context
		},
	})

	type slideImage struct {
		Title    string
		SubTitle string
		Button   string
		Link     string
		Image    oss.OSS
	}

	type slideShowArgument struct {
		SlideImages []slideImage
	}
	slideShowResource := Admin.NewResource(&slideShowArgument{})
	slideShowResource.AddProcessor(&resource.Processor{
		Handler: func(value interface{}, metaValues *resource.MetaValues, context *qor.Context) error {
			if slides, ok := value.(*slideShowArgument); ok {
				for _, slide := range slides.SlideImages {
					if slide.Title == "" {
						return errors.New("slide title is blank")
					}
				}
			}
			return nil
		},
	})

	Widgets.RegisterWidget(&widget.Widget{
		Name:        "SlideShow",
		Templates:   []string{"slideshow"},
		PreviewIcon: "/images/Widget-SlideShow.png",
		Group:       "Banners",
		Setting:     slideShowResource,
		Context: func(context *widget.Context, setting interface{}) *widget.Context {
			context.Options["Setting"] = setting
			return context
		},
	})

	Widgets.RegisterWidgetsGroup(&widget.WidgetsGroup{
		Name:    "Banner",
		Widgets: []string{"NormalBanner", "SlideShow"},
	})

	// selected Products
	type selectedProductsArgument struct {
		Products       []string
		ProductsSorter sorting.SortableCollection
	}
	selectedProductsResource := Admin.NewResource(&selectedProductsArgument{})
	selectedProductsResource.Meta(&admin.Meta{Name: "Products", Type: "select_many", Collection: func(value interface{}, context *qor.Context) [][]string {
		var collectionValues [][]string
		var products []*products.Product
		context.GetDB().Find(&products)
		for _, product := range products {
			collectionValues = append(collectionValues, []string{fmt.Sprintf("%v", product.ID), product.Name})
		}
		return collectionValues
	}})

	Widgets.RegisterWidget(&widget.Widget{
		Name:        "Products",
		Templates:   []string{"products"},
		Group:       "Products",
		PreviewIcon: "/images/Widget-Products.png",
		Setting:     selectedProductsResource,
		Context: func(context *widget.Context, setting interface{}) *widget.Context {
			if setting != nil {
				var products []*products.Product
				context.GetDB().Limit(9).Preload("ColorVariations").Where("id IN (?)", setting.(*selectedProductsArgument).Products).Find(&products)
				setting.(*selectedProductsArgument).ProductsSorter.Sort(&products)
				context.Options["Products"] = products
			}
			return context
		},
	})

	// FooterLinks
	type FooterItem struct {
		Name string
		Link string
	}

	type FooterSection struct {
		Title       string
		Items       []FooterItem
		ItemsSorter sorting.SortableCollection
	}

	type FooterLinks struct {
		Sections []FooterSection
	}

	Widgets.RegisterWidget(&widget.Widget{
		Name:        "Footer Links",
		PreviewIcon: "/images/Widget-FooterLinks.png",
		Setting:     Admin.NewResource(&FooterLinks{}),
		Context: func(context *widget.Context, setting interface{}) *widget.Context {
			context.Options["Setting"] = setting
			return context
		},
	})

	Widgets.RegisterFuncMap("render_banner_editor_content", func(val template.HTML, r *http.Request) template.HTML {
		bannerValue := banner_editor.GetContent(string(val), r)
		return template.HTML(bannerValue)
	})
}
974249
func (c *Core) setupCredentials(ctx context.Context) error {
	var persistNeeded bool

	c.authLock.Lock()
	defer c.authLock.Unlock()

	for _, entry := range c.auth.sortEntriesByPathDepth().Entries {
		var backend logical.Backend

		// Create a barrier view using the UUID
		viewPath := entry.ViewPath()

		// Singleton mounts cannot be filtered on a per-secondary basis
		// from replication
		if strutil.StrListContains(singletonMounts, entry.Type) {
			addFilterablePath(c, viewPath)
		}

		view := NewBarrierView(c.barrier, viewPath)

		// Determining the replicated state of the mount
		nilMount, err := preprocessMount(c, entry, view)
		if err != nil {
			return err
		}
		origViewReadOnlyErr := view.getReadOnlyErr()

		// Mark the view as read-only until the mounting is complete and
		// ensure that it is reset after. This ensures that there will be no
		// writes during the construction of the backend.
		view.setReadOnlyErr(logical.ErrSetupReadOnly)
		if strutil.StrListContains(singletonMounts, entry.Type) {
			defer view.setReadOnlyErr(origViewReadOnlyErr)
		} else {
			c.postUnsealFuncs = append(c.postUnsealFuncs, func() {
				view.setReadOnlyErr(origViewReadOnlyErr)
			})
		}

		// Initialize the backend
		sysView := c.mountEntrySysView(entry)

		backend, err = c.newCredentialBackend(ctx, entry, sysView, view)
		if err != nil {
			c.logger.Error("failed to create credential entry", "path", entry.Path, "error", err)
			if !c.builtinRegistry.Contains(entry.Type, consts.PluginTypeCredential) {
				// If we encounter an error instantiating the backend due to an error,
				// skip backend initialization but register the entry to the mount table
				// to preserve storage and path.
				c.logger.Warn("skipping plugin-based credential entry", "path", entry.Path)
				goto ROUTER_MOUNT
			}
			return errLoadAuthFailed
		}
		if backend == nil {
			return fmt.Errorf("nil backend returned from %q factory", entry.Type)
		}

		{
			// Check for the correct backend type
			backendType := backend.Type()
			if backendType != logical.TypeCredential {
				return fmt.Errorf("cannot mount %q of type %q as an auth backend", entry.Type, backendType)
			}

			addPathCheckers(c, entry, backend, viewPath)
		}

		// If the mount is filtered or we are on a DR secondary we don't want to
		// keep the actual backend running, so we clean it up and set it to nil
		// so the router does not have a pointer to the object.
		if nilMount {
			backend.Cleanup(ctx)
			backend = nil
		}

	ROUTER_MOUNT:
		// Mount the backend
		path := credentialRoutePrefix + entry.Path
		err = c.router.Mount(backend, path, entry, view)
		if err != nil {
			c.logger.Error("failed to mount auth entry", "path", entry.Path, "error", err)
			return errLoadAuthFailed
		}

		if c.logger.IsInfo() {
			c.logger.Info("successfully enabled credential backend", "type", entry.Type, "path", entry.Path)
		}

		// Ensure the path is tainted if set in the mount table
		if entry.Tainted {
			c.router.Taint(ctx, path)
		}

		// Check if this is the token store
		if entry.Type == "token" {
			c.tokenStore = backend.(*TokenStore)

			// At some point when this isn't beta we may persist this but for
			// now always set it on mount
			entry.Config.TokenType = logical.TokenTypeDefaultService

			// this is loaded *after* the normal mounts, including cubbyhole
			c.router.tokenStoreSaltFunc = c.tokenStore.Salt
			if !c.IsDRSecondary() {
				c.tokenStore.cubbyholeBackend = c.router.MatchingBackend(ctx, cubbyholeMountPath).(*CubbyholeBackend)
			}
		}

		// Populate cache
		NamespaceByID(ctx, entry.NamespaceID, c)
	}

	if persistNeeded {
		// persist non-local auth
		return c.persistAuth(ctx, c.auth, nil)
	}

	return nil
}
1231040
func setupContainerUser(specgen *generate.Generator, rootfs, mountLabel, ctrRunDir string, sc *pb.LinuxContainerSecurityContext, imageConfig *v1.Image) error {
	if sc == nil {
		return nil
	}
	if sc.GetRunAsGroup() != nil && sc.GetRunAsUser() == nil && sc.GetRunAsUsername() == "" {
		return fmt.Errorf("user group is specified without user or username")
	}
	imageUser := ""
	if imageConfig != nil {
		imageUser = imageConfig.Config.User
	}
	containerUser := generateUserString(
		sc.GetRunAsUsername(),
		imageUser,
		sc.GetRunAsUser(),
	)
	logrus.Debugf("CONTAINER USER: %+v", containerUser)

	// Add uid, gid and groups from user
	uid, gid, addGroups, err := utils.GetUserInfo(rootfs, containerUser)
	if err != nil {
		return err
	}

	// verify uid exists in containers /etc/passwd, else generate a passwd with the user entry
	passwdPath, err := utils.GeneratePasswd(uid, gid, rootfs, ctrRunDir)
	if err != nil {
		return err
	}
	if passwdPath != "" {
		if err := securityLabel(passwdPath, mountLabel, false); err != nil {
			return err
		}

		mnt := rspec.Mount{
			Type:        "bind",
			Source:      passwdPath,
			Destination: "/etc/passwd",
			Options:     []string{"ro", "bind", "nodev", "nosuid", "noexec"},
		}
		specgen.AddMount(mnt)
	}

	specgen.SetProcessUID(uid)
	specgen.SetProcessGID(gid)
	if sc.GetRunAsGroup() != nil {
		specgen.SetProcessGID(uint32(sc.GetRunAsGroup().GetValue()))
	}

	for _, group := range addGroups {
		specgen.AddProcessAdditionalGid(group)
	}

	// Add groups from CRI
	groups := sc.GetSupplementalGroups()
	for _, group := range groups {
		specgen.AddProcessAdditionalGid(uint32(group))
	}
	return nil
}
1241822
func (m *localVolumeMounter) SetUp(fsGroup *int64) error {
	return m.SetUpAt(m.GetPath(), fsGroup)
}
793285
func Setup(redirectURL, credFile string, scopes []string, secret []byte) {
	store = sessions.NewCookieStore(secret)
	var c Credentials
	file, err := ioutil.ReadFile(credFile)
	if err != nil {
		glog.Fatalf("[Gin-OAuth] File error: %v\n", err)
	}
	json.Unmarshal(file, &c)

	conf = &oauth2.Config{
		ClientID:     c.ClientID,
		ClientSecret: c.ClientSecret,
		RedirectURL:  redirectURL,
		Scopes:       scopes,
		Endpoint:     google.Endpoint,
	}
}