github.com/Richardknop/go-oauth2-server@v1.0.1/oauth/service.go (about)

     1  package oauth
     2  
     3  import (
     4  	"github.com/RichardKnop/go-oauth2-server/config"
     5  	"github.com/RichardKnop/go-oauth2-server/oauth/roles"
     6  	"github.com/jinzhu/gorm"
     7  )
     8  
     9  // Service struct keeps objects to avoid passing them around
    10  type Service struct {
    11  	cnf          *config.Config
    12  	db           *gorm.DB
    13  	allowedRoles []string
    14  }
    15  
    16  // NewService returns a new Service instance
    17  func NewService(cnf *config.Config, db *gorm.DB) *Service {
    18  	return &Service{
    19  		cnf:          cnf,
    20  		db:           db,
    21  		allowedRoles: []string{roles.Superuser, roles.User},
    22  	}
    23  }
    24  
    25  // GetConfig returns config.Config instance
    26  func (s *Service) GetConfig() *config.Config {
    27  	return s.cnf
    28  }
    29  
    30  // RestrictToRoles restricts this service to only specified roles
    31  func (s *Service) RestrictToRoles(allowedRoles ...string) {
    32  	s.allowedRoles = allowedRoles
    33  }
    34  
    35  // IsRoleAllowed returns true if the role is allowed to use this service
    36  func (s *Service) IsRoleAllowed(role string) bool {
    37  	for _, allowedRole := range s.allowedRoles {
    38  		if role == allowedRole {
    39  			return true
    40  		}
    41  	}
    42  	return false
    43  }
    44  
    45  // Close stops any running services
    46  func (s *Service) Close() {}