// Admin returns true if the admin feature set is on or the user is a keybase
// admin.
490394
func (set FeatureFlags) Admin(uid keybase1.UID) bool {
	for _, f := range set {
		if f == Feature("admin") {
			return true
		}
	}
	return IsKeybaseAdmin(uid)
}
1357227
func (a *admin) login(req params.LoginRequest, loginVersion int) (params.LoginResult, error) {
	var fail params.LoginResult

	a.mu.Lock()
	defer a.mu.Unlock()
	if a.loggedIn {
		// This can only happen if Login is called concurrently.
		return fail, errAlreadyLoggedIn
	}

	authResult, err := a.authenticate(req)
	if err, ok := errors.Cause(err).(*common.DischargeRequiredError); ok {
		loginResult := params.LoginResult{
			DischargeRequired:       err.Macaroon,
			DischargeRequiredReason: err.Error(),
		}
		logger.Infof("login failed with discharge-required error: %v", err)
		return loginResult, nil
	}
	if err != nil {
		return fail, errors.Trace(err)
	}

	// Fetch the API server addresses from state.
	// If the login comes from a client, return all available addresses.
	// Otherwise return the addresses suitable for agent use.
	getHostPorts := a.root.state.APIHostPortsForAgents
	if k, _ := names.TagKind(req.AuthTag); k == names.UserTagKind {
		getHostPorts = a.root.state.APIHostPortsForClients
	}
	hostPorts, err := getHostPorts()
	if err != nil {
		return fail, errors.Trace(err)
	}

	// apiRoot is the API root exposed to the client after login.
	var apiRoot rpc.Root = newAPIRoot(
		a.root.state,
		a.root.shared,
		a.srv.facades,
		a.root.resources,
		a.root,
	)
	apiRoot, err = restrictAPIRoot(
		a.srv,
		apiRoot,
		a.root.model,
		*authResult,
	)
	if err != nil {
		return fail, errors.Trace(err)
	}

	var facadeFilters []facadeFilterFunc
	var modelTag string
	if authResult.anonymousLogin {
		facadeFilters = append(facadeFilters, IsAnonymousFacade)
	}
	if authResult.controllerOnlyLogin {
		facadeFilters = append(facadeFilters, IsControllerFacade)
	} else {
		facadeFilters = append(facadeFilters, IsModelFacade)
		modelTag = a.root.model.Tag().String()
	}

	auditConfig := a.srv.GetAuditConfig()
	auditRecorder, err := a.getAuditRecorder(req, authResult, auditConfig)
	if err != nil {
		return fail, errors.Trace(err)
	}

	recorderFactory := observer.NewRecorderFactory(
		a.apiObserver, auditRecorder, auditConfig.CaptureAPIArgs,
	)
	a.root.rpcConn.ServeRoot(apiRoot, recorderFactory, serverError)
	return params.LoginResult{
		Servers:       params.FromNetworkHostsPorts(hostPorts),
		ControllerTag: a.root.model.ControllerTag().String(),
		UserInfo:      authResult.userInfo,
		ServerVersion: jujuversion.Current.String(),
		PublicDNSName: a.srv.publicDNSName(),
		ModelTag:      modelTag,
		Facades:       filterFacades(a.srv.facades, facadeFilters...),
	}, nil
}
83377
func checkAdminUserAddSyntax(ctx *cli.Context) {
	if len(ctx.Args()) != 4 {
		cli.ShowCommandHelpAndExit(ctx, "add", 1) // last argument is exit code
	}
}
119028
func (s *MemberFabricConfiguration) SetAdminUsername(v string) *MemberFabricConfiguration {
	s.AdminUsername = &v
	return s
}
1302589
func NewAdmin(c *client.Client, username string) error {
	return doNew(c, "/v1/admin/perms/", username)
}
464454
func (c *AdminListUsersCall) Context(ctx context.Context) *AdminListUsersCall {
	c.ctx_ = ctx
	return c
}
1141884
func checkAdminRequestAuthType(ctx context.Context, r *http.Request, region string) APIErrorCode {
	s3Err := ErrAccessDenied
	if _, ok := r.Header["X-Amz-Content-Sha256"]; ok &&
		getRequestAuthType(r) == authTypeSigned && !skipContentSha256Cksum(r) {
		// We only support admin credentials to access admin APIs.

		var owner bool
		_, owner, s3Err = getReqAccessKeyV4(r, region, serviceS3)
		if s3Err != ErrNone {
			return s3Err
		}

		if !owner {
			return ErrAccessDenied
		}

		// we only support V4 (no presign) with auth body
		s3Err = isReqAuthenticated(ctx, r, region, serviceS3)
	}
	if s3Err != ErrNone {
		reqInfo := (&logger.ReqInfo{}).AppendTags("requestHeaders", dumpRequest(r))
		ctx := logger.SetReqInfo(ctx, reqInfo)
		logger.LogIf(ctx, errors.New(getAPIError(s3Err).Description))
	}
	return s3Err
}
1339335
func NewAdminContext() (*AuthContext, error) {
	authContext, err := contextForBuiltinRole("", nil, teleport.RoleAdmin, fmt.Sprintf("%v", teleport.RoleAdmin))
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return authContext, nil
}
287834
func (App) ConfigureAdmin(Admin *admin.Admin) {
	// Produc Management
	Admin.AddMenu(&admin.Menu{Name: "Product Management", Priority: 1})
	color := Admin.AddResource(&products.Color{}, &admin.Config{Menu: []string{"Product Management"}, Priority: -5})
	Admin.AddResource(&products.Size{}, &admin.Config{Menu: []string{"Product Management"}, Priority: -4})
	Admin.AddResource(&products.Material{}, &admin.Config{Menu: []string{"Product Management"}, Priority: -4})

	category := Admin.AddResource(&products.Category{}, &admin.Config{Menu: []string{"Product Management"}, Priority: -3})
	category.Meta(&admin.Meta{Name: "Categories", Type: "select_many"})

	collection := Admin.AddResource(&products.Collection{}, &admin.Config{Menu: []string{"Product Management"}, Priority: -2})

	// Add ProductImage as Media Libraray
	ProductImagesResource := Admin.AddResource(&products.ProductImage{}, &admin.Config{Menu: []string{"Product Management"}, Priority: -1})

	ProductImagesResource.Filter(&admin.Filter{
		Name:       "SelectedType",
		Label:      "Media Type",
		Operations: []string{"contains"},
		Config:     &admin.SelectOneConfig{Collection: [][]string{{"video", "Video"}, {"image", "Image"}, {"file", "File"}, {"video_link", "Video Link"}}},
	})
	ProductImagesResource.Filter(&admin.Filter{
		Name:   "Color",
		Config: &admin.SelectOneConfig{RemoteDataResource: color},
	})
	ProductImagesResource.Filter(&admin.Filter{
		Name:   "Category",
		Config: &admin.SelectOneConfig{RemoteDataResource: category},
	})
	ProductImagesResource.IndexAttrs("File", "Title")

	// Add Product
	product := Admin.AddResource(&products.Product{}, &admin.Config{Menu: []string{"Product Management"}})
	product.Meta(&admin.Meta{Name: "Gender", Config: &admin.SelectOneConfig{Collection: Genders, AllowBlank: true}})

	productPropertiesRes := product.Meta(&admin.Meta{Name: "ProductProperties"}).Resource
	productPropertiesRes.NewAttrs(&admin.Section{
		Rows: [][]string{{"Name", "Value"}},
	})
	productPropertiesRes.EditAttrs(&admin.Section{
		Rows: [][]string{{"Name", "Value"}},
	})

	product.Meta(&admin.Meta{Name: "Description", Config: &admin.RichEditorConfig{Plugins: []admin.RedactorPlugin{
		{Name: "medialibrary", Source: "/admin/assets/javascripts/qor_redactor_medialibrary.js"},
		{Name: "table", Source: "/vendors/redactor_table.js"},
	},
		Settings: map[string]interface{}{
			"medialibraryUrl": "/admin/product_images",
		},
	}})
	product.Meta(&admin.Meta{Name: "Category", Config: &admin.SelectOneConfig{AllowBlank: true}})
	product.Meta(&admin.Meta{Name: "Collections", Config: &admin.SelectManyConfig{SelectMode: "bottom_sheet"}})

	product.Meta(&admin.Meta{Name: "MainImage", Config: &media_library.MediaBoxConfig{
		RemoteDataResource: ProductImagesResource,
		Max:                1,
		Sizes: map[string]*media.Size{
			"main": {Width: 560, Height: 700},
		},
	}})
	product.Meta(&admin.Meta{Name: "MainImageURL", Valuer: func(record interface{}, context *qor.Context) interface{} {
		if p, ok := record.(*products.Product); ok {
			result := bytes.NewBufferString("")
			tmpl, _ := template.New("").Parse("<img src='{{.image}}'></img>")
			tmpl.Execute(result, map[string]string{"image": p.MainImageURL()})
			return template.HTML(result.String())
		}
		return ""
	}})

	product.Filter(&admin.Filter{
		Name:   "Collections",
		Config: &admin.SelectOneConfig{RemoteDataResource: collection},
	})

	product.Filter(&admin.Filter{
		Name: "Featured",
	})

	product.Filter(&admin.Filter{
		Name: "Name",
		Type: "string",
	})

	product.Filter(&admin.Filter{
		Name: "Code",
	})

	product.Filter(&admin.Filter{
		Name: "Price",
		Type: "number",
	})

	product.Filter(&admin.Filter{
		Name: "CreatedAt",
	})

	product.Action(&admin.Action{
		Name:        "Import Product",
		URLOpenType: "slideout",
		URL: func(record interface{}, context *admin.Context) string {
			return "/admin/workers/new?job=Import Products"
		},
		Modes: []string{"collection"},
	})

	type updateInfo struct {
		CategoryID  uint
		Category    *products.Category
		MadeCountry string
		Gender      string
	}

	updateInfoRes := Admin.NewResource(&updateInfo{})
	product.Action(&admin.Action{
		Name:     "Update Info",
		Resource: updateInfoRes,
		Handler: func(argument *admin.ActionArgument) error {
			newProductInfo := argument.Argument.(*updateInfo)
			for _, record := range argument.FindSelectedRecords() {
				fmt.Printf("%#v\n", record)
				if product, ok := record.(*products.Product); ok {
					if newProductInfo.Category != nil {
						product.Category = *newProductInfo.Category
					}
					if newProductInfo.MadeCountry != "" {
						product.MadeCountry = newProductInfo.MadeCountry
					}
					if newProductInfo.Gender != "" {
						product.Gender = newProductInfo.Gender
					}
					argument.Context.GetDB().Save(product)
				}
			}
			return nil
		},
		Modes: []string{"batch"},
	})

	product.UseTheme("grid")

	// variationsResource := product.Meta(&admin.Meta{Name: "Variations", Config: &variations.VariationsConfig{}}).Resource
	// if imagesMeta := variationsResource.GetMeta("Images"); imagesMeta != nil {
	// 	imagesMeta.Config = &media_library.MediaBoxConfig{
	// 		RemoteDataResource: ProductImagesResource,
	// 		Sizes: map[string]*media.Size{
	// 			"icon":    {Width: 50, Height: 50},
	// 			"thumb":   {Width: 100, Height: 100},
	// 			"display": {Width: 300, Height: 300},
	// 		},
	// 	}
	// }

	// variationsResource.EditAttrs("-ID", "-Product")
	// oldSearchHandler := product.SearchHandler
	// product.SearchHandler = func(keyword string, context *qor.Context) *gorm.DB {
	// 	context.SetDB(context.GetDB().Preload("Variations.Color").Preload("Variations.Size").Preload("Variations.Material"))
	// 	return oldSearchHandler(keyword, context)
	// }
	colorVariationMeta := product.Meta(&admin.Meta{Name: "ColorVariations"})
	colorVariation := colorVariationMeta.Resource
	colorVariation.Meta(&admin.Meta{Name: "Images", Config: &media_library.MediaBoxConfig{
		RemoteDataResource: ProductImagesResource,
		Sizes: map[string]*media.Size{
			"icon":    {Width: 50, Height: 50},
			"preview": {Width: 300, Height: 300},
			"listing": {Width: 640, Height: 640},
		},
	}})

	colorVariation.NewAttrs("-Product", "-ColorCode")
	colorVariation.EditAttrs("-Product", "-ColorCode")

	sizeVariationMeta := colorVariation.Meta(&admin.Meta{Name: "SizeVariations"})
	sizeVariation := sizeVariationMeta.Resource
	sizeVariation.EditAttrs(
		&admin.Section{
			Rows: [][]string{
				{"Size", "AvailableQuantity"},
				{"ShareableVersion"},
			},
		},
	)
	sizeVariation.NewAttrs(sizeVariation.EditAttrs())

	product.SearchAttrs("Name", "Code", "Category.Name", "Brand.Name")
	product.IndexAttrs("MainImageURL", "Name", "Featured", "Price", "VersionName", "PublishLiveNow")
	product.EditAttrs(
		&admin.Section{
			Title: "Seo Meta",
			Rows: [][]string{
				{"Seo"},
			}},
		&admin.Section{
			Title: "Basic Information",
			Rows: [][]string{
				{"Name", "Featured"},
				{"Code", "Price"},
				{"MainImage"},
			}},
		&admin.Section{
			Title: "Organization",
			Rows: [][]string{
				{"Category", "Gender"},
				{"Collections"},
			}},
		"ProductProperties",
		"Description",
		"ColorVariations",
		"PublishReady",
	)
	// product.ShowAttrs(product.EditAttrs())
	product.NewAttrs(product.EditAttrs())

	for _, gender := range Genders {
		var gender = gender
		product.Scope(&admin.Scope{Name: gender, Group: "Gender", Handler: func(db *gorm.DB, ctx *qor.Context) *gorm.DB {
			return db.Where("gender = ?", gender)
		}})
	}

	product.Action(&admin.Action{
		Name: "View On Site",
		URL: func(record interface{}, context *admin.Context) string {
			if product, ok := record.(*products.Product); ok {
				return fmt.Sprintf("/products/%v", product.Code)
			}
			return "#"
		},
		Modes: []string{"menu_item", "edit"},
	})

}
804716
func (u *User) Has(key string) bool {
	u.RLock()
	defer u.RUnlock()

	_, ok := u.data[key]
	return ok
}
1199501
func (s *GetDomainDetailOutput) SetAdminPrivacy(v bool) *GetDomainDetailOutput {
	s.AdminPrivacy = &v
	return s
}
37564
func (u *UserStats) GetAdminUsers() int {
	if u == nil || u.AdminUsers == nil {
		return 0
	}
	return *u.AdminUsers
}
343575
func (s *Solr) adminURL(server string) string {
	return fmt.Sprintf("%s%s", server, adminCoresPath)
}
662056
func (e *SyncedEnforcer) HasPermissionForUser(user string, permission ...string) bool {
	e.m.Lock()
	defer e.m.Unlock()
	return e.Enforcer.HasPermissionForUser(user, permission...)
}
243981
func (api *BaseAPI) checkAdmin(backend Backend) error {
	allowed, err := api.Authorizer.HasPermission(permission.AdminAccess, backend.ModelTag())
	if err != nil {
		return errors.Trace(err)
	}
	if !allowed {
		allowed, err = api.Authorizer.HasPermission(permission.SuperuserAccess, backend.ControllerTag())
	}
	if err != nil {
		return errors.Trace(err)
	}
	if !allowed {
		return common.ErrPerm
	}
	return nil
}
1228440
func checkAdminServiceStatusSyntax(ctx *cli.Context) {
	if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
		cli.ShowCommandHelpAndExit(ctx, "status", 1) // last argument is exit code
	}
}
171725
func hasSuperAdminContext(ctx context.Context) bool {
	u, ok := hasUserContext(ctx)
	if !ok {
		return false
	}
	return u.SuperAdmin
}