Ana içeriğe geç

Giriş Yapma (Login)

Sistemde kimlik doğrulaması yapmak için kullanılan temel endpoint. Email ve şifre ile giriş yaparak access token ve refresh token alabilirsiniz.

📋 Endpoint Bilgileri

  • URL: /api/v1/auth/login
  • Method: POST
  • Content-Type: application/json
  • Authentication: Gerekli değil

📝 Request

Headers

Content-Type: application/json

Body Parameters

ParametreTipZorunluAçıklama
emailstringKayıtlı email adresiniz
passwordstringHesap şifreniz

Request Example

{
"email": "kullanici@example.com",
"password": "güvenli_şifre123"
}

✅ Response

Başarılı Yanıt (200 OK)

{
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",
"accessTokenExpire": 1692789600,
"refreshToken": "def502004b8f5b592c4f6c94def50200..."
}

Response Fields

AlanTipAçıklama
accessTokenstringAPI çağrıları için kullanılacak JWT token
accessTokenExpireintegerToken'ın sona erme zamanı (Unix timestamp)
refreshTokenstringYeni access token almak için kullanılacak token

❌ Hata Yanıtları

400 Bad Request

Geçersiz parametreler veya format hataları durumunda:

{
"error": "Validation Error",
"message": "Email formatı geçersiz",
"statusCode": 400
}

Yaygın 400 Hata Sebepleri:

  • Geçersiz email formatı
  • Eksik email veya password parametresi
  • Boş değerler

401 Unauthorized

Yanlış kimlik bilgileri durumunda:

{
"error": "Authentication Failed",
"message": "Email veya şifre hatalı",
"statusCode": 401
}

💻 Kod Örnekleri

JavaScript/Node.js

async function login(email, password) {
const url = "https://integration.seoauthor.ai/api/v1/auth/login";

try {
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: email,
password: password,
}),
});

if (!response.ok) {
const errorData = await response.json();
throw new Error(`Login failed: ${errorData.message}`);
}

const data = await response.json();

// Token'ları güvenli bir şekilde sakla
sessionStorage.setItem("accessToken", data.accessToken);
sessionStorage.setItem("refreshToken", data.refreshToken);
sessionStorage.setItem("tokenExpire", data.accessTokenExpire);

console.log("Login successful!");
return data;
} catch (error) {
console.error("Login error:", error.message);
throw error;
}
}

// Kullanım
login("kullanici@example.com", "güvenli_şifre123")
.then((authData) => {
console.log("Giriş başarılı:", authData);
})
.catch((error) => {
console.error("Giriş hatası:", error);
});

Python

import requests
import json
from datetime import datetime

def login(email, password):
url = "https://integration.seoauthor.ai/api/v1/auth/login"
headers = {
"Content-Type": "application/json"
}
data = {
"email": email,
"password": password
}

try:
response = requests.post(url, headers=headers, json=data)
response.raise_for_status() # HTTP hataları için exception fırlat

auth_data = response.json()

# Token'ları güvenli bir şekilde sakla (örnek: environment variables)
# os.environ['ACCESS_TOKEN'] = auth_data['accessToken']
# os.environ['REFRESH_TOKEN'] = auth_data['refreshToken']

# Token sona erme zamanını kontrol et
expire_time = datetime.fromtimestamp(auth_data['accessTokenExpire'])
print(f"Token sona erme zamanı: {expire_time}")

return auth_data
except requests.exceptions.HTTPError as e:
if response.status_code == 400:
error_data = response.json()
print(f"Geçersiz parametreler: {error_data['message']}")
elif response.status_code == 401:
print("Yanlış email veya şifre")
raise
except requests.exceptions.RequestException as e:
print(f"Bağlantı hatası: {e}")
raise

# Kullanım
try:
auth_data = login("kullanici@example.com", "güvenli_şifre123")
print("Giriş başarılı!")
print(f"Access Token: {auth_data['accessToken'][:50]}...")
except Exception as e:
print(f"Giriş hatası: {e}")

PHP

<?php
function login($email, $password) {
$url = 'https://integration.seoauthor.ai/api/v1/auth/login';
$data = [
'email' => $email,
'password' => $password
];

$options = [
'http' => [
'header' => [
"Content-Type: application/json",
"User-Agent: PHP Client"
],
'method' => 'POST',
'content' => json_encode($data)
]
];

$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);

if ($result === FALSE) {
$error = error_get_last();
throw new Exception('HTTP request failed: ' . $error['message']);
}

