Files
next-dj/SETUP.md
Beyhan Oğur e881f38e4e first commit
2026-04-26 22:12:36 +03:00

291 lines
7.2 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.
# Authentication Kurulum Kılavuzu
Bu Next.js projesi Django REST API ile entegre çalışan tam özellikli bir authentication sistemi içerir.
## 📋 Özellikler
✅ Email/Password ile kayıt ve giriş
✅ Email aktivasyonu
✅ Social Auth (Google, GitHub)
✅ Token refresh (JWT)
✅ Şifre sıfırlama
✅ Kullanıcı profili
✅ Session yönetimi
## 🚀 Kurulum
### 1. Environment Variables
`.env.local` dosyası oluşturun (`.env.example` dosyasını kopyalayın):
```bash
cp .env.example .env.local
```
`.env.local` dosyasını düzenleyin:
```env
# NextAuth Configuration
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=super-secret-key-change-this
# Django REST API
NEXT_PUBLIC_API_BASE_URL=http://localhost:8000/api/v1
# Social Auth (İsteğe bağlı)
GOOGLE_ID=your-google-client-id
GOOGLE_SECRET=your-google-client-secret
GITHUB_ID=your-github-client-id
GITHUB_SECRET=your-github-client-secret
```
### 2. NextAuth Secret Üretme
```bash
openssl rand -base64 32
```
Bu komutu çalıştırın ve çıkan değeri `NEXTAUTH_SECRET` olarak kullanın.
### 3. Django Backend
Django backend'inizin çalıştığından emin olun:
```bash
# Django projenizde
python manage.py runserver
```
Backend `http://localhost:8000` adresinde çalışıyor olmalı.
## 📱 Sayfalar ve Rotalar
### Authentication Sayfaları
| Sayfa | Route | Açıklama |
|-------|-------|----------|
| Login | `/auth/login` | Giriş sayfası (Email/Password + Social) |
| Register | `/auth/register` | Kayıt sayfası |
| Activate | `/auth/activate/[uid]/[token]` | Email aktivasyon sayfası |
| Resend Activation | `/auth/resend-activation` | Aktivasyon emaili tekrar gönderme |
| Password Reset | `/auth/password-reset` | Şifre sıfırlama talebi |
| Reset Confirm | `/auth/password-reset/confirm/[uid]/[token]` | Şifre sıfırlama onayı |
| Error | `/auth/error` | Auth hata sayfası |
### Korumalı Sayfalar
| Sayfa | Route | Açıklama |
|-------|-------|----------|
| Profile | `/profile` | Kullanıcı profili |
| Dashboard | `/dashboard` | Dashboard (mevcut) |
## 🔐 Social Authentication Kurulumu
### Google OAuth2
1. [Google Cloud Console](https://console.cloud.google.com/) adresine gidin
2. Yeni proje oluşturun veya mevcut projeyi seçin
3. "APIs & Services" > "Credentials" sayfasına gidin
4. "Create Credentials" > "OAuth 2.0 Client ID" seçin
5. Application type: "Web application"
6. Authorized redirect URIs:
- `http://localhost:3000/api/auth/callback/google`
- `https://yourdomain.com/api/auth/callback/google` (production)
7. Client ID ve Client Secret'i kopyalayıp `.env.local` dosyasına ekleyin
### GitHub OAuth2
1. [GitHub Developer Settings](https://github.com/settings/developers) adresine gidin
2. "New OAuth App" butonuna tıklayın
3. Form bilgileri:
- Application name: "Your App Name"
- Homepage URL: `http://localhost:3000`
- Authorization callback URL: `http://localhost:3000/api/auth/callback/github`
4. Client ID ve Client Secret'i `.env.local` dosyasına ekleyin
## 🔄 Authentication Flow
### 1. Kayıt (Register)
```
User fills form → POST /auth/users/ → Email sent → User clicks link →
Account activated → User can login
```
### 2. Login (Email/Password)
```
User enters credentials → POST /auth/jwt/create/ → Tokens received →
Session created → User authenticated
```
### 3. Social Login
```
User clicks Google/GitHub → OAuth flow → Access token received →
POST /auth/social/{provider}/ → Tokens received → Session created
```
### 4. Token Refresh
```
Access token expires → Auto refresh with refresh token →
New tokens received → Session updated
```
## 🛡️ Middleware ve Koruma
### Session Kontrolü
```tsx
import { useSession } from "next-auth/react";
export default function ProtectedPage() {
const { data: session, status } = useSession();
if (status === "loading") {
return <div>Loading...</div>;
}
if (status === "unauthenticated") {
redirect("/auth/login");
}
return <div>Protected content</div>;
}
```
### API İsteği Örnekleri
```tsx
// Get user profile
const response = await fetch(`${API_BASE_URL}/auth/users/me/`, {
headers: {
Authorization: `Bearer ${session.accessToken}`,
},
});
// Update user profile
const response = await fetch(`${API_BASE_URL}/auth/users/me/`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${session.accessToken}`,
},
body: JSON.stringify({
first_name: "Yeni Ad",
last_name: "Yeni Soyad",
}),
});
```
## 📧 Email Testleri (Development)
Django backend'inizde MailPit veya benzeri bir email test aracı kullanıyorsanız:
```
MailPit: http://localhost:8025
```
Gönderilen aktivasyon ve şifre sıfırlama emaillerini burada görebilirsiniz.
## 🧪 Test Senaryoları
### 1. Email/Password Kayıt
```bash
1. /auth/register sayfasına gidin
2. Form bilgilerini doldurun
3. "Kayıt Ol" butonuna tıklayın
4. Email kutunuzu kontrol edin (MailPit: http://localhost:8025)
5. Aktivasyon linkine tıklayın
6. Hesap aktifleştirilir
7. /auth/login sayfasından giriş yapın
```
### 2. Social Login
```bash
1. /auth/login sayfasına gidin
2. "Google ile Giriş Yap" veya "GitHub ile Giriş Yap" butonuna tıklayın
3. OAuth akışını tamamlayın
4. Otomatik olarak dashboard'a yönlendirilirsiniz
```
### 3. Şifre Sıfırlama
```bash
1. /auth/password-reset sayfasına gidin
2. Email adresinizi girin
3. Email kutunuzu kontrol edin
4. Şifre sıfırlama linkine tıklayın
5. Yeni şifrenizi girin
6. Yeni şifre ile giriş yapın
```
## 🐛 Hata Ayıklama
### "Authentication failed" hatası
- Django backend'in çalıştığından emin olun
- API_BASE_URL değerini kontrol edin
- Browser console'da hata mesajlarını kontrol edin
### Social auth çalışmıyor
- Google/GitHub OAuth credentials'ları doğru mu?
- Redirect URI'lar doğru ayarlanmış mı?
- Django backend'de social auth ayarları yapılmış mı?
### Token expired hatası
- Token refresh otomatik çalışmalı
- Refresh token süresi dolmuşsa yeniden login gerekli
- Session süresi: 7 gün (refresh token)
## 📝 TypeScript Types
```typescript
// next-auth.d.ts (mevcut)
interface User {
accessToken?: string;
refreshToken?: string;
expires?: number;
accessTokenExpiry?: number;
}
interface Session {
accessToken?: string;
refreshToken?: string;
expires?: number;
error?: string;
}
```
## 🔗 Faydalı Linkler
- [NextAuth.js Docs](https://next-auth.js.org/)
- [Django REST Framework](https://www.django-rest-framework.org/)
- [AUTH.md - API Documentation](./AUTH.md)
## 💡 İpuçları
1. **Development**: `.env.local` dosyasını git'e eklemeyin
2. **Production**: Environment variables'ı hosting platformunuzda ayarlayın
3. **Security**: NEXTAUTH_SECRET'i güçlü ve rastgele tutun
4. **CORS**: Django backend'de Next.js URL'ini CORS whitelist'e ekleyin
5. **HTTPS**: Production'da mutlaka HTTPS kullanın
## 🚀 Production Deployment
1. Environment variables'ı production ortamına ekleyin
2. `NEXTAUTH_URL`'i production URL'inize değiştirin
3. Django backend URL'ini production URL'i ile değiştirin
4. OAuth redirect URI'larını production URL'leri ile güncelleyin
5. HTTPS kullanın (NextAuth requirement)
---
**Last Updated:** 2025-12-24