github.com/weaviate/weaviate@v1.24.6/usecases/auth/authorization/errors/errors.go (about)

     1  //                           _       _
     2  // __      _____  __ ___   ___  __ _| |_ ___
     3  // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
     4  //  \ V  V /  __/ (_| |\ V /| | (_| | ||  __/
     5  //   \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
     6  //
     7  //  Copyright © 2016 - 2024 Weaviate B.V. All rights reserved.
     8  //
     9  //  CONTACT: hello@weaviate.io
    10  //
    11  
    12  package errors
    13  
    14  import (
    15  	"fmt"
    16  	"strings"
    17  
    18  	"github.com/weaviate/weaviate/entities/models"
    19  )
    20  
    21  // Forbidden indicates a failed authorization
    22  type Forbidden struct {
    23  	principal *models.Principal
    24  	verb      string
    25  	resource  string
    26  }
    27  
    28  // NewForbidden creates an explicit Forbidden error with details about the
    29  // principal and the attempted access on a specific resource
    30  func NewForbidden(principal *models.Principal, verb, resource string) Forbidden {
    31  	return Forbidden{
    32  		principal: principal,
    33  		verb:      verb,
    34  		resource:  resource,
    35  	}
    36  }
    37  
    38  func (f Forbidden) Error() string {
    39  	optionalGroups := ""
    40  	if len(f.principal.Groups) == 1 {
    41  		optionalGroups = fmt.Sprintf(" (of group '%s')", f.principal.Groups[0])
    42  	} else if len(f.principal.Groups) > 1 {
    43  		groups := wrapInSingleQuotes(f.principal.Groups)
    44  		groupsList := strings.Join(groups, ", ")
    45  		optionalGroups = fmt.Sprintf(" (of groups %s)", groupsList)
    46  	}
    47  
    48  	return fmt.Sprintf("forbidden: user '%s'%s has insufficient permissions to %s %s",
    49  		f.principal.Username, optionalGroups, f.verb, f.resource)
    50  }
    51  
    52  func wrapInSingleQuotes(input []string) []string {
    53  	for i, s := range input {
    54  		input[i] = fmt.Sprintf("'%s'", s)
    55  	}
    56  
    57  	return input
    58  }