// HTTP status code kontrol et
$status_line = $http_response_header[0];
preg_match('{HTTP\/\S*\s(\d{3})}', $status_line, $match);
$status_code = $match[1];

if ($status_code >= 400) {
$error_data = json_decode($result, true);
throw new Exception('Login failed: ' . $error_data['message']);
}

$auth_data = json_decode($result, true);

// Token'ları session'da sakla
session_start();
$_SESSION['access_token'] = $auth_data['accessToken'];
$_SESSION['refresh_token'] = $auth_data['refreshToken'];
$_SESSION['token_expire'] = $auth_data['accessTokenExpire'];

return $auth_data;
}

// Kullanım
try {
$auth_data = login("kullanici@example.com", "güvenli_şifre123");
echo "Giriş başarılı!\n";
echo "Token: " . substr($auth_data['accessToken'], 0, 50) . "...\n";
} catch (Exception $e) {
echo "Giriş hatası: " . $e->getMessage() . "\n";
}
?>

cURL

curl -X POST https://integration.seoauthor.ai/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "kullanici@example.com",
"password": "güvenli_şifre123"
}'

cURL ile Hata Handling

#!/bin/bash

# Login fonksiyonu
login() {
local email=$1
local password=$2

response=$(curl -s -w "\n%{http_code}" -X POST https://integration.seoauthor.ai/api/v1/auth/login \
-H "Content-Type: application/json" \
-d "{\"email\":\"$email\",\"password\":\"$password\"}")

# Response'u ayır
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | head -n -1)

if [ "$http_code" -eq 200 ]; then
echo "Giriş başarılı!"
echo "$body" | jq '.'

# Token'ları çıkar ve sakla
access_token=$(echo "$body" | jq -r '.accessToken')
echo "export ACCESS_TOKEN=\"$access_token\"" > .env
else
echo "Giriş hatası (HTTP $http_code):"
echo "$body" | jq '.'
fi
}

# Kullanım
login "kullanici@example.com" "güvenli_şifre123"

🔧 Token Süresi Kontrol Utility

class TokenValidator {
static isTokenExpired(tokenExpire) {
const now = Math.floor(Date.now() / 1000); // Unix timestamp
return now >= tokenExpire;
}

static getTimeUntilExpiry(tokenExpire) {
const now = Math.floor(Date.now() / 1000);
const secondsLeft = tokenExpire - now;

if (secondsLeft <= 0) {
return "Token süresi dolmuş";
}

const minutes = Math.floor(secondsLeft / 60);
const hours = Math.floor(minutes / 60);

if (hours > 0) {
return `${hours} saat ${minutes % 60} dakika`;
} else {
return `${minutes} dakika`;
}
}

static shouldRefreshToken(tokenExpire, bufferMinutes = 5) {
const now = Math.floor(Date.now() / 1000);
const bufferSeconds = bufferMinutes * 60;
return tokenExpire - now <= bufferSeconds;
}
}

// Kullanım örneği
const tokenExpire = 1692789600; // Örnek timestamp

if (TokenValidator.isTokenExpired(tokenExpire)) {
console.log("Token süresi dolmuş, yenileme gerekli");
} else if (TokenValidator.shouldRefreshToken(tokenExpire)) {
console.log("Token yakında sona erecek, yenileme önerilir");
console.log("Kalan süre:", TokenValidator.getTimeUntilExpiry(tokenExpire));
}

🛡️ Güvenlik Notları

Email Validation

API, email formatını doğrular ancak client-side'da da validation yapmanız önerilir:

function isValidEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}

Password Güvenliği

  • Minimum 8 karakter
  • En az bir büyük harf, bir küçük harf ve bir rakam içermeli
  • Özel karakterler kullanılması önerilir

Rate Limiting

Aynı IP adresinden çok fazla başarısız login denemesi yapılması durumunda geçici olarak engellenebilirsiniz.

İpucu

Token'ları localStorage yerine sessionStorage kullanarak saklamak daha güvenlidir. Bu şekilde tarayıcı kapatıldığında token'lar otomatik olarak silinir.

Uyarı

Production ortamında token'ları hiçbir zaman console'a log etmeyin veya client-side kaynak kodunda görünür hale getirmeyin.

Bilgi

Token süresi dolmadan önce yenilenmesi önerilir. Genellikle token'ın sona ermesinden 5-10 dakika önce refresh token ile yenileme yapılır.