forked from baron/baron-sso
feat(user): support fixed UUID registration and enhance bulk import results
- Added support for fixed UUIDs during bulk registration (Search-first + ExternalID mapping) - Implemented idempotency and visibility restoration for soft-deleted users - Enhanced bulk upload UI to show 'New/Updated/Unchanged' status and modified fields - Added logic to reclaim identifiers (login_id) from colliding records - Added frontend E2E and backend unit tests for UUID integrity and conflict handling - Fixed i18n, formatting, and mock tests to satisfy code-check - Applied 'go fix' for 'omitzero' tags and general Go standards
This commit is contained in:
@@ -26,7 +26,7 @@ func TestApiKeyHandler_CreateApiKey(t *testing.T) {
|
||||
|
||||
app.Post("/api-keys", h.CreateApiKey)
|
||||
|
||||
input := map[string]interface{}{
|
||||
input := map[string]any{
|
||||
"name": "M2M Test",
|
||||
"scopes": []string{"read", "write"},
|
||||
}
|
||||
@@ -47,7 +47,7 @@ func TestApiKeyHandler_Validation(t *testing.T) {
|
||||
app.Post("/api-keys", h.CreateApiKey)
|
||||
|
||||
// Missing name
|
||||
input := map[string]interface{}{
|
||||
input := map[string]any{
|
||||
"scopes": []string{"read"},
|
||||
}
|
||||
body, _ := json.Marshal(input)
|
||||
@@ -65,7 +65,7 @@ func TestApiKeyHandler_UpdateApiKeyScopesRequiresDatabase(t *testing.T) {
|
||||
|
||||
app.Patch("/api-keys/:id", h.UpdateApiKey)
|
||||
|
||||
body, _ := json.Marshal(map[string]interface{}{
|
||||
body, _ := json.Marshal(map[string]any{
|
||||
"scopes": []string{"org-context:read"},
|
||||
})
|
||||
req := httptest.NewRequest("PATCH", "/api-keys/api-key-id", bytes.NewReader(body))
|
||||
|
||||
@@ -16,11 +16,13 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"math/rand"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -601,7 +603,7 @@ func (h *AuthHandler) GetActiveTenants(c *fiber.Ctx) error {
|
||||
email := c.Query("email")
|
||||
if email == "" {
|
||||
// No email provided, return empty list (Security policy)
|
||||
return c.JSON([]interface{}{})
|
||||
return c.JSON([]any{})
|
||||
}
|
||||
|
||||
// 1. Verify Verification Status in Redis
|
||||
@@ -615,7 +617,7 @@ func (h *AuthHandler) GetActiveTenants(c *fiber.Ctx) error {
|
||||
// 2. Extract domain from verified email
|
||||
parts := strings.Split(email, "@")
|
||||
if len(parts) != 2 {
|
||||
return c.JSON([]interface{}{})
|
||||
return c.JSON([]any{})
|
||||
}
|
||||
domainName := parts[1]
|
||||
|
||||
@@ -623,7 +625,7 @@ func (h *AuthHandler) GetActiveTenants(c *fiber.Ctx) error {
|
||||
isInternal, _ := h.isAffiliateTenant(c.Context(), domainName)
|
||||
if !isInternal {
|
||||
// If not an affiliate email, do not show any tenants
|
||||
return c.JSON([]interface{}{})
|
||||
return c.JSON([]any{})
|
||||
}
|
||||
|
||||
// 3. List and Filter Tenants
|
||||
@@ -785,7 +787,7 @@ func (h *AuthHandler) Signup(c *fiber.Ctx) error {
|
||||
slog.Info("[Signup] Phone normalization", "raw", req.Phone, "normalized", normalizedPhone)
|
||||
|
||||
// IDP에 전달할 BrokerUser 스키마 구성
|
||||
attributes := map[string]interface{}{
|
||||
attributes := map[string]any{
|
||||
"department": req.Department,
|
||||
"affiliationType": req.AffiliationType,
|
||||
"grade": "",
|
||||
@@ -854,9 +856,7 @@ func (h *AuthHandler) Signup(c *fiber.Ctx) error {
|
||||
|
||||
// Merge metadata
|
||||
localUser.Metadata = make(domain.JSONMap)
|
||||
for k, v := range req.Metadata {
|
||||
localUser.Metadata[k] = v
|
||||
}
|
||||
maps.Copy(localUser.Metadata, req.Metadata)
|
||||
|
||||
if h.UserRepo != nil {
|
||||
go func(u *domain.User, ids []domain.UserLoginID) {
|
||||
@@ -915,7 +915,7 @@ func (h *AuthHandler) getBearerToken(c *fiber.Ctx) string {
|
||||
}
|
||||
|
||||
func firstForwardedValue(raw string) string {
|
||||
for _, part := range strings.Split(raw, ",") {
|
||||
for part := range strings.SplitSeq(raw, ",") {
|
||||
value := strings.TrimSpace(part)
|
||||
if value != "" {
|
||||
return value
|
||||
@@ -925,8 +925,8 @@ func firstForwardedValue(raw string) string {
|
||||
}
|
||||
|
||||
func forwardedDirective(raw, key string) string {
|
||||
for _, group := range strings.Split(raw, ",") {
|
||||
for _, directive := range strings.Split(group, ";") {
|
||||
for group := range strings.SplitSeq(raw, ",") {
|
||||
for directive := range strings.SplitSeq(group, ";") {
|
||||
pair := strings.SplitN(strings.TrimSpace(directive), "=", 2)
|
||||
if len(pair) != 2 {
|
||||
continue
|
||||
@@ -1075,9 +1075,9 @@ func (h *AuthHandler) GetTenantInfo(c *fiber.Ctx) error {
|
||||
if loginIdField, ok := tenant.Config["loginIdField"].(string); ok && loginIdField != "" {
|
||||
res["loginIdField"] = loginIdField
|
||||
// Find label in userSchema
|
||||
if schema, ok := tenant.Config["userSchema"].([]interface{}); ok {
|
||||
if schema, ok := tenant.Config["userSchema"].([]any); ok {
|
||||
for _, field := range schema {
|
||||
if f, ok := field.(map[string]interface{}); ok {
|
||||
if f, ok := field.(map[string]any); ok {
|
||||
if f["key"] == loginIdField {
|
||||
res["loginIdLabel"] = f["label"]
|
||||
break
|
||||
@@ -1215,9 +1215,7 @@ func buildOidcClaimsFromTraits(traits map[string]any, scopes []string, tenantID
|
||||
if includeTenantDetails {
|
||||
// tenant 스코프가 있을 때만 대표소속 namespace metadata를 top-level claim으로 펼칩니다.
|
||||
if namespaced, ok := traits[tenantID].(map[string]any); ok {
|
||||
for k, v := range namespaced {
|
||||
claims[k] = v
|
||||
}
|
||||
maps.Copy(claims, namespaced)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1570,7 +1568,7 @@ func tenantClaimAncestorSummaries(ancestors []*domain.Tenant) []map[string]any {
|
||||
return items
|
||||
}
|
||||
|
||||
func applyConfiguredIDTokenClaims(baseClaims map[string]any, metadata map[string]interface{}) map[string]any {
|
||||
func applyConfiguredIDTokenClaims(baseClaims map[string]any, metadata map[string]any) map[string]any {
|
||||
if baseClaims == nil {
|
||||
baseClaims = map[string]any{}
|
||||
}
|
||||
@@ -1670,7 +1668,7 @@ func (h *AuthHandler) withRPProfileClaims(ctx context.Context, claims map[string
|
||||
claims["rp_profiles"] = append(existing, profile)
|
||||
return claims
|
||||
}
|
||||
if existing, ok := claims["rp_profiles"].([]interface{}); ok {
|
||||
if existing, ok := claims["rp_profiles"].([]any); ok {
|
||||
claims["rp_profiles"] = append(existing, profile)
|
||||
return claims
|
||||
}
|
||||
@@ -1678,7 +1676,7 @@ func (h *AuthHandler) withRPProfileClaims(ctx context.Context, claims map[string
|
||||
return claims
|
||||
}
|
||||
|
||||
func extractClaimEnabledCustomUserSchemaKeys(metadata map[string]interface{}) []string {
|
||||
func extractClaimEnabledCustomUserSchemaKeys(metadata map[string]any) []string {
|
||||
if metadata == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -1687,12 +1685,12 @@ func extractClaimEnabledCustomUserSchemaKeys(metadata map[string]interface{}) []
|
||||
return nil
|
||||
}
|
||||
|
||||
var items []interface{}
|
||||
var items []any
|
||||
switch schema := rawSchema.(type) {
|
||||
case []interface{}:
|
||||
case []any:
|
||||
items = schema
|
||||
case []map[string]interface{}:
|
||||
items = make([]interface{}, 0, len(schema))
|
||||
case []map[string]any:
|
||||
items = make([]any, 0, len(schema))
|
||||
for _, item := range schema {
|
||||
items = append(items, item)
|
||||
}
|
||||
@@ -1703,7 +1701,7 @@ func extractClaimEnabledCustomUserSchemaKeys(metadata map[string]interface{}) []
|
||||
keys := make([]string, 0, len(items))
|
||||
seen := make(map[string]struct{})
|
||||
for _, item := range items {
|
||||
field, ok := item.(map[string]interface{})
|
||||
field, ok := item.(map[string]any)
|
||||
if !ok {
|
||||
if typed, typedOK := item.(map[string]any); typedOK {
|
||||
field = typed
|
||||
@@ -4275,11 +4273,11 @@ func (h *AuthHandler) ScanQRLogin(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
type kratosCourierRequest struct {
|
||||
Recipient string `json:"recipient"`
|
||||
TemplateType string `json:"template_type"`
|
||||
TemplateData map[string]interface{} `json:"template_data"`
|
||||
Subject string `json:"subject"`
|
||||
Body string `json:"body"`
|
||||
Recipient string `json:"recipient"`
|
||||
TemplateType string `json:"template_type"`
|
||||
TemplateData map[string]any `json:"template_data"`
|
||||
Subject string `json:"subject"`
|
||||
Body string `json:"body"`
|
||||
}
|
||||
|
||||
// HandleKratosCourierRelay - Kratos courier HTTP 요청을 받아 메일/SMS 발송으로 변환합니다.
|
||||
@@ -4604,7 +4602,7 @@ func (h *AuthHandler) isSmsCodeOnly(loginID string) bool {
|
||||
|
||||
func (h *AuthHandler) generateShortCode(code string) string {
|
||||
const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
for i := 0; i < 10; i++ {
|
||||
for range 10 {
|
||||
b := make([]byte, 2)
|
||||
if _, err := crand.Read(b); err != nil {
|
||||
break
|
||||
@@ -4646,7 +4644,7 @@ func firstNonEmpty(values ...string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func extractFirstString(data map[string]interface{}, keys ...string) string {
|
||||
func extractFirstString(data map[string]any, keys ...string) string {
|
||||
if data == nil {
|
||||
return ""
|
||||
}
|
||||
@@ -5229,10 +5227,7 @@ func (h *AuthHandler) GetAuthTimeline(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
candidates := buildLoginCandidates(profile)
|
||||
fetchLimit := limit * 10
|
||||
if fetchLimit < limit {
|
||||
fetchLimit = limit
|
||||
}
|
||||
fetchLimit := max(limit*10, limit)
|
||||
if fetchLimit > 500 {
|
||||
fetchLimit = 500
|
||||
}
|
||||
@@ -5805,9 +5800,9 @@ func (h *AuthHandler) ListLinkedRps(c *fiber.Ctx) error {
|
||||
}
|
||||
for _, log := range auditLogs {
|
||||
var details struct {
|
||||
ClientID string `json:"client_id"`
|
||||
ClientName string `json:"client_name"`
|
||||
Scopes interface{} `json:"scopes"`
|
||||
ClientID string `json:"client_id"`
|
||||
ClientName string `json:"client_name"`
|
||||
Scopes any `json:"scopes"`
|
||||
}
|
||||
// 로그 Details 파싱
|
||||
if err := json.Unmarshal([]byte(log.Details), &details); err != nil {
|
||||
@@ -5824,7 +5819,7 @@ func (h *AuthHandler) ListLinkedRps(c *fiber.Ctx) error {
|
||||
|
||||
// 스코프 추출 (consent.granted인 경우)
|
||||
scopes := []string{}
|
||||
if sList, ok := details.Scopes.([]interface{}); ok {
|
||||
if sList, ok := details.Scopes.([]any); ok {
|
||||
for _, s := range sList {
|
||||
if str, ok := s.(string); ok {
|
||||
scopes = append(scopes, str)
|
||||
@@ -5927,7 +5922,7 @@ func (h *AuthHandler) RevokeLinkedRp(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
if h.AuditRepo != nil {
|
||||
detailsMap := map[string]interface{}{
|
||||
detailsMap := map[string]any{
|
||||
"client_id": clientID,
|
||||
}
|
||||
detailsBytes, _ := json.Marshal(detailsMap)
|
||||
@@ -6085,7 +6080,7 @@ func (h *AuthHandler) GetConsentRequest(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
if h.AuditRepo != nil {
|
||||
detailsMap := map[string]interface{}{
|
||||
detailsMap := map[string]any{
|
||||
"client_id": consentRequest.Client.ClientID,
|
||||
"scopes": consentRequest.RequestedScope,
|
||||
"client_name": consentRequest.Client.ClientName,
|
||||
@@ -6135,12 +6130,12 @@ func (h *AuthHandler) GetConsentRequest(c *fiber.Ctx) error {
|
||||
// structured_scopes 파싱 및 scope_details 생성
|
||||
if metadata := consentRequest.Client.Metadata; metadata != nil {
|
||||
if rawScopes, ok := metadata["structured_scopes"]; ok {
|
||||
scopeDetails := make(map[string]map[string]interface{})
|
||||
scopeDetails := make(map[string]map[string]any)
|
||||
|
||||
// JSON 언마샬링 등을 통해 map[string]interface{} 또는 []interface{}로 들어옴
|
||||
// 안전하게 처리
|
||||
rawBytes, _ := json.Marshal(rawScopes)
|
||||
var scopesList []map[string]interface{}
|
||||
var scopesList []map[string]any
|
||||
if err := json.Unmarshal(rawBytes, &scopesList); err == nil {
|
||||
for _, item := range scopesList {
|
||||
name, _ := item["name"].(string)
|
||||
@@ -6150,7 +6145,7 @@ func (h *AuthHandler) GetConsentRequest(c *fiber.Ctx) error {
|
||||
desc, _ := item["description"].(string)
|
||||
mandatory, _ := item["mandatory"].(bool)
|
||||
|
||||
scopeDetails[name] = map[string]interface{}{
|
||||
scopeDetails[name] = map[string]any{
|
||||
"description": desc,
|
||||
"mandatory": mandatory,
|
||||
}
|
||||
@@ -6280,7 +6275,7 @@ func (h *AuthHandler) AcceptConsentRequest(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
if h.AuditRepo != nil {
|
||||
detailsMap := map[string]interface{}{
|
||||
detailsMap := map[string]any{
|
||||
"client_id": consentRequest.Client.ClientID,
|
||||
"scopes": consentRequest.RequestedScope,
|
||||
"client_name": consentRequest.Client.ClientName,
|
||||
@@ -6618,7 +6613,7 @@ func appendLoginIDsFromValues(subjects []string, email string, phone string) []s
|
||||
return subjects
|
||||
}
|
||||
|
||||
func appendLoginIDsFromTraits(subjects []string, traits map[string]interface{}) []string {
|
||||
func appendLoginIDsFromTraits(subjects []string, traits map[string]any) []string {
|
||||
if traits == nil {
|
||||
return subjects
|
||||
}
|
||||
@@ -7235,7 +7230,7 @@ func (h *AuthHandler) resolveKratosLoginID(token string) (string, error) {
|
||||
return loginID, nil
|
||||
}
|
||||
|
||||
func pickLoginIDFromTraits(traits map[string]interface{}) string {
|
||||
func pickLoginIDFromTraits(traits map[string]any) string {
|
||||
if traits == nil {
|
||||
return ""
|
||||
}
|
||||
@@ -7409,12 +7404,12 @@ func extractLoginIDFromClaims(claims map[string]any) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (h *AuthHandler) getKratosIdentity(sessionToken string) (string, map[string]interface{}, string, error) {
|
||||
func (h *AuthHandler) getKratosIdentity(sessionToken string) (string, map[string]any, string, error) {
|
||||
identityID, traits, _, usedID, err := h.getKratosIdentityWithSession(sessionToken)
|
||||
return identityID, traits, usedID, err
|
||||
}
|
||||
|
||||
func (h *AuthHandler) getKratosIdentityWithSession(sessionToken string) (string, map[string]interface{}, string, string, error) {
|
||||
func (h *AuthHandler) getKratosIdentityWithSession(sessionToken string) (string, map[string]any, string, string, error) {
|
||||
kratosURL := strings.TrimRight(os.Getenv("KRATOS_PUBLIC_URL"), "/")
|
||||
if kratosURL == "" {
|
||||
kratosURL = "http://kratos:4433"
|
||||
@@ -7442,8 +7437,8 @@ func (h *AuthHandler) getKratosIdentityWithSession(sessionToken string) (string,
|
||||
Identifier string `json:"identifier"`
|
||||
} `json:"authentication_methods"`
|
||||
Identity struct {
|
||||
ID string `json:"id"`
|
||||
Traits map[string]interface{} `json:"traits"`
|
||||
ID string `json:"id"`
|
||||
Traits map[string]any `json:"traits"`
|
||||
} `json:"identity"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
@@ -7501,7 +7496,7 @@ func (h *AuthHandler) issueKratosSession(ctx context.Context, identityID string)
|
||||
kratosAdminURL = "http://kratos:4434"
|
||||
}
|
||||
|
||||
payload := map[string]interface{}{
|
||||
payload := map[string]any{
|
||||
"identity_id": identityID,
|
||||
}
|
||||
body, _ := json.Marshal(payload)
|
||||
@@ -7534,12 +7529,12 @@ func (h *AuthHandler) issueKratosSession(ctx context.Context, identityID string)
|
||||
return parsed.SessionToken, nil
|
||||
}
|
||||
|
||||
func (h *AuthHandler) getKratosIdentityWithCookie(cookie string) (string, map[string]interface{}, string, error) {
|
||||
func (h *AuthHandler) getKratosIdentityWithCookie(cookie string) (string, map[string]any, string, error) {
|
||||
identityID, traits, _, usedID, err := h.getKratosIdentityWithCookieAndSession(cookie)
|
||||
return identityID, traits, usedID, err
|
||||
}
|
||||
|
||||
func (h *AuthHandler) getKratosIdentityWithCookieAndSession(cookie string) (string, map[string]interface{}, string, string, error) {
|
||||
func (h *AuthHandler) getKratosIdentityWithCookieAndSession(cookie string) (string, map[string]any, string, string, error) {
|
||||
kratosURL := strings.TrimRight(os.Getenv("KRATOS_PUBLIC_URL"), "/")
|
||||
if kratosURL == "" {
|
||||
kratosURL = "http://kratos:4433"
|
||||
@@ -7567,8 +7562,8 @@ func (h *AuthHandler) getKratosIdentityWithCookieAndSession(cookie string) (stri
|
||||
Identifier string `json:"identifier"`
|
||||
} `json:"authentication_methods"`
|
||||
Identity struct {
|
||||
ID string `json:"id"`
|
||||
Traits map[string]interface{} `json:"traits"`
|
||||
ID string `json:"id"`
|
||||
Traits map[string]any `json:"traits"`
|
||||
} `json:"identity"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
@@ -7616,13 +7611,13 @@ func (h *AuthHandler) getKratosSessionIDWithCookie(cookie string) (string, error
|
||||
return result.ID, nil
|
||||
}
|
||||
|
||||
func (h *AuthHandler) updateKratosIdentity(identityID string, traits map[string]interface{}) error {
|
||||
func (h *AuthHandler) updateKratosIdentity(identityID string, traits map[string]any) error {
|
||||
kratosAdminURL := strings.TrimRight(os.Getenv("KRATOS_ADMIN_URL"), "/")
|
||||
if kratosAdminURL == "" {
|
||||
kratosAdminURL = "http://kratos:4434"
|
||||
}
|
||||
|
||||
payload := map[string]interface{}{
|
||||
payload := map[string]any{
|
||||
"schema_id": "default",
|
||||
"traits": traits,
|
||||
}
|
||||
@@ -7681,7 +7676,7 @@ func (h *AuthHandler) getHydraProfile(ctx context.Context, token string) (*domai
|
||||
return h.mapKratosIdentityToProfile(identity.ID, identity.Traits), nil
|
||||
}
|
||||
|
||||
func (h *AuthHandler) mapKratosIdentityToProfile(identityID string, traits map[string]interface{}) *domain.UserProfileResponse {
|
||||
func (h *AuthHandler) mapKratosIdentityToProfile(identityID string, traits map[string]any) *domain.UserProfileResponse {
|
||||
email, _ := traits["email"].(string)
|
||||
name, _ := traits["name"].(string)
|
||||
phone, _ := traits["phone_number"].(string)
|
||||
@@ -7723,7 +7718,7 @@ func (h *AuthHandler) mapKratosIdentityToProfile(identityID string, traits map[s
|
||||
return profile
|
||||
}
|
||||
|
||||
func (h *AuthHandler) mapKratosTraitsToLocalUser(identityID string, traits map[string]interface{}, existing *domain.User) *domain.User {
|
||||
func (h *AuthHandler) mapKratosTraitsToLocalUser(identityID string, traits map[string]any, existing *domain.User) *domain.User {
|
||||
now := time.Now()
|
||||
localUser := &domain.User{
|
||||
ID: identityID,
|
||||
@@ -7810,7 +7805,7 @@ func (h *AuthHandler) mapKratosTraitsToLocalUser(identityID string, traits map[s
|
||||
return localUser
|
||||
}
|
||||
|
||||
func (h *AuthHandler) syncUpdatedKratosUserReadModel(ctx context.Context, identityID string, traits map[string]interface{}) error {
|
||||
func (h *AuthHandler) syncUpdatedKratosUserReadModel(ctx context.Context, identityID string, traits map[string]any) error {
|
||||
if h == nil || h.UserRepo == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -7880,7 +7875,7 @@ func (h *AuthHandler) UpdateMe(c *fiber.Ctx) error {
|
||||
|
||||
var (
|
||||
identityID string
|
||||
traits map[string]interface{}
|
||||
traits map[string]any
|
||||
err error
|
||||
)
|
||||
if token != "" {
|
||||
@@ -7929,10 +7924,8 @@ func (h *AuthHandler) UpdateMe(c *fiber.Ctx) error {
|
||||
if _, isCore := map[string]bool{"email": true, "phone_number": true, "name": true, "department": true, "grade": true, "companyCode": true, "affiliationType": true, "id": true, "role": true, "tenant_id": true}[k]; !isCore {
|
||||
// [Fix] Support merging namespaced metadata maps
|
||||
if incomingMap, ok := v.(map[string]any); ok {
|
||||
if existingMap, ok := traits[k].(map[string]interface{}); ok {
|
||||
for subK, subV := range incomingMap {
|
||||
existingMap[subK] = subV
|
||||
}
|
||||
if existingMap, ok := traits[k].(map[string]any); ok {
|
||||
maps.Copy(existingMap, incomingMap)
|
||||
traits[k] = existingMap
|
||||
} else {
|
||||
traits[k] = incomingMap
|
||||
@@ -8129,7 +8122,7 @@ func (h *AuthHandler) VerifyUpdateCode(c *fiber.Ctx) error {
|
||||
return c.JSON(fiber.Map{"success": true})
|
||||
}
|
||||
|
||||
func hydraClientStatus(metadata map[string]interface{}) string {
|
||||
func hydraClientStatus(metadata map[string]any) string {
|
||||
if metadata == nil {
|
||||
return "active"
|
||||
}
|
||||
@@ -8142,7 +8135,7 @@ func hydraClientStatus(metadata map[string]interface{}) string {
|
||||
return "active"
|
||||
}
|
||||
|
||||
func extractHydraClientLogo(metadata map[string]interface{}) string {
|
||||
func extractHydraClientLogo(metadata map[string]any) string {
|
||||
if metadata == nil {
|
||||
return ""
|
||||
}
|
||||
@@ -8198,7 +8191,7 @@ func resolveLinkedRPURL(clientID string, clientURI string, redirectURIs []string
|
||||
return ""
|
||||
}
|
||||
|
||||
func resolveLinkedRPAutoLoginSupported(clientID string, metadata map[string]interface{}) bool {
|
||||
func resolveLinkedRPAutoLoginSupported(clientID string, metadata map[string]any) bool {
|
||||
if readMetadataBoolValue(metadata, domain.MetadataAutoLoginSupported) {
|
||||
return true
|
||||
}
|
||||
@@ -8210,7 +8203,7 @@ func resolveLinkedRPAutoLoginSupported(clientID string, metadata map[string]inte
|
||||
}
|
||||
}
|
||||
|
||||
func resolveLinkedRPAutoLoginURL(clientID string, metadata map[string]interface{}) string {
|
||||
func resolveLinkedRPAutoLoginURL(clientID string, metadata map[string]any) string {
|
||||
clientID = strings.TrimSpace(clientID)
|
||||
if metadataURL := readMetadataStringValue(metadata, domain.MetadataAutoLoginURL); metadataURL != "" {
|
||||
if clientID == "orgfront" {
|
||||
@@ -8253,7 +8246,7 @@ func ensureOrgfrontAutoLoginURL(rawURL string) string {
|
||||
return parsed.String()
|
||||
}
|
||||
|
||||
func resolveLinkedRPInitURL(clientID string, metadata map[string]interface{}) string {
|
||||
func resolveLinkedRPInitURL(clientID string, metadata map[string]any) string {
|
||||
if !resolveLinkedRPAutoLoginSupported(clientID, metadata) {
|
||||
return ""
|
||||
}
|
||||
@@ -8548,7 +8541,7 @@ func (h *AuthHandler) ListRpHistory(c *fiber.Ctx) error {
|
||||
ts := log.Timestamp
|
||||
item.LastApprovedAt = &ts
|
||||
|
||||
if scopesRaw, ok := details["scopes"].([]interface{}); ok {
|
||||
if scopesRaw, ok := details["scopes"].([]any); ok {
|
||||
scopes := make([]string, 0, len(scopesRaw))
|
||||
for _, s := range scopesRaw {
|
||||
if str, ok := s.(string); ok {
|
||||
@@ -8811,7 +8804,7 @@ func extractStringLikeValue(raw any) string {
|
||||
}
|
||||
}
|
||||
|
||||
func extractHydraSessionID(ext map[string]interface{}) string {
|
||||
func extractHydraSessionID(ext map[string]any) string {
|
||||
if len(ext) == 0 {
|
||||
return ""
|
||||
}
|
||||
@@ -8886,13 +8879,7 @@ func (h *AuthHandler) loadSessionClientBindings(ctx context.Context, userID stri
|
||||
}
|
||||
|
||||
existing := bindings[sessionID]
|
||||
seen := false
|
||||
for _, candidate := range existing {
|
||||
if candidate == clientID {
|
||||
seen = true
|
||||
break
|
||||
}
|
||||
}
|
||||
seen := slices.Contains(existing, clientID)
|
||||
if !seen {
|
||||
bindings[sessionID] = append(existing, clientID)
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// --- Async Test Mocks ---
|
||||
@@ -133,6 +134,10 @@ func (m *AsyncMockUserRepo) CountByCompanyCodes(ctx context.Context, codes []str
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (m *AsyncMockUserRepo) DB() *gorm.DB {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *AsyncMockUserRepo) UpdateUserLoginIDs(ctx context.Context, userID string, loginIDs []domain.UserLoginID) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -22,8 +22,8 @@ func TestRevokeLinkedRp_Success(t *testing.T) {
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
// 1. Kratos whoami
|
||||
if r.URL.Path == "/sessions/whoami" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
"identity": map[string]interface{}{"id": "user-123"},
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"identity": map[string]any{"id": "user-123"},
|
||||
}), nil
|
||||
}
|
||||
// 2. Hydra Revoke
|
||||
@@ -75,15 +75,15 @@ func TestRevokeLinkedRp_SendsBackchannelLogoutTokenWhenConfigured(t *testing.T)
|
||||
var receivedBody string
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Path == "/sessions/whoami" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
"identity": map[string]interface{}{"id": "user-123"},
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"identity": map[string]any{"id": "user-123"},
|
||||
}), nil
|
||||
}
|
||||
if r.URL.Host == "hydra.test" && r.Method == http.MethodDelete && r.URL.Path == "/oauth2/auth/sessions/consent" {
|
||||
return httpResponse(r, http.StatusNoContent, ""), nil
|
||||
}
|
||||
if r.URL.Host == "hydra.test" && r.Method == http.MethodGet && r.URL.Path == "/clients/app-1" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"client_id": "app-1",
|
||||
"backchannel_logout_uri": "https://rp.example.com/backchannel-logout",
|
||||
}), nil
|
||||
@@ -158,8 +158,8 @@ func TestListRpHistory_Aggregation(t *testing.T) {
|
||||
app.Get("/api/v1/user/rp/history", h.ListRpHistory)
|
||||
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
"identity": map[string]interface{}{"id": "user-123"},
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"identity": map[string]any{"id": "user-123"},
|
||||
}), nil
|
||||
})
|
||||
http.DefaultClient = &http.Client{Transport: transport}
|
||||
|
||||
@@ -39,11 +39,11 @@ func (m *MockKratosAdminServiceForConsent) ListIdentities(ctx context.Context) (
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (m *MockKratosAdminServiceForConsent) UpdateIdentity(ctx context.Context, identityID string, traits map[string]interface{}, state string) (*service.KratosIdentity, error) {
|
||||
func (m *MockKratosAdminServiceForConsent) UpdateIdentity(ctx context.Context, identityID string, traits map[string]any, state string) (*service.KratosIdentity, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (m *MockKratosAdminServiceForConsent) CreateIdentity(ctx context.Context, traits map[string]interface{}) (*service.KratosIdentity, error) {
|
||||
func (m *MockKratosAdminServiceForConsent) CreateIdentity(ctx context.Context, traits map[string]any) (*service.KratosIdentity, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -146,12 +146,12 @@ func TestGetConsentRequest_Normal(t *testing.T) {
|
||||
// Mock Hydra transport
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-123" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"challenge": "challenge-123",
|
||||
"requested_scope": []string{"openid", "profile"},
|
||||
"skip": false,
|
||||
"subject": "user-123",
|
||||
"client": map[string]interface{}{
|
||||
"client": map[string]any{
|
||||
"client_id": "client-app",
|
||||
"client_name": "Test App",
|
||||
},
|
||||
@@ -180,7 +180,7 @@ func TestGetConsentRequest_Normal(t *testing.T) {
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
var body map[string]interface{}
|
||||
var body map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&body)
|
||||
|
||||
assert.Equal(t, "challenge-123", body["challenge"])
|
||||
@@ -190,12 +190,12 @@ func TestGetConsentRequest_Normal(t *testing.T) {
|
||||
func TestGetConsentRequest_AddsMandatoryTenantScope(t *testing.T) {
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-tenant-scope" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"challenge": "challenge-tenant-scope",
|
||||
"requested_scope": []string{"openid", "profile"},
|
||||
"skip": false,
|
||||
"subject": "user-123",
|
||||
"client": map[string]interface{}{
|
||||
"client": map[string]any{
|
||||
"client_id": "client-app",
|
||||
"client_name": "Test App",
|
||||
"metadata": map[string]any{
|
||||
@@ -224,7 +224,7 @@ func TestGetConsentRequest_AddsMandatoryTenantScope(t *testing.T) {
|
||||
// Mock profile resolution to allow tenant access
|
||||
mockKratosAdmin.On("GetIdentity", mock.Anything, "user-123").Return(&service.KratosIdentity{
|
||||
ID: "user-123",
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"email": "user@example.com",
|
||||
},
|
||||
}, nil)
|
||||
@@ -259,12 +259,12 @@ func TestGetConsentRequest_AddsMandatoryTenantScope(t *testing.T) {
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
var body map[string]interface{}
|
||||
var body map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&body)
|
||||
|
||||
assert.Equal(t, []interface{}{"openid", "tenant", "profile"}, body["requested_scope"])
|
||||
scopeDetails := body["scope_details"].(map[string]interface{})
|
||||
tenantDetail := scopeDetails["tenant"].(map[string]interface{})
|
||||
assert.Equal(t, []any{"openid", "tenant", "profile"}, body["requested_scope"])
|
||||
scopeDetails := body["scope_details"].(map[string]any)
|
||||
tenantDetail := scopeDetails["tenant"].(map[string]any)
|
||||
assert.Equal(t, true, tenantDetail["mandatory"])
|
||||
}
|
||||
|
||||
@@ -272,28 +272,28 @@ func TestGetConsentRequest_Skip_AutoAccept(t *testing.T) {
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
// Hydra: Get Consent Request
|
||||
if r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-skip" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"challenge": "challenge-skip",
|
||||
"requested_scope": []string{"openid"},
|
||||
"skip": true,
|
||||
"subject": "user-123",
|
||||
"client": map[string]interface{}{
|
||||
"client": map[string]any{
|
||||
"client_id": "client-app",
|
||||
},
|
||||
}), nil
|
||||
}
|
||||
// Kratos: Get Identity
|
||||
if r.URL.Path == "/admin/identities/user-123" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"id": "user-123",
|
||||
"traits": map[string]interface{}{
|
||||
"traits": map[string]any{
|
||||
"email": "user@test.com",
|
||||
},
|
||||
}), nil
|
||||
}
|
||||
// Hydra: Accept Consent Request
|
||||
if r.URL.Path == "/oauth2/auth/requests/consent/accept" && r.URL.Query().Get("consent_challenge") == "challenge-skip" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"redirect_to": "http://rp/cb",
|
||||
}), nil
|
||||
}
|
||||
@@ -320,7 +320,7 @@ func TestGetConsentRequest_Skip_AutoAccept(t *testing.T) {
|
||||
}
|
||||
mockKratosAdmin.On("GetIdentity", mock.Anything, "user-123").Return(&service.KratosIdentity{
|
||||
ID: "user-123",
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"email": "user@test.com",
|
||||
},
|
||||
}, nil)
|
||||
@@ -332,7 +332,7 @@ func TestGetConsentRequest_Skip_AutoAccept(t *testing.T) {
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
var body map[string]interface{}
|
||||
var body map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&body)
|
||||
assert.Equal(t, "http://rp/cb", body["redirectTo"])
|
||||
assert.Equal(t, 1, len(rpUsageSink.events))
|
||||
@@ -345,26 +345,26 @@ func TestGetConsentRequest_Skip_AutoAccept(t *testing.T) {
|
||||
func TestAcceptConsentRequest_Normal(t *testing.T) {
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-accept" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"challenge": "challenge-accept",
|
||||
"requested_scope": []string{"openid", "profile"},
|
||||
"subject": "user-123",
|
||||
"client": map[string]interface{}{
|
||||
"client": map[string]any{
|
||||
"client_id": "client-app",
|
||||
"client_name": "Test App",
|
||||
},
|
||||
}), nil
|
||||
}
|
||||
if r.URL.Path == "/admin/identities/user-123" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"id": "user-123",
|
||||
"traits": map[string]interface{}{
|
||||
"traits": map[string]any{
|
||||
"email": "user@test.com",
|
||||
},
|
||||
}), nil
|
||||
}
|
||||
if r.URL.Path == "/oauth2/auth/requests/consent/accept" && r.URL.Query().Get("consent_challenge") == "challenge-accept" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"redirect_to": "http://rp/cb",
|
||||
}), nil
|
||||
}
|
||||
@@ -393,14 +393,14 @@ func TestAcceptConsentRequest_Normal(t *testing.T) {
|
||||
}
|
||||
mockKratosAdmin.On("GetIdentity", mock.Anything, "user-123").Return(&service.KratosIdentity{
|
||||
ID: "user-123",
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"email": "user@test.com",
|
||||
},
|
||||
}, nil)
|
||||
|
||||
app := newConsentTestApp(h)
|
||||
|
||||
body, _ := json.Marshal(map[string]interface{}{
|
||||
body, _ := json.Marshal(map[string]any{
|
||||
"consent_challenge": "challenge-accept",
|
||||
"grant_scope": []string{"openid"},
|
||||
})
|
||||
@@ -419,7 +419,7 @@ func TestAcceptConsentRequest_Normal(t *testing.T) {
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "client-app", auditDetails["client_id"])
|
||||
assert.Equal(t, "Test App", auditDetails["client_name"])
|
||||
assert.Equal(t, []interface{}{"openid"}, auditDetails["scopes"])
|
||||
assert.Equal(t, []any{"openid"}, auditDetails["scopes"])
|
||||
assert.Equal(t, 1, len(rpUsageSink.events))
|
||||
assert.Equal(t, domain.RPUsageEventTypeAuthorizationGranted, rpUsageSink.events[0].EventType)
|
||||
assert.Equal(t, "user-123", rpUsageSink.events[0].Subject)
|
||||
@@ -436,11 +436,11 @@ func TestAcceptConsentRequest_EnforcesMandatoryTenantScope(t *testing.T) {
|
||||
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-tenant-accept" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"challenge": "challenge-tenant-accept",
|
||||
"requested_scope": []string{"openid", "profile"},
|
||||
"subject": "user-123",
|
||||
"client": map[string]interface{}{
|
||||
"client": map[string]any{
|
||||
"client_id": "client-app",
|
||||
"metadata": map[string]any{
|
||||
"tenant_id": "tenant-abc",
|
||||
@@ -456,9 +456,9 @@ func TestAcceptConsentRequest_EnforcesMandatoryTenantScope(t *testing.T) {
|
||||
}), nil
|
||||
}
|
||||
if r.URL.Path == "/admin/identities/user-123" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"id": "user-123",
|
||||
"traits": map[string]interface{}{
|
||||
"traits": map[string]any{
|
||||
"email": "user@test.com",
|
||||
},
|
||||
}), nil
|
||||
@@ -466,10 +466,10 @@ func TestAcceptConsentRequest_EnforcesMandatoryTenantScope(t *testing.T) {
|
||||
if r.URL.Path == "/oauth2/auth/requests/consent/accept" && r.URL.Query().Get("consent_challenge") == "challenge-tenant-accept" {
|
||||
var payload map[string]any
|
||||
assert.NoError(t, json.NewDecoder(r.Body).Decode(&payload))
|
||||
for _, scope := range payload["grant_scope"].([]interface{}) {
|
||||
for _, scope := range payload["grant_scope"].([]any) {
|
||||
capturedGrantScopes = append(capturedGrantScopes, scope.(string))
|
||||
}
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"redirect_to": "http://rp/cb",
|
||||
}), nil
|
||||
}
|
||||
@@ -492,14 +492,14 @@ func TestAcceptConsentRequest_EnforcesMandatoryTenantScope(t *testing.T) {
|
||||
}
|
||||
mockKratosAdmin.On("GetIdentity", mock.Anything, "user-123").Return(&service.KratosIdentity{
|
||||
ID: "user-123",
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"email": "user@test.com",
|
||||
},
|
||||
}, nil)
|
||||
|
||||
app := newConsentTestApp(h)
|
||||
|
||||
body, _ := json.Marshal(map[string]interface{}{
|
||||
body, _ := json.Marshal(map[string]any{
|
||||
"consent_challenge": "challenge-tenant-accept",
|
||||
"grant_scope": []string{"openid", "profile"},
|
||||
})
|
||||
|
||||
@@ -17,15 +17,15 @@ import (
|
||||
)
|
||||
|
||||
func TestBuildOidcClaimsFromTraits_DynamicClaims(t *testing.T) {
|
||||
traits := map[string]interface{}{
|
||||
traits := map[string]any{
|
||||
"email": "user@baron.com",
|
||||
"name": "홍길동",
|
||||
"tenant_id": "primary-tenant-999", // Added primary tenant
|
||||
"tenant-1": map[string]interface{}{
|
||||
"tenant-1": map[string]any{
|
||||
"department": "개발팀",
|
||||
"grade": "선임",
|
||||
},
|
||||
"tenant-2": map[string]interface{}{
|
||||
"tenant-2": map[string]any{
|
||||
"department": "재무팀",
|
||||
"grade": "팀장",
|
||||
},
|
||||
@@ -130,18 +130,18 @@ func TestRepresentativeTenantIDFromTraits(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestAcceptConsentRequest_DynamicClaims(t *testing.T) {
|
||||
var capturedClaims map[string]interface{}
|
||||
var capturedClaims map[string]any
|
||||
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
// Hydra: Get Consent Request
|
||||
if r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-dynamic" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"challenge": "challenge-dynamic",
|
||||
"requested_scope": []string{"openid", "profile", "tenant"},
|
||||
"subject": "user-123",
|
||||
"client": map[string]interface{}{
|
||||
"client": map[string]any{
|
||||
"client_id": "client-app",
|
||||
"metadata": map[string]interface{}{
|
||||
"metadata": map[string]any{
|
||||
"tenant_id": "tenant-abc",
|
||||
},
|
||||
},
|
||||
@@ -149,12 +149,12 @@ func TestAcceptConsentRequest_DynamicClaims(t *testing.T) {
|
||||
}
|
||||
// Kratos: Get Identity
|
||||
if r.URL.Path == "/admin/identities/user-123" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"id": "user-123",
|
||||
"traits": map[string]interface{}{
|
||||
"traits": map[string]any{
|
||||
"email": "user@test.com",
|
||||
"name": "Test User",
|
||||
"tenant-abc": map[string]interface{}{
|
||||
"tenant-abc": map[string]any{
|
||||
"department": "Innovation",
|
||||
"position": "Architect",
|
||||
},
|
||||
@@ -165,13 +165,13 @@ func TestAcceptConsentRequest_DynamicClaims(t *testing.T) {
|
||||
if r.URL.Path == "/oauth2/auth/requests/consent/accept" && r.URL.Query().Get("consent_challenge") == "challenge-dynamic" {
|
||||
// Capture the claims sent to Hydra
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
var acceptReq map[string]interface{}
|
||||
var acceptReq map[string]any
|
||||
json.Unmarshal(body, &acceptReq)
|
||||
if session, ok := acceptReq["session"].(map[string]interface{}); ok {
|
||||
capturedClaims = session["id_token"].(map[string]interface{})
|
||||
if session, ok := acceptReq["session"].(map[string]any); ok {
|
||||
capturedClaims = session["id_token"].(map[string]any)
|
||||
}
|
||||
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"redirect_to": "http://rp/cb",
|
||||
}), nil
|
||||
}
|
||||
@@ -192,10 +192,10 @@ func TestAcceptConsentRequest_DynamicClaims(t *testing.T) {
|
||||
}
|
||||
h.KratosAdmin.(*MockKratosAdminService).On("GetIdentity", mock.Anything, "user-123").Return(&service.KratosIdentity{
|
||||
ID: "user-123",
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"email": "user@test.com",
|
||||
"name": "Test User",
|
||||
"tenant-abc": map[string]interface{}{
|
||||
"tenant-abc": map[string]any{
|
||||
"department": "Innovation",
|
||||
"position": "Architect",
|
||||
},
|
||||
@@ -205,7 +205,7 @@ func TestAcceptConsentRequest_DynamicClaims(t *testing.T) {
|
||||
app := fiber.New()
|
||||
app.Post("/api/v1/auth/consent/accept", h.AcceptConsentRequest)
|
||||
|
||||
reqBody, _ := json.Marshal(map[string]interface{}{
|
||||
reqBody, _ := json.Marshal(map[string]any{
|
||||
"consent_challenge": "challenge-dynamic",
|
||||
"grant_scope": []string{"openid", "profile", "tenant"},
|
||||
})
|
||||
@@ -225,20 +225,20 @@ func TestAcceptConsentRequest_DynamicClaims(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestAcceptConsentRequest_UsesRepresentativeTenantIDInsteadOfClientTenantContext(t *testing.T) {
|
||||
var capturedClaims map[string]interface{}
|
||||
var capturedClaims map[string]any
|
||||
|
||||
representativeTenantID := "01970f0a-5c28-74d8-a73a-f6e9e9a7b210"
|
||||
rpContextTenantID := "01970f0b-3448-7bb8-bdc7-16b6a1d2e661"
|
||||
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-representative-tenant" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"challenge": "challenge-representative-tenant",
|
||||
"requested_scope": []string{"openid", "profile", "tenant"},
|
||||
"subject": "user-representative",
|
||||
"client": map[string]interface{}{
|
||||
"client": map[string]any{
|
||||
"client_id": "client-app",
|
||||
"metadata": map[string]interface{}{
|
||||
"metadata": map[string]any{
|
||||
"tenant_id": rpContextTenantID,
|
||||
},
|
||||
},
|
||||
@@ -246,13 +246,13 @@ func TestAcceptConsentRequest_UsesRepresentativeTenantIDInsteadOfClientTenantCon
|
||||
}
|
||||
if r.URL.Path == "/oauth2/auth/requests/consent/accept" && r.URL.Query().Get("consent_challenge") == "challenge-representative-tenant" {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
var acceptReq map[string]interface{}
|
||||
var acceptReq map[string]any
|
||||
json.Unmarshal(body, &acceptReq)
|
||||
if session, ok := acceptReq["session"].(map[string]interface{}); ok {
|
||||
capturedClaims = session["id_token"].(map[string]interface{})
|
||||
if session, ok := acceptReq["session"].(map[string]any); ok {
|
||||
capturedClaims = session["id_token"].(map[string]any)
|
||||
}
|
||||
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"redirect_to": "http://rp/cb",
|
||||
}), nil
|
||||
}
|
||||
@@ -269,12 +269,12 @@ func TestAcceptConsentRequest_UsesRepresentativeTenantIDInsteadOfClientTenantCon
|
||||
}
|
||||
h.KratosAdmin.(*MockKratosAdminService).On("GetIdentity", mock.Anything, "user-representative").Return(&service.KratosIdentity{
|
||||
ID: "user-representative",
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"email": "user@test.com",
|
||||
"name": "Test User",
|
||||
"additionalAppointments": []interface{}{
|
||||
map[string]interface{}{"tenantId": representativeTenantID, "isPrimary": true},
|
||||
map[string]interface{}{"tenantId": rpContextTenantID},
|
||||
"additionalAppointments": []any{
|
||||
map[string]any{"tenantId": representativeTenantID, "isPrimary": true},
|
||||
map[string]any{"tenantId": rpContextTenantID},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
@@ -282,7 +282,7 @@ func TestAcceptConsentRequest_UsesRepresentativeTenantIDInsteadOfClientTenantCon
|
||||
app := fiber.New()
|
||||
app.Post("/api/v1/auth/consent/accept", h.AcceptConsentRequest)
|
||||
|
||||
reqBody, _ := json.Marshal(map[string]interface{}{
|
||||
reqBody, _ := json.Marshal(map[string]any{
|
||||
"consent_challenge": "challenge-representative-tenant",
|
||||
"grant_scope": []string{"openid", "profile"},
|
||||
})
|
||||
@@ -301,7 +301,7 @@ func TestAcceptConsentRequest_UsesRepresentativeTenantIDInsteadOfClientTenantCon
|
||||
}
|
||||
|
||||
func TestAcceptConsentRequest_IncludesHanmacFamilyTenantClaimDetails(t *testing.T) {
|
||||
var capturedClaims map[string]interface{}
|
||||
var capturedClaims map[string]any
|
||||
deptID := "01970f0a-5c28-74d8-a73a-f6e9e9a7b210"
|
||||
secondDeptID := "01970f0b-3448-7bb8-bdc7-16b6a1d2e661"
|
||||
companyID := "01970f08-91da-7286-bd19-882fb98d1f2c"
|
||||
@@ -309,13 +309,13 @@ func TestAcceptConsentRequest_IncludesHanmacFamilyTenantClaimDetails(t *testing.
|
||||
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-hanmac-tenant-claim" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"challenge": "challenge-hanmac-tenant-claim",
|
||||
"requested_scope": []string{"openid", "profile", "tenant"},
|
||||
"subject": "user-hanmac",
|
||||
"client": map[string]interface{}{
|
||||
"client": map[string]any{
|
||||
"client_id": "hanmac-rp",
|
||||
"metadata": map[string]interface{}{
|
||||
"metadata": map[string]any{
|
||||
"tenant_id": deptID,
|
||||
},
|
||||
},
|
||||
@@ -323,13 +323,13 @@ func TestAcceptConsentRequest_IncludesHanmacFamilyTenantClaimDetails(t *testing.
|
||||
}
|
||||
if r.URL.Path == "/oauth2/auth/requests/consent/accept" && r.URL.Query().Get("consent_challenge") == "challenge-hanmac-tenant-claim" {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
var acceptReq map[string]interface{}
|
||||
var acceptReq map[string]any
|
||||
json.Unmarshal(body, &acceptReq)
|
||||
if session, ok := acceptReq["session"].(map[string]interface{}); ok {
|
||||
capturedClaims = session["id_token"].(map[string]interface{})
|
||||
if session, ok := acceptReq["session"].(map[string]any); ok {
|
||||
capturedClaims = session["id_token"].(map[string]any)
|
||||
}
|
||||
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"redirect_to": "http://rp/cb",
|
||||
}), nil
|
||||
}
|
||||
@@ -346,11 +346,11 @@ func TestAcceptConsentRequest_IncludesHanmacFamilyTenantClaimDetails(t *testing.
|
||||
}
|
||||
h.KratosAdmin.(*MockKratosAdminService).On("GetIdentity", mock.Anything, "user-hanmac").Return(&service.KratosIdentity{
|
||||
ID: "user-hanmac",
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"email": "hanmac-user@example.com",
|
||||
"name": "한맥 사용자",
|
||||
"additionalAppointments": []interface{}{
|
||||
map[string]interface{}{
|
||||
"additionalAppointments": []any{
|
||||
map[string]any{
|
||||
"tenantId": deptID,
|
||||
"isPrimary": true,
|
||||
"isOwner": true,
|
||||
@@ -358,7 +358,7 @@ func TestAcceptConsentRequest_IncludesHanmacFamilyTenantClaimDetails(t *testing.
|
||||
"jobTitle": "기술기획",
|
||||
"position": "팀장",
|
||||
},
|
||||
map[string]interface{}{
|
||||
map[string]any{
|
||||
"tenantId": secondDeptID,
|
||||
"isPrimary": false,
|
||||
"isOwner": false,
|
||||
@@ -404,7 +404,7 @@ func TestAcceptConsentRequest_IncludesHanmacFamilyTenantClaimDetails(t *testing.
|
||||
app := fiber.New()
|
||||
app.Post("/api/v1/auth/consent/accept", h.AcceptConsentRequest)
|
||||
|
||||
reqBody, _ := json.Marshal(map[string]interface{}{
|
||||
reqBody, _ := json.Marshal(map[string]any{
|
||||
"consent_challenge": "challenge-hanmac-tenant-claim",
|
||||
"grant_scope": []string{"openid", "profile", "tenant"},
|
||||
})
|
||||
@@ -416,10 +416,10 @@ func TestAcceptConsentRequest_IncludesHanmacFamilyTenantClaimDetails(t *testing.
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
assert.NotNil(t, capturedClaims)
|
||||
assert.Equal(t, []interface{}{deptID}, capturedClaims["lead_tenants"])
|
||||
assert.ElementsMatch(t, []interface{}{deptID, secondDeptID}, capturedClaims["joined_tenants"])
|
||||
tenants := capturedClaims["tenants"].(map[string]interface{})
|
||||
dept := tenants[deptID].(map[string]interface{})
|
||||
assert.Equal(t, []any{deptID}, capturedClaims["lead_tenants"])
|
||||
assert.ElementsMatch(t, []any{deptID, secondDeptID}, capturedClaims["joined_tenants"])
|
||||
tenants := capturedClaims["tenants"].(map[string]any)
|
||||
dept := tenants[deptID].(map[string]any)
|
||||
assert.Equal(t, true, dept["lead"])
|
||||
assert.Equal(t, true, dept["representative"])
|
||||
assert.Equal(t, "책임", dept["grade"])
|
||||
@@ -428,21 +428,21 @@ func TestAcceptConsentRequest_IncludesHanmacFamilyTenantClaimDetails(t *testing.
|
||||
assert.Equal(t, companyID, dept["parentTenantId"])
|
||||
assert.NotContains(t, dept, "parentTenant")
|
||||
|
||||
ancestors := dept["ancestors"].([]interface{})
|
||||
ancestors := dept["ancestors"].([]any)
|
||||
assert.Len(t, ancestors, 2)
|
||||
companyAncestor := ancestors[0].(map[string]interface{})
|
||||
companyAncestor := ancestors[0].(map[string]any)
|
||||
assert.Equal(t, companyID, companyAncestor["id"])
|
||||
assert.Equal(t, "hanmac", companyAncestor["slug"])
|
||||
assert.Equal(t, rootID, companyAncestor["parentTenantId"])
|
||||
assert.NotContains(t, companyAncestor, "parentTenant")
|
||||
rootAncestor := ancestors[1].(map[string]interface{})
|
||||
rootAncestor := ancestors[1].(map[string]any)
|
||||
assert.Equal(t, rootID, rootAncestor["id"])
|
||||
assert.Equal(t, "hanmac-family", rootAncestor["slug"])
|
||||
assert.Contains(t, rootAncestor, "parentTenantId")
|
||||
assert.Nil(t, rootAncestor["parentTenantId"])
|
||||
assert.NotContains(t, rootAncestor, "parentTenant")
|
||||
|
||||
secondDept := tenants[secondDeptID].(map[string]interface{})
|
||||
secondDept := tenants[secondDeptID].(map[string]any)
|
||||
assert.Equal(t, false, secondDept["lead"])
|
||||
assert.Equal(t, false, secondDept["representative"])
|
||||
assert.Equal(t, "선임", secondDept["grade"])
|
||||
@@ -512,18 +512,18 @@ func TestWithHanmacFamilyTenantClaims_DefaultClaimsOnlyWithoutTenantScope(t *tes
|
||||
}
|
||||
|
||||
func TestAcceptConsentRequest_IncludesRPProfileClaims(t *testing.T) {
|
||||
var capturedClaims map[string]interface{}
|
||||
var capturedClaims map[string]any
|
||||
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-rp-profile" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"challenge": "challenge-rp-profile",
|
||||
"requested_scope": []string{"openid", "profile", "tenant"},
|
||||
"subject": "user-123",
|
||||
"client": map[string]interface{}{
|
||||
"client": map[string]any{
|
||||
"client_id": "client-app",
|
||||
"metadata": map[string]interface{}{
|
||||
"customUserSchema": []map[string]interface{}{
|
||||
"metadata": map[string]any{
|
||||
"customUserSchema": []map[string]any{
|
||||
{
|
||||
"key": "approvalLevel",
|
||||
"label": "승인 등급",
|
||||
@@ -543,13 +543,13 @@ func TestAcceptConsentRequest_IncludesRPProfileClaims(t *testing.T) {
|
||||
}
|
||||
if r.URL.Path == "/oauth2/auth/requests/consent/accept" && r.URL.Query().Get("consent_challenge") == "challenge-rp-profile" {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
var acceptReq map[string]interface{}
|
||||
var acceptReq map[string]any
|
||||
json.Unmarshal(body, &acceptReq)
|
||||
if session, ok := acceptReq["session"].(map[string]interface{}); ok {
|
||||
capturedClaims = session["id_token"].(map[string]interface{})
|
||||
if session, ok := acceptReq["session"].(map[string]any); ok {
|
||||
capturedClaims = session["id_token"].(map[string]any)
|
||||
}
|
||||
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"redirect_to": "http://rp/cb",
|
||||
}), nil
|
||||
}
|
||||
@@ -566,7 +566,7 @@ func TestAcceptConsentRequest_IncludesRPProfileClaims(t *testing.T) {
|
||||
}
|
||||
h.KratosAdmin.(*MockKratosAdminService).On("GetIdentity", mock.Anything, "user-123").Return(&service.KratosIdentity{
|
||||
ID: "user-123",
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"email": "user@test.com",
|
||||
"name": "Test User",
|
||||
},
|
||||
@@ -585,7 +585,7 @@ func TestAcceptConsentRequest_IncludesRPProfileClaims(t *testing.T) {
|
||||
app := fiber.New()
|
||||
app.Post("/api/v1/auth/consent/accept", h.AcceptConsentRequest)
|
||||
|
||||
reqBody, _ := json.Marshal(map[string]interface{}{
|
||||
reqBody, _ := json.Marshal(map[string]any{
|
||||
"consent_challenge": "challenge-rp-profile",
|
||||
"grant_scope": []string{"openid", "profile"},
|
||||
})
|
||||
@@ -597,31 +597,31 @@ func TestAcceptConsentRequest_IncludesRPProfileClaims(t *testing.T) {
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
assert.NotNil(t, capturedClaims)
|
||||
rpProfiles, ok := capturedClaims["rp_profiles"].([]interface{})
|
||||
rpProfiles, ok := capturedClaims["rp_profiles"].([]any)
|
||||
assert.True(t, ok)
|
||||
assert.Len(t, rpProfiles, 1)
|
||||
profile := rpProfiles[0].(map[string]interface{})
|
||||
profile := rpProfiles[0].(map[string]any)
|
||||
assert.Equal(t, "client-app", profile["client_id"])
|
||||
fields := profile["fields"].(map[string]interface{})
|
||||
fields := profile["fields"].(map[string]any)
|
||||
assert.Equal(t, "A", fields["approvalLevel"])
|
||||
assert.NotContains(t, fields, "internalMemo")
|
||||
repo.AssertExpectations(t)
|
||||
}
|
||||
|
||||
func TestGetConsentRequest_Skip_DynamicClaims(t *testing.T) {
|
||||
var capturedClaims map[string]interface{}
|
||||
var capturedClaims map[string]any
|
||||
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
// Hydra: Get Consent Request
|
||||
if r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-skip-dynamic" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"challenge": "challenge-skip-dynamic",
|
||||
"requested_scope": []string{"openid", "profile", "tenant"},
|
||||
"skip": true,
|
||||
"subject": "user-456",
|
||||
"client": map[string]interface{}{
|
||||
"client": map[string]any{
|
||||
"client_id": "skip-app",
|
||||
"metadata": map[string]interface{}{
|
||||
"metadata": map[string]any{
|
||||
"tenant_id": "tenant-xyz",
|
||||
},
|
||||
},
|
||||
@@ -629,11 +629,11 @@ func TestGetConsentRequest_Skip_DynamicClaims(t *testing.T) {
|
||||
}
|
||||
// Kratos: Get Identity
|
||||
if r.URL.Path == "/admin/identities/user-456" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"id": "user-456",
|
||||
"traits": map[string]interface{}{
|
||||
"traits": map[string]any{
|
||||
"email": "skip@test.com",
|
||||
"tenant-xyz": map[string]interface{}{
|
||||
"tenant-xyz": map[string]any{
|
||||
"department": "Security",
|
||||
"position": "Officer",
|
||||
},
|
||||
@@ -644,13 +644,13 @@ func TestGetConsentRequest_Skip_DynamicClaims(t *testing.T) {
|
||||
if r.URL.Path == "/oauth2/auth/requests/consent/accept" && r.URL.Query().Get("consent_challenge") == "challenge-skip-dynamic" {
|
||||
// Capture the claims sent to Hydra
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
var acceptReq map[string]interface{}
|
||||
var acceptReq map[string]any
|
||||
json.Unmarshal(body, &acceptReq)
|
||||
if session, ok := acceptReq["session"].(map[string]interface{}); ok {
|
||||
capturedClaims = session["id_token"].(map[string]interface{})
|
||||
if session, ok := acceptReq["session"].(map[string]any); ok {
|
||||
capturedClaims = session["id_token"].(map[string]any)
|
||||
}
|
||||
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"redirect_to": "http://rp/cb",
|
||||
}), nil
|
||||
}
|
||||
@@ -671,9 +671,9 @@ func TestGetConsentRequest_Skip_DynamicClaims(t *testing.T) {
|
||||
}
|
||||
h.KratosAdmin.(*MockKratosAdminService).On("GetIdentity", mock.Anything, "user-456").Return(&service.KratosIdentity{
|
||||
ID: "user-456",
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"email": "skip@test.com",
|
||||
"tenant-xyz": map[string]interface{}{
|
||||
"tenant-xyz": map[string]any{
|
||||
"department": "Security",
|
||||
"position": "Officer",
|
||||
},
|
||||
@@ -697,19 +697,19 @@ func TestGetConsentRequest_Skip_DynamicClaims(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestAcceptConsentRequest_AppliesConfiguredIDTokenClaims(t *testing.T) {
|
||||
var capturedClaims map[string]interface{}
|
||||
var capturedClaims map[string]any
|
||||
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-configured-claims" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"challenge": "challenge-configured-claims",
|
||||
"requested_scope": []string{"openid", "profile"},
|
||||
"subject": "user-789",
|
||||
"client": map[string]interface{}{
|
||||
"client": map[string]any{
|
||||
"client_id": "client-configured-claims",
|
||||
"metadata": map[string]interface{}{
|
||||
"metadata": map[string]any{
|
||||
"tenant_id": "tenant-claims",
|
||||
"id_token_claims": []map[string]interface{}{
|
||||
"id_token_claims": []map[string]any{
|
||||
{
|
||||
"namespace": "top_level",
|
||||
"key": "locale",
|
||||
@@ -741,13 +741,13 @@ func TestAcceptConsentRequest_AppliesConfiguredIDTokenClaims(t *testing.T) {
|
||||
}
|
||||
if r.URL.Path == "/oauth2/auth/requests/consent/accept" && r.URL.Query().Get("consent_challenge") == "challenge-configured-claims" {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
var acceptReq map[string]interface{}
|
||||
var acceptReq map[string]any
|
||||
json.Unmarshal(body, &acceptReq)
|
||||
if session, ok := acceptReq["session"].(map[string]interface{}); ok {
|
||||
capturedClaims = session["id_token"].(map[string]interface{})
|
||||
if session, ok := acceptReq["session"].(map[string]any); ok {
|
||||
capturedClaims = session["id_token"].(map[string]any)
|
||||
}
|
||||
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"redirect_to": "http://rp/cb",
|
||||
}), nil
|
||||
}
|
||||
@@ -768,10 +768,10 @@ func TestAcceptConsentRequest_AppliesConfiguredIDTokenClaims(t *testing.T) {
|
||||
}
|
||||
h.KratosAdmin.(*MockKratosAdminService).On("GetIdentity", mock.Anything, "user-789").Return(&service.KratosIdentity{
|
||||
ID: "user-789",
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"email": "real-user@example.com",
|
||||
"name": "Configured User",
|
||||
"tenant-claims": map[string]interface{}{
|
||||
"tenant-claims": map[string]any{
|
||||
"department": "Platform",
|
||||
},
|
||||
},
|
||||
@@ -780,7 +780,7 @@ func TestAcceptConsentRequest_AppliesConfiguredIDTokenClaims(t *testing.T) {
|
||||
app := fiber.New()
|
||||
app.Post("/api/v1/auth/consent/accept", h.AcceptConsentRequest)
|
||||
|
||||
reqBody, _ := json.Marshal(map[string]interface{}{
|
||||
reqBody, _ := json.Marshal(map[string]any{
|
||||
"consent_challenge": "challenge-configured-claims",
|
||||
"grant_scope": []string{"openid", "profile"},
|
||||
})
|
||||
@@ -796,9 +796,9 @@ func TestAcceptConsentRequest_AppliesConfiguredIDTokenClaims(t *testing.T) {
|
||||
assert.Equal(t, "ko-KR", capturedClaims["locale"])
|
||||
assert.Equal(t, "tenant-claims", capturedClaims["tenant_id"])
|
||||
|
||||
rpClaims, ok := capturedClaims["rp_claims"].(map[string]interface{})
|
||||
rpClaims, ok := capturedClaims["rp_claims"].(map[string]any)
|
||||
if assert.True(t, ok) {
|
||||
assert.Equal(t, float64(2), rpClaims["tier"])
|
||||
assert.Equal(t, []interface{}{"sso", "claims"}, rpClaims["features"])
|
||||
assert.Equal(t, []any{"sso", "claims"}, rpClaims["features"])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,12 +61,12 @@ func newKratosWhoamiTestServer(t *testing.T, identityID string) *httptest.Server
|
||||
http.Error(w, "missing session", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"id": "session-123",
|
||||
"authenticated_at": "2026-05-21T00:00:00Z",
|
||||
"identity": map[string]interface{}{
|
||||
"identity": map[string]any{
|
||||
"id": identityID,
|
||||
"traits": map[string]interface{}{
|
||||
"traits": map[string]any{
|
||||
"email": "user@example.com",
|
||||
},
|
||||
},
|
||||
@@ -113,7 +113,7 @@ func TestEnchantedLinkFlow_Email_Success(t *testing.T) {
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
var initResp map[string]interface{}
|
||||
var initResp map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&initResp)
|
||||
pendingRef := initResp["pendingRef"].(string)
|
||||
assert.NotEmpty(t, pendingRef)
|
||||
@@ -129,7 +129,7 @@ func TestEnchantedLinkFlow_Email_Success(t *testing.T) {
|
||||
assert.NotEmpty(t, token)
|
||||
|
||||
// 2. Verify Magic Link
|
||||
verifyBody, _ := json.Marshal(map[string]interface{}{
|
||||
verifyBody, _ := json.Marshal(map[string]any{
|
||||
"token": token,
|
||||
"verifyOnly": true,
|
||||
})
|
||||
@@ -145,7 +145,7 @@ func TestEnchantedLinkFlow_Email_Success(t *testing.T) {
|
||||
resp, _ = app.Test(req, -1)
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
var pollResp map[string]interface{}
|
||||
var pollResp map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&pollResp)
|
||||
assert.Equal(t, "ok", pollResp["status"])
|
||||
assert.Equal(t, "valid-jwt", pollResp["sessionJwt"])
|
||||
@@ -177,7 +177,7 @@ func TestEnchantedLinkFlow_Sms_Success(t *testing.T) {
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
var initResp map[string]interface{}
|
||||
var initResp map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&initResp)
|
||||
assert.NotEmpty(t, initResp["userCode"])
|
||||
}
|
||||
@@ -193,7 +193,7 @@ func TestVerifyMagicLink_VerifyOnlyWithoutSharedBrowserSessionApprovesOnly(t *te
|
||||
app := fiber.New()
|
||||
app.Post("/api/v1/auth/magic-link/verify", h.VerifyMagicLink)
|
||||
|
||||
body, _ := json.Marshal(map[string]interface{}{
|
||||
body, _ := json.Marshal(map[string]any{
|
||||
"token": "token-123",
|
||||
"verifyOnly": true,
|
||||
})
|
||||
@@ -204,7 +204,7 @@ func TestVerifyMagicLink_VerifyOnlyWithoutSharedBrowserSessionApprovesOnly(t *te
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
assert.Empty(t, resp.Cookies())
|
||||
|
||||
var got map[string]interface{}
|
||||
var got map[string]any
|
||||
_ = json.NewDecoder(resp.Body).Decode(&got)
|
||||
assert.Equal(t, "approved", got["status"])
|
||||
assert.Nil(t, got["sessionJwt"])
|
||||
@@ -225,7 +225,7 @@ func TestVerifyMagicLink_VerifyOnlySharedBrowserSameSubjectApprovesOnly(t *testi
|
||||
app := fiber.New()
|
||||
app.Post("/api/v1/auth/magic-link/verify", h.VerifyMagicLink)
|
||||
|
||||
body, _ := json.Marshal(map[string]interface{}{
|
||||
body, _ := json.Marshal(map[string]any{
|
||||
"token": "token-123",
|
||||
"verifyOnly": true,
|
||||
})
|
||||
@@ -237,7 +237,7 @@ func TestVerifyMagicLink_VerifyOnlySharedBrowserSameSubjectApprovesOnly(t *testi
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
assert.Empty(t, resp.Cookies())
|
||||
|
||||
var got map[string]interface{}
|
||||
var got map[string]any
|
||||
_ = json.NewDecoder(resp.Body).Decode(&got)
|
||||
assert.Equal(t, "approved", got["status"])
|
||||
assert.Nil(t, got["sessionJwt"])
|
||||
@@ -258,7 +258,7 @@ func TestVerifyMagicLink_VerifyOnlySharedBrowserDifferentSubjectApprovesOnly(t *
|
||||
app := fiber.New()
|
||||
app.Post("/api/v1/auth/magic-link/verify", h.VerifyMagicLink)
|
||||
|
||||
body, _ := json.Marshal(map[string]interface{}{
|
||||
body, _ := json.Marshal(map[string]any{
|
||||
"token": "token-123",
|
||||
"verifyOnly": true,
|
||||
})
|
||||
@@ -270,7 +270,7 @@ func TestVerifyMagicLink_VerifyOnlySharedBrowserDifferentSubjectApprovesOnly(t *
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
assert.Empty(t, resp.Cookies())
|
||||
|
||||
var got map[string]interface{}
|
||||
var got map[string]any
|
||||
_ = json.NewDecoder(resp.Body).Decode(&got)
|
||||
assert.Equal(t, "approved", got["status"])
|
||||
assert.Nil(t, got["sessionJwt"])
|
||||
@@ -312,7 +312,7 @@ func TestVerifyLoginCode_VerifyOnlySharedBrowserDifferentSubjectApprovesOnly(t *
|
||||
app := fiber.New()
|
||||
app.Post("/api/v1/auth/login/code/verify", h.VerifyLoginCode)
|
||||
|
||||
body, _ := json.Marshal(map[string]interface{}{
|
||||
body, _ := json.Marshal(map[string]any{
|
||||
"loginId": "user@example.com",
|
||||
"code": "569765",
|
||||
"pendingRef": "pending-123",
|
||||
@@ -326,7 +326,7 @@ func TestVerifyLoginCode_VerifyOnlySharedBrowserDifferentSubjectApprovesOnly(t *
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
assert.Empty(t, resp.Cookies())
|
||||
|
||||
var got map[string]interface{}
|
||||
var got map[string]any
|
||||
_ = json.NewDecoder(resp.Body).Decode(&got)
|
||||
assert.Equal(t, "approved", got["status"])
|
||||
assert.Nil(t, got["sessionJwt"])
|
||||
@@ -349,7 +349,7 @@ func TestVerifyLoginCode_MapsSmsPhoneBeforeFlowLookup(t *testing.T) {
|
||||
app := fiber.New()
|
||||
app.Post("/api/v1/auth/login/code/verify", h.VerifyLoginCode)
|
||||
|
||||
body, _ := json.Marshal(map[string]interface{}{
|
||||
body, _ := json.Marshal(map[string]any{
|
||||
"loginId": "01041585840",
|
||||
"code": "569765",
|
||||
"pendingRef": "pending-123",
|
||||
@@ -360,7 +360,7 @@ func TestVerifyLoginCode_MapsSmsPhoneBeforeFlowLookup(t *testing.T) {
|
||||
resp, _ := app.Test(req, -1)
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
var got map[string]interface{}
|
||||
var got map[string]any
|
||||
_ = json.NewDecoder(resp.Body).Decode(&got)
|
||||
assert.Equal(t, "approved", got["status"])
|
||||
assert.Equal(t, "pending-123", got["pendingRef"])
|
||||
@@ -383,7 +383,7 @@ func TestPollEnchantedLink_ExpiredToken_ReturnsCode(t *testing.T) {
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
var got map[string]interface{}
|
||||
var got map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&got)
|
||||
assert.Equal(t, "expired_token", got["error"])
|
||||
assert.Equal(t, "expired_token", got["code"])
|
||||
@@ -415,7 +415,7 @@ func TestPollEnchantedLink_SharedBrowserSameSubjectIssuesSession(t *testing.T) {
|
||||
resp, _ := app.Test(req, -1)
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
var got map[string]interface{}
|
||||
var got map[string]any
|
||||
_ = json.NewDecoder(resp.Body).Decode(&got)
|
||||
assert.Equal(t, "ok", got["status"])
|
||||
assert.Equal(t, "valid-jwt", got["sessionJwt"])
|
||||
@@ -447,7 +447,7 @@ func TestPollEnchantedLink_SharedBrowserDifferentSubjectConflicts(t *testing.T)
|
||||
resp, _ := app.Test(req, -1)
|
||||
|
||||
assert.Equal(t, http.StatusConflict, resp.StatusCode)
|
||||
var got map[string]interface{}
|
||||
var got map[string]any
|
||||
_ = json.NewDecoder(resp.Body).Decode(&got)
|
||||
assert.Equal(t, "session_subject_conflict", got["code"])
|
||||
assert.NotContains(t, redis.data[prefixSession+"pending-123"], "valid-jwt")
|
||||
@@ -481,7 +481,7 @@ func TestHeadlessLinkInit_HeadlessLoginClientSuccess(t *testing.T) {
|
||||
Client: domain.HydraClient{
|
||||
ClientID: "headless-login-client",
|
||||
TokenEndpointAuthMethod: "none",
|
||||
Metadata: map[string]interface{}{
|
||||
Metadata: map[string]any{
|
||||
"status": "active",
|
||||
"headless_login_enabled": true,
|
||||
"headless_token_endpoint_auth_method": "private_key_jwt",
|
||||
@@ -519,7 +519,7 @@ func TestHeadlessLinkInit_HeadlessLoginClientSuccess(t *testing.T) {
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
var got map[string]interface{}
|
||||
var got map[string]any
|
||||
_ = json.NewDecoder(resp.Body).Decode(&got)
|
||||
assert.NotEmpty(t, got["pendingRef"])
|
||||
_, hasUserCode := got["userCode"]
|
||||
@@ -551,7 +551,7 @@ func TestHeadlessLinkPoll_AfterApprovalReturnsRedirect(t *testing.T) {
|
||||
ClientID: "headless-login-client",
|
||||
ClientName: "local-demo-rp",
|
||||
TokenEndpointAuthMethod: "none",
|
||||
Metadata: map[string]interface{}{
|
||||
Metadata: map[string]any{
|
||||
"status": "active",
|
||||
"headless_login_enabled": true,
|
||||
"headless_token_endpoint_auth_method": "private_key_jwt",
|
||||
@@ -604,7 +604,7 @@ func TestHeadlessLinkPoll_AfterApprovalReturnsRedirect(t *testing.T) {
|
||||
resp, _ := app.Test(req, -1)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
var initResp map[string]interface{}
|
||||
var initResp map[string]any
|
||||
_ = json.NewDecoder(resp.Body).Decode(&initResp)
|
||||
pendingRef := initResp["pendingRef"].(string)
|
||||
assert.NotEmpty(t, pendingRef)
|
||||
@@ -618,7 +618,7 @@ func TestHeadlessLinkPoll_AfterApprovalReturnsRedirect(t *testing.T) {
|
||||
}
|
||||
assert.NotEmpty(t, token)
|
||||
|
||||
verifyBody, _ := json.Marshal(map[string]interface{}{
|
||||
verifyBody, _ := json.Marshal(map[string]any{
|
||||
"token": token,
|
||||
"verifyOnly": true,
|
||||
})
|
||||
@@ -637,7 +637,7 @@ func TestHeadlessLinkPoll_AfterApprovalReturnsRedirect(t *testing.T) {
|
||||
resp, _ = app.Test(req, -1)
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
var pollResp map[string]interface{}
|
||||
var pollResp map[string]any
|
||||
_ = json.NewDecoder(resp.Body).Decode(&pollResp)
|
||||
assert.Equal(t, "http://rp/cb", pollResp["redirectTo"])
|
||||
assert.Equal(t, "ok", pollResp["status"])
|
||||
@@ -677,7 +677,7 @@ func TestHeadlessLinkPoll_ApproverSubjectConflictBlocksMixedRP(t *testing.T) {
|
||||
ClientID: "headless-login-client",
|
||||
ClientName: "local-demo-rp",
|
||||
TokenEndpointAuthMethod: "none",
|
||||
Metadata: map[string]interface{}{
|
||||
Metadata: map[string]any{
|
||||
"status": "active",
|
||||
"headless_login_enabled": true,
|
||||
"headless_token_endpoint_auth_method": "private_key_jwt",
|
||||
@@ -734,7 +734,7 @@ func TestHeadlessLinkPoll_ApproverSubjectConflictBlocksMixedRP(t *testing.T) {
|
||||
resp, _ := app.Test(req, -1)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
var initResp map[string]interface{}
|
||||
var initResp map[string]any
|
||||
_ = json.NewDecoder(resp.Body).Decode(&initResp)
|
||||
pendingRef := initResp["pendingRef"].(string)
|
||||
assert.NotEmpty(t, pendingRef)
|
||||
@@ -751,7 +751,7 @@ func TestHeadlessLinkPoll_ApproverSubjectConflictBlocksMixedRP(t *testing.T) {
|
||||
kratosPublic := newKratosWhoamiTestServer(t, "kratos-userfront-a")
|
||||
t.Setenv("KRATOS_PUBLIC_URL", kratosPublic.URL)
|
||||
|
||||
verifyBody, _ := json.Marshal(map[string]interface{}{
|
||||
verifyBody, _ := json.Marshal(map[string]any{
|
||||
"token": token,
|
||||
"verifyOnly": true,
|
||||
})
|
||||
@@ -773,7 +773,7 @@ func TestHeadlessLinkPoll_ApproverSubjectConflictBlocksMixedRP(t *testing.T) {
|
||||
assert.Equal(t, http.StatusConflict, resp.StatusCode)
|
||||
assert.False(t, acceptCalled)
|
||||
assert.Empty(t, resp.Cookies())
|
||||
var got map[string]interface{}
|
||||
var got map[string]any
|
||||
_ = json.NewDecoder(resp.Body).Decode(&got)
|
||||
assert.Equal(t, "oidc_subject_conflict", got["code"])
|
||||
assert.Equal(t, "redirect_to_userfront_login", got["recommendedAction"])
|
||||
@@ -802,7 +802,7 @@ func TestHeadlessLinkPoll_RequestCookieSubjectConflictBlocksMixedRP(t *testing.T
|
||||
Client: domain.HydraClient{
|
||||
ClientID: "headless-login-client",
|
||||
TokenEndpointAuthMethod: "none",
|
||||
Metadata: map[string]interface{}{
|
||||
Metadata: map[string]any{
|
||||
"status": "active",
|
||||
"headless_login_enabled": true,
|
||||
"headless_token_endpoint_auth_method": "private_key_jwt",
|
||||
@@ -857,7 +857,7 @@ func TestHeadlessLinkPoll_RequestCookieSubjectConflictBlocksMixedRP(t *testing.T
|
||||
resp, _ := app.Test(req, -1)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
var initResp map[string]interface{}
|
||||
var initResp map[string]any
|
||||
_ = json.NewDecoder(resp.Body).Decode(&initResp)
|
||||
pendingRef := initResp["pendingRef"].(string)
|
||||
assert.NotEmpty(t, pendingRef)
|
||||
@@ -871,7 +871,7 @@ func TestHeadlessLinkPoll_RequestCookieSubjectConflictBlocksMixedRP(t *testing.T
|
||||
}
|
||||
assert.NotEmpty(t, token)
|
||||
|
||||
verifyBody, _ := json.Marshal(map[string]interface{}{
|
||||
verifyBody, _ := json.Marshal(map[string]any{
|
||||
"token": token,
|
||||
"verifyOnly": true,
|
||||
})
|
||||
@@ -896,7 +896,7 @@ func TestHeadlessLinkPoll_RequestCookieSubjectConflictBlocksMixedRP(t *testing.T
|
||||
assert.Equal(t, http.StatusConflict, resp.StatusCode)
|
||||
assert.False(t, acceptCalled)
|
||||
assert.Empty(t, resp.Cookies())
|
||||
var got map[string]interface{}
|
||||
var got map[string]any
|
||||
_ = json.NewDecoder(resp.Body).Decode(&got)
|
||||
assert.Equal(t, "oidc_subject_conflict", got["code"])
|
||||
assert.Equal(t, "kratos-userfront-a", got["currentSubject"])
|
||||
|
||||
@@ -32,10 +32,10 @@ func TestListLinkedRps_PriorityAndAggregation(t *testing.T) {
|
||||
if r.Header.Get("X-Session-Token") == "" && r.Header.Get("Cookie") == "" {
|
||||
return httpResponse(r, http.StatusUnauthorized, "unauthorized"), nil
|
||||
}
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
"identity": map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"identity": map[string]any{
|
||||
"id": "user-123",
|
||||
"traits": map[string]interface{}{
|
||||
"traits": map[string]any{
|
||||
"email": "user@test.com",
|
||||
},
|
||||
},
|
||||
@@ -43,9 +43,9 @@ func TestListLinkedRps_PriorityAndAggregation(t *testing.T) {
|
||||
}
|
||||
case "hydra.test":
|
||||
if r.URL.Path == "/oauth2/auth/sessions/consent" {
|
||||
return httpJSONAny(r, http.StatusOK, []map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, []map[string]any{
|
||||
{
|
||||
"client": map[string]interface{}{
|
||||
"client": map[string]any{
|
||||
"client_id": "devfront",
|
||||
"client_name": "DevFront",
|
||||
"redirect_uris": []string{
|
||||
@@ -56,10 +56,10 @@ func TestListLinkedRps_PriorityAndAggregation(t *testing.T) {
|
||||
"handled_at": time.Now().Format(time.RFC3339),
|
||||
},
|
||||
{
|
||||
"client": map[string]interface{}{
|
||||
"client": map[string]any{
|
||||
"client_id": "orgfront",
|
||||
"client_name": "OrgFront",
|
||||
"metadata": map[string]interface{}{
|
||||
"metadata": map[string]any{
|
||||
"auto_login_supported": true,
|
||||
"auto_login_url": "http://localhost:5175/login",
|
||||
},
|
||||
@@ -73,13 +73,13 @@ func TestListLinkedRps_PriorityAndAggregation(t *testing.T) {
|
||||
}), nil
|
||||
}
|
||||
if r.URL.Path == "/admin/clients/client-audit" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"client_id": "client-audit",
|
||||
"client_name": "Audit App",
|
||||
}), nil
|
||||
}
|
||||
if r.URL.Path == "/admin/clients/client-consent" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"client_id": "client-consent",
|
||||
"client_name": "Consent App",
|
||||
}), nil
|
||||
@@ -206,17 +206,17 @@ func TestListLinkedRps_EnrichesLogoFromHydraClientWhenConsentSessionOmitsMetadat
|
||||
switch r.URL.Host {
|
||||
case "kratos.test":
|
||||
if r.URL.Path == "/sessions/whoami" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
"identity": map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"identity": map[string]any{
|
||||
"id": "user-123",
|
||||
},
|
||||
}), nil
|
||||
}
|
||||
case "hydra.test":
|
||||
if r.URL.Path == "/oauth2/auth/sessions/consent" {
|
||||
return httpJSONAny(r, http.StatusOK, []map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, []map[string]any{
|
||||
{
|
||||
"client": map[string]interface{}{
|
||||
"client": map[string]any{
|
||||
"client_id": "gitea-client",
|
||||
"client_name": "Gitea",
|
||||
"redirect_uris": []string{
|
||||
@@ -229,13 +229,13 @@ func TestListLinkedRps_EnrichesLogoFromHydraClientWhenConsentSessionOmitsMetadat
|
||||
}), nil
|
||||
}
|
||||
if r.URL.Path == "/clients/gitea-client" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"client_id": "gitea-client",
|
||||
"client_name": "Gitea",
|
||||
"redirect_uris": []string{
|
||||
"https://gitea.example.com/callback",
|
||||
},
|
||||
"metadata": map[string]interface{}{
|
||||
"metadata": map[string]any{
|
||||
"logo_url": "https://cdn.example.com/gitea.svg",
|
||||
},
|
||||
}), nil
|
||||
|
||||
@@ -32,6 +32,7 @@ import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// --- Mocks ---
|
||||
@@ -113,7 +114,7 @@ func (m *MockKratosAdminService) ListIdentities(ctx context.Context) ([]service.
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (m *MockKratosAdminService) UpdateIdentity(ctx context.Context, identityID string, traits map[string]interface{}, state string) (*service.KratosIdentity, error) {
|
||||
func (m *MockKratosAdminService) UpdateIdentity(ctx context.Context, identityID string, traits map[string]any, state string) (*service.KratosIdentity, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -214,6 +215,8 @@ func (r *passwordLoginUserRepo) FindByCompanyCodes(ctx context.Context, codes []
|
||||
|
||||
func (r *passwordLoginUserRepo) Delete(ctx context.Context, id string) error { return nil }
|
||||
|
||||
func (r *passwordLoginUserRepo) DB() *gorm.DB { return nil }
|
||||
|
||||
func (r *passwordLoginUserRepo) UpdateUserLoginIDs(ctx context.Context, userID string, loginIDs []domain.UserLoginID) error {
|
||||
return nil
|
||||
}
|
||||
@@ -474,7 +477,7 @@ func runHeadlessPasswordLoginWithAssertionRequest(
|
||||
Client: domain.HydraClient{
|
||||
ClientID: "headless-login-client",
|
||||
TokenEndpointAuthMethod: "none",
|
||||
Metadata: map[string]interface{}{
|
||||
Metadata: map[string]any{
|
||||
"status": "active",
|
||||
"headless_login_enabled": true,
|
||||
"headless_token_endpoint_auth_method": "private_key_jwt",
|
||||
@@ -579,7 +582,7 @@ func runHeadlessPasswordLoginWithAssertionAndLoggerRequest(
|
||||
Client: domain.HydraClient{
|
||||
ClientID: "headless-login-client",
|
||||
TokenEndpointAuthMethod: "none",
|
||||
Metadata: map[string]interface{}{
|
||||
Metadata: map[string]any{
|
||||
"status": "active",
|
||||
"headless_login_enabled": true,
|
||||
"headless_token_endpoint_auth_method": "private_key_jwt",
|
||||
@@ -667,7 +670,7 @@ func TestPasswordLogin_OIDC_Success(t *testing.T) {
|
||||
}
|
||||
json.NewEncoder(w).Encode(domain.HydraLoginRequest{
|
||||
Challenge: challenge,
|
||||
Client: domain.HydraClient{ClientID: "client-1", Metadata: map[string]interface{}{"status": "active"}},
|
||||
Client: domain.HydraClient{ClientID: "client-1", Metadata: map[string]any{"status": "active"}},
|
||||
})
|
||||
case strings.Contains(r.URL.Path, "/oauth2/auth/requests/login/accept") && r.Method == http.MethodPut:
|
||||
// AcceptLoginRequest
|
||||
@@ -710,7 +713,7 @@ func TestPasswordLogin_OIDC_Success(t *testing.T) {
|
||||
t.Fatalf("expected 200, got %d, body: %s", resp.StatusCode, string(bodyBytes))
|
||||
}
|
||||
|
||||
var got map[string]interface{}
|
||||
var got map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&got)
|
||||
if got["redirectTo"] != "http://rp/cb" {
|
||||
t.Errorf("expected redirectTo http://rp/cb, got %v", got["redirectTo"])
|
||||
@@ -738,7 +741,7 @@ func TestPasswordLogin_OIDC_AuditIncludesClientMetadata(t *testing.T) {
|
||||
Client: domain.HydraClient{
|
||||
ClientID: "devfront",
|
||||
ClientName: "DevFront",
|
||||
Metadata: map[string]interface{}{"status": "active"},
|
||||
Metadata: map[string]any{"status": "active"},
|
||||
},
|
||||
})
|
||||
case strings.Contains(r.URL.Path, "/oauth2/auth/requests/login/accept") && r.Method == http.MethodPut:
|
||||
@@ -902,7 +905,7 @@ func TestHeadlessPasswordLogin_HeadlessLoginClientSuccess(t *testing.T) {
|
||||
Client: domain.HydraClient{
|
||||
ClientID: "headless-login-client",
|
||||
TokenEndpointAuthMethod: "none",
|
||||
Metadata: map[string]interface{}{
|
||||
Metadata: map[string]any{
|
||||
"status": "active",
|
||||
"headless_login_enabled": true,
|
||||
"headless_token_endpoint_auth_method": "private_key_jwt",
|
||||
@@ -958,7 +961,7 @@ func TestHeadlessPasswordLogin_HeadlessLoginClientSuccess(t *testing.T) {
|
||||
t.Fatalf("expected 200, got %d, body: %s", resp.StatusCode, string(bodyBytes))
|
||||
}
|
||||
|
||||
var got map[string]interface{}
|
||||
var got map[string]any
|
||||
if err := json.NewDecoder(resp.Body).Decode(&got); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
@@ -1005,7 +1008,7 @@ func TestHeadlessPasswordLogin_OIDCSubjectConflictBlocksMixedRP(t *testing.T) {
|
||||
Client: domain.HydraClient{
|
||||
ClientID: "headless-login-client",
|
||||
TokenEndpointAuthMethod: "none",
|
||||
Metadata: map[string]interface{}{
|
||||
Metadata: map[string]any{
|
||||
"status": "active",
|
||||
"headless_login_enabled": true,
|
||||
"headless_token_endpoint_auth_method": "private_key_jwt",
|
||||
@@ -1051,7 +1054,7 @@ func TestHeadlessPasswordLogin_OIDCSubjectConflictBlocksMixedRP(t *testing.T) {
|
||||
require.Equal(t, http.StatusConflict, resp.StatusCode)
|
||||
require.False(t, acceptCalled)
|
||||
require.Empty(t, resp.Cookies())
|
||||
var got map[string]interface{}
|
||||
var got map[string]any
|
||||
require.NoError(t, json.NewDecoder(resp.Body).Decode(&got))
|
||||
require.Equal(t, "oidc_subject_conflict", got["code"])
|
||||
require.Equal(t, "redirect_to_userfront_login", got["recommendedAction"])
|
||||
@@ -1090,7 +1093,7 @@ func TestHeadlessPasswordLogin_OIDCSubjectSameAllowsMixedRP(t *testing.T) {
|
||||
Client: domain.HydraClient{
|
||||
ClientID: "headless-login-client",
|
||||
TokenEndpointAuthMethod: "none",
|
||||
Metadata: map[string]interface{}{
|
||||
Metadata: map[string]any{
|
||||
"status": "active",
|
||||
"headless_login_enabled": true,
|
||||
"headless_token_endpoint_auth_method": "private_key_jwt",
|
||||
@@ -1134,7 +1137,7 @@ func TestHeadlessPasswordLogin_OIDCSubjectSameAllowsMixedRP(t *testing.T) {
|
||||
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
require.Empty(t, resp.Cookies())
|
||||
var got map[string]interface{}
|
||||
var got map[string]any
|
||||
require.NoError(t, json.NewDecoder(resp.Body).Decode(&got))
|
||||
require.Equal(t, "http://rp/cb", got["redirectTo"])
|
||||
require.Nil(t, got["sessionJwt"])
|
||||
@@ -1161,7 +1164,7 @@ func TestHeadlessPasswordLogin_AuditIncludesClientMetadata(t *testing.T) {
|
||||
ClientID: "headless-login-client",
|
||||
ClientName: "Headless Login Portal",
|
||||
TokenEndpointAuthMethod: "none",
|
||||
Metadata: map[string]interface{}{
|
||||
Metadata: map[string]any{
|
||||
"status": "active",
|
||||
"headless_login_enabled": true,
|
||||
"headless_token_endpoint_auth_method": "private_key_jwt",
|
||||
@@ -1294,7 +1297,7 @@ func TestHeadlessPasswordLogin_IgnoresInlineHeadlessJWKSWhenJWKSURIIsConfigured(
|
||||
Client: domain.HydraClient{
|
||||
ClientID: "headless-login-client",
|
||||
TokenEndpointAuthMethod: "none",
|
||||
Metadata: map[string]interface{}{
|
||||
Metadata: map[string]any{
|
||||
"status": "active",
|
||||
"headless_login_enabled": true,
|
||||
"headless_token_endpoint_auth_method": "private_key_jwt",
|
||||
@@ -1395,7 +1398,7 @@ func TestHeadlessPasswordLogin_RefreshesJWKSWhenSignatureFailsForCachedKid(t *te
|
||||
Client: domain.HydraClient{
|
||||
ClientID: "headless-login-client",
|
||||
TokenEndpointAuthMethod: "none",
|
||||
Metadata: map[string]interface{}{
|
||||
Metadata: map[string]any{
|
||||
"status": "active",
|
||||
"headless_login_enabled": true,
|
||||
"headless_token_endpoint_auth_method": "private_key_jwt",
|
||||
@@ -1494,7 +1497,7 @@ func TestHeadlessPasswordLogin_MissingClientAssertionRejected(t *testing.T) {
|
||||
Client: domain.HydraClient{
|
||||
ClientID: "headless-login-client",
|
||||
TokenEndpointAuthMethod: "none",
|
||||
Metadata: map[string]interface{}{
|
||||
Metadata: map[string]any{
|
||||
"status": "active",
|
||||
"headless_login_enabled": true,
|
||||
"headless_token_endpoint_auth_method": "private_key_jwt",
|
||||
@@ -1573,7 +1576,7 @@ func TestHeadlessPasswordLogin_InvalidClientAssertionRejected(t *testing.T) {
|
||||
Client: domain.HydraClient{
|
||||
ClientID: "headless-login-client",
|
||||
TokenEndpointAuthMethod: "none",
|
||||
Metadata: map[string]interface{}{
|
||||
Metadata: map[string]any{
|
||||
"status": "active",
|
||||
"headless_login_enabled": true,
|
||||
"headless_token_endpoint_auth_method": "private_key_jwt",
|
||||
@@ -1995,7 +1998,7 @@ func TestHeadlessPasswordLogin_HeadlessDisabledRejected(t *testing.T) {
|
||||
Client: domain.HydraClient{
|
||||
ClientID: "headless-login-client",
|
||||
TokenEndpointAuthMethod: "none",
|
||||
Metadata: map[string]interface{}{
|
||||
Metadata: map[string]any{
|
||||
"status": "active",
|
||||
"headless_jwks_uri": "https://rp.example.com/.well-known/jwks.json",
|
||||
"headless_token_endpoint_auth_method": "private_key_jwt",
|
||||
@@ -2048,7 +2051,7 @@ func TestHeadlessPasswordLogin_ClientIDMismatchRejected(t *testing.T) {
|
||||
Client: domain.HydraClient{
|
||||
ClientID: "other-rp",
|
||||
TokenEndpointAuthMethod: "none",
|
||||
Metadata: map[string]interface{}{
|
||||
Metadata: map[string]any{
|
||||
"status": "active",
|
||||
"headless_login_enabled": true,
|
||||
"headless_token_endpoint_auth_method": "private_key_jwt",
|
||||
@@ -2102,7 +2105,7 @@ func TestPasswordLogin_OIDC_InactiveClient(t *testing.T) {
|
||||
hydraHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.Contains(r.URL.Path, "/oauth2/auth/requests/login") && r.Method == http.MethodGet {
|
||||
json.NewEncoder(w).Encode(domain.HydraLoginRequest{
|
||||
Client: domain.HydraClient{ClientID: "client-inactive", Metadata: map[string]interface{}{"status": "inactive"}},
|
||||
Client: domain.HydraClient{ClientID: "client-inactive", Metadata: map[string]any{"status": "inactive"}},
|
||||
})
|
||||
return
|
||||
}
|
||||
@@ -2220,7 +2223,7 @@ func TestPasswordLogin_SharedBrowserSameSubjectAllowed(t *testing.T) {
|
||||
defer resp.Body.Close()
|
||||
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
var got map[string]interface{}
|
||||
var got map[string]any
|
||||
require.NoError(t, json.NewDecoder(resp.Body).Decode(&got))
|
||||
require.Equal(t, "valid-jwt", got["sessionJwt"])
|
||||
mockIdp.AssertExpectations(t)
|
||||
@@ -2259,7 +2262,7 @@ func TestPasswordLogin_SharedBrowserDifferentSubjectConflicts(t *testing.T) {
|
||||
defer resp.Body.Close()
|
||||
|
||||
require.Equal(t, http.StatusConflict, resp.StatusCode)
|
||||
var got map[string]interface{}
|
||||
var got map[string]any
|
||||
require.NoError(t, json.NewDecoder(resp.Body).Decode(&got))
|
||||
require.Equal(t, "session_subject_conflict", got["code"])
|
||||
require.Empty(t, resp.Cookies())
|
||||
|
||||
@@ -33,10 +33,10 @@ func TestAcceptOidcLoginRequest_CookieOnly(t *testing.T) {
|
||||
if r.Header.Get("Cookie") == "" {
|
||||
return httpResponse(r, http.StatusUnauthorized, "missing cookie"), nil
|
||||
}
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
"identity": map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"identity": map[string]any{
|
||||
"id": "kratos-123",
|
||||
"traits": map[string]interface{}{},
|
||||
"traits": map[string]any{},
|
||||
},
|
||||
}), nil
|
||||
case "hydra.test":
|
||||
@@ -45,7 +45,7 @@ func TestAcceptOidcLoginRequest_CookieOnly(t *testing.T) {
|
||||
}
|
||||
gotChallenge = r.URL.Query().Get("login_challenge")
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
var payload map[string]interface{}
|
||||
var payload map[string]any
|
||||
_ = json.Unmarshal(body, &payload)
|
||||
if subject, ok := payload["subject"].(string); ok {
|
||||
gotSubject = subject
|
||||
@@ -117,10 +117,10 @@ func TestAcceptOidcLoginRequest_TokenFallbackToCookie(t *testing.T) {
|
||||
if r.Header.Get("Cookie") == "" {
|
||||
return httpResponse(r, http.StatusUnauthorized, "missing cookie"), nil
|
||||
}
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
"identity": map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"identity": map[string]any{
|
||||
"id": "kratos-456",
|
||||
"traits": map[string]interface{}{},
|
||||
"traits": map[string]any{},
|
||||
},
|
||||
}), nil
|
||||
case "hydra.test":
|
||||
@@ -128,7 +128,7 @@ func TestAcceptOidcLoginRequest_TokenFallbackToCookie(t *testing.T) {
|
||||
return httpResponse(r, http.StatusNotFound, "not found"), nil
|
||||
}
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
var payload map[string]interface{}
|
||||
var payload map[string]any
|
||||
_ = json.Unmarshal(body, &payload)
|
||||
if subject, ok := payload["subject"].(string); ok {
|
||||
gotSubject = subject
|
||||
|
||||
@@ -23,10 +23,10 @@ func TestHandleKratosCourierRelay_Email(t *testing.T) {
|
||||
app.Post("/api/v1/auth/kratos/courier", h.HandleKratosCourierRelay)
|
||||
|
||||
// Simulate Kratos Courier Request for Email
|
||||
reqBody := map[string]interface{}{
|
||||
reqBody := map[string]any{
|
||||
"recipient": "user@example.com",
|
||||
"template_type": "verification_code",
|
||||
"template_data": map[string]interface{}{
|
||||
"template_data": map[string]any{
|
||||
"verification_code": "123456",
|
||||
},
|
||||
"subject": "Verify your email",
|
||||
@@ -50,7 +50,7 @@ func TestVerifySignupCode_Success(t *testing.T) {
|
||||
|
||||
// Mock stored code in redis
|
||||
// signup:email:user@test.com -> {"code":"654321", "verified":false, "expires_at":...}
|
||||
state := map[string]interface{}{
|
||||
state := map[string]any{
|
||||
"code": "654321",
|
||||
"verified": false,
|
||||
"expires_at": 9999999999, // far future
|
||||
@@ -71,13 +71,13 @@ func TestVerifySignupCode_Success(t *testing.T) {
|
||||
resp, _ := app.Test(req, -1)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
var res map[string]interface{}
|
||||
var res map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&res)
|
||||
assert.True(t, res["success"].(bool))
|
||||
|
||||
// Check redis state updated to verified
|
||||
val, _ := redis.Get("signup:email:user@test.com")
|
||||
var updatedState map[string]interface{}
|
||||
var updatedState map[string]any
|
||||
json.Unmarshal([]byte(val), &updatedState)
|
||||
assert.True(t, updatedState["verified"].(bool))
|
||||
}
|
||||
@@ -90,7 +90,7 @@ func TestVerifySignupCode_Invalid(t *testing.T) {
|
||||
app := fiber.New()
|
||||
app.Post("/api/v1/auth/signup/verify", h.VerifySignupCode)
|
||||
|
||||
stateJSON, _ := json.Marshal(map[string]interface{}{
|
||||
stateJSON, _ := json.Marshal(map[string]any{
|
||||
"code": "111111",
|
||||
"expires_at": 9999999999,
|
||||
})
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"maps"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
@@ -33,7 +34,7 @@ func (r *recordingUpdateMeUserRepo) UpdateUserLoginIDs(ctx context.Context, user
|
||||
func TestUpdateMe_InvalidatesProfileCacheForTokenSession(t *testing.T) {
|
||||
token := "token-abc"
|
||||
identityID := "user-1"
|
||||
traits := map[string]interface{}{
|
||||
traits := map[string]any{
|
||||
"email": "qa@example.com",
|
||||
"name": "QA User",
|
||||
"phone_number": "+821012345678",
|
||||
@@ -51,8 +52,8 @@ func TestUpdateMe_InvalidatesProfileCacheForTokenSession(t *testing.T) {
|
||||
if r.Header.Get("X-Session-Token") != token {
|
||||
return httpResponse(r, http.StatusUnauthorized, `{"error":"invalid token"}`), nil
|
||||
}
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
"identity": map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"identity": map[string]any{
|
||||
"id": identityID,
|
||||
"traits": traits,
|
||||
},
|
||||
@@ -62,14 +63,12 @@ func TestUpdateMe_InvalidatesProfileCacheForTokenSession(t *testing.T) {
|
||||
r.URL.Path == "/admin/identities/"+identityID &&
|
||||
r.Method == http.MethodPut:
|
||||
var payload struct {
|
||||
Traits map[string]interface{} `json:"traits"`
|
||||
Traits map[string]any `json:"traits"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
|
||||
return httpResponse(r, http.StatusBadRequest, `{"error":"invalid body"}`), nil
|
||||
}
|
||||
for k, v := range payload.Traits {
|
||||
traits[k] = v
|
||||
}
|
||||
maps.Copy(traits, payload.Traits)
|
||||
return httpResponse(r, http.StatusOK, `{"ok":true}`), nil
|
||||
}
|
||||
|
||||
@@ -93,7 +92,7 @@ func TestUpdateMe_InvalidatesProfileCacheForTokenSession(t *testing.T) {
|
||||
getResp1, err := app.Test(getReq1, -1)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, http.StatusOK, getResp1.StatusCode)
|
||||
var profile1 map[string]interface{}
|
||||
var profile1 map[string]any
|
||||
require.NoError(t, json.NewDecoder(getResp1.Body).Decode(&profile1))
|
||||
require.Equal(t, "Old Dept", profile1["department"])
|
||||
|
||||
@@ -121,7 +120,7 @@ func TestUpdateMe_InvalidatesProfileCacheForTokenSession(t *testing.T) {
|
||||
getResp2, err := app.Test(getReq2, -1)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, http.StatusOK, getResp2.StatusCode)
|
||||
var profile2 map[string]interface{}
|
||||
var profile2 map[string]any
|
||||
require.NoError(t, json.NewDecoder(getResp2.Body).Decode(&profile2))
|
||||
require.Equal(t, "New Dept", profile2["department"])
|
||||
}
|
||||
@@ -129,7 +128,7 @@ func TestUpdateMe_InvalidatesProfileCacheForTokenSession(t *testing.T) {
|
||||
func TestUpdateMe_SyncsLocalReadModelFields(t *testing.T) {
|
||||
token := "token-sync"
|
||||
identityID := "user-sync"
|
||||
traits := map[string]interface{}{
|
||||
traits := map[string]any{
|
||||
"email": "sync@example.com",
|
||||
"name": "Old Name",
|
||||
"phone_number": "+821012345678",
|
||||
@@ -148,8 +147,8 @@ func TestUpdateMe_SyncsLocalReadModelFields(t *testing.T) {
|
||||
if r.Header.Get("X-Session-Token") != token {
|
||||
return httpResponse(r, http.StatusUnauthorized, `{"error":"invalid token"}`), nil
|
||||
}
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
"identity": map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"identity": map[string]any{
|
||||
"id": identityID,
|
||||
"traits": traits,
|
||||
},
|
||||
@@ -159,14 +158,12 @@ func TestUpdateMe_SyncsLocalReadModelFields(t *testing.T) {
|
||||
r.URL.Path == "/admin/identities/"+identityID &&
|
||||
r.Method == http.MethodPut:
|
||||
var payload struct {
|
||||
Traits map[string]interface{} `json:"traits"`
|
||||
Traits map[string]any `json:"traits"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
|
||||
return httpResponse(r, http.StatusBadRequest, `{"error":"invalid body"}`), nil
|
||||
}
|
||||
for k, v := range payload.Traits {
|
||||
traits[k] = v
|
||||
}
|
||||
maps.Copy(traits, payload.Traits)
|
||||
return httpResponse(r, http.StatusOK, `{"ok":true}`), nil
|
||||
}
|
||||
|
||||
@@ -187,7 +184,7 @@ func TestUpdateMe_SyncsLocalReadModelFields(t *testing.T) {
|
||||
app := fiber.New()
|
||||
app.Put("/api/v1/user/me", h.UpdateMe)
|
||||
|
||||
updateBody, _ := json.Marshal(map[string]interface{}{
|
||||
updateBody, _ := json.Marshal(map[string]any{
|
||||
"name": "New Name",
|
||||
"phone": "01087654321",
|
||||
"department": "New Dept",
|
||||
|
||||
@@ -68,7 +68,7 @@ func TestQRLoginFlow_Success(t *testing.T) {
|
||||
resp, _ := app.Test(req, -1)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
var initResp map[string]interface{}
|
||||
var initResp map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&initResp)
|
||||
pendingRef := initResp["pendingRef"].(string)
|
||||
|
||||
@@ -80,7 +80,7 @@ func TestQRLoginFlow_Success(t *testing.T) {
|
||||
|
||||
// Expect authorization_pending (400)
|
||||
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
|
||||
var pollResp map[string]interface{}
|
||||
var pollResp map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&pollResp)
|
||||
assert.Equal(t, "authorization_pending", pollResp["error"])
|
||||
assert.Equal(t, "authorization_pending", pollResp["code"])
|
||||
@@ -99,7 +99,7 @@ func TestQRLoginFlow_Success(t *testing.T) {
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
var successResp map[string]interface{}
|
||||
var successResp map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&successResp)
|
||||
assert.Equal(t, "ok", successResp["status"])
|
||||
assert.Equal(t, "mock-session-jwt", successResp["sessionJwt"])
|
||||
@@ -121,10 +121,10 @@ func TestScanQRLogin_Success(t *testing.T) {
|
||||
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Path == "/sessions/whoami" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
"identity": map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"identity": map[string]any{
|
||||
"id": "user-123",
|
||||
"traits": map[string]interface{}{
|
||||
"traits": map[string]any{
|
||||
"email": "user@example.com",
|
||||
},
|
||||
},
|
||||
@@ -153,20 +153,20 @@ func TestResolveConsentSubjects_TokenAndCookie(t *testing.T) {
|
||||
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.Header.Get("X-Session-Token") == "token-123" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
"identity": map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"identity": map[string]any{
|
||||
"id": "user-token",
|
||||
"traits": map[string]interface{}{
|
||||
"traits": map[string]any{
|
||||
"email": "token@test.com",
|
||||
},
|
||||
},
|
||||
}), nil
|
||||
}
|
||||
if r.Header.Get("Cookie") == "ory_kratos_session=cookie-123" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
"identity": map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"identity": map[string]any{
|
||||
"id": "user-cookie",
|
||||
"traits": map[string]interface{}{
|
||||
"traits": map[string]any{
|
||||
"email": "cookie@test.com",
|
||||
"phone": "010-1234-5678",
|
||||
},
|
||||
|
||||
@@ -92,7 +92,7 @@ func TestSignup_TenantSlugValidation(t *testing.T) {
|
||||
app.Post("/signup", h.Signup)
|
||||
|
||||
// Prepare mock state (already verified email/phone)
|
||||
verifiedState, _ := json.Marshal(map[string]interface{}{
|
||||
verifiedState, _ := json.Marshal(map[string]any{
|
||||
"verified": true,
|
||||
"expires_at": time.Now().Add(time.Hour).Unix(),
|
||||
})
|
||||
|
||||
@@ -17,9 +17,9 @@ const (
|
||||
clientAllowedTenantsKey = "allowed_tenants"
|
||||
)
|
||||
|
||||
func normalizeClientTenantAccessMetadata(metadata map[string]interface{}) (map[string]interface{}, error) {
|
||||
func normalizeClientTenantAccessMetadata(metadata map[string]any) (map[string]any, error) {
|
||||
if metadata == nil {
|
||||
metadata = map[string]interface{}{}
|
||||
metadata = map[string]any{}
|
||||
}
|
||||
|
||||
restricted := readMetadataBoolValue(metadata, clientTenantAccessRestrictedKey)
|
||||
@@ -49,7 +49,7 @@ func normalizeClientTenantAccessMetadata(metadata map[string]interface{}) (map[s
|
||||
return metadata, nil
|
||||
}
|
||||
|
||||
func clientTenantAccessRestricted(metadata map[string]interface{}) bool {
|
||||
func clientTenantAccessRestricted(metadata map[string]any) bool {
|
||||
if metadata == nil {
|
||||
return false
|
||||
}
|
||||
@@ -59,7 +59,7 @@ func clientTenantAccessRestricted(metadata map[string]interface{}) bool {
|
||||
return len(normalizeMetadataStringSlice(metadata[clientAllowedTenantsKey])) > 0
|
||||
}
|
||||
|
||||
func clientAllowedTenants(metadata map[string]interface{}) []string {
|
||||
func clientAllowedTenants(metadata map[string]any) []string {
|
||||
if metadata == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -250,7 +250,7 @@ func TestGetConsentRequest_DeniesRestrictedClientWhenProfileResolutionFails(t *t
|
||||
mockKratos := new(MockKratosAdminService)
|
||||
mockKratos.On("GetIdentity", mock.Anything, "user-123").Return(&service.KratosIdentity{
|
||||
ID: "user-123",
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"email": "user@test.com",
|
||||
"tenant_id": "tenant-a",
|
||||
"companyCode": "tenant-a",
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"slices"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -94,11 +95,8 @@ func (m *mockAuditRepo) FindByUserAndEvents(ctx context.Context, userID string,
|
||||
var results []domain.AuditLog
|
||||
for _, log := range m.logs {
|
||||
if log.UserID == userID {
|
||||
for _, et := range eventTypes {
|
||||
if log.EventType == et {
|
||||
results = append(results, log)
|
||||
break
|
||||
}
|
||||
if slices.Contains(eventTypes, log.EventType) {
|
||||
results = append(results, log)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -104,21 +105,21 @@ type devRPUsageDailyResponse struct {
|
||||
}
|
||||
|
||||
type clientSummary struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Status string `json:"status"`
|
||||
CreatedAt *time.Time `json:"createdAt,omitempty"`
|
||||
RedirectURIs []string `json:"redirectUris"`
|
||||
Scopes []string `json:"scopes"`
|
||||
ClientSecret string `json:"clientSecret,omitempty"`
|
||||
TokenEndpointAuthMethod string `json:"tokenEndpointAuthMethod,omitempty"`
|
||||
SkipConsent bool `json:"skipConsent"`
|
||||
JwksUri string `json:"jwksUri,omitempty"`
|
||||
Jwks interface{} `json:"jwks,omitempty"`
|
||||
BackchannelLogoutURI string `json:"backchannelLogoutUri,omitempty"`
|
||||
BackchannelLogoutSessionRequired bool `json:"backchannelLogoutSessionRequired"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Status string `json:"status"`
|
||||
CreatedAt *time.Time `json:"createdAt,omitempty"`
|
||||
RedirectURIs []string `json:"redirectUris"`
|
||||
Scopes []string `json:"scopes"`
|
||||
ClientSecret string `json:"clientSecret,omitempty"`
|
||||
TokenEndpointAuthMethod string `json:"tokenEndpointAuthMethod,omitempty"`
|
||||
SkipConsent bool `json:"skipConsent"`
|
||||
JwksUri string `json:"jwksUri,omitempty"`
|
||||
Jwks any `json:"jwks,omitempty"`
|
||||
BackchannelLogoutURI string `json:"backchannelLogoutUri,omitempty"`
|
||||
BackchannelLogoutSessionRequired bool `json:"backchannelLogoutSessionRequired"`
|
||||
Metadata map[string]any `json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
type clientListResponse struct {
|
||||
@@ -198,21 +199,21 @@ type consentListResponse struct {
|
||||
}
|
||||
|
||||
type clientUpsertRequest struct {
|
||||
ID *string `json:"id"`
|
||||
Name *string `json:"name"`
|
||||
Type *string `json:"type"`
|
||||
Status *string `json:"status"`
|
||||
RedirectURIs *[]string `json:"redirectUris"`
|
||||
Scopes *[]string `json:"scopes"`
|
||||
GrantTypes *[]string `json:"grantTypes"`
|
||||
ResponseTypes *[]string `json:"responseTypes"`
|
||||
TokenEndpointAuthMethod *string `json:"tokenEndpointAuthMethod"`
|
||||
SkipConsent *bool `json:"skipConsent"`
|
||||
JwksUri *string `json:"jwksUri"`
|
||||
Jwks interface{} `json:"jwks"`
|
||||
BackchannelLogoutURI *string `json:"backchannelLogoutUri"`
|
||||
BackchannelLogoutSessionRequired *bool `json:"backchannelLogoutSessionRequired"`
|
||||
Metadata *map[string]interface{} `json:"metadata"`
|
||||
ID *string `json:"id"`
|
||||
Name *string `json:"name"`
|
||||
Type *string `json:"type"`
|
||||
Status *string `json:"status"`
|
||||
RedirectURIs *[]string `json:"redirectUris"`
|
||||
Scopes *[]string `json:"scopes"`
|
||||
GrantTypes *[]string `json:"grantTypes"`
|
||||
ResponseTypes *[]string `json:"responseTypes"`
|
||||
TokenEndpointAuthMethod *string `json:"tokenEndpointAuthMethod"`
|
||||
SkipConsent *bool `json:"skipConsent"`
|
||||
JwksUri *string `json:"jwksUri"`
|
||||
Jwks any `json:"jwks"`
|
||||
BackchannelLogoutURI *string `json:"backchannelLogoutUri"`
|
||||
BackchannelLogoutSessionRequired *bool `json:"backchannelLogoutSessionRequired"`
|
||||
Metadata *map[string]any `json:"metadata"`
|
||||
}
|
||||
|
||||
type normalizedIDTokenClaim struct {
|
||||
@@ -303,7 +304,7 @@ func tenantIDFromProfile(profile *domain.UserProfileResponse) string {
|
||||
func addClientIDToSet(set map[string]struct{}, raw any) {
|
||||
switch value := raw.(type) {
|
||||
case string:
|
||||
for _, chunk := range strings.Split(value, ",") {
|
||||
for chunk := range strings.SplitSeq(value, ",") {
|
||||
id := strings.TrimSpace(chunk)
|
||||
if id != "" {
|
||||
set[id] = struct{}{}
|
||||
@@ -672,7 +673,7 @@ func isProtectedSystemClientID(clientID string) bool {
|
||||
return ok
|
||||
}
|
||||
|
||||
func tenantAccessPolicyChanged(before, after map[string]interface{}) bool {
|
||||
func tenantAccessPolicyChanged(before, after map[string]any) bool {
|
||||
if clientTenantAccessRestricted(before) != clientTenantAccessRestricted(after) {
|
||||
return true
|
||||
}
|
||||
@@ -1162,7 +1163,7 @@ func extractAuthClaimsFromBearer(authHeader string) (string, string) {
|
||||
}
|
||||
}
|
||||
|
||||
var claims map[string]interface{}
|
||||
var claims map[string]any
|
||||
if err := json.Unmarshal(payload, &claims); err != nil {
|
||||
return "", ""
|
||||
}
|
||||
@@ -1295,10 +1296,7 @@ func (h *DevHandler) ListClients(c *fiber.Ctx) error {
|
||||
if offset > len(allItems) {
|
||||
offset = len(allItems)
|
||||
}
|
||||
end := offset + limit
|
||||
if end > len(allItems) {
|
||||
end = len(allItems)
|
||||
}
|
||||
end := min(offset+limit, len(allItems))
|
||||
items = allItems[offset:end]
|
||||
if len(allItems) > end && len(items) > 0 {
|
||||
lastTimestamp, lastID := clientSummaryCursorKey(items[len(items)-1])
|
||||
@@ -1788,7 +1786,7 @@ func (h *DevHandler) CreateClient(c *fiber.Ctx) error {
|
||||
|
||||
metadata := mergeMetadata(nil, req.Metadata)
|
||||
if metadata == nil {
|
||||
metadata = map[string]interface{}{}
|
||||
metadata = map[string]any{}
|
||||
}
|
||||
|
||||
// [Tenant Isolation] Record owner information
|
||||
@@ -1858,11 +1856,11 @@ func (h *DevHandler) CreateClient(c *fiber.Ctx) error {
|
||||
ResponseTypes: responseTypes,
|
||||
Scope: strings.Join(scopes, " "),
|
||||
TokenEndpointAuthMethod: tokenAuthMethod,
|
||||
SkipConsent: boolPtr(valueOrBool(req.SkipConsent, true)),
|
||||
SkipConsent: new(valueOrBool(req.SkipConsent, true)),
|
||||
JWKSUri: jwksURI,
|
||||
JWKS: jwks,
|
||||
BackChannelLogoutURI: backchannelLogoutURI,
|
||||
BackChannelLogoutSessionRequired: boolPtr(backchannelLogoutSessionRequired),
|
||||
BackChannelLogoutSessionRequired: new(backchannelLogoutSessionRequired),
|
||||
Metadata: metadata,
|
||||
}
|
||||
|
||||
@@ -2005,7 +2003,7 @@ func (h *DevHandler) UpdateClient(c *fiber.Ctx) error {
|
||||
metadata := mergeMetadata(current.Metadata, req.Metadata)
|
||||
if status != "" {
|
||||
if metadata == nil {
|
||||
metadata = map[string]interface{}{}
|
||||
metadata = map[string]any{}
|
||||
}
|
||||
metadata["status"] = status
|
||||
}
|
||||
@@ -2061,11 +2059,11 @@ func (h *DevHandler) UpdateClient(c *fiber.Ctx) error {
|
||||
ResponseTypes: derefSlice(req.ResponseTypes, current.ResponseTypes),
|
||||
Scope: buildScope(valueOrSlice(req.Scopes, strings.Fields(current.Scope))),
|
||||
TokenEndpointAuthMethod: resolvedTokenAuthMethod,
|
||||
SkipConsent: boolPtr(resolvedSkipConsent),
|
||||
SkipConsent: new(resolvedSkipConsent),
|
||||
JWKSUri: resolvedJWKSURI,
|
||||
JWKS: resolvedJWKS,
|
||||
BackChannelLogoutURI: strings.TrimSpace(resolvedBackchannelLogoutURI),
|
||||
BackChannelLogoutSessionRequired: boolPtr(resolvedBackchannelLogoutSessionRequired),
|
||||
BackChannelLogoutSessionRequired: new(resolvedBackchannelLogoutSessionRequired),
|
||||
Metadata: metadata,
|
||||
}
|
||||
if err := validateReservedSystemClientName(updated.ClientID, updated.ClientName); err != nil {
|
||||
@@ -2359,10 +2357,7 @@ func (h *DevHandler) ListConsents(c *fiber.Ctx) error {
|
||||
if offset > len(items) {
|
||||
offset = len(items)
|
||||
}
|
||||
end := offset + limit
|
||||
if end > len(items) {
|
||||
end = len(items)
|
||||
}
|
||||
end := min(offset+limit, len(items))
|
||||
pageItems := items[offset:end]
|
||||
if len(items) > end && len(pageItems) > 0 {
|
||||
lastTimestamp, lastID := consentSummaryCursorKey(pageItems[len(pageItems)-1])
|
||||
@@ -2948,7 +2943,7 @@ func (h *DevHandler) mapClientSummary(client domain.HydraClient) clientSummary {
|
||||
}
|
||||
}
|
||||
|
||||
func readMetadataStringValue(metadata map[string]interface{}, key string) string {
|
||||
func readMetadataStringValue(metadata map[string]any, key string) string {
|
||||
if metadata == nil {
|
||||
return ""
|
||||
}
|
||||
@@ -2956,7 +2951,7 @@ func readMetadataStringValue(metadata map[string]interface{}, key string) string
|
||||
return strings.TrimSpace(raw)
|
||||
}
|
||||
|
||||
func readMetadataBoolValue(metadata map[string]interface{}, key string) bool {
|
||||
func readMetadataBoolValue(metadata map[string]any, key string) bool {
|
||||
if metadata == nil {
|
||||
return false
|
||||
}
|
||||
@@ -2964,7 +2959,7 @@ func readMetadataBoolValue(metadata map[string]interface{}, key string) bool {
|
||||
return value
|
||||
}
|
||||
|
||||
func readStringSliceMetadata(metadata map[string]interface{}, key string) []string {
|
||||
func readStringSliceMetadata(metadata map[string]any, key string) []string {
|
||||
if metadata == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -2981,7 +2976,7 @@ func readStringSliceMetadata(metadata map[string]interface{}, key string) []stri
|
||||
}
|
||||
}
|
||||
return result
|
||||
case []interface{}:
|
||||
case []any:
|
||||
result := make([]string, 0, len(typed))
|
||||
for _, item := range typed {
|
||||
if str, ok := item.(string); ok {
|
||||
@@ -2996,7 +2991,7 @@ func readStringSliceMetadata(metadata map[string]interface{}, key string) []stri
|
||||
}
|
||||
}
|
||||
|
||||
func readMetadataValueOrNil(metadata map[string]interface{}, key string) interface{} {
|
||||
func readMetadataValueOrNil(metadata map[string]any, key string) any {
|
||||
if metadata == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -3007,9 +3002,9 @@ func readMetadataValueOrNil(metadata map[string]interface{}, key string) interfa
|
||||
return value
|
||||
}
|
||||
|
||||
func normalizeBackchannelLogoutMetadata(metadata map[string]interface{}, logoutURI string, sessionRequired bool) (map[string]interface{}, error) {
|
||||
func normalizeBackchannelLogoutMetadata(metadata map[string]any, logoutURI string, sessionRequired bool) (map[string]any, error) {
|
||||
if metadata == nil {
|
||||
metadata = map[string]interface{}{}
|
||||
metadata = map[string]any{}
|
||||
}
|
||||
|
||||
trimmedURI := strings.TrimSpace(logoutURI)
|
||||
@@ -3078,7 +3073,7 @@ func isAllowedLocalBackchannelLogoutHost(rawHost string) bool {
|
||||
return !strings.Contains(host, ".")
|
||||
}
|
||||
|
||||
func normalizeClientAutoLoginMetadata(metadata map[string]interface{}) (map[string]interface{}, error) {
|
||||
func normalizeClientAutoLoginMetadata(metadata map[string]any) (map[string]any, error) {
|
||||
if metadata == nil {
|
||||
return metadata, nil
|
||||
}
|
||||
@@ -3105,11 +3100,11 @@ func normalizeClientAutoLoginMetadata(metadata map[string]interface{}) (map[stri
|
||||
func normalizeHeadlessClientConfig(
|
||||
tokenAuthMethod string,
|
||||
jwksURI string,
|
||||
jwks interface{},
|
||||
metadata map[string]interface{},
|
||||
) (string, string, interface{}, map[string]interface{}) {
|
||||
jwks any,
|
||||
metadata map[string]any,
|
||||
) (string, string, any, map[string]any) {
|
||||
if metadata == nil {
|
||||
metadata = map[string]interface{}{}
|
||||
metadata = map[string]any{}
|
||||
}
|
||||
delete(metadata, domain.MetadataRequestObjectSigningAlg)
|
||||
|
||||
@@ -3145,7 +3140,7 @@ func normalizeHeadlessClientConfig(
|
||||
return tokenAuthMethod, jwksURI, jwks, metadata
|
||||
}
|
||||
|
||||
func validateHeadlessClientInput(jwksURI string, jwks interface{}, metadata map[string]interface{}) error {
|
||||
func validateHeadlessClientInput(jwksURI string, jwks any, metadata map[string]any) error {
|
||||
if !readMetadataBoolValue(metadata, domain.MetadataHeadlessLoginEnabled) {
|
||||
return nil
|
||||
}
|
||||
@@ -3164,14 +3159,14 @@ func validateHeadlessClientInput(jwksURI string, jwks interface{}, metadata map[
|
||||
return nil
|
||||
}
|
||||
|
||||
func normalizeClientTypeForHeadless(clientType string, metadata map[string]interface{}) string {
|
||||
func normalizeClientTypeForHeadless(clientType string, metadata map[string]any) string {
|
||||
if readMetadataBoolValue(metadata, domain.MetadataHeadlessLoginEnabled) {
|
||||
return "private"
|
||||
}
|
||||
return clientType
|
||||
}
|
||||
|
||||
func normalizeIDTokenClaimsMetadata(metadata map[string]interface{}) (map[string]interface{}, error) {
|
||||
func normalizeIDTokenClaimsMetadata(metadata map[string]any) (map[string]any, error) {
|
||||
if metadata == nil {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -3189,16 +3184,16 @@ func normalizeIDTokenClaimsMetadata(metadata map[string]interface{}) (map[string
|
||||
return metadata, nil
|
||||
}
|
||||
|
||||
func normalizeIDTokenClaims(rawClaims interface{}) ([]normalizedIDTokenClaim, error) {
|
||||
rawList, ok := rawClaims.([]interface{})
|
||||
func normalizeIDTokenClaims(rawClaims any) ([]normalizedIDTokenClaim, error) {
|
||||
rawList, ok := rawClaims.([]any)
|
||||
if !ok {
|
||||
if typedList, ok := rawClaims.([]map[string]interface{}); ok {
|
||||
rawList = make([]interface{}, 0, len(typedList))
|
||||
if typedList, ok := rawClaims.([]map[string]any); ok {
|
||||
rawList = make([]any, 0, len(typedList))
|
||||
for _, item := range typedList {
|
||||
rawList = append(rawList, item)
|
||||
}
|
||||
} else if typedList, ok := rawClaims.([]map[string]any); ok {
|
||||
rawList = make([]interface{}, 0, len(typedList))
|
||||
rawList = make([]any, 0, len(typedList))
|
||||
for _, item := range typedList {
|
||||
rawList = append(rawList, item)
|
||||
}
|
||||
@@ -3211,13 +3206,11 @@ func normalizeIDTokenClaims(rawClaims interface{}) ([]normalizedIDTokenClaim, er
|
||||
seen := make(map[string]struct{}, len(rawList))
|
||||
|
||||
for _, item := range rawList {
|
||||
record, ok := item.(map[string]interface{})
|
||||
record, ok := item.(map[string]any)
|
||||
if !ok {
|
||||
if typedRecord, ok := item.(map[string]any); ok {
|
||||
record = make(map[string]interface{}, len(typedRecord))
|
||||
for key, value := range typedRecord {
|
||||
record[key] = value
|
||||
}
|
||||
record = make(map[string]any, len(typedRecord))
|
||||
maps.Copy(record, typedRecord)
|
||||
} else {
|
||||
return nil, errors.New("metadata.id_token_claims items must be objects")
|
||||
}
|
||||
@@ -3271,7 +3264,7 @@ func normalizeIDTokenClaims(rawClaims interface{}) ([]normalizedIDTokenClaim, er
|
||||
return normalized, nil
|
||||
}
|
||||
|
||||
func readInterfaceString(value interface{}, fallback string) string {
|
||||
func readInterfaceString(value any, fallback string) string {
|
||||
if value == nil {
|
||||
return fallback
|
||||
}
|
||||
@@ -3373,8 +3366,9 @@ func valueOr(ptr *string, fallback string) string {
|
||||
return *ptr
|
||||
}
|
||||
|
||||
//go:fix inline
|
||||
func boolPtr(value bool) *bool {
|
||||
return &value
|
||||
return new(value)
|
||||
}
|
||||
|
||||
func valueOrBool(ptr *bool, fallback bool) bool {
|
||||
@@ -3398,17 +3392,13 @@ func derefSlice(ptr *[]string, fallback []string) []string {
|
||||
return *ptr
|
||||
}
|
||||
|
||||
func mergeMetadata(current map[string]interface{}, incoming *map[string]interface{}) map[string]interface{} {
|
||||
func mergeMetadata(current map[string]any, incoming *map[string]any) map[string]any {
|
||||
if incoming == nil {
|
||||
return current
|
||||
}
|
||||
merged := map[string]interface{}{}
|
||||
for k, v := range current {
|
||||
merged[k] = v
|
||||
}
|
||||
for k, v := range *incoming {
|
||||
merged[k] = v
|
||||
}
|
||||
merged := map[string]any{}
|
||||
maps.Copy(merged, current)
|
||||
maps.Copy(merged, *incoming)
|
||||
return merged
|
||||
}
|
||||
|
||||
@@ -3433,9 +3423,7 @@ func (h *DevHandler) setAuditDetailsExtra(c *fiber.Ctx, extra map[string]any) {
|
||||
}
|
||||
if existing := c.Locals("audit_details_extra"); existing != nil {
|
||||
if m, ok := existing.(map[string]any); ok {
|
||||
for k, v := range extra {
|
||||
m[k] = v
|
||||
}
|
||||
maps.Copy(m, extra)
|
||||
c.Locals("audit_details_extra", m)
|
||||
return
|
||||
}
|
||||
@@ -3494,7 +3482,7 @@ func resolveDevAuditClientID(logItem domain.AuditLog, details map[string]any) st
|
||||
return resolvedID
|
||||
}
|
||||
|
||||
func resolveStatusFromMetadata(metadata map[string]interface{}) string {
|
||||
func resolveStatusFromMetadata(metadata map[string]any) string {
|
||||
if metadata != nil {
|
||||
if value, ok := metadata["status"].(string); ok && strings.ToLower(strings.TrimSpace(value)) == "inactive" {
|
||||
return "inactive"
|
||||
|
||||
@@ -26,18 +26,18 @@ func TestDevHandler_Isolation(t *testing.T) {
|
||||
HTTPClient: &http.Client{
|
||||
Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.Method == http.MethodGet && r.URL.Path == "/clients" {
|
||||
return httpJSONAny(r, http.StatusOK, []map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, []map[string]any{
|
||||
{
|
||||
"client_id": "client-tenant-a",
|
||||
"client_name": "App Tenant A",
|
||||
"token_endpoint_auth_method": "none", // PKCE
|
||||
"metadata": map[string]interface{}{"tenant_id": "tenant-a"},
|
||||
"metadata": map[string]any{"tenant_id": "tenant-a"},
|
||||
},
|
||||
{
|
||||
"client_id": "client-tenant-b",
|
||||
"client_name": "App Tenant B",
|
||||
"token_endpoint_auth_method": "none", // PKCE
|
||||
"metadata": map[string]interface{}{"tenant_id": "tenant-b"},
|
||||
"metadata": map[string]any{"tenant_id": "tenant-b"},
|
||||
},
|
||||
}), nil
|
||||
}
|
||||
@@ -47,15 +47,15 @@ func TestDevHandler_Isolation(t *testing.T) {
|
||||
if id == "client-tenant-b" {
|
||||
tenantID = "tenant-b"
|
||||
}
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"client_id": id,
|
||||
"client_name": "App " + id,
|
||||
"token_endpoint_auth_method": "none",
|
||||
"metadata": map[string]interface{}{"tenant_id": tenantID},
|
||||
"metadata": map[string]any{"tenant_id": tenantID},
|
||||
}), nil
|
||||
}
|
||||
if r.Method == http.MethodPost && r.URL.Path == "/clients" {
|
||||
var body map[string]interface{}
|
||||
var body map[string]any
|
||||
json.NewDecoder(r.Body).Decode(&body)
|
||||
return httpJSONAny(r, http.StatusCreated, body), nil
|
||||
}
|
||||
@@ -205,7 +205,7 @@ func TestDevHandler_Isolation(t *testing.T) {
|
||||
})
|
||||
app.Put("/api/v1/dev/clients/:id", h.UpdateClient)
|
||||
|
||||
body, _ := json.Marshal(map[string]interface{}{
|
||||
body, _ := json.Marshal(map[string]any{
|
||||
"client_name": "Updated Name",
|
||||
})
|
||||
|
||||
@@ -235,7 +235,7 @@ func TestDevHandler_Isolation(t *testing.T) {
|
||||
})
|
||||
app.Post("/api/v1/dev/clients", h.CreateClient)
|
||||
|
||||
body, _ := json.Marshal(map[string]interface{}{
|
||||
body, _ := json.Marshal(map[string]any{
|
||||
"client_name": "New App",
|
||||
"type": "pkce",
|
||||
"redirectUris": []string{"http://localhost/cb"},
|
||||
|
||||
@@ -35,10 +35,10 @@ func (m *devMockRPUserMetadataRepo) Upsert(ctx context.Context, metadata *domain
|
||||
func TestDevHandler_RPUserMetadataRoundTrip(t *testing.T) {
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Path == "/clients/client-1" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"client_id": "client-1",
|
||||
"client_name": "Client One",
|
||||
"metadata": map[string]interface{}{
|
||||
"metadata": map[string]any{
|
||||
"tenant_id": "tenant-1",
|
||||
},
|
||||
}), nil
|
||||
|
||||
@@ -88,7 +88,7 @@ func (m *devMockKratosAdmin) GetIdentity(ctx context.Context, identityID string)
|
||||
return nil, args.Error(1)
|
||||
}
|
||||
|
||||
func (m *devMockKratosAdmin) UpdateIdentity(ctx context.Context, identityID string, traits map[string]interface{}, state string) (*service.KratosIdentity, error) {
|
||||
func (m *devMockKratosAdmin) UpdateIdentity(ctx context.Context, identityID string, traits map[string]any, state string) (*service.KratosIdentity, error) {
|
||||
args := m.Called(ctx, identityID, traits, state)
|
||||
if identity, ok := args.Get(0).(*service.KratosIdentity); ok {
|
||||
return identity, args.Error(1)
|
||||
@@ -292,9 +292,9 @@ func TestGetCurrentProfile_PreservesExistingAuditUserContext(t *testing.T) {
|
||||
func TestListClients_Success(t *testing.T) {
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Path == "/clients" {
|
||||
return httpJSONAny(r, http.StatusOK, []map[string]interface{}{
|
||||
{"client_id": "client-1", "client_name": "App One", "metadata": map[string]interface{}{"status": "active"}},
|
||||
{"client_id": "client-2", "client_name": "App Two", "metadata": map[string]interface{}{"status": "inactive"}},
|
||||
return httpJSONAny(r, http.StatusOK, []map[string]any{
|
||||
{"client_id": "client-1", "client_name": "App One", "metadata": map[string]any{"status": "active"}},
|
||||
{"client_id": "client-2", "client_name": "App Two", "metadata": map[string]any{"status": "inactive"}},
|
||||
}), nil
|
||||
}
|
||||
return httpJSONAny(r, http.StatusNotFound, nil), nil
|
||||
@@ -326,9 +326,9 @@ func TestListClients_Success(t *testing.T) {
|
||||
func TestListClients_UserSeesOnlyClientsAllowedByReBAC(t *testing.T) {
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Path == "/clients" {
|
||||
return httpJSONAny(r, http.StatusOK, []map[string]interface{}{
|
||||
{"client_id": "client-denied", "client_name": "Denied App", "metadata": map[string]interface{}{"tenant_id": "tenant-a", "status": "active"}},
|
||||
{"client_id": "client-allowed", "client_name": "Allowed App", "metadata": map[string]interface{}{"tenant_id": "tenant-b", "status": "active"}},
|
||||
return httpJSONAny(r, http.StatusOK, []map[string]any{
|
||||
{"client_id": "client-denied", "client_name": "Denied App", "metadata": map[string]any{"tenant_id": "tenant-a", "status": "active"}},
|
||||
{"client_id": "client-allowed", "client_name": "Allowed App", "metadata": map[string]any{"tenant_id": "tenant-b", "status": "active"}},
|
||||
}), nil
|
||||
}
|
||||
return httpJSONAny(r, http.StatusNotFound, nil), nil
|
||||
@@ -796,9 +796,9 @@ func TestUpdateClient_AuditDetailsIncludeGeneralSettingChanges(t *testing.T) {
|
||||
func TestListClients_ProtectedSystemClientHidden(t *testing.T) {
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Path == "/clients" {
|
||||
return httpJSONAny(r, http.StatusOK, []map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, []map[string]any{
|
||||
{"client_id": "oathkeeper-introspect", "client_name": "Internal Client"},
|
||||
{"client_id": "client-1", "client_name": "App One", "metadata": map[string]interface{}{"status": "active"}},
|
||||
{"client_id": "client-1", "client_name": "App One", "metadata": map[string]any{"status": "active"}},
|
||||
}), nil
|
||||
}
|
||||
return httpJSONAny(r, http.StatusNotFound, nil), nil
|
||||
@@ -834,12 +834,12 @@ func TestListClients_ProtectedSystemClientHidden(t *testing.T) {
|
||||
func TestListClients_ReservedSystemNameAliasHidden(t *testing.T) {
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Path == "/clients" {
|
||||
return httpJSONAny(r, http.StatusOK, []map[string]interface{}{
|
||||
{"client_id": "adminfront", "client_name": "AdminFront", "metadata": map[string]interface{}{"status": "active"}},
|
||||
{"client_id": "4f2c9fd6-1111-2222-3333-444444444444", "client_name": "AdminFront", "metadata": map[string]interface{}{"status": "active"}},
|
||||
{"client_id": "devfront", "client_name": "DevFront", "metadata": map[string]interface{}{"status": "active"}},
|
||||
{"client_id": "7d2c9fd6-1111-2222-3333-444444444444", "client_name": "DevFront", "metadata": map[string]interface{}{"status": "active"}},
|
||||
{"client_id": "client-1", "client_name": "App One", "metadata": map[string]interface{}{"status": "active"}},
|
||||
return httpJSONAny(r, http.StatusOK, []map[string]any{
|
||||
{"client_id": "adminfront", "client_name": "AdminFront", "metadata": map[string]any{"status": "active"}},
|
||||
{"client_id": "4f2c9fd6-1111-2222-3333-444444444444", "client_name": "AdminFront", "metadata": map[string]any{"status": "active"}},
|
||||
{"client_id": "devfront", "client_name": "DevFront", "metadata": map[string]any{"status": "active"}},
|
||||
{"client_id": "7d2c9fd6-1111-2222-3333-444444444444", "client_name": "DevFront", "metadata": map[string]any{"status": "active"}},
|
||||
{"client_id": "client-1", "client_name": "App One", "metadata": map[string]any{"status": "active"}},
|
||||
}), nil
|
||||
}
|
||||
return httpJSONAny(r, http.StatusNotFound, nil), nil
|
||||
@@ -878,10 +878,10 @@ func TestListClients_ReservedSystemNameAliasHidden(t *testing.T) {
|
||||
func TestGetClient_ReservedSystemNameAliasHidden(t *testing.T) {
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Path == "/clients/4f2c9fd6-1111-2222-3333-444444444444" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"client_id": "4f2c9fd6-1111-2222-3333-444444444444",
|
||||
"client_name": "AdminFront",
|
||||
"metadata": map[string]interface{}{"status": "active"},
|
||||
"metadata": map[string]any{"status": "active"},
|
||||
}), nil
|
||||
}
|
||||
return httpJSONAny(r, http.StatusNotFound, nil), nil
|
||||
@@ -910,13 +910,13 @@ func TestGetClient_ReservedSystemNameAliasHidden(t *testing.T) {
|
||||
func TestUpdateClientStatus_Success(t *testing.T) {
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.Method == http.MethodGet && r.URL.Path == "/clients/client-1" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
"client_id": "client-1", "metadata": map[string]interface{}{"status": "active"},
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"client_id": "client-1", "metadata": map[string]any{"status": "active"},
|
||||
}), nil
|
||||
}
|
||||
if r.Method == http.MethodPatch && r.URL.Path == "/clients/client-1" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
"client_id": "client-1", "metadata": map[string]interface{}{"status": "inactive"},
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"client_id": "client-1", "metadata": map[string]any{"status": "inactive"},
|
||||
}), nil
|
||||
}
|
||||
return httpJSONAny(r, http.StatusNotFound, nil), nil
|
||||
@@ -936,7 +936,7 @@ func TestUpdateClientStatus_Success(t *testing.T) {
|
||||
})
|
||||
app.Patch("/api/v1/dev/clients/:id/status", h.UpdateClientStatus)
|
||||
|
||||
body, _ := json.Marshal(map[string]interface{}{"status": "inactive"})
|
||||
body, _ := json.Marshal(map[string]any{"status": "inactive"})
|
||||
req := httptest.NewRequest(http.MethodPatch, "/api/v1/dev/clients/client-1/status", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, _ := app.Test(req, -1)
|
||||
@@ -950,20 +950,20 @@ func TestUpdateClientStatus_Success(t *testing.T) {
|
||||
func TestUpdateClientStatus_UserAllowedByStatusPermission(t *testing.T) {
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.Method == http.MethodGet && r.URL.Path == "/clients/client-1" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"client_id": "client-1",
|
||||
"client_name": "App One",
|
||||
"metadata": map[string]interface{}{
|
||||
"metadata": map[string]any{
|
||||
"tenant_id": "tenant-1",
|
||||
"status": "active",
|
||||
},
|
||||
}), nil
|
||||
}
|
||||
if r.Method == http.MethodPatch && r.URL.Path == "/clients/client-1" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"client_id": "client-1",
|
||||
"client_name": "App One",
|
||||
"metadata": map[string]interface{}{
|
||||
"metadata": map[string]any{
|
||||
"tenant_id": "tenant-1",
|
||||
"status": "inactive",
|
||||
},
|
||||
@@ -995,7 +995,7 @@ func TestUpdateClientStatus_UserAllowedByStatusPermission(t *testing.T) {
|
||||
})
|
||||
app.Patch("/api/v1/dev/clients/:id/status", h.UpdateClientStatus)
|
||||
|
||||
body, _ := json.Marshal(map[string]interface{}{"status": "inactive"})
|
||||
body, _ := json.Marshal(map[string]any{"status": "inactive"})
|
||||
req := httptest.NewRequest(http.MethodPatch, "/api/v1/dev/clients/client-1/status", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, _ := app.Test(req, -1)
|
||||
@@ -1010,20 +1010,20 @@ func TestUpdateClientStatus_UserAllowedByStatusPermission(t *testing.T) {
|
||||
func TestUpdateClientStatus_UserAllowedByEditConfigPermission(t *testing.T) {
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.Method == http.MethodGet && r.URL.Path == "/clients/client-1" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"client_id": "client-1",
|
||||
"client_name": "App One",
|
||||
"metadata": map[string]interface{}{
|
||||
"metadata": map[string]any{
|
||||
"tenant_id": "tenant-1",
|
||||
"status": "active",
|
||||
},
|
||||
}), nil
|
||||
}
|
||||
if r.Method == http.MethodPatch && r.URL.Path == "/clients/client-1" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"client_id": "client-1",
|
||||
"client_name": "App One",
|
||||
"metadata": map[string]interface{}{
|
||||
"metadata": map[string]any{
|
||||
"tenant_id": "tenant-1",
|
||||
"status": "inactive",
|
||||
},
|
||||
@@ -1055,7 +1055,7 @@ func TestUpdateClientStatus_UserAllowedByEditConfigPermission(t *testing.T) {
|
||||
})
|
||||
app.Patch("/api/v1/dev/clients/:id/status", h.UpdateClientStatus)
|
||||
|
||||
body, _ := json.Marshal(map[string]interface{}{"status": "inactive"})
|
||||
body, _ := json.Marshal(map[string]any{"status": "inactive"})
|
||||
req := httptest.NewRequest(http.MethodPatch, "/api/v1/dev/clients/client-1/status", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, _ := app.Test(req, -1)
|
||||
@@ -1070,7 +1070,7 @@ func TestUpdateClientStatus_UserAllowedByEditConfigPermission(t *testing.T) {
|
||||
func TestUpdateClientStatus_ProtectedSystemClientForbidden(t *testing.T) {
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.Method == http.MethodGet && r.URL.Path == "/clients/oathkeeper-introspect" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"client_id": "oathkeeper-introspect",
|
||||
}), nil
|
||||
}
|
||||
@@ -1091,7 +1091,7 @@ func TestUpdateClientStatus_ProtectedSystemClientForbidden(t *testing.T) {
|
||||
})
|
||||
app.Patch("/api/v1/dev/clients/:id/status", h.UpdateClientStatus)
|
||||
|
||||
body, _ := json.Marshal(map[string]interface{}{"status": "inactive"})
|
||||
body, _ := json.Marshal(map[string]any{"status": "inactive"})
|
||||
req := httptest.NewRequest(http.MethodPatch, "/api/v1/dev/clients/oathkeeper-introspect/status", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, _ := app.Test(req, -1)
|
||||
@@ -1102,7 +1102,7 @@ func TestUpdateClientStatus_ProtectedSystemClientForbidden(t *testing.T) {
|
||||
func TestDeleteClient_Success(t *testing.T) {
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.Method == http.MethodGet && r.URL.Path == "/clients/client-1" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{"client_id": "client-1"}), nil
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{"client_id": "client-1"}), nil
|
||||
}
|
||||
if r.Method == http.MethodDelete && r.URL.Path == "/clients/client-1" {
|
||||
return &http.Response{StatusCode: http.StatusNoContent, Body: http.NoBody}, nil
|
||||
@@ -1142,7 +1142,7 @@ func TestDeleteClient_Success(t *testing.T) {
|
||||
func TestDeleteClient_ProtectedSystemClientForbidden(t *testing.T) {
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.Method == http.MethodGet && r.URL.Path == "/clients/oathkeeper-introspect" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{"client_id": "oathkeeper-introspect"}), nil
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{"client_id": "oathkeeper-introspect"}), nil
|
||||
}
|
||||
return httpJSONAny(r, http.StatusNotFound, nil), nil
|
||||
})
|
||||
@@ -1172,7 +1172,7 @@ func TestDeleteClient_ProtectedSystemClientForbidden(t *testing.T) {
|
||||
func TestGetClient_ProtectedSystemClientHidden(t *testing.T) {
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.Method == http.MethodGet && r.URL.Path == "/clients/oathkeeper-introspect" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"client_id": "oathkeeper-introspect",
|
||||
"client_name": "Internal Client",
|
||||
}), nil
|
||||
@@ -1203,10 +1203,10 @@ func TestGetClient_ProtectedSystemClientHidden(t *testing.T) {
|
||||
func TestGetClient_RPAdminAllowedByKetoViewPermission(t *testing.T) {
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.Method == http.MethodGet && r.URL.Path == "/clients/client-1" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"client_id": "client-1",
|
||||
"client_name": "App One",
|
||||
"metadata": map[string]interface{}{
|
||||
"metadata": map[string]any{
|
||||
"tenant_id": "tenant-b",
|
||||
"status": "active",
|
||||
},
|
||||
@@ -1248,11 +1248,11 @@ func TestGetClient_RPAdminAllowedByKetoViewPermission(t *testing.T) {
|
||||
func TestGetClient_RedactsSecretWithoutViewSecretPermission(t *testing.T) {
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.Method == http.MethodGet && r.URL.Path == "/clients/client-1" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"client_id": "client-1",
|
||||
"client_name": "App One",
|
||||
"client_secret": "stored-secret",
|
||||
"metadata": map[string]interface{}{
|
||||
"metadata": map[string]any{
|
||||
"tenant_id": "tenant-1",
|
||||
"status": "active",
|
||||
},
|
||||
@@ -1297,11 +1297,11 @@ func TestGetClient_RedactsSecretWithoutViewSecretPermission(t *testing.T) {
|
||||
func TestGetClient_UserAllowedToViewSecretByPermission(t *testing.T) {
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.Method == http.MethodGet && r.URL.Path == "/clients/client-1" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{
|
||||
"client_id": "client-1",
|
||||
"client_name": "App One",
|
||||
"client_secret": "stored-secret",
|
||||
"metadata": map[string]interface{}{
|
||||
"metadata": map[string]any{
|
||||
"tenant_id": "tenant-1",
|
||||
"status": "active",
|
||||
},
|
||||
@@ -1346,10 +1346,10 @@ func TestGetClient_UserAllowedToViewSecretByPermission(t *testing.T) {
|
||||
func TestRotateClientSecret_Success(t *testing.T) {
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.Method == http.MethodGet && r.URL.Path == "/clients/client-1" {
|
||||
return httpJSONAny(r, http.StatusOK, map[string]interface{}{"client_id": "client-1"}), nil
|
||||
return httpJSONAny(r, http.StatusOK, map[string]any{"client_id": "client-1"}), nil
|
||||
}
|
||||
if r.Method == http.MethodPut && r.URL.Path == "/clients/client-1" {
|
||||
var body map[string]interface{}
|
||||
var body map[string]any
|
||||
json.NewDecoder(r.Body).Decode(&body)
|
||||
return httpJSONAny(r, http.StatusOK, body), nil
|
||||
}
|
||||
@@ -1390,7 +1390,7 @@ func TestRotateClientSecret_Success(t *testing.T) {
|
||||
func TestCreateClient_RPAdminAllowedByTenantGrantPermission(t *testing.T) {
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.Method == http.MethodPost && r.URL.Path == "/clients" {
|
||||
var body map[string]interface{}
|
||||
var body map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
body["client_secret"] = "generated-secret"
|
||||
return httpJSONAny(r, http.StatusCreated, body), nil
|
||||
@@ -1443,7 +1443,7 @@ func TestCreateClient_RPAdminAllowedByTenantGrantPermission(t *testing.T) {
|
||||
func TestCreateClient_ApprovedDeveloperCanCreatePrivateClient(t *testing.T) {
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.Method == http.MethodPost && r.URL.Path == "/clients" {
|
||||
var body map[string]interface{}
|
||||
var body map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
body["client_secret"] = "generated-secret"
|
||||
return httpJSONAny(r, http.StatusCreated, body), nil
|
||||
@@ -1625,11 +1625,11 @@ func TestRevokeDeveloperGrantRelation_DeletesRequiredTenantRelations(t *testing.
|
||||
func TestGetStats_Success(t *testing.T) {
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Path == "/clients" {
|
||||
return httpJSONAny(r, http.StatusOK, []map[string]interface{}{
|
||||
{"client_id": "c1", "metadata": map[string]interface{}{"tenant_id": "t1"}},
|
||||
{"client_id": "c2", "metadata": map[string]interface{}{"tenant_id": "t1"}},
|
||||
{"client_id": "oathkeeper-introspect", "metadata": map[string]interface{}{"tenant_id": "t1"}},
|
||||
{"client_id": "c3", "metadata": map[string]interface{}{"tenant_id": "t2"}},
|
||||
return httpJSONAny(r, http.StatusOK, []map[string]any{
|
||||
{"client_id": "c1", "metadata": map[string]any{"tenant_id": "t1"}},
|
||||
{"client_id": "c2", "metadata": map[string]any{"tenant_id": "t1"}},
|
||||
{"client_id": "oathkeeper-introspect", "metadata": map[string]any{"tenant_id": "t1"}},
|
||||
{"client_id": "c3", "metadata": map[string]any{"tenant_id": "t2"}},
|
||||
}), nil
|
||||
}
|
||||
return httpJSONAny(r, http.StatusNotFound, nil), nil
|
||||
@@ -1693,9 +1693,9 @@ func TestGetStats_UserScopesAuditMetricsToVisibleClients(t *testing.T) {
|
||||
now := time.Now()
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Path == "/clients" {
|
||||
return httpJSONAny(r, http.StatusOK, []map[string]interface{}{
|
||||
{"client_id": "client-owned", "metadata": map[string]interface{}{"tenant_id": "tenant-a"}},
|
||||
{"client_id": "client-other", "metadata": map[string]interface{}{"tenant_id": "tenant-a"}},
|
||||
return httpJSONAny(r, http.StatusOK, []map[string]any{
|
||||
{"client_id": "client-owned", "metadata": map[string]any{"tenant_id": "tenant-a"}},
|
||||
{"client_id": "client-other", "metadata": map[string]any{"tenant_id": "tenant-a"}},
|
||||
}), nil
|
||||
}
|
||||
return httpJSONAny(r, http.StatusNotFound, nil), nil
|
||||
@@ -1785,9 +1785,9 @@ func TestGetStats_UserScopesAuditMetricsToVisibleClients(t *testing.T) {
|
||||
func TestGetRPUsageDaily_UserScopesItemsToVisibleClients(t *testing.T) {
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Path == "/clients" {
|
||||
return httpJSONAny(r, http.StatusOK, []map[string]interface{}{
|
||||
{"client_id": "client-owned", "client_name": "Owned App", "metadata": map[string]interface{}{"tenant_id": "tenant-a"}},
|
||||
{"client_id": "client-other", "client_name": "Other App", "metadata": map[string]interface{}{"tenant_id": "tenant-a"}},
|
||||
return httpJSONAny(r, http.StatusOK, []map[string]any{
|
||||
{"client_id": "client-owned", "client_name": "Owned App", "metadata": map[string]any{"tenant_id": "tenant-a"}},
|
||||
{"client_id": "client-other", "client_name": "Other App", "metadata": map[string]any{"tenant_id": "tenant-a"}},
|
||||
}), nil
|
||||
}
|
||||
return httpJSONAny(r, http.StatusNotFound, nil), nil
|
||||
@@ -1997,7 +1997,7 @@ func TestCreateClient_DefaultsSkipConsentToTrue(t *testing.T) {
|
||||
|
||||
func TestNormalizeClientAutoLoginMetadata(t *testing.T) {
|
||||
t.Run("keeps supported flag and URL", func(t *testing.T) {
|
||||
metadata, err := normalizeClientAutoLoginMetadata(map[string]interface{}{
|
||||
metadata, err := normalizeClientAutoLoginMetadata(map[string]any{
|
||||
"auto_login_supported": true,
|
||||
"auto_login_url": "https://rp.example.com/login?auto=1",
|
||||
})
|
||||
@@ -2007,14 +2007,14 @@ func TestNormalizeClientAutoLoginMetadata(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("requires URL when supported", func(t *testing.T) {
|
||||
_, err := normalizeClientAutoLoginMetadata(map[string]interface{}{
|
||||
_, err := normalizeClientAutoLoginMetadata(map[string]any{
|
||||
"auto_login_supported": true,
|
||||
})
|
||||
assert.Error(t, err)
|
||||
})
|
||||
|
||||
t.Run("removes URL when unsupported", func(t *testing.T) {
|
||||
metadata, err := normalizeClientAutoLoginMetadata(map[string]interface{}{
|
||||
metadata, err := normalizeClientAutoLoginMetadata(map[string]any{
|
||||
"auto_login_supported": false,
|
||||
"auto_login_url": "https://rp.example.com/login?auto=1",
|
||||
})
|
||||
@@ -2293,9 +2293,9 @@ func TestCreateClient_NormalizesIDTokenClaimsMetadata(t *testing.T) {
|
||||
resp, _ := app.Test(req, -1)
|
||||
assert.Equal(t, http.StatusCreated, resp.StatusCode)
|
||||
|
||||
claims, ok := captured.Metadata[domain.MetadataIDTokenClaims].([]interface{})
|
||||
claims, ok := captured.Metadata[domain.MetadataIDTokenClaims].([]any)
|
||||
if assert.True(t, ok) && assert.Len(t, claims, 2) {
|
||||
first, ok := claims[0].(map[string]interface{})
|
||||
first, ok := claims[0].(map[string]any)
|
||||
if assert.True(t, ok) {
|
||||
assert.Equal(t, "top_level", first["namespace"])
|
||||
assert.Equal(t, "locale", first["key"])
|
||||
@@ -2305,7 +2305,7 @@ func TestCreateClient_NormalizesIDTokenClaimsMetadata(t *testing.T) {
|
||||
assert.False(t, hasID)
|
||||
}
|
||||
|
||||
second, ok := claims[1].(map[string]interface{})
|
||||
second, ok := claims[1].(map[string]any)
|
||||
if assert.True(t, ok) {
|
||||
assert.Equal(t, "rp_claims", second["namespace"])
|
||||
assert.Equal(t, "tier", second["key"])
|
||||
@@ -2464,7 +2464,7 @@ func TestUpdateClient_AllowsExplicitSkipConsentFalse(t *testing.T) {
|
||||
Scope: "openid profile",
|
||||
TokenEndpointAuthMethod: "none",
|
||||
SkipConsent: ¤tSkipConsent,
|
||||
Metadata: map[string]interface{}{"status": "active"},
|
||||
Metadata: map[string]any{"status": "active"},
|
||||
}), nil
|
||||
}
|
||||
if r.Method == http.MethodPut && r.URL.Path == "/clients/client-1" {
|
||||
@@ -2620,7 +2620,7 @@ func TestUpdateClient_RevokesExistingConsentsWhenTenantPolicyChanges(t *testing.
|
||||
ResponseTypes: []string{"code"},
|
||||
Scope: "openid tenant profile email",
|
||||
TokenEndpointAuthMethod: "none",
|
||||
Metadata: map[string]interface{}{
|
||||
Metadata: map[string]any{
|
||||
"tenant_access_restricted": true,
|
||||
"allowed_tenants": []string{"tenant-a"},
|
||||
},
|
||||
@@ -2704,7 +2704,7 @@ func TestUpdateClient_DoesNotRevokeConsentsWhenTenantPolicyUnchanged(t *testing.
|
||||
ResponseTypes: []string{"code"},
|
||||
Scope: "openid tenant profile email",
|
||||
TokenEndpointAuthMethod: "none",
|
||||
Metadata: map[string]interface{}{
|
||||
Metadata: map[string]any{
|
||||
"tenant_access_restricted": true,
|
||||
"allowed_tenants": []string{"tenant-a"},
|
||||
},
|
||||
@@ -2991,9 +2991,9 @@ func TestListAuditLogs_UserAllowedByRPAuditPermission(t *testing.T) {
|
||||
}
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Path == "/clients" {
|
||||
return httpJSONAny(r, http.StatusOK, []map[string]interface{}{
|
||||
{"client_id": "client-allowed", "client_name": "Allowed App", "metadata": map[string]interface{}{"tenant_id": "tenant-a"}},
|
||||
{"client_id": "client-denied", "client_name": "Denied App", "metadata": map[string]interface{}{"tenant_id": "tenant-b"}},
|
||||
return httpJSONAny(r, http.StatusOK, []map[string]any{
|
||||
{"client_id": "client-allowed", "client_name": "Allowed App", "metadata": map[string]any{"tenant_id": "tenant-a"}},
|
||||
{"client_id": "client-denied", "client_name": "Denied App", "metadata": map[string]any{"tenant_id": "tenant-b"}},
|
||||
}), nil
|
||||
}
|
||||
return httpJSONAny(r, http.StatusNotFound, nil), nil
|
||||
@@ -3124,7 +3124,7 @@ func TestListClientRelations_RPAdminAllowedByViewRelationshipsPermission(t *test
|
||||
mockKratos := new(devMockKratosAdmin)
|
||||
mockKratos.On("GetIdentity", mock.Anything, "user-2").Return(&service.KratosIdentity{
|
||||
ID: "user-2",
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"name": "김용연",
|
||||
"email": "kyy@example.com",
|
||||
"id": "kyy01",
|
||||
@@ -3195,7 +3195,7 @@ func TestListClientRelations_DedupesDuplicateRelations(t *testing.T) {
|
||||
mockKratos := new(devMockKratosAdmin)
|
||||
mockKratos.On("GetIdentity", mock.Anything, "user-1").Return(&service.KratosIdentity{
|
||||
ID: "user-1",
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"name": "Tester",
|
||||
"email": "tester@example.com",
|
||||
},
|
||||
@@ -3371,7 +3371,7 @@ func TestSearchUsers_RPAdminSearchByNameOrEmailWithinTenantScope(t *testing.T) {
|
||||
mockKratos.On("ListIdentities", mock.Anything).Return([]service.KratosIdentity{
|
||||
{
|
||||
ID: "user-1",
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"name": "Alice Kim",
|
||||
"email": "alice@example.com",
|
||||
"id": "alice01",
|
||||
@@ -3380,7 +3380,7 @@ func TestSearchUsers_RPAdminSearchByNameOrEmailWithinTenantScope(t *testing.T) {
|
||||
},
|
||||
{
|
||||
ID: "user-2",
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"name": "Bob Lee",
|
||||
"email": "bob@example.com",
|
||||
"id": "bob01",
|
||||
@@ -3451,7 +3451,7 @@ func TestSearchUsers_UserAllowedByRPAdminRelation(t *testing.T) {
|
||||
mockKratos.On("ListIdentities", mock.Anything).Return([]service.KratosIdentity{
|
||||
{
|
||||
ID: "target-user",
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"name": "김용연",
|
||||
"email": "kyy@example.com",
|
||||
"id": "kyy01",
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"baron-sso-backend/internal/domain"
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -235,10 +236,8 @@ func nextAvailableHanmacLocalPart(base string, usedLocalParts map[string]bool) s
|
||||
}
|
||||
|
||||
func appendUniqueString(values []string, value string) []string {
|
||||
for _, existing := range values {
|
||||
if existing == value {
|
||||
return values
|
||||
}
|
||||
if slices.Contains(values, value) {
|
||||
return values
|
||||
}
|
||||
return append(values, value)
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -312,10 +313,7 @@ func (h *TenantHandler) ListTenants(c *fiber.Ctx) error {
|
||||
}
|
||||
offset = 0
|
||||
} else if offset < len(tenants) {
|
||||
end := offset + limit
|
||||
if end > len(tenants) {
|
||||
end = len(tenants)
|
||||
}
|
||||
end := min(offset+limit, len(tenants))
|
||||
tenants = tenants[offset:end]
|
||||
if total > int64(end) && len(tenants) > 0 {
|
||||
last := tenants[len(tenants)-1]
|
||||
@@ -980,12 +978,8 @@ func mergeTenantCSVRecordConfig(current domain.JSONMap, record tenantCSVRecord)
|
||||
}
|
||||
|
||||
merged := make(domain.JSONMap, len(current)+len(recordConfig))
|
||||
for key, value := range current {
|
||||
merged[key] = value
|
||||
}
|
||||
for key, value := range recordConfig {
|
||||
merged[key] = value
|
||||
}
|
||||
maps.Copy(merged, current)
|
||||
maps.Copy(merged, recordConfig)
|
||||
return merged, true, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -107,6 +107,10 @@ type MockUserRepoForHandler struct {
|
||||
deletedIDs []string
|
||||
}
|
||||
|
||||
func (m *MockUserRepoForHandler) DB() *gorm.DB {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *MockUserRepoForHandler) Create(ctx context.Context, user *domain.User) error { return nil }
|
||||
func (m *MockUserRepoForHandler) Update(ctx context.Context, user *domain.User) error { return nil }
|
||||
func (m *MockUserRepoForHandler) Delete(ctx context.Context, id string) error {
|
||||
@@ -229,7 +233,7 @@ func TestTenantHandler_CreateTenant(t *testing.T) {
|
||||
|
||||
app.Post("/tenants", h.CreateTenant)
|
||||
|
||||
input := map[string]interface{}{
|
||||
input := map[string]any{
|
||||
"name": "Test Tenant",
|
||||
"slug": "test-tenant",
|
||||
"domains": []string{"test.com"},
|
||||
@@ -244,7 +248,7 @@ func TestTenantHandler_CreateTenant(t *testing.T) {
|
||||
resp, _ := app.Test(req)
|
||||
|
||||
assert.Equal(t, http.StatusCreated, resp.StatusCode)
|
||||
var got map[string]interface{}
|
||||
var got map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&got)
|
||||
assert.Equal(t, "t1", got["id"])
|
||||
}
|
||||
@@ -1191,7 +1195,7 @@ func TestTenantHandler_ImportTenantsCSVCreatesTenant(t *testing.T) {
|
||||
resp, _ := app.Test(req)
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
var got map[string]interface{}
|
||||
var got map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&got)
|
||||
assert.Equal(t, float64(1), got["created"])
|
||||
assert.Equal(t, float64(0), got["updated"])
|
||||
@@ -1246,7 +1250,7 @@ func TestTenantHandler_ImportTenantsCSVResolvesParentSlugToID(t *testing.T) {
|
||||
resp, _ := app.Test(req)
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
var got map[string]interface{}
|
||||
var got map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&got)
|
||||
assert.Equal(t, float64(2), got["created"])
|
||||
assert.Equal(t, float64(0), got["failed"])
|
||||
@@ -1292,7 +1296,7 @@ func TestTenantHandler_ImportTenantsCSVDoesNotAssignCreatorAsOrganizationMember(
|
||||
resp, _ := app.Test(req)
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
var got map[string]interface{}
|
||||
var got map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&got)
|
||||
assert.Equal(t, float64(1), got["created"])
|
||||
assert.Equal(t, float64(0), got["failed"])
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"net/http"
|
||||
"os"
|
||||
"regexp"
|
||||
@@ -201,7 +202,7 @@ func metadataBoolFromMap(metadata map[string]any, keys ...string) (bool, bool) {
|
||||
return false, false
|
||||
}
|
||||
|
||||
func roleFromTraits(traits map[string]interface{}) string {
|
||||
func roleFromTraits(traits map[string]any) string {
|
||||
if role, ok := domain.NormalizeRoleAlias(extractTraitString(traits, "role")); ok {
|
||||
return role
|
||||
}
|
||||
@@ -219,7 +220,7 @@ func normalizeAssignableSystemRole(value string) (string, bool) {
|
||||
return role, role == domain.RoleSuperAdmin || role == domain.RoleUser
|
||||
}
|
||||
|
||||
func gradeFromTraits(traits map[string]interface{}) string {
|
||||
func gradeFromTraits(traits map[string]any) string {
|
||||
value := strings.TrimSpace(extractTraitString(traits, "grade"))
|
||||
if value == "" {
|
||||
return ""
|
||||
@@ -265,7 +266,7 @@ func tenantSlugPointerFromRequest(tenantSlug *string, legacyCompanyCode *string)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func identityTenantAccessKeys(traits map[string]interface{}) []string {
|
||||
func identityTenantAccessKeys(traits map[string]any) []string {
|
||||
keys := make([]string, 0, 2)
|
||||
if tenantID := strings.ToLower(strings.TrimSpace(extractTraitString(traits, "tenant_id"))); tenantID != "" {
|
||||
keys = append(keys, tenantID)
|
||||
@@ -523,10 +524,7 @@ func (h *UserHandler) ListUsers(c *fiber.Ctx) error {
|
||||
if offset > len(filtered) {
|
||||
offset = len(filtered)
|
||||
}
|
||||
end := offset + limit
|
||||
if end > len(filtered) {
|
||||
end = len(filtered)
|
||||
}
|
||||
end := min(offset+limit, len(filtered))
|
||||
pageIdentities = filtered[offset:end]
|
||||
if total > int64(end) && len(pageIdentities) > 0 {
|
||||
lastTimestamp, lastID := kratosIdentityCursorKey(pageIdentities[len(pageIdentities)-1])
|
||||
@@ -578,11 +576,32 @@ func (h *UserHandler) GetUser(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
identity, err := h.KratosAdmin.GetIdentity(c.Context(), userID)
|
||||
if err != nil {
|
||||
return errorJSON(c, fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
if identity == nil {
|
||||
return errorJSON(c, fiber.StatusNotFound, "user not found")
|
||||
if err != nil || identity == nil {
|
||||
// [FIX] Support fixed UUID lookup fallback
|
||||
id, searchErr := h.KratosAdmin.FindIdentityIDByIdentifier(c.Context(), userID)
|
||||
if searchErr == nil && id != "" {
|
||||
identity, err = h.KratosAdmin.GetIdentity(c.Context(), id)
|
||||
}
|
||||
|
||||
if err != nil || identity == nil {
|
||||
// Second Fallback: By Email from local DB
|
||||
if h.UserRepo != nil {
|
||||
local, _ := h.UserRepo.FindByID(c.Context(), userID)
|
||||
if local != nil && local.Email != "" {
|
||||
id, _ = h.KratosAdmin.FindIdentityIDByIdentifier(c.Context(), local.Email)
|
||||
if id != "" {
|
||||
identity, err = h.KratosAdmin.GetIdentity(c.Context(), id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil || identity == nil {
|
||||
if identity == nil {
|
||||
return errorJSON(c, fiber.StatusNotFound, "user not found")
|
||||
}
|
||||
return errorJSON(c, fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// [New] Check access scope
|
||||
@@ -685,7 +704,7 @@ func (h *UserHandler) CreateUser(c *fiber.Ctx) error {
|
||||
role = normalizedRole
|
||||
}
|
||||
|
||||
attributes := map[string]interface{}{
|
||||
attributes := map[string]any{
|
||||
"department": req.Department,
|
||||
"grade": strings.TrimSpace(req.Grade),
|
||||
"position": req.Position,
|
||||
@@ -775,7 +794,7 @@ func (h *UserHandler) CreateUser(c *fiber.Ctx) error {
|
||||
if tenantID != "" && h.TenantService != nil {
|
||||
tenant, err := h.TenantService.GetTenant(c.Context(), tenantID)
|
||||
if err == nil && tenant != nil {
|
||||
if schema, ok := tenant.Config["userSchema"].([]interface{}); ok {
|
||||
if schema, ok := tenant.Config["userSchema"].([]any); ok {
|
||||
if err := h.validateMetadata(req.Metadata, schema, true); err != nil {
|
||||
return errorJSON(c, fiber.StatusBadRequest, "metadata validation failed: "+err.Error())
|
||||
}
|
||||
@@ -850,6 +869,8 @@ func (h *UserHandler) CreateUser(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
type bulkUserItem struct {
|
||||
ID string `json:"id"`
|
||||
UUID string `json:"uuid"`
|
||||
Email string `json:"email"`
|
||||
LoginID string `json:"loginId"`
|
||||
Name string `json:"name"`
|
||||
@@ -876,6 +897,7 @@ type bulkUserResult struct {
|
||||
Success bool `json:"success"`
|
||||
Message string `json:"message,omitempty"`
|
||||
UserID string `json:"userId,omitempty"`
|
||||
ModifiedFields []string `json:"modifiedFields,omitempty"`
|
||||
}
|
||||
|
||||
func (h *UserHandler) BulkCreateUsers(c *fiber.Ctx) error {
|
||||
@@ -912,7 +934,7 @@ func (h *UserHandler) BulkCreateUsers(c *fiber.Ctx) error {
|
||||
ID string
|
||||
Slug string
|
||||
Name string
|
||||
Schema []interface{}
|
||||
Schema []any
|
||||
Groups []domain.UserGroup
|
||||
LoginIDField string
|
||||
}
|
||||
@@ -926,7 +948,7 @@ func (h *UserHandler) BulkCreateUsers(c *fiber.Ctx) error {
|
||||
Slug: tenant.Slug,
|
||||
Name: tenant.Name,
|
||||
}
|
||||
if s, ok := tenant.Config["userSchema"].([]interface{}); ok {
|
||||
if s, ok := tenant.Config["userSchema"].([]any); ok {
|
||||
tItem.Schema = s
|
||||
}
|
||||
if lf, ok := tenant.Config["loginIdField"].(string); ok {
|
||||
@@ -1012,6 +1034,7 @@ func (h *UserHandler) BulkCreateUsers(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
for _, item := range req.Users {
|
||||
var identityID string
|
||||
email := strings.TrimSpace(item.Email)
|
||||
name := strings.TrimSpace(item.Name)
|
||||
tenantID := strings.TrimSpace(item.TenantID)
|
||||
@@ -1200,7 +1223,7 @@ func (h *UserHandler) BulkCreateUsers(c *fiber.Ctx) error {
|
||||
role = "user"
|
||||
}
|
||||
|
||||
attributes := map[string]interface{}{
|
||||
attributes := map[string]any{
|
||||
"department": dept,
|
||||
"grade": strings.TrimSpace(item.Grade),
|
||||
"position": strings.TrimSpace(item.Position),
|
||||
@@ -1222,13 +1245,27 @@ func (h *UserHandler) BulkCreateUsers(c *fiber.Ctx) error {
|
||||
|
||||
userPhone := normalizePhoneNumber(item.Phone)
|
||||
|
||||
// Validate provided UUID if any
|
||||
requestedID := strings.TrimSpace(item.ID)
|
||||
if requestedID == "" {
|
||||
requestedID = strings.TrimSpace(item.UUID)
|
||||
}
|
||||
if requestedID != "" {
|
||||
// Basic UUID format validation
|
||||
matched, _ := regexp.MatchString(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`, strings.ToLower(requestedID))
|
||||
if !matched {
|
||||
results = append(results, bulkUserResult{Email: userEmail, Success: false, Message: "invalid UUID format: " + requestedID})
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// Validate all collected LoginIDs
|
||||
if collectedIDs, ok := attributes["custom_login_ids"].([]string); ok {
|
||||
valid := true
|
||||
// Collect all emails
|
||||
allEmails := []string{userEmail}
|
||||
if secondaryRaw, exists := item.Metadata["sub_email"]; exists {
|
||||
if secondaryEmails, ok := secondaryRaw.([]interface{}); ok {
|
||||
if secondaryEmails, ok := secondaryRaw.([]any); ok {
|
||||
for _, se := range secondaryEmails {
|
||||
if seStr, ok := se.(string); ok {
|
||||
allEmails = append(allEmails, seStr)
|
||||
@@ -1251,32 +1288,125 @@ func (h *UserHandler) BulkCreateUsers(c *fiber.Ctx) error {
|
||||
}
|
||||
}
|
||||
|
||||
identityID, err := h.OryProvider.CreateUser(&domain.BrokerUser{
|
||||
Email: userEmail,
|
||||
Name: item.Name,
|
||||
PhoneNumber: userPhone,
|
||||
Attributes: attributes,
|
||||
}, password)
|
||||
if err != nil {
|
||||
// 만약 이미 존재하는 사용자라면 로컬 DB 및 Keto 관계만 업데이트(Sync)를 시도
|
||||
if strings.Contains(err.Error(), "409") || strings.Contains(err.Error(), "already exists") || strings.Contains(err.Error(), "exists already") {
|
||||
identityID, err = h.KratosAdmin.FindIdentityIDByIdentifier(c.Context(), userEmail)
|
||||
if err != nil || identityID == "" {
|
||||
results = append(results, bulkUserResult{Email: userEmail, OriginalEmail: emailEvaluation.OriginalEmail, SuggestedEmail: emailEvaluation.SuggestedEmail, Status: "blockingError", Warnings: emailEvaluation.Warnings, Success: false, Message: "이미 다른 사용자가 해당 식별자(이메일/사번 등)를 사용 중입니다."})
|
||||
resultStatus := "created"
|
||||
// 1. Search-first for Idempotency and Fixed UUID Guarantee
|
||||
if requestedID != "" {
|
||||
// Use h.KratosAdmin to search for existing ID or ExternalID
|
||||
existingID, _ := h.KratosAdmin.FindIdentityIDByIdentifier(c.Context(), requestedID)
|
||||
if existingID != "" {
|
||||
// Verify it's the same user (optional, but safer)
|
||||
identityID = existingID
|
||||
resultStatus = "updated"
|
||||
slog.Info("BulkCreate: Found existing identity by UUID/Identifier", "requestedID", requestedID, "identityID", identityID)
|
||||
}
|
||||
}
|
||||
|
||||
if identityID == "" {
|
||||
var err error
|
||||
identityID, err = h.OryProvider.CreateUser(&domain.BrokerUser{
|
||||
ID: requestedID,
|
||||
Email: userEmail,
|
||||
Name: item.Name,
|
||||
PhoneNumber: userPhone,
|
||||
Attributes: attributes,
|
||||
}, password)
|
||||
if err != nil {
|
||||
// 만약 이미 존재하는 사용자라면 로컬 DB 및 Keto 관계만 업데이트(Sync)를 시도
|
||||
if strings.Contains(err.Error(), "409") || strings.Contains(err.Error(), "already exists") || strings.Contains(err.Error(), "exists already") || strings.Contains(err.Error(), "external_id") {
|
||||
// Detect if it's a UUID conflict or Identifier (Email/LoginID) conflict
|
||||
if requestedID != "" && (strings.Contains(err.Error(), requestedID) || strings.Contains(err.Error(), "uuid already exists") || strings.Contains(err.Error(), "external_id")) {
|
||||
// Check if the EXISTING user with this UUID is actually the same person (same email)
|
||||
existingID, lookupErr := h.KratosAdmin.FindIdentityIDByIdentifier(c.Context(), userEmail)
|
||||
if lookupErr == nil && existingID != "" {
|
||||
identityID = existingID
|
||||
resultStatus = "updated"
|
||||
slog.Info("BulkCreate: Conflict detected but same email, reusing identity", "email", userEmail, "identityID", identityID)
|
||||
} else {
|
||||
results = append(results, bulkUserResult{Email: userEmail, OriginalEmail: emailEvaluation.OriginalEmail, SuggestedEmail: emailEvaluation.SuggestedEmail, Status: "blockingError", Warnings: emailEvaluation.Warnings, Success: false, Message: "Conflict: UUID already exists (" + requestedID + ")"})
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
identityID, err = h.KratosAdmin.FindIdentityIDByIdentifier(c.Context(), userEmail)
|
||||
if err != nil || identityID == "" {
|
||||
results = append(results, bulkUserResult{Email: userEmail, OriginalEmail: emailEvaluation.OriginalEmail, SuggestedEmail: emailEvaluation.SuggestedEmail, Status: "blockingError", Warnings: emailEvaluation.Warnings, Success: false, Message: "이미 다른 사용자가 해당 식별자(이메일/사번 등)를 사용 중입니다."})
|
||||
continue
|
||||
}
|
||||
resultStatus = "updated"
|
||||
slog.Info("BulkCreate: User already exists by identifier, reusing identity", "email", userEmail, "identityID", identityID)
|
||||
}
|
||||
} else {
|
||||
results = append(results, bulkUserResult{Email: userEmail, OriginalEmail: emailEvaluation.OriginalEmail, SuggestedEmail: emailEvaluation.SuggestedEmail, Status: emailEvaluation.Status, Warnings: emailEvaluation.Warnings, Success: false, Message: err.Error()})
|
||||
continue
|
||||
}
|
||||
slog.Info("BulkCreate: User already exists, syncing local DB and Keto", "email", email, "identityID", identityID)
|
||||
} else {
|
||||
results = append(results, bulkUserResult{Email: userEmail, OriginalEmail: emailEvaluation.OriginalEmail, SuggestedEmail: emailEvaluation.SuggestedEmail, Status: emailEvaluation.Status, Warnings: emailEvaluation.Warnings, Success: false, Message: err.Error()})
|
||||
continue
|
||||
resultStatus = "created"
|
||||
slog.Info("BulkCreate: New identity created", "email", userEmail, "identityID", identityID)
|
||||
}
|
||||
} else {
|
||||
slog.Info("BulkCreate: Existing identity found by search-first", "email", userEmail, "identityID", identityID)
|
||||
}
|
||||
|
||||
var modifiedFields []string
|
||||
isRestoration := false
|
||||
if resultStatus == "updated" && identityID != "" {
|
||||
existing, err := h.KratosAdmin.GetIdentity(c.Context(), identityID)
|
||||
if err == nil && existing != nil {
|
||||
// 1. Check for Restoration (Soft-deleted in local DB)
|
||||
if h.UserRepo != nil {
|
||||
var existingLocal domain.User
|
||||
err := h.UserRepo.DB().Unscoped().Where("id = ?", identityID).First(&existingLocal).Error
|
||||
if err == nil {
|
||||
// Check if it was soft-deleted
|
||||
if existingLocal.DeletedAt.Valid {
|
||||
isRestoration = true
|
||||
modifiedFields = append(modifiedFields, "Status")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Compare Traits
|
||||
if name != "" && !strings.EqualFold(extractTraitString(existing.Traits, "name"), name) {
|
||||
modifiedFields = append(modifiedFields, "Name")
|
||||
}
|
||||
if item.Phone != "" && normalizePhoneNumber(extractTraitString(existing.Traits, "phone_number")) != normalizePhoneNumber(item.Phone) {
|
||||
modifiedFields = append(modifiedFields, "Phone")
|
||||
}
|
||||
if dept != "" && !strings.EqualFold(extractTraitString(existing.Traits, "department"), dept) {
|
||||
modifiedFields = append(modifiedFields, "Department")
|
||||
}
|
||||
if item.Grade != "" && !strings.EqualFold(gradeFromTraits(existing.Traits), strings.TrimSpace(item.Grade)) {
|
||||
modifiedFields = append(modifiedFields, "Grade")
|
||||
}
|
||||
if item.Position != "" && !strings.EqualFold(extractTraitString(existing.Traits, "position"), strings.TrimSpace(item.Position)) {
|
||||
modifiedFields = append(modifiedFields, "Position")
|
||||
}
|
||||
if item.JobTitle != "" && !strings.EqualFold(extractTraitString(existing.Traits, "jobTitle"), strings.TrimSpace(item.JobTitle)) {
|
||||
modifiedFields = append(modifiedFields, "JobTitle")
|
||||
}
|
||||
if tItem.ID != "" && extractTraitString(existing.Traits, "tenant_id") != tItem.ID {
|
||||
modifiedFields = append(modifiedFields, "Tenant")
|
||||
}
|
||||
if role != "" && !strings.EqualFold(roleFromTraits(existing.Traits), role) {
|
||||
modifiedFields = append(modifiedFields, "Role")
|
||||
}
|
||||
|
||||
// 3. Finalize Status: If no fields actually changed, it's "unchanged"
|
||||
if len(modifiedFields) == 0 && !isRestoration {
|
||||
resultStatus = "unchanged"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// [CRITICAL FIX] Sync to local DB directly using current data
|
||||
// Don't fetch from Kratos here as it might have propagation lag
|
||||
// Use the REQUESTED UUID as the primary ID for Baron SSO if provided
|
||||
targetLocalID := identityID
|
||||
if requestedID != "" {
|
||||
targetLocalID = requestedID
|
||||
}
|
||||
|
||||
if h.UserRepo != nil {
|
||||
localUser := &domain.User{
|
||||
ID: identityID,
|
||||
ID: targetLocalID,
|
||||
Email: userEmail,
|
||||
Name: name,
|
||||
Phone: normalizePhoneNumber(item.Phone),
|
||||
@@ -1295,9 +1425,7 @@ func (h *UserHandler) BulkCreateUsers(c *fiber.Ctx) error {
|
||||
|
||||
// Merge metadata
|
||||
localUser.Metadata = make(domain.JSONMap)
|
||||
for k, v := range item.Metadata {
|
||||
localUser.Metadata[k] = v
|
||||
}
|
||||
maps.Copy(localUser.Metadata, item.Metadata)
|
||||
|
||||
if err := h.UserRepo.Update(c.Context(), localUser); err != nil {
|
||||
slog.Error("Failed to sync bulk user to local DB", "email", email, "error", err)
|
||||
@@ -1313,9 +1441,30 @@ func (h *UserHandler) BulkCreateUsers(c *fiber.Ctx) error {
|
||||
for i := range loginIDRecords {
|
||||
loginIDRecords[i].UserID = localUser.ID
|
||||
}
|
||||
|
||||
// [FIX] Pre-check and cleanup colliding identifiers from OTHER users
|
||||
for _, lid := range loginIDRecords {
|
||||
var existingID domain.UserLoginID
|
||||
// Search in DB (including soft-deleted) for any record with the same login_id but DIFFERENT user_id
|
||||
if err := h.UserRepo.DB().Unscoped().Where("login_id = ? AND user_id != ?", lid.LoginID, localUser.ID).First(&existingID).Error; err == nil {
|
||||
slog.Info("BulkCreate: Cleaning up colliding identifier from another user", "loginID", lid.LoginID, "oldUserID", existingID.UserID)
|
||||
_ = h.UserRepo.DB().Unscoped().Where("login_id = ?", lid.LoginID).Delete(&domain.UserLoginID{}).Error
|
||||
}
|
||||
}
|
||||
|
||||
if err := h.UserRepo.UpdateUserLoginIDs(c.Context(), localUser.ID, loginIDRecords); err != nil {
|
||||
slog.Error("Failed to update user login IDs in bulk", "userID", localUser.ID, "error", err)
|
||||
markUserProjectionFailed(c.Context(), h.UserProjectionRepo, err)
|
||||
results = append(results, bulkUserResult{
|
||||
Email: userEmail,
|
||||
OriginalEmail: emailEvaluation.OriginalEmail,
|
||||
SuggestedEmail: emailEvaluation.SuggestedEmail,
|
||||
Status: "blockingError",
|
||||
Warnings: emailEvaluation.Warnings,
|
||||
Success: false,
|
||||
Message: "LoginID sync failed: " + err.Error(),
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
if h.KetoOutboxRepo != nil {
|
||||
@@ -1355,10 +1504,11 @@ func (h *UserHandler) BulkCreateUsers(c *fiber.Ctx) error {
|
||||
Email: userEmail,
|
||||
OriginalEmail: emailEvaluation.OriginalEmail,
|
||||
SuggestedEmail: emailEvaluation.SuggestedEmail,
|
||||
Status: emailEvaluation.Status,
|
||||
Status: resultStatus,
|
||||
Warnings: emailEvaluation.Warnings,
|
||||
Success: true,
|
||||
UserID: identityID,
|
||||
UserID: targetLocalID,
|
||||
ModifiedFields: modifiedFields,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1575,7 +1725,7 @@ func (h *UserHandler) BulkUpdateUsers(c *fiber.Ctx) error {
|
||||
// Pre-fetch tenant cache if tenantSlug is being changed.
|
||||
type tenantCacheItem struct {
|
||||
ID string
|
||||
Schema []interface{}
|
||||
Schema []any
|
||||
}
|
||||
tenantCache := make(map[string]tenantCacheItem)
|
||||
|
||||
@@ -1913,7 +2063,7 @@ func (h *UserHandler) UpdateUser(c *fiber.Ctx) error {
|
||||
if h.TenantService != nil {
|
||||
tenant, err := h.TenantService.GetTenant(c.Context(), key)
|
||||
if err == nil && tenant != nil {
|
||||
if schema, ok := tenant.Config["userSchema"].([]interface{}); ok {
|
||||
if schema, ok := tenant.Config["userSchema"].([]any); ok {
|
||||
if subMeta, ok := val.(map[string]any); ok {
|
||||
if err := h.validateMetadataWithAuth(subMeta, schema, isAdmin, false); err != nil {
|
||||
return errorJSON(c, fiber.StatusBadRequest, "metadata validation failed for tenant "+tenant.Name+": "+err.Error())
|
||||
@@ -1934,7 +2084,7 @@ func (h *UserHandler) UpdateUser(c *fiber.Ctx) error {
|
||||
tenant, _ = h.TenantService.GetTenant(c.Context(), tenantID)
|
||||
}
|
||||
if tenant != nil {
|
||||
if schema, ok := tenant.Config["userSchema"].([]interface{}); ok {
|
||||
if schema, ok := tenant.Config["userSchema"].([]any); ok {
|
||||
if err := h.validateMetadataWithAuth(req.Metadata, schema, isAdmin, false); err != nil {
|
||||
return errorJSON(c, fiber.StatusBadRequest, "metadata validation failed: "+err.Error())
|
||||
}
|
||||
@@ -1946,7 +2096,7 @@ func (h *UserHandler) UpdateUser(c *fiber.Ctx) error {
|
||||
|
||||
traits := identity.Traits
|
||||
if traits == nil {
|
||||
traits = map[string]interface{}{}
|
||||
traits = map[string]any{}
|
||||
}
|
||||
delete(traits, "hanmacFamily")
|
||||
delete(traits, "userType")
|
||||
@@ -2035,10 +2185,8 @@ func (h *UserHandler) UpdateUser(c *fiber.Ctx) error {
|
||||
if !coreTraits[k] {
|
||||
// Ensure we are merging maps (tenant namespaces) correctly, not overwriting with slices
|
||||
if incomingMap, ok := v.(map[string]any); ok {
|
||||
if existingMap, ok := traits[k].(map[string]interface{}); ok {
|
||||
for subK, subV := range incomingMap {
|
||||
existingMap[subK] = subV
|
||||
}
|
||||
if existingMap, ok := traits[k].(map[string]any); ok {
|
||||
maps.Copy(existingMap, incomingMap)
|
||||
traits[k] = existingMap
|
||||
} else {
|
||||
traits[k] = incomingMap // New namespace
|
||||
@@ -2059,7 +2207,7 @@ func (h *UserHandler) UpdateUser(c *fiber.Ctx) error {
|
||||
|
||||
allEmails := []string{userEmail}
|
||||
if secondaryRaw, exists := traits["sub_email"]; exists {
|
||||
if secondaryEmails, ok := secondaryRaw.([]interface{}); ok {
|
||||
if secondaryEmails, ok := secondaryRaw.([]any); ok {
|
||||
for _, se := range secondaryEmails {
|
||||
if seStr, ok := se.(string); ok {
|
||||
allEmails = append(allEmails, seStr)
|
||||
@@ -2198,6 +2346,8 @@ func (h *UserHandler) DeleteUser(c *fiber.Ctx) error {
|
||||
return errorJSON(c, fiber.StatusBadRequest, "user id is required")
|
||||
}
|
||||
|
||||
slog.Info("[UserHandler] Attempting to delete user", "userID", userID)
|
||||
|
||||
// [New] Check access scope before deletion
|
||||
requester, _ := c.Locals("user_profile").(*domain.UserProfileResponse)
|
||||
|
||||
@@ -2228,13 +2378,44 @@ func (h *UserHandler) DeleteUser(c *fiber.Ctx) error {
|
||||
}
|
||||
}
|
||||
|
||||
// [FIX] Support fixed UUID deletion
|
||||
// If userID is a fixed UUID, it might not be the Kratos internal ID.
|
||||
actualKratosID := userID
|
||||
if h.KratosAdmin != nil {
|
||||
// 1. Try finding by identifier (which checks external_id if it's a UUID)
|
||||
id, err := h.KratosAdmin.FindIdentityIDByIdentifier(c.Context(), userID)
|
||||
if err == nil && id != "" {
|
||||
actualKratosID = id
|
||||
slog.Info("[UserHandler] Mapped userID to Kratos identity ID", "userID", userID, "actualKratosID", actualKratosID)
|
||||
} else {
|
||||
// 2. Fallback: If not found by ID/ExternalID, try finding by EMAIL from local DB
|
||||
if h.UserRepo != nil {
|
||||
local, err := h.UserRepo.FindByID(c.Context(), userID)
|
||||
if err == nil && local != nil && local.Email != "" {
|
||||
id, err := h.KratosAdmin.FindIdentityIDByIdentifier(c.Context(), local.Email)
|
||||
if err == nil && id != "" {
|
||||
actualKratosID = id
|
||||
slog.Info("[UserHandler] Mapped userID to Kratos identity ID via email", "userID", userID, "email", local.Email, "actualKratosID", actualKratosID)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err := h.enqueueDeletedUserRelyingPartyCleanup(c.Context(), requester, userID); err != nil {
|
||||
slog.Error("[UserHandler] Failed to enqueue RP cleanup", "userID", userID, "error", err)
|
||||
return errorJSON(c, fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
|
||||
if err := h.KratosAdmin.DeleteIdentity(c.Context(), userID); err != nil {
|
||||
return errorJSON(c, fiber.StatusInternalServerError, err.Error())
|
||||
if err := h.KratosAdmin.DeleteIdentity(c.Context(), actualKratosID); err != nil {
|
||||
slog.Error("[UserHandler] Failed to delete Kratos identity", "userID", userID, "actualKratosID", actualKratosID, "error", err)
|
||||
// If Kratos says 404, it might already be gone, so we can proceed to cleanup local DB
|
||||
if !strings.Contains(err.Error(), "404") {
|
||||
return errorJSON(c, fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
}
|
||||
slog.Info("[UserHandler] Successfully deleted Kratos identity", "userID", userID, "actualKratosID", actualKratosID)
|
||||
|
||||
if h.Worksmobile != nil && identity != nil {
|
||||
localUser := h.mapToLocalUser(*identity)
|
||||
if err := h.Worksmobile.EnqueueUserDeleteIfInScope(c.Context(), *localUser); err != nil {
|
||||
@@ -2259,6 +2440,8 @@ func (h *UserHandler) DeleteUser(c *fiber.Ctx) error {
|
||||
if err := h.UserRepo.Delete(context.Background(), userID); err != nil {
|
||||
slog.Error("[UserHandler] Failed to delete local user read-model", "userID", userID, "error", err)
|
||||
markUserProjectionFailed(context.Background(), h.UserProjectionRepo, err)
|
||||
} else {
|
||||
slog.Info("[UserHandler] Successfully deleted local user read-model", "userID", userID)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2387,7 +2570,7 @@ func (h *UserHandler) listDeletedUserRelyingPartyRelations(ctx context.Context,
|
||||
var tuples []service.RelationTuple
|
||||
var err error
|
||||
|
||||
for attempt := 0; attempt < 3; attempt++ {
|
||||
for attempt := range 3 {
|
||||
tuples, err = h.KetoService.ListRelations(ctx, "RelyingParty", "", "", subject)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -2427,6 +2610,21 @@ func (h *UserHandler) mapIdentitySummary(ctx context.Context, identity service.K
|
||||
traits := identity.Traits
|
||||
role := roleFromTraits(traits)
|
||||
|
||||
// [FIX] Prioritize Local DB ID (the fixed UUID from user)
|
||||
finalID := identity.ID
|
||||
email := extractTraitString(traits, "email")
|
||||
if h.UserRepo != nil && email != "" {
|
||||
// 1. Try finding by email first as it's a strong identifier
|
||||
if local, err := h.UserRepo.FindByEmail(ctx, email); err == nil && local != nil {
|
||||
finalID = local.ID
|
||||
} else if identity.ExternalID != "" {
|
||||
// 2. Try finding by ID directly (in case ID was fixed to ExternalID)
|
||||
if local, err := h.UserRepo.FindByID(ctx, identity.ExternalID); err == nil && local != nil {
|
||||
finalID = local.ID
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tenantID := extractTraitString(traits, "tenant_id")
|
||||
tenantSlug := ""
|
||||
var tenantSummary *domain.Tenant
|
||||
@@ -2440,7 +2638,7 @@ func (h *UserHandler) mapIdentitySummary(ctx context.Context, identity service.K
|
||||
|
||||
var customLoginIDs []string
|
||||
if raw, ok := traits["custom_login_ids"]; ok {
|
||||
if ids, ok := raw.([]interface{}); ok {
|
||||
if ids, ok := raw.([]any); ok {
|
||||
for _, id := range ids {
|
||||
if s, ok := id.(string); ok {
|
||||
customLoginIDs = append(customLoginIDs, s)
|
||||
@@ -2452,7 +2650,7 @@ func (h *UserHandler) mapIdentitySummary(ctx context.Context, identity service.K
|
||||
}
|
||||
|
||||
summary := userSummary{
|
||||
ID: identity.ID,
|
||||
ID: finalID,
|
||||
Email: extractTraitString(traits, "email"),
|
||||
LoginID: resolvePasswordLoginID(traits),
|
||||
CustomLoginIDs: customLoginIDs,
|
||||
@@ -2512,8 +2710,15 @@ func (h *UserHandler) mapToLocalUser(identity service.KratosIdentity) *domain.Us
|
||||
traits := identity.Traits
|
||||
role := roleFromTraits(traits)
|
||||
|
||||
// [FIX] Prioritize ExternalID as the primary ID for Baron SSO if it exists.
|
||||
// This ensures that admin-provided UUIDs are kept consistent across async syncs.
|
||||
finalID := identity.ID
|
||||
if identity.ExternalID != "" {
|
||||
finalID = identity.ExternalID
|
||||
}
|
||||
|
||||
user := &domain.User{
|
||||
ID: identity.ID,
|
||||
ID: finalID,
|
||||
Email: extractTraitString(traits, "email"),
|
||||
Name: extractTraitString(traits, "name"),
|
||||
Phone: extractTraitString(traits, "phone_number"),
|
||||
@@ -2637,7 +2842,7 @@ func (h *UserHandler) syncKetoRole(ctx context.Context, userID, newRole, oldRole
|
||||
}
|
||||
}
|
||||
|
||||
func extractTraitString(traits map[string]interface{}, key string) string {
|
||||
func extractTraitString(traits map[string]any, key string) string {
|
||||
if traits == nil {
|
||||
return ""
|
||||
}
|
||||
@@ -2649,12 +2854,12 @@ func extractTraitString(traits map[string]interface{}, key string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func extractTraitStringArray(traits map[string]interface{}, key string) []string {
|
||||
func extractTraitStringArray(traits map[string]any, key string) []string {
|
||||
if traits == nil {
|
||||
return nil
|
||||
}
|
||||
if raw, ok := traits[key]; ok {
|
||||
if slice, ok := raw.([]interface{}); ok {
|
||||
if slice, ok := raw.([]any); ok {
|
||||
var result []string
|
||||
for _, v := range slice {
|
||||
if s, ok := v.(string); ok {
|
||||
@@ -2670,10 +2875,10 @@ func extractTraitStringArray(traits map[string]interface{}, key string) []string
|
||||
return nil
|
||||
}
|
||||
|
||||
func resolvePasswordLoginID(traits map[string]interface{}) string {
|
||||
func resolvePasswordLoginID(traits map[string]any) string {
|
||||
// First check custom_login_ids (array)
|
||||
if raw, ok := traits["custom_login_ids"]; ok {
|
||||
if ids, ok := raw.([]interface{}); ok && len(ids) > 0 {
|
||||
if ids, ok := raw.([]any); ok && len(ids) > 0 {
|
||||
if first, ok := ids[0].(string); ok {
|
||||
return first
|
||||
}
|
||||
@@ -2693,7 +2898,7 @@ func resolvePasswordLoginID(traits map[string]interface{}) string {
|
||||
|
||||
// syncCustomLoginIDs collects all fields marked as isLoginId: true from tenant schemas
|
||||
// and populates traits["custom_login_ids"] and returns domain.UserLoginID records for DB.
|
||||
func syncCustomLoginIDs(ctx context.Context, tenantService service.TenantService, traits map[string]interface{}, metadata map[string]any, userID string) []domain.UserLoginID {
|
||||
func syncCustomLoginIDs(ctx context.Context, tenantService service.TenantService, traits map[string]any, metadata map[string]any, userID string) []domain.UserLoginID {
|
||||
if tenantService == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -2726,13 +2931,13 @@ func syncCustomLoginIDs(ctx context.Context, tenantService service.TenantService
|
||||
continue
|
||||
}
|
||||
|
||||
schema, ok := tenant.Config["userSchema"].([]interface{})
|
||||
schema, ok := tenant.Config["userSchema"].([]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
for _, fieldRaw := range schema {
|
||||
field, ok := fieldRaw.(map[string]interface{})
|
||||
field, ok := fieldRaw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
@@ -2751,7 +2956,7 @@ func syncCustomLoginIDs(ctx context.Context, tenantService service.TenantService
|
||||
var val string
|
||||
if namespaced, ok := metadata[tid].(map[string]any); ok {
|
||||
val, _ = namespaced[fieldKey].(string)
|
||||
} else if namespaced, ok := metadata[tid].(map[string]interface{}); ok {
|
||||
} else if namespaced, ok := metadata[tid].(map[string]any); ok {
|
||||
val, _ = namespaced[fieldKey].(string)
|
||||
}
|
||||
|
||||
@@ -2761,7 +2966,7 @@ func syncCustomLoginIDs(ctx context.Context, tenantService service.TenantService
|
||||
|
||||
if val == "" {
|
||||
// Check existing trait (namespaced)
|
||||
if namespaced, ok := traits[tid].(map[string]interface{}); ok {
|
||||
if namespaced, ok := traits[tid].(map[string]any); ok {
|
||||
val, _ = namespaced[fieldKey].(string)
|
||||
} else if namespaced, ok := traits[tid].(map[string]any); ok {
|
||||
val, _ = namespaced[fieldKey].(string)
|
||||
@@ -2833,13 +3038,13 @@ func isMetadataMap(value any) bool {
|
||||
if _, ok := value.(map[string]any); ok {
|
||||
return true
|
||||
}
|
||||
if _, ok := value.(map[string]interface{}); ok {
|
||||
if _, ok := value.(map[string]any); ok {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func normalizeCustomLoginIDsTrait(traits map[string]interface{}) {
|
||||
func normalizeCustomLoginIDsTrait(traits map[string]any) {
|
||||
raw, exists := traits["custom_login_ids"]
|
||||
if !exists {
|
||||
return
|
||||
@@ -2847,7 +3052,7 @@ func normalizeCustomLoginIDsTrait(traits map[string]interface{}) {
|
||||
switch values := raw.(type) {
|
||||
case []string:
|
||||
return
|
||||
case []interface{}:
|
||||
case []any:
|
||||
normalized := make([]string, 0, len(values))
|
||||
for _, value := range values {
|
||||
if text, ok := value.(string); ok && strings.TrimSpace(text) != "" {
|
||||
@@ -2909,14 +3114,14 @@ func normalizePhoneNumber(phone string) string {
|
||||
return normalized
|
||||
}
|
||||
|
||||
func (h *UserHandler) validateMetadata(metadata map[string]any, schema []interface{}, checkRequired bool) error {
|
||||
func (h *UserHandler) validateMetadata(metadata map[string]any, schema []any, checkRequired bool) error {
|
||||
return h.validateMetadataWithAuth(metadata, schema, true, checkRequired)
|
||||
}
|
||||
|
||||
func (h *UserHandler) validateMetadataWithAuth(metadata map[string]any, schema []interface{}, isAdmin bool, checkRequired bool) error {
|
||||
schemaMap := make(map[string]map[string]interface{})
|
||||
func (h *UserHandler) validateMetadataWithAuth(metadata map[string]any, schema []any, isAdmin bool, checkRequired bool) error {
|
||||
schemaMap := make(map[string]map[string]any)
|
||||
for _, s := range schema {
|
||||
if m, ok := s.(map[string]interface{}); ok {
|
||||
if m, ok := s.(map[string]any); ok {
|
||||
if key, ok := m["key"].(string); ok {
|
||||
schemaMap[key] = m
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ func (m *MockKratosAdmin) GetIdentity(ctx context.Context, id string) (*service.
|
||||
return args.Get(0).(*service.KratosIdentity), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockKratosAdmin) UpdateIdentity(ctx context.Context, id string, traits map[string]interface{}, state string) (*service.KratosIdentity, error) {
|
||||
func (m *MockKratosAdmin) UpdateIdentity(ctx context.Context, id string, traits map[string]any, state string) (*service.KratosIdentity, error) {
|
||||
args := m.Called(ctx, id, traits, state)
|
||||
if args.Get(0) == nil {
|
||||
return nil, args.Error(1)
|
||||
@@ -445,8 +445,8 @@ func TestUserHandler_BulkCreateUsers(t *testing.T) {
|
||||
ID: "t-123",
|
||||
Slug: "test-tenant",
|
||||
Config: domain.JSONMap{
|
||||
"userSchema": []interface{}{
|
||||
map[string]interface{}{"key": "emp_id", "label": "EmpID", "required": true, "isLoginId": true},
|
||||
"userSchema": []any{
|
||||
map[string]any{"key": "emp_id", "label": "EmpID", "required": true, "isLoginId": true},
|
||||
},
|
||||
},
|
||||
}, nil).Once()
|
||||
@@ -455,28 +455,32 @@ func TestUserHandler_BulkCreateUsers(t *testing.T) {
|
||||
ID: "t-123",
|
||||
Slug: "test-tenant",
|
||||
Config: domain.JSONMap{
|
||||
"userSchema": []interface{}{
|
||||
map[string]interface{}{"key": "emp_id", "label": "EmpID", "required": true, "isLoginId": true},
|
||||
"userSchema": []any{
|
||||
map[string]any{"key": "emp_id", "label": "EmpID", "required": true, "isLoginId": true},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockOry.On("GetPasswordPolicy").Return(&domain.PasswordPolicy{MinLength: 8}, nil)
|
||||
|
||||
// [FIX] Search-first diagnostic calls
|
||||
mockKratos.On("FindIdentityIDByIdentifier", mock.Anything, mock.Anything).Return("", nil).Maybe()
|
||||
|
||||
mockOry.On("CreateUser", mock.Anything, mock.Anything).Return("u-1", nil).Twice()
|
||||
|
||||
payload := map[string]interface{}{
|
||||
"users": []map[string]interface{}{
|
||||
payload := map[string]any{
|
||||
"users": []map[string]any{
|
||||
{
|
||||
"email": "user1@test.com",
|
||||
"name": "User One",
|
||||
"tenantSlug": "test-tenant",
|
||||
"metadata": map[string]interface{}{"emp_id": "E001"},
|
||||
"metadata": map[string]any{"emp_id": "E001"},
|
||||
},
|
||||
{
|
||||
"email": "user2@test.com",
|
||||
"name": "User Two",
|
||||
"tenantSlug": "test-tenant",
|
||||
"metadata": map[string]interface{}{"emp_id": "E002"},
|
||||
"metadata": map[string]any{"emp_id": "E002"},
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -487,20 +491,20 @@ func TestUserHandler_BulkCreateUsers(t *testing.T) {
|
||||
resp, _ := app.Test(req)
|
||||
assert.Equal(t, 200, resp.StatusCode)
|
||||
|
||||
var result map[string]interface{}
|
||||
var result map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&result)
|
||||
results := result["results"].([]interface{})
|
||||
results := result["results"].([]any)
|
||||
assert.Len(t, results, 2)
|
||||
assert.True(t, results[0].(map[string]interface{})["success"].(bool))
|
||||
assert.True(t, results[1].(map[string]interface{})["success"].(bool))
|
||||
assert.True(t, results[0].(map[string]any)["success"].(bool))
|
||||
assert.True(t, results[1].(map[string]any)["success"].(bool))
|
||||
})
|
||||
|
||||
t.Run("Fail - Tenant Not Found", func(t *testing.T) {
|
||||
mockTenant.On("GetTenantBySlug", mock.Anything, "wrong-tenant").Return(nil, errors.New("not found")).Once()
|
||||
mockOry.On("GetPasswordPolicy").Return(&domain.PasswordPolicy{MinLength: 8}, nil)
|
||||
|
||||
payload := map[string]interface{}{
|
||||
"users": []map[string]interface{}{
|
||||
payload := map[string]any{
|
||||
"users": []map[string]any{
|
||||
{
|
||||
"email": "fail@test.com",
|
||||
"name": "Fail User",
|
||||
@@ -513,12 +517,12 @@ func TestUserHandler_BulkCreateUsers(t *testing.T) {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, _ := app.Test(req)
|
||||
var result map[string]interface{}
|
||||
var result map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&result)
|
||||
results := result["results"].([]interface{})
|
||||
results := result["results"].([]any)
|
||||
|
||||
assert.False(t, results[0].(map[string]interface{})["success"].(bool))
|
||||
assert.Contains(t, results[0].(map[string]interface{})["message"].(string), "tenant not found")
|
||||
assert.False(t, results[0].(map[string]any)["success"].(bool))
|
||||
assert.Contains(t, results[0].(map[string]any)["message"].(string), "tenant not found")
|
||||
})
|
||||
|
||||
t.Run("Fail - Schema Validation (Required)", func(t *testing.T) {
|
||||
@@ -526,8 +530,8 @@ func TestUserHandler_BulkCreateUsers(t *testing.T) {
|
||||
ID: "t-123",
|
||||
Slug: "test-tenant",
|
||||
Config: domain.JSONMap{
|
||||
"userSchema": []interface{}{
|
||||
map[string]interface{}{"key": "emp_id", "label": "EmpID", "required": true, "isLoginId": true},
|
||||
"userSchema": []any{
|
||||
map[string]any{"key": "emp_id", "label": "EmpID", "required": true, "isLoginId": true},
|
||||
},
|
||||
},
|
||||
}, nil).Once()
|
||||
@@ -536,19 +540,19 @@ func TestUserHandler_BulkCreateUsers(t *testing.T) {
|
||||
ID: "t-123",
|
||||
Slug: "test-tenant",
|
||||
Config: domain.JSONMap{
|
||||
"userSchema": []interface{}{
|
||||
map[string]interface{}{"key": "emp_id", "label": "EmpID", "required": true, "isLoginId": true},
|
||||
"userSchema": []any{
|
||||
map[string]any{"key": "emp_id", "label": "EmpID", "required": true, "isLoginId": true},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
payload := map[string]interface{}{
|
||||
"users": []map[string]interface{}{
|
||||
payload := map[string]any{
|
||||
"users": []map[string]any{
|
||||
{
|
||||
"email": "missing-meta@test.com",
|
||||
"name": "No Meta",
|
||||
"tenantSlug": "test-tenant",
|
||||
"metadata": map[string]interface{}{}, // emp_id missing
|
||||
"metadata": map[string]any{}, // emp_id missing
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -557,12 +561,12 @@ func TestUserHandler_BulkCreateUsers(t *testing.T) {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, _ := app.Test(req)
|
||||
var result map[string]interface{}
|
||||
var result map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&result)
|
||||
results := result["results"].([]interface{})
|
||||
results := result["results"].([]any)
|
||||
|
||||
assert.False(t, results[0].(map[string]interface{})["success"].(bool))
|
||||
assert.Contains(t, results[0].(map[string]interface{})["message"].(string), "field emp_id is required")
|
||||
assert.False(t, results[0].(map[string]any)["success"].(bool))
|
||||
assert.Contains(t, results[0].(map[string]any)["message"].(string), "field emp_id is required")
|
||||
})
|
||||
|
||||
t.Run("Fail - Schema Validation (Regex)", func(t *testing.T) {
|
||||
@@ -570,19 +574,19 @@ func TestUserHandler_BulkCreateUsers(t *testing.T) {
|
||||
ID: "t-123",
|
||||
Slug: "test-tenant",
|
||||
Config: domain.JSONMap{
|
||||
"userSchema": []interface{}{
|
||||
map[string]interface{}{"key": "emp_id", "validation": "^E[0-9]{3}$"},
|
||||
"userSchema": []any{
|
||||
map[string]any{"key": "emp_id", "validation": "^E[0-9]{3}$"},
|
||||
},
|
||||
},
|
||||
}, nil).Once()
|
||||
|
||||
payload := map[string]interface{}{
|
||||
"users": []map[string]interface{}{
|
||||
payload := map[string]any{
|
||||
"users": []map[string]any{
|
||||
{
|
||||
"email": "regex-fail@test.com",
|
||||
"name": "Regex Fail",
|
||||
"tenantSlug": "test-tenant",
|
||||
"metadata": map[string]interface{}{"emp_id": "abc"}, // Should start with E and 3 digits
|
||||
"metadata": map[string]any{"emp_id": "abc"}, // Should start with E and 3 digits
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -591,12 +595,12 @@ func TestUserHandler_BulkCreateUsers(t *testing.T) {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, _ := app.Test(req)
|
||||
var result map[string]interface{}
|
||||
var result map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&result)
|
||||
results := result["results"].([]interface{})
|
||||
results := result["results"].([]any)
|
||||
|
||||
assert.False(t, results[0].(map[string]interface{})["success"].(bool))
|
||||
assert.Contains(t, results[0].(map[string]interface{})["message"].(string), "match validation pattern")
|
||||
assert.False(t, results[0].(map[string]any)["success"].(bool))
|
||||
assert.Contains(t, results[0].(map[string]any)["message"].(string), "match validation pattern")
|
||||
})
|
||||
}
|
||||
|
||||
@@ -650,20 +654,20 @@ func TestUserHandler_BulkCreateUsers_ResolvesAdditionalAppointment(t *testing.T)
|
||||
metadata["employee_id"] == "EMP002"
|
||||
}), mock.Anything).Return("u-appointment", nil).Once()
|
||||
|
||||
payload := map[string]interface{}{
|
||||
"users": []map[string]interface{}{
|
||||
payload := map[string]any{
|
||||
"users": []map[string]any{
|
||||
{
|
||||
"email": "dual@test.com",
|
||||
"name": "Dual User",
|
||||
"tenantSlug": "test-tenant",
|
||||
"metadata": map[string]interface{}{"employee_id": "EMP001"},
|
||||
"additionalAppointments": []map[string]interface{}{
|
||||
"metadata": map[string]any{"employee_id": "EMP001"},
|
||||
"additionalAppointments": []map[string]any{
|
||||
{
|
||||
"tenantSlug": "second-tenant",
|
||||
"department": "센터",
|
||||
"grade": "수석",
|
||||
"jobTitle": "Architecture",
|
||||
"metadata": map[string]interface{}{"employee_id": "EMP002"},
|
||||
"metadata": map[string]any{"employee_id": "EMP002"},
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -734,8 +738,8 @@ func TestUserHandler_BulkCreateUsers_AppendsEmailDomainTenantAtLowestPriority(t
|
||||
appointment["sourceDomain"] == "samaneng.com"
|
||||
}), mock.Anything).Return("u-domain-assigned", nil).Once()
|
||||
|
||||
payload := map[string]interface{}{
|
||||
"users": []map[string]interface{}{
|
||||
payload := map[string]any{
|
||||
"users": []map[string]any{
|
||||
{
|
||||
"email": "user@samaneng.com",
|
||||
"name": "Domain User",
|
||||
@@ -750,10 +754,10 @@ func TestUserHandler_BulkCreateUsers_AppendsEmailDomainTenantAtLowestPriority(t
|
||||
resp, _ := app.Test(req)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
var result map[string]interface{}
|
||||
var result map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&result)
|
||||
results := result["results"].([]interface{})
|
||||
assert.True(t, results[0].(map[string]interface{})["success"].(bool))
|
||||
results := result["results"].([]any)
|
||||
assert.True(t, results[0].(map[string]any)["success"].(bool))
|
||||
mockTenant.AssertExpectations(t)
|
||||
mockOry.AssertExpectations(t)
|
||||
}
|
||||
@@ -785,8 +789,8 @@ func TestUserHandler_BulkCreateUsers_UsesEmailDomainTenantAsPrimaryWhenExplicitT
|
||||
user.Attributes["additionalAppointments"] == nil
|
||||
}), mock.Anything).Return("u-domain-primary", nil).Once()
|
||||
|
||||
payload := map[string]interface{}{
|
||||
"users": []map[string]interface{}{
|
||||
payload := map[string]any{
|
||||
"users": []map[string]any{
|
||||
{
|
||||
"email": "user@samaneng.com",
|
||||
"name": "Domain Primary User",
|
||||
@@ -800,10 +804,10 @@ func TestUserHandler_BulkCreateUsers_UsesEmailDomainTenantAsPrimaryWhenExplicitT
|
||||
resp, _ := app.Test(req)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
var result map[string]interface{}
|
||||
var result map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&result)
|
||||
results := result["results"].([]interface{})
|
||||
assert.True(t, results[0].(map[string]interface{})["success"].(bool))
|
||||
results := result["results"].([]any)
|
||||
assert.True(t, results[0].(map[string]any)["success"].(bool))
|
||||
mockTenant.AssertExpectations(t)
|
||||
mockOry.AssertExpectations(t)
|
||||
}
|
||||
@@ -853,9 +857,9 @@ func TestUserHandler_ListUsersReturnsNextCursorWhenMoreRowsExist(t *testing.T) {
|
||||
app.Get("/users", h.ListUsers)
|
||||
|
||||
mockKratos.On("ListIdentities", mock.Anything).Return([]service.KratosIdentity{
|
||||
{ID: "u-3", State: "active", CreatedAt: createdAt, Traits: map[string]interface{}{"email": "c@example.com", "name": "C"}},
|
||||
{ID: "u-2", State: "active", CreatedAt: createdAt.Add(-time.Minute), Traits: map[string]interface{}{"email": "b@example.com", "name": "B"}},
|
||||
{ID: "u-1", State: "active", CreatedAt: createdAt.Add(-2 * time.Minute), Traits: map[string]interface{}{"email": "a@example.com", "name": "A"}},
|
||||
{ID: "u-3", State: "active", CreatedAt: createdAt, Traits: map[string]any{"email": "c@example.com", "name": "C"}},
|
||||
{ID: "u-2", State: "active", CreatedAt: createdAt.Add(-time.Minute), Traits: map[string]any{"email": "b@example.com", "name": "B"}},
|
||||
{ID: "u-1", State: "active", CreatedAt: createdAt.Add(-2 * time.Minute), Traits: map[string]any{"email": "a@example.com", "name": "A"}},
|
||||
}, nil).Once()
|
||||
|
||||
req := httptest.NewRequest("GET", "/users?limit=2", nil)
|
||||
@@ -915,8 +919,8 @@ func TestUserHandler_BulkCreateUsers_HanmacEmailPolicy(t *testing.T) {
|
||||
return user.Email == "cyhan2@hanmaceng.co.kr"
|
||||
}), mock.Anything).Return("u-hanmac", nil).Once()
|
||||
|
||||
payload := map[string]interface{}{
|
||||
"users": []map[string]interface{}{
|
||||
payload := map[string]any{
|
||||
"users": []map[string]any{
|
||||
{
|
||||
"email": "@hanmaceng.co.kr",
|
||||
"name": "한치영",
|
||||
@@ -931,14 +935,14 @@ func TestUserHandler_BulkCreateUsers_HanmacEmailPolicy(t *testing.T) {
|
||||
resp, _ := app.Test(req)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
var result map[string]interface{}
|
||||
var result map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&result)
|
||||
results := result["results"].([]interface{})
|
||||
row := results[0].(map[string]interface{})
|
||||
results := result["results"].([]any)
|
||||
row := results[0].(map[string]any)
|
||||
assert.True(t, row["success"].(bool))
|
||||
assert.Equal(t, "cyhan2@hanmaceng.co.kr", row["email"])
|
||||
assert.Equal(t, "@hanmaceng.co.kr", row["originalEmail"])
|
||||
assert.Contains(t, row["warnings"].([]interface{}), "suggested")
|
||||
assert.Contains(t, row["warnings"].([]any), "suggested")
|
||||
})
|
||||
|
||||
t.Run("full email duplicate local part is blocking error", func(t *testing.T) {
|
||||
@@ -957,8 +961,8 @@ func TestUserHandler_BulkCreateUsers_HanmacEmailPolicy(t *testing.T) {
|
||||
mockRepo.On("FindByCompanyCodes", mock.Anything, []string{"hanmac-family", "hanmac"}).Return([]domain.User{}, nil).Once()
|
||||
mockOry.On("GetPasswordPolicy").Return(&domain.PasswordPolicy{MinLength: 8}, nil).Once()
|
||||
|
||||
payload := map[string]interface{}{
|
||||
"users": []map[string]interface{}{
|
||||
payload := map[string]any{
|
||||
"users": []map[string]any{
|
||||
{
|
||||
"email": "han@samaneng.com",
|
||||
"name": "한치영",
|
||||
@@ -973,10 +977,10 @@ func TestUserHandler_BulkCreateUsers_HanmacEmailPolicy(t *testing.T) {
|
||||
resp, _ := app.Test(req)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
var result map[string]interface{}
|
||||
var result map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&result)
|
||||
results := result["results"].([]interface{})
|
||||
row := results[0].(map[string]interface{})
|
||||
results := result["results"].([]any)
|
||||
row := results[0].(map[string]any)
|
||||
assert.False(t, row["success"].(bool))
|
||||
assert.Equal(t, "blockingError", row["status"])
|
||||
assert.Contains(t, row["message"].(string), "한맥가족 내에서 이미 사용 중인 이메일 ID입니다.")
|
||||
@@ -1017,7 +1021,7 @@ func TestUserHandler_CreateUser_HanmacEmailPolicyBlocksDuplicateLocalPart(t *tes
|
||||
}, nil).Once()
|
||||
mockRepo.On("FindByCompanyCodes", mock.Anything, []string{"hanmac-family", "hanmac"}).Return([]domain.User{}, nil).Once()
|
||||
|
||||
payload := map[string]interface{}{
|
||||
payload := map[string]any{
|
||||
"email": "han@samaneng.com",
|
||||
"name": "한치영",
|
||||
"tenantSlug": "hanmac",
|
||||
@@ -1029,7 +1033,7 @@ func TestUserHandler_CreateUser_HanmacEmailPolicyBlocksDuplicateLocalPart(t *tes
|
||||
resp, _ := app.Test(req)
|
||||
assert.Equal(t, http.StatusConflict, resp.StatusCode)
|
||||
|
||||
var result map[string]interface{}
|
||||
var result map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&result)
|
||||
assert.Contains(t, result["error"].(string), "한맥가족 내에서 이미 사용 중인 이메일 ID입니다.")
|
||||
mockOry.AssertNotCalled(t, "CreateUser")
|
||||
@@ -1049,12 +1053,12 @@ func TestUserHandler_BulkUpdateUsers(t *testing.T) {
|
||||
|
||||
t.Run("Success - Update Role and Status", func(t *testing.T) {
|
||||
mockKratos.On("GetIdentity", mock.Anything, "u-1").Return(&service.KratosIdentity{
|
||||
ID: "u-1", Traits: map[string]interface{}{"email": "u1@test.com", "tenant_id": "tenant-1"}, State: "active",
|
||||
ID: "u-1", Traits: map[string]any{"email": "u1@test.com", "tenant_id": "tenant-1"}, State: "active",
|
||||
}, nil).Once()
|
||||
|
||||
mockKratos.On("UpdateIdentity", mock.Anything, "u-1", mock.Anything, "inactive").Return(&service.KratosIdentity{
|
||||
ID: "u-1",
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"email": "u1@test.com",
|
||||
"name": "Bulk User",
|
||||
"tenant_id": "tenant-1",
|
||||
@@ -1063,7 +1067,7 @@ func TestUserHandler_BulkUpdateUsers(t *testing.T) {
|
||||
}, nil).Once()
|
||||
|
||||
status := "inactive"
|
||||
payload := map[string]interface{}{
|
||||
payload := map[string]any{
|
||||
"userIds": []string{"u-1"},
|
||||
"status": &status,
|
||||
}
|
||||
@@ -1074,10 +1078,10 @@ func TestUserHandler_BulkUpdateUsers(t *testing.T) {
|
||||
resp, _ := app.Test(req)
|
||||
assert.Equal(t, 200, resp.StatusCode)
|
||||
|
||||
var result map[string]interface{}
|
||||
var result map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&result)
|
||||
results := result["results"].([]interface{})
|
||||
assert.True(t, results[0].(map[string]interface{})["success"].(bool))
|
||||
results := result["results"].([]any)
|
||||
assert.True(t, results[0].(map[string]any)["success"].(bool))
|
||||
assert.Len(t, worksmobile.upserts, 1)
|
||||
assert.Equal(t, "u-1", worksmobile.upserts[0].ID)
|
||||
assert.Equal(t, domain.UserStatusPreboarding, worksmobile.upserts[0].Status)
|
||||
@@ -1085,7 +1089,7 @@ func TestUserHandler_BulkUpdateUsers(t *testing.T) {
|
||||
|
||||
t.Run("Fail - Super admin cannot assign tenant or RP admin roles", func(t *testing.T) {
|
||||
for _, role := range []string{domain.RoleTenantAdmin, domain.RoleRPAdmin} {
|
||||
payload := map[string]interface{}{
|
||||
payload := map[string]any{
|
||||
"userIds": []string{"u-1"},
|
||||
"role": role,
|
||||
}
|
||||
@@ -1107,7 +1111,7 @@ func TestUserHandler_BulkUpdateUsers(t *testing.T) {
|
||||
})
|
||||
|
||||
role := domain.RoleSuperAdmin
|
||||
payload := map[string]interface{}{
|
||||
payload := map[string]any{
|
||||
"userIds": []string{"u-1"},
|
||||
"role": &role,
|
||||
}
|
||||
@@ -1137,7 +1141,7 @@ func TestUserHandler_BulkDeleteUsers(t *testing.T) {
|
||||
mockKratos.On("DeleteIdentity", mock.Anything, "u-1").Return(nil).Once()
|
||||
mockKratos.On("DeleteIdentity", mock.Anything, "u-2").Return(nil).Once()
|
||||
|
||||
payload := map[string]interface{}{
|
||||
payload := map[string]any{
|
||||
"userIds": []string{"u-1", "u-2"},
|
||||
}
|
||||
body, _ := json.Marshal(payload)
|
||||
@@ -1182,6 +1186,10 @@ func TestUserHandler_DeleteUserDeletesLocalReadModel(t *testing.T) {
|
||||
mockOutbox.On("Create", mock.Anything, mock.MatchedBy(func(entry *domain.KetoOutbox) bool {
|
||||
return entry.Namespace == "System" && entry.Object == "global" && entry.Relation == "super_admins" && entry.Subject == "User:u-1" && entry.Action == domain.KetoOutboxActionDelete
|
||||
})).Return(nil).Once()
|
||||
|
||||
// [FIX] Diagnostic call for fixed UUID mapping
|
||||
mockKratos.On("FindIdentityIDByIdentifier", mock.Anything, "u-1").Return("", nil).Maybe()
|
||||
|
||||
mockKratos.On("DeleteIdentity", mock.Anything, "u-1").Return(nil).Once()
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/users/u-1", nil)
|
||||
@@ -1220,7 +1228,7 @@ func TestUserHandler_BulkDeleteUsers_CleansUpRelyingPartyRelations(t *testing.T)
|
||||
})).Return(nil).Once()
|
||||
mockKratos.On("DeleteIdentity", mock.Anything, "u-1").Return(nil).Once()
|
||||
|
||||
payload := map[string]interface{}{
|
||||
payload := map[string]any{
|
||||
"userIds": []string{"u-1"},
|
||||
}
|
||||
body, _ := json.Marshal(payload)
|
||||
@@ -1281,6 +1289,10 @@ func TestUserHandler_DeleteUserFallsBackToKetoOutboxWhenLiveRelationsAreEmpty(t
|
||||
mockOutbox.On("Create", mock.Anything, mock.MatchedBy(func(entry *domain.KetoOutbox) bool {
|
||||
return entry.Namespace == "System" && entry.Object == "global" && entry.Relation == "super_admins" && entry.Subject == "User:u-1" && entry.Action == domain.KetoOutboxActionDelete
|
||||
})).Return(nil).Once()
|
||||
|
||||
// [FIX] Diagnostic call for fixed UUID mapping
|
||||
mockKratos.On("FindIdentityIDByIdentifier", mock.Anything, "u-1").Return("", nil).Maybe()
|
||||
|
||||
mockKratos.On("DeleteIdentity", mock.Anything, "u-1").Return(nil).Once()
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/users/u-1", nil)
|
||||
@@ -1323,6 +1335,10 @@ func TestUserHandler_DeleteUserRecordsCascadeRelyingPartyCleanupAudit(t *testing
|
||||
mockOutbox.On("Create", mock.Anything, mock.MatchedBy(func(entry *domain.KetoOutbox) bool {
|
||||
return entry.Namespace == "System" && entry.Object == "global" && entry.Relation == "super_admins" && entry.Subject == "User:u-1" && entry.Action == domain.KetoOutboxActionDelete
|
||||
})).Return(nil).Once()
|
||||
|
||||
// [FIX] Diagnostic call for fixed UUID mapping
|
||||
mockKratos.On("FindIdentityIDByIdentifier", mock.Anything, "u-1").Return("", nil).Maybe()
|
||||
|
||||
mockKratos.On("DeleteIdentity", mock.Anything, "u-1").Return(nil).Once()
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/users/u-1", nil)
|
||||
@@ -1373,21 +1389,21 @@ func TestUserHandler_UpdateUser_AdminOnlyField(t *testing.T) {
|
||||
tenantID := "t-123"
|
||||
mockKratos.On("GetIdentity", mock.Anything, "u-1").Return(&service.KratosIdentity{
|
||||
ID: "u-1",
|
||||
Traits: map[string]interface{}{"email": "user@test.com", "tenant_id": tenantID},
|
||||
Traits: map[string]any{"email": "user@test.com", "tenant_id": tenantID},
|
||||
}, nil)
|
||||
|
||||
mockTenant.On("GetTenant", mock.Anything, tenantID).Return(&domain.Tenant{
|
||||
ID: tenantID,
|
||||
Slug: "test-tenant",
|
||||
Config: domain.JSONMap{
|
||||
"userSchema": []interface{}{
|
||||
map[string]interface{}{"key": "salary", "adminOnly": true},
|
||||
"userSchema": []any{
|
||||
map[string]any{"key": "salary", "adminOnly": true},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
payload := map[string]interface{}{
|
||||
"metadata": map[string]interface{}{"salary": 5000},
|
||||
payload := map[string]any{
|
||||
"metadata": map[string]any{"salary": 5000},
|
||||
}
|
||||
body, _ := json.Marshal(payload)
|
||||
req := httptest.NewRequest("PUT", "/users/u-1", bytes.NewReader(body))
|
||||
@@ -1396,7 +1412,7 @@ func TestUserHandler_UpdateUser_AdminOnlyField(t *testing.T) {
|
||||
resp, _ := app.Test(req)
|
||||
assert.Equal(t, 400, resp.StatusCode) // validation failed
|
||||
|
||||
var result map[string]interface{}
|
||||
var result map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&result)
|
||||
assert.Contains(t, result["error"].(string), "field salary is admin only")
|
||||
})
|
||||
@@ -1414,11 +1430,11 @@ func TestUserHandler_UpdateUser_RejectsDeprecatedAdminRoles(t *testing.T) {
|
||||
for _, role := range []string{domain.RoleTenantAdmin, domain.RoleRPAdmin} {
|
||||
mockKratos.On("GetIdentity", mock.Anything, "u-1").Return(&service.KratosIdentity{
|
||||
ID: "u-1",
|
||||
Traits: map[string]interface{}{"email": "user@test.com", "role": domain.RoleUser},
|
||||
Traits: map[string]any{"email": "user@test.com", "role": domain.RoleUser},
|
||||
State: "active",
|
||||
}, nil).Once()
|
||||
|
||||
payload := map[string]interface{}{"role": role}
|
||||
payload := map[string]any{"role": role}
|
||||
body, _ := json.Marshal(payload)
|
||||
req := httptest.NewRequest("PUT", "/users/u-1", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
@@ -1437,20 +1453,20 @@ func TestSyncCustomLoginIDs_IgnoresFlatMetadataMaps(t *testing.T) {
|
||||
ID: tenantID,
|
||||
Slug: "test-tenant",
|
||||
Config: domain.JSONMap{
|
||||
"userSchema": []interface{}{
|
||||
map[string]interface{}{"key": "emp_no", "isLoginId": true},
|
||||
"userSchema": []any{
|
||||
map[string]any{"key": "emp_no", "isLoginId": true},
|
||||
},
|
||||
},
|
||||
}, nil).Once()
|
||||
|
||||
traits := map[string]interface{}{
|
||||
traits := map[string]any{
|
||||
"tenant_id": tenantID,
|
||||
}
|
||||
metadata := map[string]any{
|
||||
tenantID: map[string]interface{}{
|
||||
tenantID: map[string]any{
|
||||
"emp_no": "E1001",
|
||||
},
|
||||
"worksmobileAliasEmails": map[string]interface{}{
|
||||
"worksmobileAliasEmails": map[string]any{
|
||||
"0": "alias@hanmaceng.co.kr",
|
||||
},
|
||||
}
|
||||
@@ -1482,7 +1498,7 @@ func TestUserHandler_UpdateUser_LoginIDSync(t *testing.T) {
|
||||
userID := "u-1"
|
||||
mockKratos.On("GetIdentity", mock.Anything, userID).Return(&service.KratosIdentity{
|
||||
ID: userID,
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"email": "user@test.com",
|
||||
"companyCode": "test-tenant",
|
||||
"tenant_id": tenantID,
|
||||
@@ -1493,8 +1509,8 @@ func TestUserHandler_UpdateUser_LoginIDSync(t *testing.T) {
|
||||
ID: tenantID,
|
||||
Slug: "test-tenant",
|
||||
Config: domain.JSONMap{
|
||||
"userSchema": []interface{}{
|
||||
map[string]interface{}{"key": "emp_no", "label": "Employee No", "isLoginId": true},
|
||||
"userSchema": []any{
|
||||
map[string]any{"key": "emp_no", "label": "Employee No", "isLoginId": true},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
@@ -1502,8 +1518,8 @@ func TestUserHandler_UpdateUser_LoginIDSync(t *testing.T) {
|
||||
ID: tenantID,
|
||||
Slug: "test-tenant",
|
||||
Config: domain.JSONMap{
|
||||
"userSchema": []interface{}{
|
||||
map[string]interface{}{"key": "emp_no", "label": "Employee No", "isLoginId": true},
|
||||
"userSchema": []any{
|
||||
map[string]any{"key": "emp_no", "label": "Employee No", "isLoginId": true},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
@@ -1511,20 +1527,20 @@ func TestUserHandler_UpdateUser_LoginIDSync(t *testing.T) {
|
||||
mockTenant.On("ListManageableTenants", mock.Anything, userID).Return([]domain.Tenant{}, nil).Once()
|
||||
|
||||
// Expect traits to include 'custom_login_ids' synced from 'emp_no'
|
||||
mockKratos.On("UpdateIdentity", mock.Anything, userID, mock.MatchedBy(func(traits map[string]interface{}) bool {
|
||||
mockKratos.On("UpdateIdentity", mock.Anything, userID, mock.MatchedBy(func(traits map[string]any) bool {
|
||||
ids, ok := traits["custom_login_ids"].([]string)
|
||||
return ok && len(ids) > 0 && ids[0] == "E1001"
|
||||
}), mock.Anything).Return(&service.KratosIdentity{
|
||||
ID: userID,
|
||||
Traits: map[string]interface{}{
|
||||
"custom_login_ids": []interface{}{"E1001"},
|
||||
Traits: map[string]any{
|
||||
"custom_login_ids": []any{"E1001"},
|
||||
"email": "user@test.com",
|
||||
},
|
||||
}, nil).Once()
|
||||
|
||||
payload := map[string]interface{}{
|
||||
"metadata": map[string]interface{}{
|
||||
tenantID: map[string]interface{}{
|
||||
payload := map[string]any{
|
||||
"metadata": map[string]any{
|
||||
tenantID: map[string]any{
|
||||
"emp_no": "E1001",
|
||||
},
|
||||
},
|
||||
@@ -1555,12 +1571,12 @@ func TestUserHandler_UpdateUser_LoginIDSync(t *testing.T) {
|
||||
userID := "u-2"
|
||||
mockKratos.On("GetIdentity", mock.Anything, userID).Return(&service.KratosIdentity{
|
||||
ID: userID,
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"email": "user2@test.com",
|
||||
"companyCode": "test-tenant",
|
||||
"tenant_id": tenantID,
|
||||
"id": "old-id",
|
||||
tenantID: map[string]interface{}{
|
||||
tenantID: map[string]any{
|
||||
"emp_no": "E2002",
|
||||
},
|
||||
},
|
||||
@@ -1570,8 +1586,8 @@ func TestUserHandler_UpdateUser_LoginIDSync(t *testing.T) {
|
||||
ID: tenantID,
|
||||
Slug: "test-tenant",
|
||||
Config: domain.JSONMap{
|
||||
"userSchema": []interface{}{
|
||||
map[string]interface{}{"key": "emp_no", "isLoginId": true},
|
||||
"userSchema": []any{
|
||||
map[string]any{"key": "emp_no", "isLoginId": true},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
@@ -1579,8 +1595,8 @@ func TestUserHandler_UpdateUser_LoginIDSync(t *testing.T) {
|
||||
ID: tenantID,
|
||||
Slug: "test-tenant",
|
||||
Config: domain.JSONMap{
|
||||
"userSchema": []interface{}{
|
||||
map[string]interface{}{"key": "emp_no", "isLoginId": true},
|
||||
"userSchema": []any{
|
||||
map[string]any{"key": "emp_no", "isLoginId": true},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
@@ -1588,17 +1604,17 @@ func TestUserHandler_UpdateUser_LoginIDSync(t *testing.T) {
|
||||
mockTenant.On("ListManageableTenants", mock.Anything, userID).Return([]domain.Tenant{}, nil).Once()
|
||||
|
||||
// Even if metadata is empty, it should sync from existing traits
|
||||
mockKratos.On("UpdateIdentity", mock.Anything, userID, mock.MatchedBy(func(traits map[string]interface{}) bool {
|
||||
mockKratos.On("UpdateIdentity", mock.Anything, userID, mock.MatchedBy(func(traits map[string]any) bool {
|
||||
ids, ok := traits["custom_login_ids"].([]string)
|
||||
return ok && len(ids) > 0 && ids[0] == "E2002"
|
||||
}), mock.Anything).Return(&service.KratosIdentity{
|
||||
ID: userID,
|
||||
Traits: map[string]interface{}{
|
||||
"custom_login_ids": []interface{}{"E2002"},
|
||||
Traits: map[string]any{
|
||||
"custom_login_ids": []any{"E2002"},
|
||||
},
|
||||
}, nil).Once()
|
||||
|
||||
payload := map[string]interface{}{
|
||||
payload := map[string]any{
|
||||
"name": "New Name",
|
||||
}
|
||||
body, _ := json.Marshal(payload)
|
||||
@@ -1630,8 +1646,8 @@ func TestUserHandler_UpdateUser_PasswordUsesProvider(t *testing.T) {
|
||||
userID := "u-1"
|
||||
mockKratos.On("GetIdentity", mock.Anything, userID).Return(&service.KratosIdentity{
|
||||
ID: userID,
|
||||
Traits: map[string]interface{}{
|
||||
"custom_login_ids": []interface{}{"dyddus1210"},
|
||||
Traits: map[string]any{
|
||||
"custom_login_ids": []any{"dyddus1210"},
|
||||
"email": "dyddus1210@gmail.com",
|
||||
"companyCode": "test-tenant",
|
||||
"tenant_id": "t-1",
|
||||
@@ -1643,8 +1659,8 @@ func TestUserHandler_UpdateUser_PasswordUsesProvider(t *testing.T) {
|
||||
ID: "t-1",
|
||||
Slug: "test-tenant",
|
||||
Config: domain.JSONMap{
|
||||
"userSchema": []interface{}{
|
||||
map[string]interface{}{"key": "emp_id", "isLoginId": true},
|
||||
"userSchema": []any{
|
||||
map[string]any{"key": "emp_id", "isLoginId": true},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
@@ -1652,27 +1668,27 @@ func TestUserHandler_UpdateUser_PasswordUsesProvider(t *testing.T) {
|
||||
ID: "t-1",
|
||||
Slug: "test-tenant",
|
||||
Config: domain.JSONMap{
|
||||
"userSchema": []interface{}{
|
||||
map[string]interface{}{"key": "emp_id", "isLoginId": true},
|
||||
"userSchema": []any{
|
||||
map[string]any{"key": "emp_id", "isLoginId": true},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
mockTenant.On("ListManageableTenants", mock.Anything, userID).Return([]domain.Tenant{}, nil).Once()
|
||||
|
||||
mockKratos.On("UpdateIdentity", mock.Anything, userID, mock.MatchedBy(func(traits map[string]interface{}) bool {
|
||||
mockKratos.On("UpdateIdentity", mock.Anything, userID, mock.MatchedBy(func(traits map[string]any) bool {
|
||||
ids, ok := traits["custom_login_ids"].([]string)
|
||||
return ok && len(ids) > 0 && ids[0] == "dyddus1210"
|
||||
}), "").Return(&service.KratosIdentity{
|
||||
ID: userID,
|
||||
Traits: map[string]interface{}{
|
||||
"custom_login_ids": []interface{}{"dyddus1210"},
|
||||
Traits: map[string]any{
|
||||
"custom_login_ids": []any{"dyddus1210"},
|
||||
"email": "dyddus1210@gmail.com",
|
||||
},
|
||||
}, nil).Once()
|
||||
|
||||
mockOry.On("UpdateUserPassword", "dyddus1210", "asdfzxcv1234!", (*http.Request)(nil)).Return(nil).Once()
|
||||
|
||||
payload := map[string]interface{}{
|
||||
payload := map[string]any{
|
||||
"password": "asdfzxcv1234!",
|
||||
}
|
||||
body, _ := json.Marshal(payload)
|
||||
@@ -1704,7 +1720,7 @@ func TestUserHandler_UpdateUser_PasswordFallsBackToEmail(t *testing.T) {
|
||||
userID := "u-2"
|
||||
mockKratos.On("GetIdentity", mock.Anything, userID).Return(&service.KratosIdentity{
|
||||
ID: userID,
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"email": "dyddus1210@gmail.com",
|
||||
"companyCode": "test-tenant",
|
||||
},
|
||||
@@ -1716,18 +1732,18 @@ func TestUserHandler_UpdateUser_PasswordFallsBackToEmail(t *testing.T) {
|
||||
}, nil)
|
||||
mockTenant.On("ListManageableTenants", mock.Anything, userID).Return([]domain.Tenant{}, nil).Once()
|
||||
|
||||
mockKratos.On("UpdateIdentity", mock.Anything, userID, mock.MatchedBy(func(traits map[string]interface{}) bool {
|
||||
mockKratos.On("UpdateIdentity", mock.Anything, userID, mock.MatchedBy(func(traits map[string]any) bool {
|
||||
return traits["email"] == "dyddus1210@gmail.com"
|
||||
}), "").Return(&service.KratosIdentity{
|
||||
ID: userID,
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"email": "dyddus1210@gmail.com",
|
||||
},
|
||||
}, nil).Once()
|
||||
|
||||
mockOry.On("UpdateUserPassword", "dyddus1210@gmail.com", "asdfzxcv1234!", (*http.Request)(nil)).Return(nil).Once()
|
||||
|
||||
payload := map[string]interface{}{
|
||||
payload := map[string]any{
|
||||
"password": "asdfzxcv1234!",
|
||||
}
|
||||
body, _ := json.Marshal(payload)
|
||||
@@ -1757,8 +1773,8 @@ func TestUserHandler_CreateUser_LoginIDSync(t *testing.T) {
|
||||
ID: tenantID,
|
||||
Slug: "test-tenant",
|
||||
Config: domain.JSONMap{
|
||||
"userSchema": []interface{}{
|
||||
map[string]interface{}{"key": "emp_no", "label": "Employee No", "isLoginId": true},
|
||||
"userSchema": []any{
|
||||
map[string]any{"key": "emp_no", "label": "Employee No", "isLoginId": true},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
@@ -1766,8 +1782,8 @@ func TestUserHandler_CreateUser_LoginIDSync(t *testing.T) {
|
||||
ID: tenantID,
|
||||
Slug: "test-tenant",
|
||||
Config: domain.JSONMap{
|
||||
"userSchema": []interface{}{
|
||||
map[string]interface{}{"key": "emp_no", "label": "Employee No", "isLoginId": true},
|
||||
"userSchema": []any{
|
||||
map[string]any{"key": "emp_no", "label": "Employee No", "isLoginId": true},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
@@ -1783,8 +1799,8 @@ func TestUserHandler_CreateUser_LoginIDSync(t *testing.T) {
|
||||
// Mock GetIdentity after creation
|
||||
mockKratos.On("GetIdentity", mock.Anything, "u-1").Return(&service.KratosIdentity{
|
||||
ID: "u-1",
|
||||
Traits: map[string]interface{}{
|
||||
"custom_login_ids": []interface{}{"E1001"},
|
||||
Traits: map[string]any{
|
||||
"custom_login_ids": []any{"E1001"},
|
||||
"email": "new@test.com",
|
||||
"companyCode": "test-tenant",
|
||||
},
|
||||
@@ -1793,12 +1809,12 @@ func TestUserHandler_CreateUser_LoginIDSync(t *testing.T) {
|
||||
// Mock ListManageableTenants for mapIdentitySummary
|
||||
mockTenant.On("ListManageableTenants", mock.Anything, "u-1").Return([]domain.Tenant{}, nil).Once()
|
||||
|
||||
payload := map[string]interface{}{
|
||||
payload := map[string]any{
|
||||
"email": "new@test.com",
|
||||
"name": "New User",
|
||||
"tenantSlug": "test-tenant",
|
||||
"metadata": map[string]interface{}{
|
||||
tenantID: map[string]interface{}{
|
||||
"metadata": map[string]any{
|
||||
tenantID: map[string]any{
|
||||
"emp_no": "E1001",
|
||||
},
|
||||
},
|
||||
@@ -1849,25 +1865,25 @@ func TestUserHandler_CreateUser_UsesAdditionalAppointmentAsPrimaryTenant(t *test
|
||||
}), mock.Anything).Return("u-appointment", nil).Once()
|
||||
mockKratos.On("GetIdentity", mock.Anything, "u-appointment").Return(&service.KratosIdentity{
|
||||
ID: "u-appointment",
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"email": "new@samaneng.com",
|
||||
"name": "Appointment User",
|
||||
"companyCode": "saman",
|
||||
"tenant_id": tenantID,
|
||||
"additionalAppointments": []interface{}{
|
||||
map[string]interface{}{"tenantId": tenantID, "tenantSlug": "saman"},
|
||||
"additionalAppointments": []any{
|
||||
map[string]any{"tenantId": tenantID, "tenantSlug": "saman"},
|
||||
},
|
||||
},
|
||||
State: "active",
|
||||
}, nil).Once()
|
||||
|
||||
payload := map[string]interface{}{
|
||||
payload := map[string]any{
|
||||
"email": "new@samaneng.com",
|
||||
"name": "Appointment User",
|
||||
"additionalAppointments": []map[string]interface{}{
|
||||
"additionalAppointments": []map[string]any{
|
||||
{"tenantId": tenantID, "tenantSlug": "saman", "tenantName": "삼안"},
|
||||
},
|
||||
"metadata": map[string]interface{}{
|
||||
"metadata": map[string]any{
|
||||
"userType": "hanmac",
|
||||
},
|
||||
}
|
||||
@@ -1939,7 +1955,7 @@ func TestUserHandler_CreateUser_AutoCreatesPersonalTenantWhenAssignmentMissing(t
|
||||
}), mock.Anything).Return("u-personal", nil).Once()
|
||||
mockKratos.On("GetIdentity", mock.Anything, "u-personal").Return(&service.KratosIdentity{
|
||||
ID: "u-personal",
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"email": "personal-user@example.com",
|
||||
"name": "Personal User",
|
||||
"companyCode": "personal-01970f0d96667548963d2890351f03dd",
|
||||
@@ -1947,7 +1963,7 @@ func TestUserHandler_CreateUser_AutoCreatesPersonalTenantWhenAssignmentMissing(t
|
||||
},
|
||||
State: "active",
|
||||
}, nil).Once()
|
||||
payload := map[string]interface{}{
|
||||
payload := map[string]any{
|
||||
"email": "personal-user@example.com",
|
||||
"name": "Personal User",
|
||||
}
|
||||
@@ -1992,7 +2008,7 @@ func TestUserHandler_CreateUserAcceptsTenantSlugAndRejectsCompanyCode(t *testing
|
||||
mockKratos.On("GetIdentity", mock.Anything, "user-id").Return(&service.KratosIdentity{
|
||||
ID: "user-id",
|
||||
State: "active",
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"email": "user@test.com",
|
||||
"name": "Test User",
|
||||
"tenant_id": "tenant-id",
|
||||
@@ -2029,7 +2045,7 @@ func TestUserHandler_UpdateUserAcceptsTenantSlugAndRejectsCompanyCode(t *testing
|
||||
identity := &service.KratosIdentity{
|
||||
ID: "user-id",
|
||||
State: "active",
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"email": "user@test.com",
|
||||
"name": "Test User",
|
||||
"tenant_id": "old-tenant-id",
|
||||
@@ -2046,13 +2062,13 @@ func TestUserHandler_UpdateUserAcceptsTenantSlugAndRejectsCompanyCode(t *testing
|
||||
Slug: "new-tenant",
|
||||
Config: domain.JSONMap{},
|
||||
}, nil).Once()
|
||||
mockKratos.On("UpdateIdentity", mock.Anything, "user-id", mock.MatchedBy(func(traits map[string]interface{}) bool {
|
||||
mockKratos.On("UpdateIdentity", mock.Anything, "user-id", mock.MatchedBy(func(traits map[string]any) bool {
|
||||
_, hasCompanyCode := traits["companyCode"]
|
||||
return !hasCompanyCode && traits["tenant_id"] == "new-tenant-id"
|
||||
}), "").Return(&service.KratosIdentity{
|
||||
ID: "user-id",
|
||||
State: "active",
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"email": "user@test.com",
|
||||
"name": "Test User",
|
||||
"tenant_id": "new-tenant-id",
|
||||
@@ -2091,7 +2107,7 @@ func TestUserHandler_BulkUpdateUsersAcceptsTenantSlugAndRejectsCompanyCode(t *te
|
||||
mockKratos.On("GetIdentity", mock.Anything, "user-id").Return(&service.KratosIdentity{
|
||||
ID: "user-id",
|
||||
State: "active",
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"email": "user@test.com",
|
||||
"name": "Test User",
|
||||
"tenant_id": "old-tenant-id",
|
||||
@@ -2102,13 +2118,13 @@ func TestUserHandler_BulkUpdateUsersAcceptsTenantSlugAndRejectsCompanyCode(t *te
|
||||
ID: "new-tenant-id",
|
||||
Slug: "new-tenant",
|
||||
}, nil).Once()
|
||||
mockKratos.On("UpdateIdentity", mock.Anything, "user-id", mock.MatchedBy(func(traits map[string]interface{}) bool {
|
||||
mockKratos.On("UpdateIdentity", mock.Anything, "user-id", mock.MatchedBy(func(traits map[string]any) bool {
|
||||
_, hasCompanyCode := traits["companyCode"]
|
||||
return !hasCompanyCode && traits["tenant_id"] == "new-tenant-id"
|
||||
}), "active").Return(&service.KratosIdentity{
|
||||
ID: "user-id",
|
||||
State: "active",
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"email": "user@test.com",
|
||||
"name": "Test User",
|
||||
"tenant_id": "new-tenant-id",
|
||||
@@ -2137,7 +2153,7 @@ func TestUserHandler_MapToLocalUserKeepsRoleAndGradeSeparate(t *testing.T) {
|
||||
identity := service.KratosIdentity{
|
||||
ID: "user-grade-id",
|
||||
State: "active",
|
||||
Traits: map[string]interface{}{
|
||||
Traits: map[string]any{
|
||||
"email": "grade@example.com",
|
||||
"name": "Grade User",
|
||||
"role": domain.RoleUser,
|
||||
|
||||
257
backend/internal/handler/user_handler_uuid_test.go
Normal file
257
backend/internal/handler/user_handler_uuid_test.go
Normal file
@@ -0,0 +1,257 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"baron-sso-backend/internal/domain"
|
||||
"baron-sso-backend/internal/service"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
func TestUserHandler_BulkCreateUsers_UUIDSupport(t *testing.T) {
|
||||
app := fiber.New()
|
||||
mockKratos := new(MockKratosAdmin)
|
||||
mockOry := new(MockOryProvider)
|
||||
mockTenant := new(MockTenantServiceForUser)
|
||||
|
||||
h := &UserHandler{
|
||||
KratosAdmin: mockKratos,
|
||||
OryProvider: mockOry,
|
||||
TenantService: mockTenant,
|
||||
}
|
||||
|
||||
app.Post("/users/bulk", h.BulkCreateUsers)
|
||||
|
||||
t.Run("Success - Provided UUID", func(t *testing.T) {
|
||||
testUuid := "550e8400-e29b-41d4-a716-446655440000"
|
||||
mockTenant.On("GetTenantBySlug", mock.Anything, "test-tenant").Return(&domain.Tenant{
|
||||
ID: "t-1",
|
||||
Slug: "test-tenant",
|
||||
}, nil).Once()
|
||||
|
||||
mockOry.On("GetPasswordPolicy").Return(&domain.PasswordPolicy{MinLength: 8}, nil)
|
||||
|
||||
// 1. Search-first check: Simulate user NOT found by this UUID
|
||||
mockKratos.On("FindIdentityIDByIdentifier", mock.Anything, testUuid).Return("", nil).Once()
|
||||
|
||||
// 2. Create identity
|
||||
mockOry.On("CreateUser", mock.MatchedBy(func(user *domain.BrokerUser) bool {
|
||||
return user.ID == testUuid && user.Email == "uuid@test.com"
|
||||
}), mock.Anything).Return(testUuid, nil).Once()
|
||||
|
||||
payload := map[string]any{
|
||||
"users": []map[string]any{
|
||||
{
|
||||
"email": "uuid@test.com",
|
||||
"name": "UUID User",
|
||||
"tenantSlug": "test-tenant",
|
||||
"id": testUuid,
|
||||
},
|
||||
},
|
||||
}
|
||||
body, _ := json.Marshal(payload)
|
||||
req := httptest.NewRequest("POST", "/users/bulk", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, _ := app.Test(req)
|
||||
assert.Equal(t, 200, resp.StatusCode)
|
||||
|
||||
var result struct {
|
||||
Results []bulkUserResult `json:"results"`
|
||||
}
|
||||
json.NewDecoder(resp.Body).Decode(&result)
|
||||
assert.Len(t, result.Results, 1)
|
||||
assert.True(t, result.Results[0].Success)
|
||||
assert.Equal(t, testUuid, result.Results[0].UserID)
|
||||
})
|
||||
|
||||
t.Run("Success - Provided UUID Already Exists (Idempotency)", func(t *testing.T) {
|
||||
testUuid := "550e8400-e29b-41d4-a716-446655440005"
|
||||
mockTenant.On("GetTenantBySlug", mock.Anything, "test-tenant").Return(&domain.Tenant{
|
||||
ID: "t-1",
|
||||
Slug: "test-tenant",
|
||||
}, nil).Once()
|
||||
|
||||
mockOry.On("GetPasswordPolicy").Return(&domain.PasswordPolicy{MinLength: 8}, nil)
|
||||
|
||||
// 1. Search-first check: Simulate user FOUND by this UUID
|
||||
mockKratos.On("FindIdentityIDByIdentifier", mock.Anything, testUuid).Return(testUuid, nil).Once()
|
||||
|
||||
// 2. Fetch existing identity for field comparison
|
||||
mockKratos.On("GetIdentity", mock.Anything, testUuid).Return(&service.KratosIdentity{
|
||||
ID: testUuid,
|
||||
Traits: map[string]any{
|
||||
"email": "existing@test.com",
|
||||
"name": "Old Name",
|
||||
},
|
||||
}, nil).Once()
|
||||
|
||||
payload := map[string]any{
|
||||
"users": []map[string]any{
|
||||
{
|
||||
"email": "existing@test.com",
|
||||
"name": "Existing User",
|
||||
"tenantSlug": "test-tenant",
|
||||
"id": testUuid,
|
||||
},
|
||||
},
|
||||
}
|
||||
body, _ := json.Marshal(payload)
|
||||
req := httptest.NewRequest("POST", "/users/bulk", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, _ := app.Test(req)
|
||||
assert.Equal(t, 200, resp.StatusCode)
|
||||
|
||||
var result struct {
|
||||
Results []bulkUserResult `json:"results"`
|
||||
}
|
||||
json.NewDecoder(resp.Body).Decode(&result)
|
||||
assert.Len(t, result.Results, 1)
|
||||
assert.True(t, result.Results[0].Success)
|
||||
assert.Equal(t, testUuid, result.Results[0].UserID)
|
||||
assert.Equal(t, "updated", result.Results[0].Status)
|
||||
// Should have "Name" in modified fields since we changed from "Old Name" to "Existing User"
|
||||
assert.Contains(t, result.Results[0].ModifiedFields, "Name")
|
||||
})
|
||||
|
||||
t.Run("Fail - Duplicate UUID Conflict", func(t *testing.T) {
|
||||
testUuid := "550e8400-e29b-41d4-a716-446655440001"
|
||||
mockTenant.On("GetTenantBySlug", mock.Anything, "test-tenant").Return(&domain.Tenant{
|
||||
ID: "t-1",
|
||||
Slug: "test-tenant",
|
||||
}, nil).Once()
|
||||
|
||||
mockOry.On("GetPasswordPolicy").Return(&domain.PasswordPolicy{MinLength: 8}, nil)
|
||||
|
||||
// 1. Search-first check: Simulate NOT found by this UUID (initial check)
|
||||
mockKratos.On("FindIdentityIDByIdentifier", mock.Anything, testUuid).Return("", nil).Once()
|
||||
|
||||
// 2. Create identity: Simulate Ory returning a 409 conflict for the UUID
|
||||
conflictErr := fmt.Errorf("ory provider: identity already exists for uuid=%s", testUuid)
|
||||
mockOry.On("CreateUser", mock.MatchedBy(func(user *domain.BrokerUser) bool {
|
||||
return user.ID == testUuid
|
||||
}), mock.Anything).Return("", conflictErr).Once()
|
||||
|
||||
// 3. Conflict double-check: Search by EMAIL to see if it's the same person
|
||||
// If NOT found by email, it means it's a different person using this UUID
|
||||
mockKratos.On("FindIdentityIDByIdentifier", mock.Anything, "conflict@test.com").Return("", nil).Once()
|
||||
|
||||
payload := map[string]any{
|
||||
"users": []map[string]any{
|
||||
{
|
||||
"email": "conflict@test.com",
|
||||
"name": "Conflict User",
|
||||
"tenantSlug": "test-tenant",
|
||||
"uuid": testUuid,
|
||||
},
|
||||
},
|
||||
}
|
||||
body, _ := json.Marshal(payload)
|
||||
req := httptest.NewRequest("POST", "/users/bulk", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, _ := app.Test(req)
|
||||
assert.Equal(t, 200, resp.StatusCode)
|
||||
|
||||
var result struct {
|
||||
Results []bulkUserResult `json:"results"`
|
||||
}
|
||||
json.NewDecoder(resp.Body).Decode(&result)
|
||||
assert.Len(t, result.Results, 1)
|
||||
assert.False(t, result.Results[0].Success)
|
||||
assert.Contains(t, result.Results[0].Message, "Conflict: UUID already exists")
|
||||
})
|
||||
|
||||
t.Run("Fail - Invalid UUID Format", func(t *testing.T) {
|
||||
invalidUuid := "not-a-uuid"
|
||||
mockTenant.On("GetTenantBySlug", mock.Anything, "test-tenant").Return(&domain.Tenant{
|
||||
ID: "t-1",
|
||||
Slug: "test-tenant",
|
||||
}, nil).Once()
|
||||
|
||||
mockOry.On("GetPasswordPolicy").Return(&domain.PasswordPolicy{MinLength: 8}, nil)
|
||||
|
||||
// 1. Search-first check (even for invalid format, it currently tries to search)
|
||||
mockKratos.On("FindIdentityIDByIdentifier", mock.Anything, invalidUuid).Return("", nil).Once()
|
||||
|
||||
payload := map[string]any{
|
||||
"users": []map[string]any{
|
||||
{
|
||||
"email": "invalid@test.com",
|
||||
"name": "Invalid User",
|
||||
"tenantSlug": "test-tenant",
|
||||
"id": invalidUuid,
|
||||
},
|
||||
},
|
||||
}
|
||||
body, _ := json.Marshal(payload)
|
||||
req := httptest.NewRequest("POST", "/users/bulk", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, _ := app.Test(req)
|
||||
assert.Equal(t, 200, resp.StatusCode)
|
||||
|
||||
var result struct {
|
||||
Results []bulkUserResult `json:"results"`
|
||||
}
|
||||
json.NewDecoder(resp.Body).Decode(&result)
|
||||
assert.Len(t, result.Results, 1)
|
||||
assert.False(t, result.Results[0].Success)
|
||||
assert.Contains(t, result.Results[0].Message, "invalid UUID format")
|
||||
})
|
||||
|
||||
t.Run("Success - Import after Delete (Visibility Check)", func(t *testing.T) {
|
||||
// This test is to ensure that if a user is deleted and then re-imported with the same UUID,
|
||||
// the process succeeds and ideally would result in a visible user.
|
||||
// NOTE: In this unit test we mock the Repository, so we can't fully test DB behavior,
|
||||
// but we can verify the Handler logic flow.
|
||||
|
||||
testUuid := "550e8400-e29b-41d4-a716-446655440007"
|
||||
mockTenant.On("GetTenantBySlug", mock.Anything, "test-tenant").Return(&domain.Tenant{
|
||||
ID: "t-1",
|
||||
Slug: "test-tenant",
|
||||
}, nil).Once()
|
||||
|
||||
mockOry.On("GetPasswordPolicy").Return(&domain.PasswordPolicy{MinLength: 8}, nil)
|
||||
|
||||
// 1. Search-first: Simulate NOT found (it was deleted from Kratos)
|
||||
mockKratos.On("FindIdentityIDByIdentifier", mock.Anything, testUuid).Return("", nil).Once()
|
||||
|
||||
// 2. Create identity: Succeeds and returns a NEW Kratos ID
|
||||
newKratosId := "new-kratos-id-after-delete"
|
||||
mockOry.On("CreateUser", mock.MatchedBy(func(user *domain.BrokerUser) bool {
|
||||
return user.ID == testUuid
|
||||
}), mock.Anything).Return(newKratosId, nil).Once()
|
||||
|
||||
payload := map[string]any{
|
||||
"users": []map[string]any{
|
||||
{
|
||||
"email": "reimport@test.com",
|
||||
"name": "Re-import User",
|
||||
"tenantSlug": "test-tenant",
|
||||
"id": testUuid,
|
||||
},
|
||||
},
|
||||
}
|
||||
body, _ := json.Marshal(payload)
|
||||
req := httptest.NewRequest("POST", "/users/bulk", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, _ := app.Test(req)
|
||||
assert.Equal(t, 200, resp.StatusCode)
|
||||
|
||||
var result struct {
|
||||
Results []bulkUserResult `json:"results"`
|
||||
}
|
||||
json.NewDecoder(resp.Body).Decode(&result)
|
||||
assert.True(t, result.Results[0].Success)
|
||||
assert.Equal(t, testUuid, result.Results[0].UserID)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user