// hasGrant is current user is covered by any given grants.
765357
func hasGrant(c context.Context, grantsList ...[]string) (bool, error) {
	currentIdentity := auth.CurrentIdentity(c)
	var groups []string
	for _, grants := range grantsList {
		for _, grant := range grants {
			if strings.HasPrefix(grant, "group:") {
				groups = append(groups, grant[len("group:"):])
				continue
			}
			grantedIdentity := identity.Identity(grant)
			if !strings.ContainsRune(grant, ':') {
				// Just email.
				grantedIdentity = identity.Identity("user:" + grant)
			}
			if grantedIdentity == currentIdentity {
				return true, nil
			}
		}
	}
	if isMember, err := auth.IsMember(c, groups...); err != nil {
		return false, transient.Tag.Apply(err)
	} else {
		return isMember, nil
	}
}
624074
func hasPermissionToDir(info os.FileInfo) bool {
	user, err := user.Current()
	if err != nil {
		return true
	}
	uid, _ := strconv.Atoi(user.Uid)
	// super-user
	if uid == 0 {
		return true
	}

	st, _ := info.Sys().(*syscall.Stat_t)
	if st == nil {
		return true
	}
	perm := info.Mode().Perm()
	// user (u)
	if perm&0100 != 0 && st.Uid == uint32(uid) {
		return true
	}

	gid, _ := strconv.Atoi(user.Gid)
	// other users in group (g)
	if perm&0010 != 0 && st.Uid != uint32(uid) && st.Gid == uint32(gid) {
		return true
	}
	// remaining users (o)
	if perm&0001 != 0 && st.Uid != uint32(uid) && st.Gid != uint32(gid) {
		return true
	}

	return false
}
1085368
func (u *Client) PasswordGrant(clientId, clientSecret, username, password string) (string, string, error) {
	values := url.Values{
		"grant_type":    {"password"},
		"response_type": {"token"},
		"username":      {username},
		"password":      {password},
		"client_id":     {clientId},
		"client_secret": {clientSecret},
	}

	token, err := u.tokenGrantRequest(values)

	return token.AccessToken, token.RefreshToken, err
}
449329
func (c *Config) HasCertAuth() bool {
	return len(c.TLS.CertData) != 0 || len(c.TLS.CertFile) != 0
}
846765
func (o *InvitationManager) HasInvite(globalid string, username string) (hasInvite bool, err error) {
	count, err := o.collection.Find(bson.M{"organization": globalid, "user": username}).Count()
	return count != 0, err
}
919539
func (emptyGrant) GrantNeeded(user user.Info, grant *api.Grant, w http.ResponseWriter, req *http.Request) (bool, bool, error) {
	return false, false, nil
}
353411
func (o *Ownership) IsPermitted(
	user *auth.UserInfo,
	accessType Ownership_AccessType,
) bool {
	// There is no owner, so it is a public resource
	if o.IsPublic() {
		return true
	}

	// If we are missing user information then do not allow.
	// It is ok for the the user claims to have an empty Groups setting
	if user == nil ||
		len(user.Username) == 0 {
		return false
	}

	if o.IsOwner(user) ||
		o.IsUserAllowedByGroup(user, accessType) ||
		o.IsUserAllowedByCollaborators(user, accessType) {
		return true
	}

	return false
}
971154
func (meta Meta) HasPermission(mode roles.PermissionMode, context *qor.Context) bool {
	if meta.Permission == nil {
		return true
	}
	var roles = []interface{}{}
	for _, role := range context.Roles {
		roles = append(roles, role)
	}
	return meta.Permission.HasPermission(mode, roles...)
}
952081
func ToGrant(username string, perm chronograf.Permission) string {
	if len(perm.Allowed) == 0 {
		return ""
	}
	return ToInfluxQL("GRANT", "TO", username, perm)
}
581426
func (c Claims) Has(key string) bool {
	return jwt.Claims(c).Has(key)
}
897404
func (g *autoGrant) GrantNeeded(user user.Info, grant *api.Grant, w http.ResponseWriter, req *http.Request) (bool, bool, error) {
	return true, false, nil
}
632166
func (state *ServicesState) HasServer(hostname string) bool {
	_, ok := state.Servers[hostname]
	return ok
}
351470
func (g *redirectGrant) GrantNeeded(user user.Info, grant *api.Grant, w http.ResponseWriter, req *http.Request) (bool, bool, error) {
	_, lastSegment := path.Split(req.URL.Path)

	// We're going to descend one dir for the approve endpoint.
	// Make our "then" URL a relative backstep, so we can return to this URL (with no trailing slash) even via an auth proxy.
	// Depends on any auth proxies matching the last segment of the URL we used to get here, proxying subpaths of this URL, and passing through the complete query.
	// Example:
	//   User -> https://auth.example.com/foo/oauth/authorize?... -> https://api.example.com/oauth/authorize?...
	//        <- Location: authorize/approve?then=../authorize?...
	//   User -> https://auth.example.com/foo/oauth/authorize/approve?then=../authorize?...
	//           submits grant approval form, gets redirected to 'then' URL
	//        <- Location: ../authorize?...
	//   User -> https://auth.example.com/foo/oauth/authorize?...
	reqURL := &(*req.URL)
	reqURL.Host = ""
	reqURL.Scheme = ""
	reqURL.Path = path.Join("..", lastSegment)

	// Make our redirect URL a relative redirect to the subpath
	redirectURL := &url.URL{
		Path: path.Join(lastSegment, g.subpath),
		RawQuery: url.Values{
			"then":         {reqURL.String()},
			"client_id":    {grant.Client.GetId()},
			"scope":        {grant.Scope},
			"redirect_uri": {grant.RedirectURI},
		}.Encode(),
	}
	w.Header().Set("Location", redirectURL.String())
	w.WriteHeader(http.StatusFound)
	return false, true, nil
}
281805
func (r *MintOAuthTokenViaGrantRPC) MintOAuthTokenViaGrant(c context.Context, req *minter.MintOAuthTokenViaGrantRequest) (*minter.MintOAuthTokenViaGrantResponse, error) {
	state := auth.GetState(c)

	// Don't allow delegation tokens here to reduce total number of possible
	// scenarios. Proxies aren't expected to use delegation for these tokens.
	callerID := state.User().Identity
	if callerID != state.PeerIdentity() {
		logging.Errorf(c, "Trying to use delegation, it's forbidden")
		return nil, status.Errorf(codes.PermissionDenied, "delegation is forbidden for this API call")
	}

	// Prevent GrantToken from leaking into the logs.
	reqcpy := *req
	if reqcpy.GrantToken != "" {
		reqcpy.GrantToken = "..."
	}
	utils.LogRequest(c, r, &reqcpy, callerID)

	if err := utils.ValidateAndNormalizeRequest(c, req.OauthScope, &req.MinValidityDuration, req.AuditTags); err != nil {
		if status.Code(err) == codes.Unknown {
			return nil, status.Errorf(codes.InvalidArgument, "invalid request: %q", err)
		}
		return nil, err
	}
	grantBody, rule, err := r.validateRequest(c, req, callerID)
	if err != nil {
		// err was already logged.
		return nil, err
	}

	accessTok, err := r.MintAccessToken(c, auth.MintAccessTokenParams{
		ServiceAccount: grantBody.ServiceAccount,
		Scopes:         req.OauthScope,
		MinTTL:         time.Duration(req.MinValidityDuration) * time.Second,
	})
	if err != nil {
		logging.WithError(err).Errorf(c, "Failed to mint oauth token for %q", grantBody.ServiceAccount)
		code := codes.InvalidArgument // mostly likely misconfigured IAM roles
		if transient.Tag.In(err) {
			code = codes.Internal
		}
		return nil, status.Errorf(code, "failed to mint oauth token for %q - %s", grantBody.ServiceAccount, err)
	}

	// Grab a string that identifies token server version. This almost always
	// just hits local memory cache.
	serviceVer, err := utils.ServiceVersion(c, r.Signer)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "can't grab service version - %s", err)
	}

	// The RPC response.
	resp := &minter.MintOAuthTokenViaGrantResponse{
		AccessToken:    accessTok.AccessToken,
		Expiry:         google.NewTimestamp(accessTok.Expiry),
		ServiceVersion: serviceVer,
	}

	// Log it to BigQuery.
	if r.LogOAuthToken != nil {
		// Errors during logging are considered not fatal. bqlog library has
		// a monitoring counter that tracks number of errors, so they are not
		// totally invisible.
		info := MintedOAuthTokenInfo{
			RequestedAt: clock.Now(c),
			Request:     req,
			Response:    resp,
			GrantBody:   grantBody,
			ConfigRev:   rule.Revision,
			Rule:        rule.Rule,
			PeerIP:      state.PeerIP(),
			RequestID:   info.RequestID(c),
			AuthDBRev:   authdb.Revision(state.DB()),
		}
		if logErr := r.LogOAuthToken(c, &info); logErr != nil {
			logging.WithError(logErr).Errorf(c, "Failed to insert the oauth token into the BigQuery log")
		}
	}

	return resp, nil
}
396746
func getGrants(username, clientID string, r *http.Request) ([]string, error) {

	// Add grants
	grantMgr := grants.NewManager(r)
	rawGrants, err := grantMgr.GetGrantsForUser(username, clientID)
	if err != nil && !db.IsNotFound(err) {
		return nil, err
	}
	if err != nil {
		rawGrants = &grants.SavedGrants{Grants: []grants.Grant{}}
	}

	fullGrants := make([]string, len(rawGrants.Grants))
	for i, g := range rawGrants.Grants {
		fullGrants[i] = grants.FullName(g)
	}

	log.Debug("Found ", len(fullGrants), " grant(s)")
	return fullGrants, nil
}
561847
func (s *CreateSnapshotCopyGrantOutput) SetSnapshotCopyGrant(v *SnapshotCopyGrant) *CreateSnapshotCopyGrantOutput {
	s.SnapshotCopyGrant = v
	return s
}
873765
func (s *SeesawEngine) HAState(args *ipc.HAState, reply *int) error {
	if args == nil {
		return errors.New("args is nil")
	}
	ctx := args.Ctx
	s.trace("HAState", ctx)
	if ctx == nil {
		return errors.New("context is nil")
	}

	if !ctx.IsTrusted() {
		return errors.New("insufficient access")
	}

	s.engine.setHAState(args.State)
	return nil
}