Files
AuthCentral/ROLE_UPDATE_FIX.md
Beyhan Oğur 8b1fbdee99 first commit
2026-04-26 21:37:58 +03:00

8.0 KiB
Raw Blame History

Rol Güncelleme Sorunu Çözüldü!

🐛 Sorun

PUT /v1/admin/users/54687716-1aed-41ff-aa13-bb05dd7f34e7

Request:
{
  "email": "beyhan@beyhan.dev",
  "user_name": "Beyhan Oğur",
  "roles": ["admin"],
  "email_verified": true
}

Sonuç:
✅ Email güncellendi
✅ Username güncellendi  
✅ email_verified güncellendi
❌ Roles güncellenmedi

🔍 Kök Neden

UpdateUser handler'ında roles field'ı input struct'ında yoktu:

// ❌ Önce
var input struct {
    Email         *string `json:"email"`
    Password      *string `json:"password"`
    UserName      *string `json:"user_name"`
    EmailVerified *bool   `json:"email_verified"`
    // roles yok!
}

Gelen JSON'daki roles field'ı parse edilmiyordu.


Çözüm

1. Input Struct'ına Roles Eklendi

// ✅ Sonra
var input struct {
    Email         *string  `json:"email"`
    Password      *string  `json:"password"`
    UserName      *string  `json:"user_name"`
    EmailVerified *bool    `json:"email_verified"`
    Roles         []string `json:"roles"` // ✅ Eklendi
}

2. Rol Güncelleme Mantığı Eklendi

// Update basic user fields
if err := h.userService.UpdateUser(userID, updates); err != nil {
    c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update user"})
    return
}

// ✅ Update roles if provided
if input.Roles != nil && len(input.Roles) > 0 {
    if err := h.userService.AssignRoles(userID, input.Roles); err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update roles: " + err.Error()})
        return
    }
}

// Get updated user to return (with roles)
user, err := h.userService.GetUserByID(userID)
// ...

🎯 Şimdi Nasıl Çalışıyor

1. Sadece Rol Güncelleme

curl -X PUT http://localhost:8080/v1/admin/users/54687716-1aed-41ff-aa13-bb05dd7f34e7 \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "roles": ["admin"]
  }'

Response:

{
  "message": "User updated successfully",
  "user": {
    "id": "54687716-1aed-41ff-aa13-bb05dd7f34e7",
    "email": "beyhan@beyhan.dev",
    "username": "Beyhan Oğur",
    "roles": [
      {
        "id": "role-uuid",
        "name": "admin",
        "description": "Default admin role"
      }
    ]
  }
}

2. Email + Username + Rol Birlikte

curl -X PUT http://localhost:8080/v1/admin/users/54687716-1aed-41ff-aa13-bb05dd7f34e7 \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "beyhan@beyhan.dev",
    "user_name": "Beyhan Oğur",
    "roles": ["admin"],
    "email_verified": true
  }'

Artık Tümü Güncelleniyor:

  • Email
  • Username
  • Roles (admin)
  • Email verified

3. Birden Fazla Rol

curl -X PUT http://localhost:8080/v1/admin/users/54687716-1aed-41ff-aa13-bb05dd7f34e7 \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "roles": ["admin", "user"]
  }'

📊 Özellikler

Tüm Alanlar Tek İstekle Güncellenebilir

Field Type Örnek
email string "beyhan@beyhan.dev"
user_name string "Beyhan Oğur"
password string "NewPass123!"
email_verified boolean true
roles string[] ["admin"] veya ["admin", "user"]

Partial Update Destekleniyor

# Sadece rol
{"roles": ["admin"]}

# Sadece email
{"email": "new@example.com"}

# Rol + Email
{"email": "new@example.com", "roles": ["admin"]}

# Hepsi
{
  "email": "new@example.com",
  "user_name": "newname",
  "roles": ["admin"],
  "email_verified": true
}

Rol Değiştirme

# User'dan Admin'e
{"roles": ["admin"]}

# Admin'den User'a
{"roles": ["user"]}

# Her ikisi de
{"roles": ["admin", "user"]}

# Rolü kaldırma (boş liste)
{"roles": []}

🧪 Test Senaryoları

Test 1: Normal Kullanıcıyı Admin Yap

# 1. Kullanıcıyı bul
curl -X GET "http://localhost:8080/v1/admin/users/search?q=user@example.com" \
  -H "Authorization: Bearer $TOKEN"

# 2. Kullanıcıyı admin yap
USER_ID="user-uuid-here"

curl -X PUT "http://localhost:8080/v1/admin/users/$USER_ID" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "roles": ["admin"]
  }'

# 3. Doğrula
curl -X GET "http://localhost:8080/v1/admin/users/$USER_ID" \
  -H "Authorization: Bearer $TOKEN"

Test 2: Admin'i Normal Kullanıcı Yap

curl -X PUT "http://localhost:8080/v1/admin/users/$USER_ID" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "roles": ["user"]
  }'

Test 3: Tüm Bilgileri Birlikte Güncelle

curl -X PUT "http://localhost:8080/v1/admin/users/$USER_ID" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "tamamen-yeni@example.com",
    "user_name": "Yeni İsim",
    "password": "YeniSifre123!",
    "roles": ["admin"],
    "email_verified": true
  }'

💻 JavaScript Örneği

async function updateUserWithRoles(userId, updates) {
  const token = localStorage.getItem('admin_token');
  
  const response = await fetch(`http://localhost:8080/v1/admin/users/${userId}`, {
    method: 'PUT',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(updates)
  });
  
  const result = await response.json();
  
  if (response.ok) {
    console.log('✅ Güncelleme başarılı:', result.message);
    console.log('📊 Güncellenmiş kullanıcı:', result.user);
    console.log('🎭 Yeni roller:', result.user.roles);
    return result.user;
  } else {
    console.error('❌ Hata:', result.error);
    throw new Error(result.error);
  }
}

// Kullanım Örnekleri

// 1. Kullanıcıyı admin yap
await updateUserWithRoles('54687716-1aed-41ff-aa13-bb05dd7f34e7', {
  roles: ['admin']
});

// 2. Email + rol güncelle
await updateUserWithRoles('54687716-1aed-41ff-aa13-bb05dd7f34e7', {
  email: 'beyhan@beyhan.dev',
  user_name: 'Beyhan Oğur',
  roles: ['admin'],
  email_verified: true
});

// 3. Birden fazla rol ata
await updateUserWithRoles('54687716-1aed-41ff-aa13-bb05dd7f34e7', {
  roles: ['admin', 'user']
});

📁 Güncellenen Dosyalar

  1. api/handlers/user_management_handler.go

    • Input struct'a Roles []string eklendi
    • Rol güncelleme mantığı eklendi
    • AssignRoles service çağrısı eklendi
  2. USER_UPDATE_GUIDE.md

    • Roles field dokümante edildi
    • Yeni örnekler eklendi
  3. USER_MANAGEMENT_API.md

    • PUT endpoint güncellendi
    • Rol güncelleme örnekleri eklendi

🎊 Artık Çalışıyor!

Önce

PUT /v1/admin/users/:id
{
  "email": "new@example.com",
  "roles": ["admin"]  # ❌ Güncellenmiyordu
}

Şimdi

PUT /v1/admin/users/:id
{
  "email": "new@example.com",
  "roles": ["admin"]  # ✅ Güncelleniyor!
}

Response:
{
  "message": "User updated successfully",
  "user": {
    "email": "new@example.com",
    "roles": [{"name": "admin"}]  # ✅ Güncellenmiş!
  }
}

🚀 Hemen Deneyin

# 1. Admin giriş
curl -X POST http://localhost:8080/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"admin@gauth.local","password":"Admin@123"}'

# Token'ı kaydet
TOKEN="your-token-here"

# 2. Kullanıcı güncelle (rol dahil)
curl -X PUT http://localhost:8080/v1/admin/users/54687716-1aed-41ff-aa13-bb05dd7f34e7 \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "beyhan@beyhan.dev",
    "user_name": "Beyhan Oğur",
    "roles": ["admin"],
    "email_verified": true
  }'

# 3. Response'da tüm güncellemeleri göreceksiniz! ✅

Sorun Tamamen Çözüldü!

Artık tek bir PUT isteği ile:

  • Email güncelleyebilirsiniz
  • Username değiştirebilirsiniz
  • Şifre sıfırlayabilirsiniz
  • Email doğrulaması aktif edebilirsiniz
  • Rolleri güncelleyebilirsiniz 🎉

Roller artık tam çalışıyor! 🎊