github.com/hellofresh/janus@v0.0.0-20230925145208-ce8de8183c67/pkg/jwt/github/team_verifier.go (about)

     1  package github
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"net/http"
     7  )
     8  
     9  // Team represents a github team within the organization
    10  type Team struct {
    11  	Name         string
    12  	Organization string
    13  }
    14  
    15  // TeamVerifier checks if the current user belongs any of the defined teams
    16  type TeamVerifier struct {
    17  	teams        []Team
    18  	gitHubClient Client
    19  }
    20  
    21  // NewTeamVerifier creates a new instance of TeamVerifier
    22  func NewTeamVerifier(teams []Team, gitHubClient Client) *TeamVerifier {
    23  	return &TeamVerifier{
    24  		teams:        teams,
    25  		gitHubClient: gitHubClient,
    26  	}
    27  }
    28  
    29  // Verify makes a check and return a boolean if the check was successful or not
    30  func (v *TeamVerifier) Verify(r *http.Request, httpClient *http.Client) (bool, error) {
    31  	usersOrgTeams, err := v.gitHubClient.Teams(httpClient)
    32  	if err != nil {
    33  		return false, fmt.Errorf("failed to get teams: %w", err)
    34  	}
    35  
    36  	for _, team := range v.teams {
    37  		if teams, ok := usersOrgTeams[team.Organization]; ok {
    38  			for _, teamUserBelongsTo := range teams {
    39  				if teamUserBelongsTo == team.Name {
    40  					return true, nil
    41  				}
    42  			}
    43  		}
    44  	}
    45  
    46  	return false, errors.New("you are not part of the allowed teams")
    47  }