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

646 lines
14 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 👥 Kullanıcı Yönetimi (Admin) API Dokümantasyonu
## 🔐 Default Admin Kullanıcı
Uygulama ilk kez çalıştırıldığında otomatik olarak bir admin kullanıcı oluşturulur:
```
Email: admin@gauth.local
Password: Admin@123
Role: admin
```
⚠️ **Güvenlik Uyarısı:** İlk giriş sonrası bu şifreyi mutlaka değiştirin!
---
## 🚀 Admin ile Giriş Yapma
```bash
curl -X POST http://localhost:8080/v1/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "admin@gauth.local",
"password": "Admin@123"
}'
```
**Response:**
```json
{
"access_token": "eyJhbGciOiJIUz...",
"refresh_token": "eyJhbGciOiJIUz...",
"user": {
"id": "uuid",
"email": "admin@gauth.local",
"user_name": "admin",
"roles": [
{
"name": "admin",
"description": "Default admin role"
}
]
}
}
```
**Not:** Gelen `access_token`'ı tüm admin işlemlerde kullanacaksınız.
---
## 📍 User Management Endpoint'leri
Base URL: `/v1/admin/users`
**Tüm endpoint'ler için gereklidir:**
- ✅ Authentication (Bearer token)
- ✅ Admin rolü
---
### 1. Tüm Kullanıcıları Listele
```
GET /v1/admin/users
Authorization: Bearer {admin_token}
```
**Query Parameters:**
- `page` (optional): Sayfa numarası (default: 1)
- `limit` (optional): Sayfa başına kayıt (default: 10, max: 100)
**Response (200):**
```json
{
"users": [
{
"id": "uuid",
"email": "user@example.com",
"user_name": "username",
"email_verified": true,
"created_at": "2026-02-04T00:00:00Z",
"roles": [
{
"id": "uuid",
"name": "user",
"description": "Default user role"
}
],
"social_accounts": []
}
],
"pagination": {
"page": 1,
"limit": 10,
"total": 25,
"totalPages": 3
}
}
```
**cURL Örneği:**
```bash
TOKEN="your_admin_token_here"
curl -X GET "http://localhost:8080/v1/admin/users?page=1&limit=10" \
-H "Authorization: Bearer $TOKEN"
```
---
### 2. Kullanıcı Ara
```
GET /v1/admin/users/search?q={search_query}
Authorization: Bearer {admin_token}
```
**Query Parameters:**
- `q` (required): Arama terimi (email veya username'de arar)
- `page` (optional): Sayfa numarası
- `limit` (optional): Sayfa başına kayıt
**Response (200):**
```json
{
"users": [...],
"pagination": {
"page": 1,
"limit": 10,
"total": 5,
"totalPages": 1
}
}
```
**cURL Örneği:**
```bash
curl -X GET "http://localhost:8080/v1/admin/users/search?q=john&page=1&limit=10" \
-H "Authorization: Bearer $TOKEN"
```
---
### 3. Kullanıcı Detayı
```
GET /v1/admin/users/{user_id}
Authorization: Bearer {admin_token}
```
**Response (200):**
```json
{
"id": "uuid",
"email": "user@example.com",
"user_name": "username",
"email_verified": true,
"created_at": "2026-02-04T00:00:00Z",
"roles": [
{
"id": "uuid",
"name": "user",
"permissions": [
{
"name": "user:read",
"description": "Can read user data"
}
]
}
],
"social_accounts": [
{
"provider": "google",
"provider_user_id": "123456"
}
]
}
```
**cURL Örneği:**
```bash
curl -X GET "http://localhost:8080/v1/admin/users/UUID_HERE" \
-H "Authorization: Bearer $TOKEN"
```
---
### 4. Yeni Kullanıcı Oluştur (Admin Oluşturma)
```
POST /v1/admin/users
Authorization: Bearer {admin_token}
Content-Type: application/json
```
**Request Body:**
```json
{
"email": "newadmin@example.com",
"password": "SecurePass123!",
"user_name": "newadmin",
"email_verified": true,
"roles": ["admin"]
}
```
**Field Açıklamaları:**
- `email` (required): Email adresi
- `password` (required): Şifre (min 6 karakter)
- `user_name` (required): Kullanıcı adı
- `email_verified` (optional): Email doğrulanmış mı? (default: false)
- `roles` (optional): Roller dizisi (default: ["user"])
- Geçerli roller: `"admin"`, `"user"`
**Response (201):**
```json
{
"id": "uuid",
"email": "newadmin@example.com",
"user_name": "newadmin",
"email_verified": true,
"roles": [
{
"id": "uuid",
"name": "admin",
"description": "Default admin role"
}
],
"created_at": "2026-02-04T00:00:00Z"
}
```
**cURL Örneği - Yeni Admin Oluşturma:**
```bash
curl -X POST http://localhost:8080/v1/admin/users \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"email": "yeni-admin@example.com",
"password": "GuvenlıSifre123!",
"user_name": "yeniadmin",
"email_verified": true,
"roles": ["admin"]
}'
```
**cURL Örneği - Normal Kullanıcı Oluşturma:**
```bash
curl -X POST http://localhost:8080/v1/admin/users \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"password": "UserPass123!",
"user_name": "normaluser",
"email_verified": false,
"roles": ["user"]
}'
```
---
### 5. Kullanıcı Güncelle
```
PUT /v1/admin/users/{user_id}
Authorization: Bearer {admin_token}
Content-Type: application/json
```
**Request Body (tüm alanlar optional):**
```json
{
"email": "newemail@example.com",
"password": "NewPassword123!",
"user_name": "newusername",
"email_verified": true,
"roles": ["admin", "user"]
}
```
**Response (200):**
```json
{
"message": "User updated successfully",
"user": {
"id": "uuid",
"email": "newemail@example.com",
"username": "newusername",
"email_verified": true,
"roles": [
{"name": "admin"},
{"name": "user"}
],
"updated_at": "2026-02-04T..."
}
}
```
**cURL Örneği:**
```bash
# Sadece şifre değiştir
curl -X PUT "http://localhost:8080/v1/admin/users/UUID_HERE" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"password": "YeniSifre123!"
}'
# Email doğrulaması aktif et
curl -X PUT "http://localhost:8080/v1/admin/users/UUID_HERE" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"email_verified": true
}'
# Kullanıcıyı admin yap (rol güncelleme)
curl -X PUT "http://localhost:8080/v1/admin/users/UUID_HERE" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"roles": ["admin"]
}'
# Tüm bilgileri güncelle
curl -X PUT "http://localhost:8080/v1/admin/users/UUID_HERE" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"email": "beyhan@beyhan.dev",
"user_name": "Beyhan Oğur",
"roles": ["admin"],
"email_verified": true
}'
```
---
### 6. Kullanıcıya Roller Ata
```
POST /v1/admin/users/{user_id}/roles
Authorization: Bearer {admin_token}
Content-Type: application/json
```
**Request Body:**
```json
{
"roles": ["admin", "user"]
}
```
**Response (200):**
```json
{
"message": "Roles assigned successfully"
}
```
**cURL Örneği - Kullanıcıyı Admin Yap:**
```bash
curl -X POST "http://localhost:8080/v1/admin/users/UUID_HERE/roles" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"roles": ["admin"]
}'
```
---
### 7. Kullanıcıdan Rol Kaldır
```
DELETE /v1/admin/users/{user_id}/roles/{role_name}
Authorization: Bearer {admin_token}
```
**Response (200):**
```json
{
"message": "Role removed successfully"
}
```
**cURL Örneği - Admin Rolünü Kaldır:**
```bash
curl -X DELETE "http://localhost:8080/v1/admin/users/UUID_HERE/roles/admin" \
-H "Authorization: Bearer $TOKEN"
```
---
### 8. Kullanıcı Sil
```
DELETE /v1/admin/users/{user_id}
Authorization: Bearer {admin_token}
```
**Response (200):**
```json
{
"message": "User deleted successfully"
}
```
**Not:** Kendi hesabınızı silemezsiniz!
**cURL Örneği:**
```bash
curl -X DELETE "http://localhost:8080/v1/admin/users/UUID_HERE" \
-H "Authorization: Bearer $TOKEN"
```
---
## 🔒 Admin Middleware
Tüm `/v1/admin/*` ve `/v1/settings/*` endpoint'leri için:
1.`AuthMiddleware` - Token kontrolü
2.`AdminMiddleware` - Admin rol kontrolü
Eğer kullanıcı admin rolüne sahip değilse:
```json
{
"error": "Admin access required"
}
```
---
## 📊 Kullanım Senaryoları
### Senaryo 1: Yeni Admin Kullanıcı Oluşturma
```bash
# 1. Admin olarak giriş yap
curl -X POST http://localhost:8080/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"admin@gauth.local","password":"Admin@123"}'
# Response'dan access_token al
TOKEN="eyJhbGciOiJIUz..."
# 2. Yeni admin kullanıcı oluştur
curl -X POST http://localhost:8080/v1/admin/users \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"email": "ikinci-admin@example.com",
"password": "Admin@456",
"user_name": "admin2",
"email_verified": true,
"roles": ["admin"]
}'
# 3. Oluşturulan kullanıcı ile test et
curl -X POST http://localhost:8080/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"ikinci-admin@example.com","password":"Admin@456"}'
```
### Senaryo 2: Normal Kullanıcıyı Admin Yap
```bash
# 1. Kullanıcıyı bul
curl -X GET "http://localhost:8080/v1/admin/users/search?q=user@example.com" \
-H "Authorization: Bearer $TOKEN"
# Response'dan user ID'yi al
USER_ID="uuid-here"
# 2. Admin rolü ata
curl -X POST "http://localhost:8080/v1/admin/users/$USER_ID/roles" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"roles": ["admin", "user"]}'
```
### Senaryo 3: Kullanıcı Şifresini Sıfırla
```bash
curl -X PUT "http://localhost:8080/v1/admin/users/$USER_ID" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"password": "YeniGeçiciSifre123!"
}'
```
---
## 💻 Frontend Entegrasyonu
### JavaScript Örneği
```javascript
const API_BASE = 'http://localhost:8080/v1/admin';
const token = localStorage.getItem('access_token');
// User Management Class
class UserManagement {
constructor(token) {
this.token = token;
this.headers = {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
};
}
// Tüm kullanıcıları getir
async getAllUsers(page = 1, limit = 10) {
const res = await fetch(`${API_BASE}/users?page=${page}&limit=${limit}`, {
headers: { 'Authorization': `Bearer ${this.token}` }
});
return res.json();
}
// Kullanıcı ara
async searchUsers(query, page = 1) {
const res = await fetch(`${API_BASE}/users/search?q=${query}&page=${page}`, {
headers: { 'Authorization': `Bearer ${this.token}` }
});
return res.json();
}
// Yeni admin kullanıcı oluştur
async createAdmin(email, password, username) {
const res = await fetch(`${API_BASE}/users`, {
method: 'POST',
headers: this.headers,
body: JSON.stringify({
email,
password,
user_name: username,
email_verified: true,
roles: ['admin']
})
});
return res.json();
}
// Kullanıcıyı admin yap
async makeAdmin(userId) {
const res = await fetch(`${API_BASE}/users/${userId}/roles`, {
method: 'POST',
headers: this.headers,
body: JSON.stringify({
roles: ['admin']
})
});
return res.json();
}
// Kullanıcı sil
async deleteUser(userId) {
const res = await fetch(`${API_BASE}/users/${userId}`, {
method: 'DELETE',
headers: { 'Authorization': `Bearer ${this.token}` }
});
return res.json();
}
// Şifre sıfırla
async resetPassword(userId, newPassword) {
const res = await fetch(`${API_BASE}/users/${userId}`, {
method: 'PUT',
headers: this.headers,
body: JSON.stringify({ password: newPassword })
});
return res.json();
}
}
// Kullanım
const userMgmt = new UserManagement(token);
// Tüm kullanıcıları listele
userMgmt.getAllUsers(1, 10).then(data => {
console.log('Users:', data.users);
console.log('Total:', data.pagination.total);
});
// Yeni admin oluştur
userMgmt.createAdmin('yeni@admin.com', 'Secure123!', 'yeniadmin')
.then(user => console.log('Admin created:', user));
// Kullanıcı ara
userMgmt.searchUsers('john').then(data => {
console.log('Search results:', data.users);
});
```
---
## 🎯 Endpoint Özeti
| Method | Endpoint | Açıklama |
|--------|----------|----------|
| GET | `/v1/admin/users` | Tüm kullanıcıları listele |
| GET | `/v1/admin/users/search` | Kullanıcı ara |
| GET | `/v1/admin/users/:id` | Kullanıcı detayı |
| POST | `/v1/admin/users` | Yeni kullanıcı/admin oluştur |
| PUT | `/v1/admin/users/:id` | Kullanıcı güncelle |
| DELETE | `/v1/admin/users/:id` | Kullanıcı sil |
| POST | `/v1/admin/users/:id/roles` | Rol ata |
| DELETE | `/v1/admin/users/:id/roles/:role` | Rol kaldır |
**Toplam:** 8 endpoint
---
## ⚠️ Önemli Notlar
1. **Default Admin Şifresi**: İlk giriş sonrası mutlaka değiştirin!
2. **Kendi Hesabınızı Silemezsiniz**: Sistem bunu engelleyecektir
3. **Pagination**: Max limit 100, default 10
4. **Search**: Email ve username alanlarında case-insensitive arama yapar
5. **Roles**: Sadece "admin" ve "user" rolleri vardır
6. **Email Verified**: Admin oluştururken `true` yapın ki direkt giriş yapabilsin
---
## 🎊 Başarıyla Tamamlandı!
Artık:
- ✅ Default admin kullanıcısı var
- ✅ Yeni admin kullanıcıları oluşturabilirsiniz
- ✅ Kullanıcıları yönetebilirsiniz
- ✅ Rolleri atayabilirsiniz
- ✅ Frontend'den kontrol edebilirsiniz
**İlk adım:**
```bash
# Admin ile giriş yap
curl -X POST http://localhost:8080/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"admin@gauth.local","password":"Admin@123"}'
```
**İyi yönetimler! 👥**