Commit f8ace0ef authored by Ben Wells's avatar Ben Wells
Browse files

Various simplifications and spelling fixes

parent bfbaf17c
Pipeline #1480 failed with stages
in 31 seconds
package accountmapping
import (
"cloud.google.com/go/datastore"
"context"
"entitlements/common"
"entitlements/models"
......@@ -10,6 +9,8 @@ import (
"strings"
"sync"
"time"
"cloud.google.com/go/datastore"
)
//go:generate mockgen -destination=../mocks/tenant_info.go -package=mocks -imports datatore=cloud.google.com/go/datastore -source=tenant_info.go
......@@ -101,13 +102,13 @@ func (db DbAccessor) refreshTenantInfo() error {
if len(tenants) != len(keys) {
if err != nil {
return errors.New(fmt.Sprintf("Error mapping tenantinfo: %v", err.Error()))
return fmt.Errorf("Error mapping tenantinfo: %v", err.Error())
}
return errors.New("TenantInfo mapping failed.")
}
tenantNameMap = make(map[string]string)
for i, _ := range keys {
for i := range keys {
tenantName := strings.TrimSpace(tenants[i].Name)
tenantNameMap[tenants[i].DataPartitionId] = tenantName
for _, crmId := range tenants[i].CrmAccountID {
......
package api
import (
"entitlements/common"
"entitlements/logging"
"entitlements/middleware"
"entitlements/validation"
"net/http"
"entitlements/common"
"github.com/gorilla/mux"
)
......@@ -29,12 +29,12 @@ func AddRoutes(router *mux.Router, middleware middleware.MiddlewareInterface, va
middleware.AuthzOwner(api.DeleteMember, common.RootUsersGroup, true), []string{common.UsersGroup, common.EntitlementUsersGroup})),
[]func(r *http.Request) error{validators.SingleDataPartitionIdValidator, validators.GroupEmailValidator})))).Methods("DELETE")
if common.FeatureCreateTokenApi == true {
if common.FeatureCreateTokenApi {
router.HandleFunc("/auth/token", logging.Correlate(middleware.MapDataPartitionIds(middleware.PullGroups(middleware.Authz(
authServiceAPI.GetAccessToken, []string{common.UsersGroup, common.EntitlementUsersGroup}))))).Methods("GET")
}
if common.FeatureGroupsByEmail == true {
if common.FeatureGroupsByEmail {
router.HandleFunc("/members/{member_email}/groups", logging.Correlate(middleware.MapDataPartitionIds(middleware.PullGroups(middleware.Authz(
api.ListGroupsByEmail, []string{common.UsersGroup, common.EntitlementAdminsGroup}))))).Methods("GET")
}
......
......@@ -11,7 +11,7 @@ import (
"time"
"google.golang.org/api/admin/directory/v1"
admin "google.golang.org/api/admin/directory/v1"
"github.com/jpillora/backoff"
)
......@@ -38,7 +38,7 @@ func NewGoogleService() *GoogleService {
gAdmin, err := GetGSuiteAdminClient(context.Background())
if err != nil {
logging.WriteLog(err.Error(), logging.LogLevelError)
log.Fatalf("failed to intialize google cloud identity admin client")
log.Fatalf("failed to initialize google cloud identity admin client")
}
return &GoogleService{googleAdmin: gAdmin, backOffRetry: createBackoff()}
}
......@@ -136,9 +136,9 @@ func needExponentialBackoffRetry(backOffRetry *backoff.Backoff, retry int, err e
return false
}
func getGoogleCloudServiceAccount(Service []*admin.Service) *admin.Service {
func getGoogleCloudServiceAccount(service []*admin.Service) *admin.Service {
rand.Seed(time.Now().UTC().UnixNano())
return Service[rand.Intn(common.SuperAdminUsersCount)]
return service[rand.Intn(common.SuperAdminUsersCount)]
}
func isRetryable(retry int, err error) bool {
......
......@@ -12,7 +12,7 @@ import (
"cloud.google.com/go/storage"
"golang.org/x/oauth2/google"
"google.golang.org/api/admin/directory/v1"
admin "google.golang.org/api/admin/directory/v1"
"google.golang.org/api/option"
)
......@@ -22,7 +22,7 @@ func GetGSuiteAdminClient(ctx context.Context) ([]*admin.Service, error) {
storageClient, err := storage.NewClient(ctx, option.WithCredentialsFile(common.StorageClientFile))
if err != nil {
logging.WriteLog(err.Error(), logging.LogLevelError)
log.Printf("Error occured while retrieving storage client: %v", err)
log.Printf("Error occurred while retrieving storage client: %v", err)
return nil, err
}
......@@ -34,7 +34,7 @@ func GetGSuiteAdminClient(ctx context.Context) ([]*admin.Service, error) {
rc, err := storageClient.Bucket(common.EntitlementBucket).Object(common.EntitlementServiceAccountFile).NewReader(ctx)
if err != nil {
logging.WriteLog(err.Error(), logging.LogLevelError)
log.Printf("Error occured while retrieving new reader: %v", err)
log.Printf("Error occurred while retrieving new reader: %v", err)
return nil, err
}
......@@ -42,7 +42,7 @@ func GetGSuiteAdminClient(ctx context.Context) ([]*admin.Service, error) {
err = rc.Close()
if err != nil {
logging.WriteLog(err.Error(), logging.LogLevelError)
log.Printf("Internal error occured when closing the connection: %v", err)
log.Printf("Internal error occurred when closing the connection: %v", err)
}
}()
b, err := ioutil.ReadAll(rc)
......
......@@ -7,9 +7,10 @@ import (
"entitlements/utility"
"errors"
"fmt"
"time"
"github.com/dgrijalva/jwt-go"
"gopkg.in/square/go-jose.v2"
"time"
"bytes"
"entitlements/common"
......@@ -30,7 +31,7 @@ type TokenService struct {
}
// NewTokenService initializes SAuth token service
func NewTokenService( httpClientWrapper httpwrapper.HttpRequest, redisClient redis.Cache) TokenIssuer {
func NewTokenService(httpClientWrapper httpwrapper.HttpRequest, redisClient redis.Cache) TokenIssuer {
return TokenService{client: httpClientWrapper, redisClient: redisClient}
}
......@@ -64,7 +65,7 @@ func (tksvc TokenService) GetEmailIdentityFromJwt(tokenString string) (string, s
logging.WriteLog(fmt.Sprintf("%s: %s", msg, tokenString), logging.LogLevelError)
return nil, errors.New(msg)
})
if err != nil{
if err != nil {
return "", "", err
}
var emailField string
......@@ -87,7 +88,7 @@ func (tksvc TokenService) getPublicKey(kid string) (*rsa.PublicKey, error) {
return rsaPublicKey, nil
}
publicKeyMap := make(map[string]interface{}, 0)
publicKeyMap := make(map[string]interface{})
err := tksvc.getPublicKeyMap(common.GoogleJWKUri, &publicKeyMap)
if err != nil {
return nil, err
......@@ -103,7 +104,7 @@ func (tksvc TokenService) getPublicKey(kid string) (*rsa.PublicKey, error) {
rsaPublicKey := marshalRsaKey(keyBytes)
return rsaPublicKey, nil
} else {
return nil, errors.New(fmt.Sprintf("Not found public key by the given kid: %s", kid))
return nil, fmt.Errorf("Not found public key by the given kid: %s", kid)
}
}
......@@ -133,7 +134,7 @@ func (tksvc TokenService) getPublicKeyMap(jwkUri string, publicKeyMap *map[strin
func unmarshalBytesToMap(object_bytes []byte) map[string]interface{} {
var map_object map[string]interface{}
if object_bytes == nil || len(object_bytes) == 0 {
if len(object_bytes) == 0 {
return map_object
}
json_decoder := jsonDecoder(object_bytes)
......
......@@ -2,13 +2,14 @@ package jwt
import (
"entitlements/common"
"entitlements/logging"
"entitlements/utility"
"errors"
"github.com/gorilla/context"
"net/http"
"strings"
"entitlements/utility"
"github.com/dgrijalva/jwt-go"
"entitlements/logging"
"github.com/gorilla/context"
)
func ExtractBearerToken(r *http.Request, headerName string) (string, error) {
......@@ -64,8 +65,8 @@ func extractFieldFromToken(token *jwt.Token, fieldName string) (string, error) {
if token.Claims != nil {
field, ok := token.Claims.(jwt.MapClaims)[fieldName].(string)
if ok == false || len(field) == 0 {
return "", errors.New(msg+". "+fieldName+" not found in token")
if !ok || len(field) == 0 {
return "", errors.New(msg + ". " + fieldName + " not found in token")
}
logging.WriteLog(fieldName+" is extracted from the token with value "+field, logging.LogLevelInfo)
return field, nil
......
......@@ -118,9 +118,7 @@ func (r *Client) ScanKeys(keyword string, dbindex int) ([]string, error) {
} else {
iter, _ = redis.Int(arr[0], nil)
keys, _ := redis.Strings(arr[1], nil)
for _, key := range keys {
foundKeys = append(foundKeys, key)
}
foundKeys = append(foundKeys, keys...)
}
if iter == 0 {
break
......
......@@ -10,10 +10,11 @@ import (
"entitlements/redis"
"entitlements/utility"
"fmt"
"google.golang.org/api/admin/directory/v1"
"log"
"net/http"
"strings"
admin "google.golang.org/api/admin/directory/v1"
)
// EntitlementsServiceInterface interface
......@@ -39,7 +40,7 @@ type EntitlementsService struct {
func NewEntitlementsService(cache redis.OperationsInterface, mapper mapping.IdentityMapper) *EntitlementsService {
gAdmin := domain.NewGoogleService()
if gAdmin == nil {
log.Println("failed to intialize google cloud IAM client")
log.Println("failed to initialize google cloud IAM client")
return nil
}
return &EntitlementsService{gAdmin, cache, mapper}
......
package utility
import (
"fmt"
"net/http"
"github.com/gorilla/context"
"fmt"
)
type (
AuditAction string
AuditStatus string
AuditAction string
AuditStatus string
AuditActionID string
)
......@@ -28,30 +29,30 @@ const (
)
const (
ListGroupActionID AuditActionID = "ET001"
ListGroupMessageSuccess string = "List group success"
ListGroupActionID AuditActionID = "ET001"
ListGroupMessageSuccess string = "List group success"
CreateGroupActionID AuditActionID = "ET002"
CreateGroupMessageSuccess string = "Create group success"
CreateGroupMessageFailure string = "Create group failure"
CreateGroupActionID AuditActionID = "ET002"
CreateGroupMessageSuccess string = "Create group success"
CreateGroupMessageFailure string = "Create group failure"
ListMemberActionID AuditActionID = "ET003"
ListMemberMessageSuccess string = "List member success"
ListMemberMessageFailure string = "List member failure"
ListMemberActionID AuditActionID = "ET003"
ListMemberMessageSuccess string = "List member success"
ListMemberMessageFailure string = "List member failure"
CreateMemberActionID AuditActionID = "ET004"
CreateMemberMessageSuccess string = "Create member success"
CreateMemberMessageFailure string = "Create member failure"
CreateMemberActionID AuditActionID = "ET004"
CreateMemberMessageSuccess string = "Create member success"
CreateMemberMessageFailure string = "Create member failure"
DeleteMemberActionID AuditActionID = "ET005"
DeleteMemberMessageSuccess string = "Delete member success"
DeleteMemberMessageFailure string = "Delete member failure"
DeleteMemberActionID AuditActionID = "ET005"
DeleteMemberMessageSuccess string = "Delete member success"
DeleteMemberMessageFailure string = "Delete member failure"
AuthorizationActionID AuditActionID = "ET006"
AuthorizeUserFailure string = "User is not authorized"
AuthorizationActionID AuditActionID = "ET006"
AuthorizeUserFailure string = "User is not authorized"
ValidationActionID AuditActionID = "ET007"
ValidationDomainFailure string = "Domain is mismatched"
ValidationActionID AuditActionID = "ET007"
ValidationDomainFailure string = "Domain is mismatched"
CreateAccessTokenActionID AuditActionID = "ET008"
CreateAccessTokenMessageSuccess string = "Create access token success"
......@@ -79,7 +80,7 @@ type AuditResource struct {
func GetAuditInfo(request *http.Request) (interface{}, error) {
output, ok := context.GetOk(request, contextAuditInfoKey)
if ok != true {
if !ok {
return nil, fmt.Errorf("no auditInfo in request")
}
return output.(AuditInfo), nil
......
......@@ -14,6 +14,7 @@ import (
"strings"
"fmt"
"github.com/gorilla/context"
"github.com/gorilla/mux"
"google.golang.org/api/googleapi"
......@@ -119,7 +120,7 @@ func DecodeBody(r *http.Request, o interface{}) error {
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&o)
if err != nil {
return errors.New(fmt.Sprintf("Invalid request body: %v", err.Error()))
return fmt.Errorf("Invalid request body: %v", err.Error())
}
return nil
}
......@@ -69,14 +69,12 @@ func TestWriteResponse(t *testing.T) {
})
}
func TestRedirectHttps(t *testing.T) {
g := goblin.Goblin(t)
handlerFunct := http.HandlerFunc(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handlerFunct := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusAccepted)
}))
})
g.Describe("Redirect https", func() {
g.It("Should return StatusPermanentRedirect", func() {
......@@ -87,7 +85,7 @@ func TestRedirectHttps(t *testing.T) {
req.Header.Set("x-forwarded-proto", "http")
rr := httptest.NewRecorder()
handler := http.Handler(RedirectToHttps(handlerFunct))
handler := RedirectToHttps(handlerFunct)
handler.ServeHTTP(rr, req)
g.Assert(rr.Code).Equal(http.StatusFound)
})
......@@ -99,7 +97,7 @@ func TestRedirectHttps(t *testing.T) {
}
req.Header.Set("x-forwarded-proto", "https")
rr := httptest.NewRecorder()
handler := http.Handler(RedirectToHttps(handlerFunct))
handler := RedirectToHttps(handlerFunct)
handler.ServeHTTP(rr, req)
g.Assert(rr.Code).Equal(http.StatusAccepted)
})
......
......@@ -2,8 +2,8 @@ package utility
import (
"entitlements/common"
"strings"
"errors"
"strings"
)
// StringInSlice returns whether a string is in a given slice
......@@ -16,7 +16,6 @@ func StringInSlice(a string, list []string) bool {
return false
}
// AppendGroupIfMissing appends the value if missing
func AppendGroupIfMissing(slice []*common.GroupResponse, g *common.GroupResponse) []*common.GroupResponse {
......@@ -45,7 +44,7 @@ func RemoveDuplicateString(elements []string) []string {
result := make([]string, 0)
for v := range elements {
if encountered[elements[v]] == false {
if !encountered[elements[v]] {
encountered[elements[v]] = true
result = append(result, elements[v])
}
......@@ -57,7 +56,7 @@ func NormalizeKey(key string) string {
return strings.TrimSpace(strings.ToLower(key))
}
func FilterGroups(groupList []*common.GroupResponse, filter string) ([]*common.GroupResponse,error){
func FilterGroups(groupList []*common.GroupResponse, filter string) ([]*common.GroupResponse, error) {
var filteredGroups []*common.GroupResponse
filter = common.FilterTypes[NormalizeKey(filter)]
if filter == "" {
......@@ -65,9 +64,9 @@ func FilterGroups(groupList []*common.GroupResponse, filter string) ([]*common.G
}
for _, group := range groupList {
if strings.HasPrefix(group.Email, filter){
if strings.HasPrefix(group.Email, filter) {
filteredGroups = append(filteredGroups, group)
}
}
return filteredGroups, nil
}
\ No newline at end of file
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment