Files
atahango/belgeler/USER_UPDATE_GUIDE.md
Beyhan Oğur bbbf76b184 first commit
2026-04-26 21:35:24 +03:00

9.3 KiB
Raw Permalink Blame History

🔧 Kullanıcı Güncelleme API Rehberi

PUT /v1/admin/users/:id

Kullanıcı bilgilerini güncelleme endpoint'i (Sadece admin).


📋 Endpoint Detayları

Method: PUT
Path: /v1/admin/users/{user_id}
Auth: Required (Admin role)
Content-Type: application/json

🔐 Authentication

Bu endpoint admin rolü gerektirir:

Authorization: Bearer {admin_access_token}

📥 Request Body

Tüm alanlar optional'dir. Sadece güncellemek istediğiniz alanları gönderin.

{
  "email": "newemail@example.com",
  "user_name": "newusername",
  "password": "NewPassword123!",
  "email_verified": true,
  "roles": ["admin", "user"]
}

Field Açıklamaları

Field Type Required ıklama
email string Yeni email adresi
user_name string Yeni kullanıcı adı
password string Yeni şifre (otomatik hash'lenir)
email_verified boolean Email doğrulama durumu
roles string[] Kullanıcı rolleri (["admin"], ["user"], ["admin","user"])

📤 Response

Success (200 OK)

{
  "message": "User updated successfully",
  "user": {
    "id": "54687716-1aed-41ff-aa13-bb05dd7f34e7",
    "email": "newemail@example.com",
    "username": "newusername",
    "email_verified": true,
    "created_at": "2026-02-04T00:00:00Z",
    "updated_at": "2026-02-04T02:45:00Z",
    "roles": [
      {
        "id": "role-uuid",
        "name": "user",
        "description": "Default user role"
      }
    ],
    "social_accounts": []
  }
}

Error Responses

400 Bad Request

{
  "error": "invalid input format"
}

401 Unauthorized

{
  "error": "Unauthorized"
}

403 Forbidden

{
  "error": "Admin access required"
}

404 Not Found

{
  "error": "User not found"
}

500 Internal Server Error

{
  "error": "Failed to update user"
}

🧪 Kullanım Örnekleri

1. Sadece Email Güncelleme

curl -X PUT http://localhost:8080/v1/admin/users/54687716-1aed-41ff-aa13-bb05dd7f34e7 \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "yeni-email@example.com"
  }'

2. Sadece Username Güncelleme

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

3. Şifre Sıfırlama

curl -X PUT http://localhost:8080/v1/admin/users/54687716-1aed-41ff-aa13-bb05dd7f34e7 \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "password": "YeniGüvenliŞifre123!"
  }'

4. Email Doğrulamayı Aktif Etme

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

5. Birden Fazla Alan Güncelleme

curl -X PUT http://localhost:8080/v1/admin/users/54687716-1aed-41ff-aa13-bb05dd7f34e7 \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "yeni@example.com",
    "user_name": "yeniadi",
    "password": "YeniŞifre123!",
    "email_verified": true
  }'

6. Kullanıcıyı Admin Yapma

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

7. Kullanıcıya Birden Fazla Rol Atama

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

8. Tüm Bilgileri Güncelleme (Email, Username, Roles)

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

💻 JavaScript/TypeScript Örneği

Fetch API

async function updateUser(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)
  });
  
  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.error);
  }
  
  return response.json();
}

// Kullanım
try {
  const result = await updateUser('54687716-1aed-41ff-aa13-bb05dd7f34e7', {
    email: 'yeni@example.com',
    user_name: 'yeniadi'
  });
  
  console.log('Güncelleme başarılı:', result.message);
  console.log('Güncellenmiş kullanıcı:', result.user);
} catch (error) {
  console.error('Güncelleme hatası:', error.message);
}

Axios

import axios from 'axios';

const api = axios.create({
  baseURL: 'http://localhost:8080/v1',
  headers: {
    'Content-Type': 'application/json'
  }
});

// Add token interceptor
api.interceptors.request.use(config => {
  const token = localStorage.getItem('admin_token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

// Update user function
async function updateUser(userId, updates) {
  try {
    const { data } = await api.put(`/admin/users/${userId}`, updates);
    return data;
  } catch (error) {
    throw error.response?.data || error;
  }
}

// Kullanım
updateUser('54687716-1aed-41ff-aa13-bb05dd7f34e7', {
  email: 'yeni@example.com',
  email_verified: true
})
.then(result => {
  console.log('Başarılı:', result.message);
  console.log('Kullanıcı:', result.user);
})
.catch(error => {
  console.error('Hata:', error.error);
});

🔄 Complete Flow: Admin ile Kullanıcı Güncelleme

1. Admin Olarak Giriş Yapın

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

Response:

{
  "access_token": "eyJhbGciOiJIUz...",
  "user": {
    "id": "admin-uuid",
    "email": "admin@gauth.local",
    "roles": [{"name": "admin"}]
  }
}

Token'ı kaydedin:

TOKEN="eyJhbGciOiJIUz..."

2. Kullanıcıyı Bulun

# ID biliyorsanız direkt kullanın
# veya arama yapın:
curl -X GET "http://localhost:8080/v1/admin/users/search?q=kullanici@example.com" \
  -H "Authorization: Bearer $TOKEN"

3. Kullanıcıyı Güncelleyin

USER_ID="54687716-1aed-41ff-aa13-bb05dd7f34e7"

curl -X PUT "http://localhost:8080/v1/admin/users/$USER_ID" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "yeni-email@example.com",
    "user_name": "yenikullanici",
    "email_verified": true
  }'

4. Güncellemeyi Doğrulayın

curl -X GET "http://localhost:8080/v1/admin/users/$USER_ID" \
  -H "Authorization: Bearer $TOKEN"

⚠️ Önemli Notlar

  1. Şifre Hash'leme: Şifre otomatik olarak bcrypt ile hash'lenir, plain text göndermeniz yeterli

  2. Partial Update: Sadece göndermek istediğiniz alanları gönderin, diğerleri değişmez

  3. Email Unique Kontrolü: Email zaten başka bir kullanıcıda varsa hata alırsınız

  4. Kendi Hesabınız: Kendi admin hesabınızı da güncelleyebilirsiniz (ama silemezsiniz)

  5. Güncellenen Kullanıcı: Response'da güncellenmiş kullanıcı bilgileri döner


🐛 Sorun Giderme

Güncelleme Yapılmıyor

Sorun: Response "User updated successfully" döndürüyor ama güncelleme yok.

Çözüm: Bu sorun düzeltildi! Şimdi:

  • Kullanıcı önce database'den getiriliyor
  • Updates direkt user instance'ına uygulanıyor
  • Güncellenmiş kullanıcı response'da dönüyor

Token Hatası

Sorun: "Unauthorized" hatası

Çözüm:

  • Token'ın doğru olduğundan emin olun
  • Token'ın expire olmadığını kontrol edin
  • Bearer prefix'ini unutmayın

Admin Rolü Hatası

Sorun: "Admin access required"

Çözüm:

  • Kullanıcınızın admin rolü olduğundan emin olun
  • Rolleri kontrol edin: GET /v1/auth/me

📚 İlgili Endpoint'ler

  • GET /v1/admin/users - Tüm kullanıcıları listele
  • GET /v1/admin/users/:id - Kullanıcı detayı
  • POST /v1/admin/users - Yeni kullanıcı oluştur
  • DELETE /v1/admin/users/:id - Kullanıcı sil
  • POST /v1/admin/users/:id/roles - Rol ata

Özet

Endpoint: PUT /v1/admin/users/{id}

Ne Yapabilirsiniz:

  • Email güncelleme
  • Username değiştirme
  • Şifre sıfırlama
  • Email doğrulama durumu değiştirme
  • Birden fazla alanı aynı anda güncelleme

Response:

  • Başarı mesajı
  • Güncellenmiş kullanıcı bilgileri

Güvenlik:

  • Admin authentication gerekli
  • Şifre otomatik hash'lenir
  • Partial update desteklenir

Artık kullanıcı güncelleme tamamen çalışıyor! 🎉