From 3c2fd574a6cf6c6fadbe4f6b65ea2b812387374b Mon Sep 17 00:00:00 2001 From: Yang Luo Date: Wed, 6 Sep 2023 18:35:13 +0800 Subject: [PATCH] Refactor GenerateCasToken() --- object/token_cas.go | 72 ++++++++++++++++++++++++++------------------- 1 file changed, 42 insertions(+), 30 deletions(-) diff --git a/object/token_cas.go b/object/token_cas.go index d1490ad8..ef9b6ad7 100644 --- a/object/token_cas.go +++ b/object/token_cas.go @@ -185,38 +185,50 @@ func StoreCasTokenForProxyTicket(token *CasAuthenticationSuccess, targetService, } func GenerateCasToken(userId string, service string) (string, error) { - if user, err := GetUser(userId); err != nil { + user, err := GetUser(userId) + if err != nil { return "", err - } else if user != nil { - authenticationSuccess := CasAuthenticationSuccess{ - User: user.Name, - Attributes: &CasAttributes{ - AuthenticationDate: time.Now(), - UserAttributes: &CasUserAttributes{}, - }, - ProxyGrantingTicket: fmt.Sprintf("PGTIOU-%s", util.GenerateId()), - } - data, _ := json.Marshal(user) - tmp := map[string]string{} - json.Unmarshal(data, &tmp) - for k, v := range tmp { - if v != "" { - authenticationSuccess.Attributes.UserAttributes.Attributes = append(authenticationSuccess.Attributes.UserAttributes.Attributes, &CasNamedAttribute{ - Name: k, - Value: v, - }) - } - } - st := fmt.Sprintf("ST-%d", rand.Int()) - stToServiceResponse.Store(st, &CasAuthenticationSuccessWrapper{ - AuthenticationSuccess: &authenticationSuccess, - Service: service, - UserId: userId, - }) - return st, nil - } else { - return "", fmt.Errorf("invalid user Id") } + if user == nil { + return "", fmt.Errorf("The user: %s doesn't exist", userId) + } + + authenticationSuccess := CasAuthenticationSuccess{ + User: user.Name, + Attributes: &CasAttributes{ + AuthenticationDate: time.Now(), + UserAttributes: &CasUserAttributes{}, + }, + ProxyGrantingTicket: fmt.Sprintf("PGTIOU-%s", util.GenerateId()), + } + + data, err := json.Marshal(user) + if err != nil { + return "", err + } + + tmp := map[string]string{} + err = json.Unmarshal(data, &tmp) + if err != nil { + return "", err + } + + for k, v := range tmp { + if v != "" { + authenticationSuccess.Attributes.UserAttributes.Attributes = append(authenticationSuccess.Attributes.UserAttributes.Attributes, &CasNamedAttribute{ + Name: k, + Value: v, + }) + } + } + + st := fmt.Sprintf("ST-%d", rand.Int()) + stToServiceResponse.Store(st, &CasAuthenticationSuccessWrapper{ + AuthenticationSuccess: &authenticationSuccess, + Service: service, + UserId: userId, + }) + return st, nil } // GetValidationBySaml