test: add tests for parseClaim

This commit is contained in:
fiftin 2024-03-24 22:08:49 +01:00
parent f31a3500d1
commit 54587b0e07
2 changed files with 63 additions and 4 deletions

View File

@ -429,6 +429,8 @@ type oidcClaimResult struct {
func parseClaim(str string, claims map[string]interface{}) (string, bool) {
for _, s := range strings.Split(str, "|") {
s = strings.TrimSpace(s)
if strings.Contains(s, "{{") {
tpl, err := template.New("").Parse(s)
@ -442,11 +444,13 @@ func parseClaim(str string, claims map[string]interface{}) (string, bool) {
return "", false
}
return email.String(), true
res := email.String()
return res, res != ""
}
res, ok := claims[s].(string)
if ok {
if res != "" && ok {
return res, ok
}
}
@ -465,12 +469,12 @@ func parseClaims(claims map[string]interface{}, provider util.OidcProvider) (res
}
res.username, ok = parseClaim(provider.UsernameClaim, claims)
if !ok || res.username == "" {
if !ok {
res.username = getRandomUsername()
}
res.name, ok = parseClaim(provider.NameClaim, claims)
if !ok || res.name == "" {
if !ok {
res.name = getRandomProfileName()
}

55
api/login_test.go Normal file
View File

@ -0,0 +1,55 @@
package api
import (
"testing"
)
func TestParseClaim(t *testing.T) {
claims := map[string]interface{}{
"username": "fiftin",
"email": "",
"id": 1234567,
}
res, ok := parseClaim("email | {{ .id }}@test.com", claims)
if !ok {
t.Fail()
}
if res != "1234567@test.com" {
t.Fatalf("%s must be %d@test.com", res, claims["id"])
}
}
func TestParseClaim2(t *testing.T) {
claims := map[string]interface{}{
"username": "fiftin",
"email": "",
"id": 1234567,
}
res, ok := parseClaim("username", claims)
if !ok {
t.Fail()
}
if res != claims["username"] {
t.Fail()
}
}
func TestParseClaim3(t *testing.T) {
claims := map[string]interface{}{
"username": "fiftin",
"email": "",
"id": 1234567,
}
_, ok := parseClaim("email", claims)
if ok {
t.Fail()
}
}