first commit: Complete phishing test management panel with Node.js backend and React frontend
This commit is contained in:
26
backend/.env.example
Normal file
26
backend/.env.example
Normal file
@@ -0,0 +1,26 @@
|
||||
# Server Configuration
|
||||
NODE_ENV=development
|
||||
PORT=3000
|
||||
BASE_URL=http://localhost:3000
|
||||
|
||||
# Session Secret
|
||||
SESSION_SECRET=your-secret-key-change-this-in-production
|
||||
|
||||
# Database
|
||||
DB_PATH=./database/oltalama.db
|
||||
|
||||
# Gmail Configuration (App Password gerekli)
|
||||
GMAIL_USER=your-email@gmail.com
|
||||
GMAIL_APP_PASSWORD=your-16-digit-app-password
|
||||
GMAIL_FROM_NAME=Güvenlik Ekibi
|
||||
|
||||
# Telegram Bot Configuration
|
||||
TELEGRAM_BOT_TOKEN=your-bot-token-here
|
||||
TELEGRAM_CHAT_ID=your-chat-id-here
|
||||
|
||||
# Admin User (İlk kurulumda)
|
||||
ADMIN_USERNAME=admin
|
||||
ADMIN_PASSWORD=admin123
|
||||
|
||||
# Logging
|
||||
LOG_LEVEL=info
|
||||
35
backend/.gitignore
vendored
Normal file
35
backend/.gitignore
vendored
Normal file
@@ -0,0 +1,35 @@
|
||||
# Dependencies
|
||||
node_modules/
|
||||
package-lock.json
|
||||
yarn.lock
|
||||
|
||||
# Environment variables
|
||||
.env
|
||||
|
||||
# Database
|
||||
database/*.db
|
||||
database/*.db-journal
|
||||
database/*.db-shm
|
||||
database/*.db-wal
|
||||
|
||||
# Logs
|
||||
logs/*.log
|
||||
*.log
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
|
||||
# Test coverage
|
||||
coverage/
|
||||
|
||||
# Temporary files
|
||||
temp/
|
||||
tmp/
|
||||
|
||||
171
backend/README.md
Normal file
171
backend/README.md
Normal file
@@ -0,0 +1,171 @@
|
||||
# Oltalama Backend API
|
||||
|
||||
Phishing test yönetim sistemi backend API'si.
|
||||
|
||||
## ✨ Özellikler
|
||||
|
||||
✅ **Authentication** - Session-based login/logout
|
||||
✅ **Company Management** - Şirket CRUD & istatistikler
|
||||
✅ **Token Management** - Tracking token oluşturma & mail gönderimi
|
||||
✅ **Tracking** - IP, GeoIP, User-Agent tracking
|
||||
✅ **Telegram** - Gerçek zamanlı bildirimler
|
||||
✅ **Mail** - Gmail entegrasyonu (Nodemailer)
|
||||
✅ **Templates** - HTML mail şablonları (Handlebars)
|
||||
✅ **Stats** - Dashboard ve detaylı istatistikler
|
||||
|
||||
## 🚀 Kurulum
|
||||
|
||||
```bash
|
||||
npm install
|
||||
cp .env.example .env
|
||||
# .env dosyasını düzenle
|
||||
|
||||
npm run db:migrate
|
||||
npm run db:seed
|
||||
npm run dev
|
||||
```
|
||||
|
||||
## 📡 API Endpoints
|
||||
|
||||
### Authentication
|
||||
```
|
||||
POST /api/auth/login - Giriş
|
||||
POST /api/auth/logout - Çıkış
|
||||
GET /api/auth/check - Session kontrolü
|
||||
GET /api/auth/me - Kullanıcı bilgisi
|
||||
```
|
||||
|
||||
### Companies
|
||||
```
|
||||
GET /api/companies - Tüm şirketler
|
||||
POST /api/companies - Yeni şirket
|
||||
GET /api/companies/:id - Şirket detay
|
||||
PUT /api/companies/:id - Şirket güncelle
|
||||
DELETE /api/companies/:id - Şirket sil
|
||||
GET /api/companies/:id/tokens - Şirket tokenları
|
||||
GET /api/companies/:id/stats - Şirket istatistikleri
|
||||
```
|
||||
|
||||
### Tokens
|
||||
```
|
||||
GET /api/tokens - Tüm tokenlar
|
||||
POST /api/tokens/create - Token oluştur
|
||||
POST /api/tokens/create-and-send - Token oluştur + mail gönder
|
||||
GET /api/tokens/:id - Token detay
|
||||
PUT /api/tokens/:id - Token güncelle
|
||||
DELETE /api/tokens/:id - Token sil
|
||||
POST /api/tokens/:id/send - Mail gönder
|
||||
GET /api/tokens/:id/clicks - Tıklama geçmişi
|
||||
```
|
||||
|
||||
### Tracking (Public)
|
||||
```
|
||||
GET /t/:token - Tracking endpoint (IP, GeoIP, Telegram)
|
||||
```
|
||||
|
||||
### Templates
|
||||
```
|
||||
GET /api/templates - Tüm şablonlar
|
||||
GET /api/templates/:type - Şablon detay
|
||||
POST /api/templates/preview - Önizleme
|
||||
```
|
||||
|
||||
### Settings
|
||||
```
|
||||
GET /api/settings - Tüm ayarlar
|
||||
PUT /api/settings/gmail - Gmail ayarları
|
||||
PUT /api/settings/telegram - Telegram ayarları
|
||||
POST /api/settings/test-gmail - Gmail testi
|
||||
POST /api/settings/test-telegram - Telegram testi
|
||||
```
|
||||
|
||||
### Stats
|
||||
```
|
||||
GET /api/stats/dashboard - Dashboard özet
|
||||
GET /api/stats/recent-clicks - Son tıklamalar
|
||||
GET /api/stats/by-company - Şirket bazlı stats
|
||||
```
|
||||
|
||||
## 🔐 Default Credentials
|
||||
|
||||
```
|
||||
Username: admin
|
||||
Password: admin123
|
||||
```
|
||||
|
||||
## 📊 Database
|
||||
|
||||
SQLite database: `database/oltalama.db`
|
||||
|
||||
**Tablolar:**
|
||||
- companies (3 örnek şirket)
|
||||
- tracking_tokens
|
||||
- click_logs
|
||||
- mail_templates (2 şablon)
|
||||
- settings
|
||||
- admin_user
|
||||
|
||||
## 🧪 Test
|
||||
|
||||
```bash
|
||||
# Health check
|
||||
curl http://localhost:3000/health
|
||||
|
||||
# Login
|
||||
curl -X POST http://localhost:3000/api/auth/login \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"username":"admin","password":"admin123"}'
|
||||
```
|
||||
|
||||
## 📝 Environment Variables
|
||||
|
||||
```env
|
||||
PORT=3000
|
||||
BASE_URL=http://localhost:3000
|
||||
SESSION_SECRET=your-secret-key
|
||||
|
||||
# Gmail
|
||||
GMAIL_USER=your-email@gmail.com
|
||||
GMAIL_APP_PASSWORD=your-app-password
|
||||
GMAIL_FROM_NAME=Güvenlik Ekibi
|
||||
|
||||
# Telegram
|
||||
TELEGRAM_BOT_TOKEN=your-bot-token
|
||||
TELEGRAM_CHAT_ID=your-chat-id
|
||||
```
|
||||
|
||||
## 🏗️ Yapı
|
||||
|
||||
```
|
||||
src/
|
||||
├── config/ - Database, Logger, Session
|
||||
├── controllers/ - Route handlers (auth, company, token, tracking, etc.)
|
||||
├── middlewares/ - Auth, error handler, rate limiter
|
||||
├── models/ - Sequelize models
|
||||
├── routes/ - API routes
|
||||
├── services/ - Business logic (mail, telegram, token)
|
||||
├── utils/ - Helpers (geoip, user-agent parser, token generator)
|
||||
├── validators/ - Joi schemas
|
||||
├── public/ - Static files (landing page)
|
||||
└── app.js - Express app
|
||||
```
|
||||
|
||||
## ✅ Durum
|
||||
|
||||
**Tamamlanan:**
|
||||
- ✅ Authentication sistem
|
||||
- ✅ Company yönetimi
|
||||
- ✅ Token yönetimi
|
||||
- ✅ Tracking endpoint
|
||||
- ✅ Telegram bildirimleri
|
||||
- ✅ Mail gönderimi
|
||||
- ✅ GeoIP tracking
|
||||
- ✅ User-Agent parsing
|
||||
- ✅ Stats & Analytics
|
||||
- ✅ Landing page
|
||||
|
||||
**Sırada:**
|
||||
- Frontend (React)
|
||||
- API Documentation (Swagger)
|
||||
- Unit tests
|
||||
|
||||
31
backend/migrations/001-create-tables.js
Normal file
31
backend/migrations/001-create-tables.js
Normal file
@@ -0,0 +1,31 @@
|
||||
const { sequelize } = require('../src/models');
|
||||
|
||||
async function up() {
|
||||
try {
|
||||
console.log('🔄 Creating database tables...');
|
||||
|
||||
// Sync all models (create tables)
|
||||
await sequelize.sync({ force: false });
|
||||
|
||||
console.log('✅ All tables created successfully!');
|
||||
} catch (error) {
|
||||
console.error('❌ Error creating tables:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function down() {
|
||||
try {
|
||||
console.log('🔄 Dropping all tables...');
|
||||
|
||||
await sequelize.drop();
|
||||
|
||||
console.log('✅ All tables dropped successfully!');
|
||||
} catch (error) {
|
||||
console.error('❌ Error dropping tables:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { up, down };
|
||||
|
||||
32
backend/migrations/run-migrations.js
Normal file
32
backend/migrations/run-migrations.js
Normal file
@@ -0,0 +1,32 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
require('dotenv').config();
|
||||
|
||||
async function runMigrations() {
|
||||
console.log('🚀 Starting database migrations...\n');
|
||||
|
||||
const migrationsDir = __dirname;
|
||||
const migrationFiles = fs
|
||||
.readdirSync(migrationsDir)
|
||||
.filter(file => file.endsWith('.js') && file !== 'run-migrations.js')
|
||||
.sort();
|
||||
|
||||
for (const file of migrationFiles) {
|
||||
console.log(`📦 Running migration: ${file}`);
|
||||
const migration = require(path.join(migrationsDir, file));
|
||||
|
||||
try {
|
||||
await migration.up();
|
||||
console.log(`✅ ${file} completed\n`);
|
||||
} catch (error) {
|
||||
console.error(`❌ ${file} failed:`, error.message);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('🎉 All migrations completed successfully!');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
runMigrations();
|
||||
|
||||
45
backend/package.json
Normal file
45
backend/package.json
Normal file
@@ -0,0 +1,45 @@
|
||||
{
|
||||
"name": "oltalama-backend",
|
||||
"version": "1.0.0",
|
||||
"description": "Phishing Test Yönetim Paneli - Backend",
|
||||
"main": "src/app.js",
|
||||
"scripts": {
|
||||
"start": "node src/app.js",
|
||||
"dev": "nodemon src/app.js",
|
||||
"db:migrate": "node migrations/run-migrations.js",
|
||||
"db:seed": "node seeders/run-seeders.js",
|
||||
"test": "jest --coverage"
|
||||
},
|
||||
"keywords": [
|
||||
"phishing",
|
||||
"security",
|
||||
"awareness"
|
||||
],
|
||||
"author": "",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"bcrypt": "^5.1.1",
|
||||
"connect-sqlite3": "^0.9.16",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^16.3.1",
|
||||
"express": "^4.18.2",
|
||||
"express-rate-limit": "^7.1.5",
|
||||
"express-session": "^1.17.3",
|
||||
"geoip-lite": "^1.4.7",
|
||||
"handlebars": "^4.7.8",
|
||||
"helmet": "^7.1.0",
|
||||
"joi": "^17.11.0",
|
||||
"node-telegram-bot-api": "^0.64.0",
|
||||
"nodemailer": "^6.9.7",
|
||||
"sequelize": "^6.35.2",
|
||||
"sqlite3": "^5.1.6",
|
||||
"useragent": "^2.3.0",
|
||||
"uuid": "^9.0.1",
|
||||
"winston": "^3.11.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"jest": "^29.7.0",
|
||||
"nodemon": "^3.0.2",
|
||||
"supertest": "^6.3.3"
|
||||
}
|
||||
}
|
||||
183
backend/seeders/001-seed-initial-data.js
Normal file
183
backend/seeders/001-seed-initial-data.js
Normal file
@@ -0,0 +1,183 @@
|
||||
const bcrypt = require('bcrypt');
|
||||
const { Company, AdminUser, MailTemplate } = require('../src/models');
|
||||
require('dotenv').config();
|
||||
|
||||
async function up() {
|
||||
try {
|
||||
console.log('🌱 Seeding initial data...');
|
||||
|
||||
// 1. Create admin user
|
||||
const hashedPassword = await bcrypt.hash(
|
||||
process.env.ADMIN_PASSWORD || 'admin123',
|
||||
10
|
||||
);
|
||||
|
||||
await AdminUser.findOrCreate({
|
||||
where: { id: 1 },
|
||||
defaults: {
|
||||
id: 1,
|
||||
username: process.env.ADMIN_USERNAME || 'admin',
|
||||
password_hash: hashedPassword,
|
||||
},
|
||||
});
|
||||
console.log('✅ Admin user created');
|
||||
|
||||
// 2. Create sample companies
|
||||
const companies = [
|
||||
{
|
||||
name: 'Türk Telekom',
|
||||
description: 'Telekomünikasyon şirketi test kampanyası',
|
||||
industry: 'Telecom',
|
||||
},
|
||||
{
|
||||
name: 'İş Bankası',
|
||||
description: 'Bankacılık sektörü test kampanyası',
|
||||
industry: 'Banking',
|
||||
},
|
||||
{
|
||||
name: 'PTT',
|
||||
description: 'Kargo ve posta test kampanyası',
|
||||
industry: 'Government',
|
||||
},
|
||||
];
|
||||
|
||||
for (const company of companies) {
|
||||
await Company.findOrCreate({
|
||||
where: { name: company.name },
|
||||
defaults: company,
|
||||
});
|
||||
}
|
||||
console.log('✅ Sample companies created');
|
||||
|
||||
// 3. Create mail templates
|
||||
const templates = [
|
||||
{
|
||||
name: 'Banka Güvenlik Bildirimi',
|
||||
template_type: 'bank',
|
||||
subject_template: '{{company_name}} - Acil Güvenlik Bildirimi',
|
||||
body_html: `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<style>
|
||||
body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
|
||||
.container { max-width: 600px; margin: 0 auto; padding: 20px; }
|
||||
.header { background: #003d7a; color: white; padding: 20px; text-align: center; }
|
||||
.content { padding: 30px; background: #f9f9f9; }
|
||||
.button { display: inline-block; padding: 15px 30px; background: #e31e24; color: white; text-decoration: none; border-radius: 5px; margin: 20px 0; }
|
||||
.footer { padding: 20px; text-align: center; font-size: 12px; color: #666; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>{{company_name}}</h1>
|
||||
<p>Güvenlik Bildirimi</p>
|
||||
</div>
|
||||
<div class="content">
|
||||
{{#if employee_name}}
|
||||
<p>Sayın {{employee_name}},</p>
|
||||
{{else}}
|
||||
<p>Sayın Müşterimiz,</p>
|
||||
{{/if}}
|
||||
|
||||
<p>Hesabınızda olağandışı bir aktivite tespit edildi. Güvenliğiniz için hesabınızı derhal doğrulamanız gerekmektedir.</p>
|
||||
|
||||
<p><strong>Tespit Edilen Sorun:</strong> Yetkisiz giriş denemesi</p>
|
||||
<p><strong>Tarih:</strong> {{current_date}}</p>
|
||||
|
||||
<p>Hesabınızı güvende tutmak için lütfen aşağıdaki butona tıklayarak kimliğinizi doğrulayın:</p>
|
||||
|
||||
<center>
|
||||
<a href="{{tracking_url}}" class="button">Hesabımı Doğrula</a>
|
||||
</center>
|
||||
|
||||
<p><strong>Uyarı:</strong> Bu işlemi 24 saat içinde tamamlamazsanız, hesabınız güvenlik nedeniyle geçici olarak askıya alınacaktır.</p>
|
||||
</div>
|
||||
<div class="footer">
|
||||
<p>© {{current_year}} {{company_name}}. Tüm hakları saklıdır.</p>
|
||||
<p>Bu bir otomatik mesajdır, lütfen yanıtlamayınız.</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`,
|
||||
description: 'Banka güvenlik bildirimi şablonu',
|
||||
},
|
||||
{
|
||||
name: 'E-Devlet Kimlik Doğrulama',
|
||||
template_type: 'edevlet',
|
||||
subject_template: 'E-Devlet - Kimlik Doğrulama Gerekli',
|
||||
body_html: `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<style>
|
||||
body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
|
||||
.container { max-width: 600px; margin: 0 auto; padding: 20px; }
|
||||
.header { background: #c00; color: white; padding: 20px; text-align: center; }
|
||||
.content { padding: 30px; background: #f9f9f9; }
|
||||
.button { display: inline-block; padding: 15px 30px; background: #c00; color: white; text-decoration: none; border-radius: 5px; margin: 20px 0; }
|
||||
.footer { padding: 20px; text-align: center; font-size: 12px; color: #666; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>🇹🇷 E-DEVLET KAPISI</h1>
|
||||
</div>
|
||||
<div class="content">
|
||||
{{#if employee_name}}
|
||||
<p>Sayın {{employee_name}},</p>
|
||||
{{else}}
|
||||
<p>Sayın Vatandaşımız,</p>
|
||||
{{/if}}
|
||||
|
||||
<p>E-Devlet hesabınızla ilgili güvenlik güncellemesi yapılması gerekmektedir.</p>
|
||||
|
||||
<p><strong>Güncelleme Sebebi:</strong> Yeni güvenlik protokolü</p>
|
||||
<p><strong>Son Tarih:</strong> 48 saat</p>
|
||||
|
||||
<p>Hesabınızı aktif tutmak için lütfen kimliğinizi doğrulayın:</p>
|
||||
|
||||
<center>
|
||||
<a href="{{tracking_url}}" class="button">Kimliğimi Doğrula</a>
|
||||
</center>
|
||||
|
||||
<p>Bu işlemi tamamlamazsanız, bazı e-devlet hizmetlerine erişiminiz kısıtlanabilir.</p>
|
||||
</div>
|
||||
<div class="footer">
|
||||
<p>© {{current_year}} T.C. Cumhurbaşkanlığı Dijital Dönüşüm Ofisi</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`,
|
||||
description: 'E-Devlet kimlik doğrulama şablonu',
|
||||
},
|
||||
];
|
||||
|
||||
for (const template of templates) {
|
||||
await MailTemplate.findOrCreate({
|
||||
where: { template_type: template.template_type },
|
||||
defaults: template,
|
||||
});
|
||||
}
|
||||
console.log('✅ Mail templates created');
|
||||
|
||||
console.log('\n✨ Seeding completed successfully!');
|
||||
} catch (error) {
|
||||
console.error('❌ Error seeding data:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function down() {
|
||||
// Not implemented - be careful!
|
||||
console.log('⚠️ Seed rollback not implemented');
|
||||
}
|
||||
|
||||
module.exports = { up, down };
|
||||
|
||||
32
backend/seeders/run-seeders.js
Normal file
32
backend/seeders/run-seeders.js
Normal file
@@ -0,0 +1,32 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
require('dotenv').config();
|
||||
|
||||
async function runSeeders() {
|
||||
console.log('🌱 Starting database seeders...\n');
|
||||
|
||||
const seedersDir = __dirname;
|
||||
const seederFiles = fs
|
||||
.readdirSync(seedersDir)
|
||||
.filter(file => file.endsWith('.js') && file !== 'run-seeders.js')
|
||||
.sort();
|
||||
|
||||
for (const file of seederFiles) {
|
||||
console.log(`📦 Running seeder: ${file}`);
|
||||
const seeder = require(path.join(seedersDir, file));
|
||||
|
||||
try {
|
||||
await seeder.up();
|
||||
console.log(`✅ ${file} completed\n`);
|
||||
} catch (error) {
|
||||
console.error(`❌ ${file} failed:`, error.message);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('🎉 All seeders completed successfully!');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
runSeeders();
|
||||
|
||||
99
backend/src/app.js
Normal file
99
backend/src/app.js
Normal file
@@ -0,0 +1,99 @@
|
||||
require('dotenv').config();
|
||||
const express = require('express');
|
||||
const session = require('express-session');
|
||||
const helmet = require('helmet');
|
||||
const cors = require('cors');
|
||||
const logger = require('./config/logger');
|
||||
const sessionConfig = require('./config/session');
|
||||
const { testConnection } = require('./config/database');
|
||||
const errorHandler = require('./middlewares/errorHandler');
|
||||
const { apiLimiter } = require('./middlewares/rateLimiter');
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 3000;
|
||||
|
||||
// Security middleware
|
||||
app.use(helmet());
|
||||
app.use(cors({
|
||||
origin: process.env.FRONTEND_URL || 'http://localhost:3001',
|
||||
credentials: true,
|
||||
}));
|
||||
|
||||
// Body parsing middleware
|
||||
app.use(express.json());
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
|
||||
// Serve static files (landing page)
|
||||
app.use(express.static('src/public'));
|
||||
|
||||
// Session middleware
|
||||
app.use(session(sessionConfig));
|
||||
|
||||
// Rate limiting
|
||||
app.use('/api', apiLimiter);
|
||||
|
||||
// Request logging
|
||||
app.use((req, res, next) => {
|
||||
logger.info(`${req.method} ${req.path}`, {
|
||||
ip: req.ip,
|
||||
userAgent: req.get('user-agent'),
|
||||
});
|
||||
next();
|
||||
});
|
||||
|
||||
// Health check
|
||||
app.get('/health', (req, res) => {
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Server is running',
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
});
|
||||
|
||||
// API Routes
|
||||
app.use('/api/auth', require('./routes/auth.routes'));
|
||||
app.use('/api/companies', require('./routes/company.routes'));
|
||||
app.use('/api/tokens', require('./routes/token.routes'));
|
||||
app.use('/api/templates', require('./routes/template.routes'));
|
||||
app.use('/api/settings', require('./routes/settings.routes'));
|
||||
app.use('/api/stats', require('./routes/stats.routes'));
|
||||
|
||||
// Public tracking route (no rate limit on this specific route)
|
||||
app.use('/t', require('./routes/tracking.routes'));
|
||||
|
||||
// 404 handler
|
||||
app.use((req, res) => {
|
||||
res.status(404).json({
|
||||
success: false,
|
||||
error: 'Endpoint not found',
|
||||
});
|
||||
});
|
||||
|
||||
// Error handler (must be last)
|
||||
app.use(errorHandler);
|
||||
|
||||
// Start server
|
||||
const startServer = async () => {
|
||||
try {
|
||||
// Test database connection
|
||||
await testConnection();
|
||||
|
||||
// Start listening
|
||||
app.listen(PORT, () => {
|
||||
logger.info(`🚀 Server is running on port ${PORT}`);
|
||||
logger.info(`📊 Environment: ${process.env.NODE_ENV || 'development'}`);
|
||||
logger.info(`🔗 Health check: http://localhost:${PORT}/health`);
|
||||
console.log(`\n✨ Oltalama Backend Server Started!`);
|
||||
console.log(`🌐 API: http://localhost:${PORT}/api`);
|
||||
console.log(`🎯 Tracking: http://localhost:${PORT}/t/:token\n`);
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Failed to start server:', error);
|
||||
process.exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
startServer();
|
||||
|
||||
module.exports = app;
|
||||
|
||||
29
backend/src/config/database.js
Normal file
29
backend/src/config/database.js
Normal file
@@ -0,0 +1,29 @@
|
||||
const { Sequelize } = require('sequelize');
|
||||
const path = require('path');
|
||||
require('dotenv').config();
|
||||
|
||||
const dbPath = process.env.DB_PATH || path.join(__dirname, '../../database/oltalama.db');
|
||||
|
||||
const sequelize = new Sequelize({
|
||||
dialect: 'sqlite',
|
||||
storage: dbPath,
|
||||
logging: process.env.NODE_ENV === 'development' ? console.log : false,
|
||||
define: {
|
||||
timestamps: true,
|
||||
underscored: false,
|
||||
},
|
||||
});
|
||||
|
||||
// Test database connection
|
||||
const testConnection = async () => {
|
||||
try {
|
||||
await sequelize.authenticate();
|
||||
console.log('✅ Database connection has been established successfully.');
|
||||
} catch (error) {
|
||||
console.error('❌ Unable to connect to the database:', error);
|
||||
process.exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { sequelize, testConnection };
|
||||
|
||||
49
backend/src/config/logger.js
Normal file
49
backend/src/config/logger.js
Normal file
@@ -0,0 +1,49 @@
|
||||
const winston = require('winston');
|
||||
const path = require('path');
|
||||
|
||||
const logDir = path.join(__dirname, '../../logs');
|
||||
|
||||
// Define log format
|
||||
const logFormat = winston.format.combine(
|
||||
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
|
||||
winston.format.errors({ stack: true }),
|
||||
winston.format.splat(),
|
||||
winston.format.json()
|
||||
);
|
||||
|
||||
// Create logger
|
||||
const logger = winston.createLogger({
|
||||
level: process.env.LOG_LEVEL || 'info',
|
||||
format: logFormat,
|
||||
defaultMeta: { service: 'oltalama-backend' },
|
||||
transports: [
|
||||
// Write all logs to combined.log
|
||||
new winston.transports.File({
|
||||
filename: path.join(logDir, 'combined.log'),
|
||||
maxsize: 5242880, // 5MB
|
||||
maxFiles: 5,
|
||||
}),
|
||||
// Write errors to error.log
|
||||
new winston.transports.File({
|
||||
filename: path.join(logDir, 'error.log'),
|
||||
level: 'error',
|
||||
maxsize: 5242880,
|
||||
maxFiles: 5,
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
// If not production, log to console too
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
logger.add(
|
||||
new winston.transports.Console({
|
||||
format: winston.format.combine(
|
||||
winston.format.colorize(),
|
||||
winston.format.simple()
|
||||
),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = logger;
|
||||
|
||||
23
backend/src/config/session.js
Normal file
23
backend/src/config/session.js
Normal file
@@ -0,0 +1,23 @@
|
||||
const session = require('express-session');
|
||||
const SQLiteStore = require('connect-sqlite3')(session);
|
||||
const path = require('path');
|
||||
require('dotenv').config();
|
||||
|
||||
const sessionConfig = {
|
||||
store: new SQLiteStore({
|
||||
db: 'sessions.db',
|
||||
dir: path.join(__dirname, '../../database'),
|
||||
}),
|
||||
secret: process.env.SESSION_SECRET || 'your-secret-key-change-this',
|
||||
resave: false,
|
||||
saveUninitialized: false,
|
||||
cookie: {
|
||||
secure: process.env.NODE_ENV === 'production', // HTTPS only in production
|
||||
httpOnly: true,
|
||||
maxAge: 24 * 60 * 60 * 1000, // 24 hours
|
||||
},
|
||||
name: 'oltalama.sid',
|
||||
};
|
||||
|
||||
module.exports = sessionConfig;
|
||||
|
||||
119
backend/src/controllers/auth.controller.js
Normal file
119
backend/src/controllers/auth.controller.js
Normal file
@@ -0,0 +1,119 @@
|
||||
const bcrypt = require('bcrypt');
|
||||
const { AdminUser } = require('../models');
|
||||
const logger = require('../config/logger');
|
||||
|
||||
// Login
|
||||
exports.login = async (req, res, next) => {
|
||||
try {
|
||||
const { username, password } = req.body;
|
||||
|
||||
// Find admin user
|
||||
const admin = await AdminUser.findOne({ where: { username } });
|
||||
|
||||
if (!admin) {
|
||||
logger.warn(`Login attempt with invalid username: ${username}`);
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
error: 'Invalid username or password',
|
||||
});
|
||||
}
|
||||
|
||||
// Verify password
|
||||
const isValidPassword = await bcrypt.compare(password, admin.password_hash);
|
||||
|
||||
if (!isValidPassword) {
|
||||
logger.warn(`Failed login attempt for user: ${username}`);
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
error: 'Invalid username or password',
|
||||
});
|
||||
}
|
||||
|
||||
// Update last login
|
||||
await admin.update({ last_login: new Date() });
|
||||
|
||||
// Create session
|
||||
req.session.userId = admin.id;
|
||||
req.session.username = admin.username;
|
||||
req.session.isAdmin = true;
|
||||
|
||||
logger.info(`User logged in successfully: ${username}`);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Login successful',
|
||||
user: {
|
||||
id: admin.id,
|
||||
username: admin.username,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
// Logout
|
||||
exports.logout = async (req, res, next) => {
|
||||
try {
|
||||
const username = req.session.username;
|
||||
|
||||
req.session.destroy((err) => {
|
||||
if (err) {
|
||||
logger.error('Logout error:', err);
|
||||
return next(err);
|
||||
}
|
||||
|
||||
logger.info(`User logged out: ${username}`);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Logout successful',
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
// Check authentication status
|
||||
exports.checkAuth = async (req, res) => {
|
||||
if (req.session && req.session.userId) {
|
||||
res.json({
|
||||
success: true,
|
||||
authenticated: true,
|
||||
user: {
|
||||
id: req.session.userId,
|
||||
username: req.session.username,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
res.json({
|
||||
success: true,
|
||||
authenticated: false,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Get current user info
|
||||
exports.me = async (req, res, next) => {
|
||||
try {
|
||||
const admin = await AdminUser.findByPk(req.session.userId, {
|
||||
attributes: ['id', 'username', 'last_login', 'created_at'],
|
||||
});
|
||||
|
||||
if (!admin) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
error: 'User not found',
|
||||
});
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: admin,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
225
backend/src/controllers/company.controller.js
Normal file
225
backend/src/controllers/company.controller.js
Normal file
@@ -0,0 +1,225 @@
|
||||
const { Company, TrackingToken, sequelize } = require('../models');
|
||||
const logger = require('../config/logger');
|
||||
|
||||
// Get all companies
|
||||
exports.getAllCompanies = async (req, res, next) => {
|
||||
try {
|
||||
const companies = await Company.findAll({
|
||||
order: [['created_at', 'DESC']],
|
||||
});
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: companies,
|
||||
count: companies.length,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
// Get company by ID
|
||||
exports.getCompanyById = async (req, res, next) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
const company = await Company.findByPk(id);
|
||||
|
||||
if (!company) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
error: 'Company not found',
|
||||
});
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: company,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
// Create new company
|
||||
exports.createCompany = async (req, res, next) => {
|
||||
try {
|
||||
const { name, description, logo_url, industry } = req.body;
|
||||
|
||||
const company = await Company.create({
|
||||
name,
|
||||
description,
|
||||
logo_url,
|
||||
industry,
|
||||
});
|
||||
|
||||
logger.info(`Company created: ${name} (ID: ${company.id})`);
|
||||
|
||||
res.status(201).json({
|
||||
success: true,
|
||||
message: 'Company created successfully',
|
||||
data: company,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
// Update company
|
||||
exports.updateCompany = async (req, res, next) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const { name, description, logo_url, industry, active } = req.body;
|
||||
|
||||
const company = await Company.findByPk(id);
|
||||
|
||||
if (!company) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
error: 'Company not found',
|
||||
});
|
||||
}
|
||||
|
||||
await company.update({
|
||||
name: name || company.name,
|
||||
description: description !== undefined ? description : company.description,
|
||||
logo_url: logo_url !== undefined ? logo_url : company.logo_url,
|
||||
industry: industry || company.industry,
|
||||
active: active !== undefined ? active : company.active,
|
||||
});
|
||||
|
||||
logger.info(`Company updated: ${company.name} (ID: ${id})`);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Company updated successfully',
|
||||
data: company,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
// Delete company
|
||||
exports.deleteCompany = async (req, res, next) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
const company = await Company.findByPk(id);
|
||||
|
||||
if (!company) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
error: 'Company not found',
|
||||
});
|
||||
}
|
||||
|
||||
const companyName = company.name;
|
||||
await company.destroy();
|
||||
|
||||
logger.info(`Company deleted: ${companyName} (ID: ${id})`);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Company deleted successfully',
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
// Get company tokens
|
||||
exports.getCompanyTokens = async (req, res, next) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const { limit = 50, offset = 0 } = req.query;
|
||||
|
||||
const company = await Company.findByPk(id);
|
||||
|
||||
if (!company) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
error: 'Company not found',
|
||||
});
|
||||
}
|
||||
|
||||
const tokens = await TrackingToken.findAll({
|
||||
where: { company_id: id },
|
||||
order: [['created_at', 'DESC']],
|
||||
limit: parseInt(limit),
|
||||
offset: parseInt(offset),
|
||||
});
|
||||
|
||||
const total = await TrackingToken.count({ where: { company_id: id } });
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: tokens,
|
||||
pagination: {
|
||||
total,
|
||||
limit: parseInt(limit),
|
||||
offset: parseInt(offset),
|
||||
hasMore: parseInt(offset) + parseInt(limit) < total,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
// Get company stats
|
||||
exports.getCompanyStats = async (req, res, next) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
const company = await Company.findByPk(id);
|
||||
|
||||
if (!company) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
error: 'Company not found',
|
||||
});
|
||||
}
|
||||
|
||||
// Get detailed stats
|
||||
const stats = await sequelize.query(
|
||||
`
|
||||
SELECT
|
||||
COUNT(*) as total_tokens,
|
||||
SUM(CASE WHEN mail_sent = 1 THEN 1 ELSE 0 END) as mails_sent,
|
||||
SUM(CASE WHEN clicked = 1 THEN 1 ELSE 0 END) as tokens_clicked,
|
||||
SUM(click_count) as total_clicks,
|
||||
MAX(last_click_at) as last_activity
|
||||
FROM tracking_tokens
|
||||
WHERE company_id = ?
|
||||
`,
|
||||
{
|
||||
replacements: [id],
|
||||
type: sequelize.QueryTypes.SELECT,
|
||||
}
|
||||
);
|
||||
|
||||
const result = stats[0];
|
||||
const clickRate = result.total_tokens > 0
|
||||
? ((result.tokens_clicked / result.total_tokens) * 100).toFixed(2)
|
||||
: 0;
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: {
|
||||
company,
|
||||
stats: {
|
||||
total_tokens: parseInt(result.total_tokens) || 0,
|
||||
mails_sent: parseInt(result.mails_sent) || 0,
|
||||
tokens_clicked: parseInt(result.tokens_clicked) || 0,
|
||||
total_clicks: parseInt(result.total_clicks) || 0,
|
||||
click_rate: parseFloat(clickRate),
|
||||
last_activity: result.last_activity,
|
||||
},
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
127
backend/src/controllers/settings.controller.js
Normal file
127
backend/src/controllers/settings.controller.js
Normal file
@@ -0,0 +1,127 @@
|
||||
const { Settings } = require('../models');
|
||||
const mailService = require('../services/mail.service');
|
||||
const telegramService = require('../services/telegram.service');
|
||||
|
||||
// Get all settings
|
||||
exports.getAllSettings = async (req, res, next) => {
|
||||
try {
|
||||
const settings = await Settings.findAll();
|
||||
|
||||
// Hide sensitive values
|
||||
const sanitized = settings.map(s => ({
|
||||
...s.toJSON(),
|
||||
value: s.is_encrypted ? '********' : s.value,
|
||||
}));
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: sanitized,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
// Update Gmail settings
|
||||
exports.updateGmailSettings = async (req, res, next) => {
|
||||
try {
|
||||
const { gmail_user, gmail_password, gmail_from_name } = req.body;
|
||||
|
||||
if (gmail_user) {
|
||||
await Settings.upsert({
|
||||
key: 'gmail_user',
|
||||
value: gmail_user,
|
||||
is_encrypted: false,
|
||||
description: 'Gmail email address',
|
||||
});
|
||||
}
|
||||
|
||||
if (gmail_password) {
|
||||
await Settings.upsert({
|
||||
key: 'gmail_password',
|
||||
value: gmail_password,
|
||||
is_encrypted: true,
|
||||
description: 'Gmail App Password',
|
||||
});
|
||||
}
|
||||
|
||||
if (gmail_from_name) {
|
||||
await Settings.upsert({
|
||||
key: 'gmail_from_name',
|
||||
value: gmail_from_name,
|
||||
is_encrypted: false,
|
||||
description: 'Sender name for emails',
|
||||
});
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Gmail settings updated successfully',
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
// Update Telegram settings
|
||||
exports.updateTelegramSettings = async (req, res, next) => {
|
||||
try {
|
||||
const { telegram_bot_token, telegram_chat_id } = req.body;
|
||||
|
||||
if (telegram_bot_token) {
|
||||
await Settings.upsert({
|
||||
key: 'telegram_bot_token',
|
||||
value: telegram_bot_token,
|
||||
is_encrypted: true,
|
||||
description: 'Telegram Bot Token',
|
||||
});
|
||||
}
|
||||
|
||||
if (telegram_chat_id) {
|
||||
await Settings.upsert({
|
||||
key: 'telegram_chat_id',
|
||||
value: telegram_chat_id,
|
||||
is_encrypted: false,
|
||||
description: 'Telegram Chat ID',
|
||||
});
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Telegram settings updated successfully',
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
// Test Gmail connection
|
||||
exports.testGmail = async (req, res, next) => {
|
||||
try {
|
||||
const result = await mailService.testConnection();
|
||||
|
||||
res.json(result);
|
||||
} catch (error) {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Test Telegram connection
|
||||
exports.testTelegram = async (req, res, next) => {
|
||||
try {
|
||||
const result = await telegramService.sendTestMessage();
|
||||
|
||||
res.json(result);
|
||||
} catch (error) {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = exports;
|
||||
|
||||
103
backend/src/controllers/stats.controller.js
Normal file
103
backend/src/controllers/stats.controller.js
Normal file
@@ -0,0 +1,103 @@
|
||||
const { Company, TrackingToken, ClickLog, sequelize } = require('../models');
|
||||
|
||||
// Dashboard stats
|
||||
exports.getDashboardStats = async (req, res, next) => {
|
||||
try {
|
||||
// Get overall stats
|
||||
const totalCompanies = await Company.count();
|
||||
const totalTokens = await TrackingToken.count();
|
||||
const clickedTokens = await TrackingToken.count({ where: { clicked: true } });
|
||||
const totalClicks = await TrackingToken.sum('click_count') || 0;
|
||||
|
||||
const clickRate = totalTokens > 0 ? ((clickedTokens / totalTokens) * 100).toFixed(2) : 0;
|
||||
|
||||
// Get today's activity
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
|
||||
const todayClicks = await ClickLog.count({
|
||||
where: {
|
||||
clicked_at: {
|
||||
[sequelize.Sequelize.Op.gte]: today,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Get company-based summary
|
||||
const companyStats = await Company.findAll({
|
||||
attributes: ['id', 'name', 'industry', 'total_tokens', 'total_clicks', 'click_rate'],
|
||||
order: [['total_clicks', 'DESC']],
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: {
|
||||
overview: {
|
||||
total_companies: totalCompanies,
|
||||
total_tokens: totalTokens,
|
||||
clicked_tokens: clickedTokens,
|
||||
total_clicks: parseInt(totalClicks),
|
||||
click_rate: parseFloat(clickRate),
|
||||
today_clicks: todayClicks,
|
||||
},
|
||||
top_companies: companyStats,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
// Recent clicks
|
||||
exports.getRecentClicks = async (req, res, next) => {
|
||||
try {
|
||||
const { limit = 20 } = req.query;
|
||||
|
||||
const clicks = await ClickLog.findAll({
|
||||
include: [
|
||||
{
|
||||
model: TrackingToken,
|
||||
as: 'token',
|
||||
attributes: ['target_email', 'employee_name', 'company_id'],
|
||||
include: [
|
||||
{
|
||||
model: Company,
|
||||
as: 'company',
|
||||
attributes: ['name', 'industry'],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
order: [['clicked_at', 'DESC']],
|
||||
limit: parseInt(limit),
|
||||
});
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: clicks,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
// Company-based stats for charts
|
||||
exports.getCompanyBasedStats = async (req, res, next) => {
|
||||
try {
|
||||
const companies = await Company.findAll({
|
||||
attributes: ['id', 'name', 'total_tokens', 'total_clicks', 'click_rate'],
|
||||
order: [['name', 'ASC']],
|
||||
});
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: companies,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = exports;
|
||||
|
||||
72
backend/src/controllers/template.controller.js
Normal file
72
backend/src/controllers/template.controller.js
Normal file
@@ -0,0 +1,72 @@
|
||||
const { MailTemplate } = require('../models');
|
||||
const mailService = require('../services/mail.service');
|
||||
|
||||
// Get all templates
|
||||
exports.getAllTemplates = async (req, res, next) => {
|
||||
try {
|
||||
const templates = await MailTemplate.findAll({
|
||||
order: [['created_at', 'DESC']],
|
||||
});
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: templates,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
// Get template by type
|
||||
exports.getTemplateByType = async (req, res, next) => {
|
||||
try {
|
||||
const { type } = req.params;
|
||||
|
||||
const template = await MailTemplate.findOne({
|
||||
where: { template_type: type },
|
||||
});
|
||||
|
||||
if (!template) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
error: 'Template not found',
|
||||
});
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: template,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
// Preview template
|
||||
exports.previewTemplate = async (req, res, next) => {
|
||||
try {
|
||||
const { template_html, company_name, employee_name } = req.body;
|
||||
|
||||
const data = {
|
||||
company_name: company_name || 'Örnek Şirket',
|
||||
employee_name: employee_name || null,
|
||||
tracking_url: 'https://example.com/t/preview-token',
|
||||
current_date: new Date().toLocaleDateString('tr-TR'),
|
||||
current_year: new Date().getFullYear(),
|
||||
};
|
||||
|
||||
const rendered = mailService.renderTemplate(template_html, data);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: {
|
||||
rendered_html: rendered,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = exports;
|
||||
|
||||
239
backend/src/controllers/token.controller.js
Normal file
239
backend/src/controllers/token.controller.js
Normal file
@@ -0,0 +1,239 @@
|
||||
const { TrackingToken, Company, ClickLog } = require('../models');
|
||||
const tokenService = require('../services/token.service');
|
||||
const logger = require('../config/logger');
|
||||
|
||||
// Get all tokens
|
||||
exports.getAllTokens = async (req, res, next) => {
|
||||
try {
|
||||
const { company_id, limit = 50, offset = 0 } = req.query;
|
||||
|
||||
const where = {};
|
||||
if (company_id) {
|
||||
where.company_id = company_id;
|
||||
}
|
||||
|
||||
const tokens = await TrackingToken.findAll({
|
||||
where,
|
||||
include: [{ model: Company, as: 'company', attributes: ['id', 'name', 'industry'] }],
|
||||
order: [['created_at', 'DESC']],
|
||||
limit: parseInt(limit),
|
||||
offset: parseInt(offset),
|
||||
});
|
||||
|
||||
const total = await TrackingToken.count({ where });
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: tokens,
|
||||
pagination: {
|
||||
total,
|
||||
limit: parseInt(limit),
|
||||
offset: parseInt(offset),
|
||||
hasMore: parseInt(offset) + parseInt(limit) < total,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
// Get token by ID
|
||||
exports.getTokenById = async (req, res, next) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
const token = await TrackingToken.findByPk(id, {
|
||||
include: [{ model: Company, as: 'company' }],
|
||||
});
|
||||
|
||||
if (!token) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
error: 'Token not found',
|
||||
});
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: token,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
// Create token (without sending mail)
|
||||
exports.createToken = async (req, res, next) => {
|
||||
try {
|
||||
const { company_id, target_email, employee_name, template_type } = req.body;
|
||||
|
||||
const token = await tokenService.createToken({
|
||||
company_id,
|
||||
target_email,
|
||||
employee_name,
|
||||
template_type,
|
||||
});
|
||||
|
||||
const trackingUrl = `${process.env.BASE_URL}/t/${token.token}`;
|
||||
|
||||
res.status(201).json({
|
||||
success: true,
|
||||
message: 'Token created successfully',
|
||||
data: {
|
||||
...token.toJSON(),
|
||||
tracking_url: trackingUrl,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
// Create token and send mail
|
||||
exports.createAndSendToken = async (req, res, next) => {
|
||||
try {
|
||||
const { company_id, target_email, employee_name, template_type } = req.body;
|
||||
|
||||
// Create token
|
||||
const token = await tokenService.createToken({
|
||||
company_id,
|
||||
target_email,
|
||||
employee_name,
|
||||
template_type,
|
||||
});
|
||||
|
||||
// Send mail
|
||||
try {
|
||||
await tokenService.sendMail(token.id);
|
||||
} catch (mailError) {
|
||||
logger.error('Failed to send mail:', mailError);
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
error: 'Token created but failed to send mail',
|
||||
details: mailError.message,
|
||||
token_id: token.id,
|
||||
});
|
||||
}
|
||||
|
||||
const trackingUrl = `${process.env.BASE_URL}/t/${token.token}`;
|
||||
|
||||
res.status(201).json({
|
||||
success: true,
|
||||
message: 'Token created and mail sent successfully',
|
||||
data: {
|
||||
...token.toJSON(),
|
||||
tracking_url: trackingUrl,
|
||||
mail_sent: true,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
// Send mail for existing token
|
||||
exports.sendTokenMail = async (req, res, next) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
await tokenService.sendMail(id);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Mail sent successfully',
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
// Update token
|
||||
exports.updateToken = async (req, res, next) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const { notes } = req.body;
|
||||
|
||||
const token = await TrackingToken.findByPk(id);
|
||||
|
||||
if (!token) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
error: 'Token not found',
|
||||
});
|
||||
}
|
||||
|
||||
await token.update({ notes });
|
||||
|
||||
logger.info(`Token updated: ${id}`);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Token updated successfully',
|
||||
data: token,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
// Delete token
|
||||
exports.deleteToken = async (req, res, next) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
const token = await TrackingToken.findByPk(id);
|
||||
|
||||
if (!token) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
error: 'Token not found',
|
||||
});
|
||||
}
|
||||
|
||||
const companyId = token.company_id;
|
||||
|
||||
await token.destroy();
|
||||
|
||||
// Update company stats
|
||||
await tokenService.updateCompanyStats(companyId);
|
||||
|
||||
logger.info(`Token deleted: ${id}`);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Token deleted successfully',
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
// Get token click logs
|
||||
exports.getTokenClicks = async (req, res, next) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
const token = await TrackingToken.findByPk(id);
|
||||
|
||||
if (!token) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
error: 'Token not found',
|
||||
});
|
||||
}
|
||||
|
||||
const clicks = await ClickLog.findAll({
|
||||
where: { token_id: id },
|
||||
order: [['clicked_at', 'DESC']],
|
||||
});
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: clicks,
|
||||
count: clicks.length,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
111
backend/src/controllers/tracking.controller.js
Normal file
111
backend/src/controllers/tracking.controller.js
Normal file
@@ -0,0 +1,111 @@
|
||||
const { TrackingToken, ClickLog, Company } = require('../models');
|
||||
const { getGeoLocation } = require('../utils/geoip');
|
||||
const { parseUserAgent } = require('../utils/userAgentParser');
|
||||
const telegramService = require('../services/telegram.service');
|
||||
const tokenService = require('../services/token.service');
|
||||
const logger = require('../config/logger');
|
||||
|
||||
exports.trackClick = async (req, res, next) => {
|
||||
try {
|
||||
const { token } = req.params;
|
||||
|
||||
// Find token
|
||||
const trackingToken = await TrackingToken.findOne({
|
||||
where: { token },
|
||||
include: [{ model: Company, as: 'company' }],
|
||||
});
|
||||
|
||||
if (!trackingToken) {
|
||||
logger.warn(`Invalid token accessed: ${token}`);
|
||||
return res.redirect(process.env.BASE_URL || 'https://google.com');
|
||||
}
|
||||
|
||||
// Get IP address
|
||||
const ipAddress = req.headers['x-forwarded-for']?.split(',')[0].trim()
|
||||
|| req.connection.remoteAddress
|
||||
|| req.socket.remoteAddress
|
||||
|| req.ip;
|
||||
|
||||
// Get user agent
|
||||
const userAgent = req.headers['user-agent'] || '';
|
||||
const referer = req.headers['referer'] || req.headers['referrer'] || null;
|
||||
|
||||
// Parse geo location
|
||||
const geoData = getGeoLocation(ipAddress);
|
||||
|
||||
// Parse user agent
|
||||
const uaData = parseUserAgent(userAgent);
|
||||
|
||||
// Create click log
|
||||
const clickLog = await ClickLog.create({
|
||||
token_id: trackingToken.id,
|
||||
ip_address: ipAddress,
|
||||
country: geoData.country,
|
||||
city: geoData.city,
|
||||
latitude: geoData.latitude,
|
||||
longitude: geoData.longitude,
|
||||
user_agent: userAgent,
|
||||
browser: uaData.browser,
|
||||
os: uaData.os,
|
||||
device: uaData.device,
|
||||
referer,
|
||||
});
|
||||
|
||||
// Update token stats
|
||||
const isFirstClick = !trackingToken.clicked;
|
||||
await trackingToken.update({
|
||||
clicked: true,
|
||||
click_count: trackingToken.click_count + 1,
|
||||
first_click_at: isFirstClick ? new Date() : trackingToken.first_click_at,
|
||||
last_click_at: new Date(),
|
||||
});
|
||||
|
||||
// Update company stats
|
||||
await tokenService.updateCompanyStats(trackingToken.company_id);
|
||||
|
||||
// Get updated company for Telegram notification
|
||||
const company = await Company.findByPk(trackingToken.company_id);
|
||||
|
||||
// Send Telegram notification
|
||||
try {
|
||||
const timestamp = new Date().toLocaleString('tr-TR', {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
});
|
||||
|
||||
await telegramService.sendNotification({
|
||||
companyName: company.name,
|
||||
targetEmail: trackingToken.target_email,
|
||||
employeeName: trackingToken.employee_name,
|
||||
ipAddress,
|
||||
country: geoData.country,
|
||||
city: geoData.city,
|
||||
browser: uaData.browser,
|
||||
os: uaData.os,
|
||||
timestamp,
|
||||
clickCount: trackingToken.click_count + 1,
|
||||
companyTotalClicks: company.total_clicks,
|
||||
companyTotalTokens: company.total_tokens,
|
||||
});
|
||||
|
||||
await clickLog.update({ telegram_sent: true });
|
||||
} catch (telegramError) {
|
||||
logger.error('Telegram notification failed:', telegramError);
|
||||
// Don't fail the request if Telegram fails
|
||||
}
|
||||
|
||||
logger.info(`Click tracked: ${token} from ${ipAddress} (${geoData.city}, ${geoData.country})`);
|
||||
|
||||
// Redirect to landing page
|
||||
res.redirect('/landing.html');
|
||||
} catch (error) {
|
||||
logger.error('Tracking error:', error);
|
||||
// Even on error, redirect to something
|
||||
res.redirect(process.env.BASE_URL || 'https://google.com');
|
||||
}
|
||||
};
|
||||
|
||||
25
backend/src/middlewares/auth.js
Normal file
25
backend/src/middlewares/auth.js
Normal file
@@ -0,0 +1,25 @@
|
||||
const requireAuth = (req, res, next) => {
|
||||
if (!req.session || !req.session.userId) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
error: 'Authentication required',
|
||||
});
|
||||
}
|
||||
next();
|
||||
};
|
||||
|
||||
const requireAdmin = (req, res, next) => {
|
||||
if (!req.session || !req.session.userId || !req.session.isAdmin) {
|
||||
return res.status(403).json({
|
||||
success: false,
|
||||
error: 'Admin access required',
|
||||
});
|
||||
}
|
||||
next();
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
requireAuth,
|
||||
requireAdmin,
|
||||
};
|
||||
|
||||
49
backend/src/middlewares/errorHandler.js
Normal file
49
backend/src/middlewares/errorHandler.js
Normal file
@@ -0,0 +1,49 @@
|
||||
const logger = require('../config/logger');
|
||||
|
||||
const errorHandler = (err, req, res, next) => {
|
||||
logger.error('Error:', {
|
||||
message: err.message,
|
||||
stack: err.stack,
|
||||
path: req.path,
|
||||
method: req.method,
|
||||
});
|
||||
|
||||
// Joi validation error
|
||||
if (err.isJoi) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Validation error',
|
||||
details: err.details.map(d => d.message),
|
||||
});
|
||||
}
|
||||
|
||||
// Sequelize errors
|
||||
if (err.name === 'SequelizeValidationError') {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Validation error',
|
||||
details: err.errors.map(e => e.message),
|
||||
});
|
||||
}
|
||||
|
||||
if (err.name === 'SequelizeUniqueConstraintError') {
|
||||
return res.status(409).json({
|
||||
success: false,
|
||||
error: 'Duplicate entry',
|
||||
details: err.errors.map(e => e.message),
|
||||
});
|
||||
}
|
||||
|
||||
// Default error
|
||||
const statusCode = err.statusCode || 500;
|
||||
const message = err.message || 'Internal server error';
|
||||
|
||||
res.status(statusCode).json({
|
||||
success: false,
|
||||
error: message,
|
||||
...(process.env.NODE_ENV === 'development' && { stack: err.stack }),
|
||||
});
|
||||
};
|
||||
|
||||
module.exports = errorHandler;
|
||||
|
||||
44
backend/src/middlewares/rateLimiter.js
Normal file
44
backend/src/middlewares/rateLimiter.js
Normal file
@@ -0,0 +1,44 @@
|
||||
const rateLimit = require('express-rate-limit');
|
||||
|
||||
// General API rate limiter
|
||||
const apiLimiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000, // 15 minutes
|
||||
max: 100, // Limit each IP to 100 requests per windowMs
|
||||
message: {
|
||||
success: false,
|
||||
error: 'Too many requests, please try again later',
|
||||
},
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
});
|
||||
|
||||
// Stricter limiter for auth endpoints
|
||||
const authLimiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000, // 15 minutes
|
||||
max: 5, // Limit each IP to 5 login attempts per windowMs
|
||||
message: {
|
||||
success: false,
|
||||
error: 'Too many login attempts, please try again after 15 minutes',
|
||||
},
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
});
|
||||
|
||||
// Tracking endpoint (public) - more lenient
|
||||
const trackingLimiter = rateLimit({
|
||||
windowMs: 1 * 60 * 1000, // 1 minute
|
||||
max: 10, // 10 requests per minute per IP
|
||||
message: {
|
||||
success: false,
|
||||
error: 'Too many requests',
|
||||
},
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
apiLimiter,
|
||||
authLimiter,
|
||||
trackingLimiter,
|
||||
};
|
||||
|
||||
38
backend/src/models/AdminUser.js
Normal file
38
backend/src/models/AdminUser.js
Normal file
@@ -0,0 +1,38 @@
|
||||
const { DataTypes } = require('sequelize');
|
||||
const { sequelize } = require('../config/database');
|
||||
|
||||
const AdminUser = sequelize.define('AdminUser', {
|
||||
id: {
|
||||
type: DataTypes.INTEGER,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
validate: {
|
||||
isOne(value) {
|
||||
if (value !== 1) {
|
||||
throw new Error('Only one admin user is allowed (id must be 1)');
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
username: {
|
||||
type: DataTypes.STRING(100),
|
||||
allowNull: false,
|
||||
unique: true,
|
||||
},
|
||||
password_hash: {
|
||||
type: DataTypes.STRING(255),
|
||||
allowNull: false,
|
||||
},
|
||||
last_login: {
|
||||
type: DataTypes.DATE,
|
||||
allowNull: true,
|
||||
},
|
||||
}, {
|
||||
tableName: 'admin_user',
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
});
|
||||
|
||||
module.exports = AdminUser;
|
||||
|
||||
71
backend/src/models/ClickLog.js
Normal file
71
backend/src/models/ClickLog.js
Normal file
@@ -0,0 +1,71 @@
|
||||
const { DataTypes } = require('sequelize');
|
||||
const { sequelize } = require('../config/database');
|
||||
|
||||
const ClickLog = sequelize.define('ClickLog', {
|
||||
id: {
|
||||
type: DataTypes.INTEGER,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
},
|
||||
token_id: {
|
||||
type: DataTypes.INTEGER,
|
||||
allowNull: false,
|
||||
comment: 'FK -> tracking_tokens.id',
|
||||
},
|
||||
ip_address: {
|
||||
type: DataTypes.STRING(45),
|
||||
allowNull: false,
|
||||
},
|
||||
country: {
|
||||
type: DataTypes.STRING(100),
|
||||
allowNull: true,
|
||||
},
|
||||
city: {
|
||||
type: DataTypes.STRING(100),
|
||||
allowNull: true,
|
||||
},
|
||||
latitude: {
|
||||
type: DataTypes.DECIMAL(10, 8),
|
||||
allowNull: true,
|
||||
},
|
||||
longitude: {
|
||||
type: DataTypes.DECIMAL(11, 8),
|
||||
allowNull: true,
|
||||
},
|
||||
user_agent: {
|
||||
type: DataTypes.TEXT,
|
||||
allowNull: true,
|
||||
},
|
||||
browser: {
|
||||
type: DataTypes.STRING(100),
|
||||
allowNull: true,
|
||||
},
|
||||
os: {
|
||||
type: DataTypes.STRING(100),
|
||||
allowNull: true,
|
||||
},
|
||||
device: {
|
||||
type: DataTypes.STRING(100),
|
||||
allowNull: true,
|
||||
},
|
||||
referer: {
|
||||
type: DataTypes.TEXT,
|
||||
allowNull: true,
|
||||
},
|
||||
telegram_sent: {
|
||||
type: DataTypes.BOOLEAN,
|
||||
defaultValue: false,
|
||||
},
|
||||
}, {
|
||||
tableName: 'click_logs',
|
||||
timestamps: true,
|
||||
createdAt: 'clicked_at',
|
||||
updatedAt: false,
|
||||
indexes: [
|
||||
{ fields: ['token_id'] },
|
||||
{ fields: ['ip_address'] },
|
||||
],
|
||||
});
|
||||
|
||||
module.exports = ClickLog;
|
||||
|
||||
56
backend/src/models/Company.js
Normal file
56
backend/src/models/Company.js
Normal file
@@ -0,0 +1,56 @@
|
||||
const { DataTypes } = require('sequelize');
|
||||
const { sequelize } = require('../config/database');
|
||||
|
||||
const Company = sequelize.define('Company', {
|
||||
id: {
|
||||
type: DataTypes.INTEGER,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
},
|
||||
name: {
|
||||
type: DataTypes.STRING(255),
|
||||
allowNull: false,
|
||||
validate: {
|
||||
notEmpty: true,
|
||||
},
|
||||
},
|
||||
description: {
|
||||
type: DataTypes.TEXT,
|
||||
allowNull: true,
|
||||
},
|
||||
logo_url: {
|
||||
type: DataTypes.TEXT,
|
||||
allowNull: true,
|
||||
},
|
||||
industry: {
|
||||
type: DataTypes.STRING(100),
|
||||
allowNull: true,
|
||||
comment: 'Sektör: Banking, Telecom, Government, etc.',
|
||||
},
|
||||
active: {
|
||||
type: DataTypes.BOOLEAN,
|
||||
defaultValue: true,
|
||||
},
|
||||
// İstatistikler (denormalized)
|
||||
total_tokens: {
|
||||
type: DataTypes.INTEGER,
|
||||
defaultValue: 0,
|
||||
},
|
||||
total_clicks: {
|
||||
type: DataTypes.INTEGER,
|
||||
defaultValue: 0,
|
||||
},
|
||||
click_rate: {
|
||||
type: DataTypes.DECIMAL(5, 2),
|
||||
defaultValue: 0,
|
||||
comment: 'Tıklama oranı %',
|
||||
},
|
||||
}, {
|
||||
tableName: 'companies',
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
});
|
||||
|
||||
module.exports = Company;
|
||||
|
||||
48
backend/src/models/MailTemplate.js
Normal file
48
backend/src/models/MailTemplate.js
Normal file
@@ -0,0 +1,48 @@
|
||||
const { DataTypes } = require('sequelize');
|
||||
const { sequelize } = require('../config/database');
|
||||
|
||||
const MailTemplate = sequelize.define('MailTemplate', {
|
||||
id: {
|
||||
type: DataTypes.INTEGER,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
},
|
||||
name: {
|
||||
type: DataTypes.STRING(255),
|
||||
allowNull: false,
|
||||
},
|
||||
template_type: {
|
||||
type: DataTypes.STRING(50),
|
||||
allowNull: false,
|
||||
unique: true,
|
||||
comment: 'bank, edevlet, corporate, etc.',
|
||||
},
|
||||
subject_template: {
|
||||
type: DataTypes.STRING(500),
|
||||
allowNull: true,
|
||||
},
|
||||
body_html: {
|
||||
type: DataTypes.TEXT,
|
||||
allowNull: false,
|
||||
},
|
||||
description: {
|
||||
type: DataTypes.TEXT,
|
||||
allowNull: true,
|
||||
},
|
||||
preview_image: {
|
||||
type: DataTypes.TEXT,
|
||||
allowNull: true,
|
||||
},
|
||||
active: {
|
||||
type: DataTypes.BOOLEAN,
|
||||
defaultValue: true,
|
||||
},
|
||||
}, {
|
||||
tableName: 'mail_templates',
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
});
|
||||
|
||||
module.exports = MailTemplate;
|
||||
|
||||
36
backend/src/models/Settings.js
Normal file
36
backend/src/models/Settings.js
Normal file
@@ -0,0 +1,36 @@
|
||||
const { DataTypes } = require('sequelize');
|
||||
const { sequelize } = require('../config/database');
|
||||
|
||||
const Settings = sequelize.define('Settings', {
|
||||
id: {
|
||||
type: DataTypes.INTEGER,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
},
|
||||
key: {
|
||||
type: DataTypes.STRING(100),
|
||||
allowNull: false,
|
||||
unique: true,
|
||||
comment: 'gmail_user, telegram_token, etc.',
|
||||
},
|
||||
value: {
|
||||
type: DataTypes.TEXT,
|
||||
allowNull: true,
|
||||
},
|
||||
is_encrypted: {
|
||||
type: DataTypes.BOOLEAN,
|
||||
defaultValue: false,
|
||||
},
|
||||
description: {
|
||||
type: DataTypes.TEXT,
|
||||
allowNull: true,
|
||||
},
|
||||
}, {
|
||||
tableName: 'settings',
|
||||
timestamps: true,
|
||||
createdAt: false,
|
||||
updatedAt: 'updated_at',
|
||||
});
|
||||
|
||||
module.exports = Settings;
|
||||
|
||||
78
backend/src/models/TrackingToken.js
Normal file
78
backend/src/models/TrackingToken.js
Normal file
@@ -0,0 +1,78 @@
|
||||
const { DataTypes } = require('sequelize');
|
||||
const { sequelize } = require('../config/database');
|
||||
|
||||
const TrackingToken = sequelize.define('TrackingToken', {
|
||||
id: {
|
||||
type: DataTypes.INTEGER,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
},
|
||||
token: {
|
||||
type: DataTypes.STRING(64),
|
||||
allowNull: false,
|
||||
unique: true,
|
||||
comment: 'Benzersiz tracking token (32 byte hex)',
|
||||
},
|
||||
company_id: {
|
||||
type: DataTypes.INTEGER,
|
||||
allowNull: false,
|
||||
comment: 'FK -> companies.id',
|
||||
},
|
||||
target_email: {
|
||||
type: DataTypes.STRING(255),
|
||||
allowNull: false,
|
||||
},
|
||||
employee_name: {
|
||||
type: DataTypes.STRING(255),
|
||||
allowNull: true,
|
||||
},
|
||||
template_type: {
|
||||
type: DataTypes.STRING(50),
|
||||
defaultValue: 'bank',
|
||||
},
|
||||
mail_subject: {
|
||||
type: DataTypes.STRING(500),
|
||||
allowNull: true,
|
||||
},
|
||||
mail_sent: {
|
||||
type: DataTypes.BOOLEAN,
|
||||
defaultValue: false,
|
||||
},
|
||||
sent_at: {
|
||||
type: DataTypes.DATE,
|
||||
allowNull: true,
|
||||
},
|
||||
clicked: {
|
||||
type: DataTypes.BOOLEAN,
|
||||
defaultValue: false,
|
||||
},
|
||||
click_count: {
|
||||
type: DataTypes.INTEGER,
|
||||
defaultValue: 0,
|
||||
},
|
||||
first_click_at: {
|
||||
type: DataTypes.DATE,
|
||||
allowNull: true,
|
||||
},
|
||||
last_click_at: {
|
||||
type: DataTypes.DATE,
|
||||
allowNull: true,
|
||||
},
|
||||
notes: {
|
||||
type: DataTypes.TEXT,
|
||||
allowNull: true,
|
||||
},
|
||||
}, {
|
||||
tableName: 'tracking_tokens',
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: false,
|
||||
indexes: [
|
||||
{ fields: ['token'], unique: true },
|
||||
{ fields: ['company_id'] },
|
||||
{ fields: ['target_email'] },
|
||||
],
|
||||
});
|
||||
|
||||
module.exports = TrackingToken;
|
||||
|
||||
43
backend/src/models/index.js
Normal file
43
backend/src/models/index.js
Normal file
@@ -0,0 +1,43 @@
|
||||
const { sequelize } = require('../config/database');
|
||||
const Company = require('./Company');
|
||||
const TrackingToken = require('./TrackingToken');
|
||||
const ClickLog = require('./ClickLog');
|
||||
const MailTemplate = require('./MailTemplate');
|
||||
const Settings = require('./Settings');
|
||||
const AdminUser = require('./AdminUser');
|
||||
|
||||
// Define relationships
|
||||
|
||||
// Company -> TrackingToken (One-to-Many)
|
||||
Company.hasMany(TrackingToken, {
|
||||
foreignKey: 'company_id',
|
||||
as: 'tokens',
|
||||
onDelete: 'CASCADE',
|
||||
});
|
||||
TrackingToken.belongsTo(Company, {
|
||||
foreignKey: 'company_id',
|
||||
as: 'company',
|
||||
});
|
||||
|
||||
// TrackingToken -> ClickLog (One-to-Many)
|
||||
TrackingToken.hasMany(ClickLog, {
|
||||
foreignKey: 'token_id',
|
||||
as: 'clicks',
|
||||
onDelete: 'CASCADE',
|
||||
});
|
||||
ClickLog.belongsTo(TrackingToken, {
|
||||
foreignKey: 'token_id',
|
||||
as: 'token',
|
||||
});
|
||||
|
||||
// Export models
|
||||
module.exports = {
|
||||
sequelize,
|
||||
Company,
|
||||
TrackingToken,
|
||||
ClickLog,
|
||||
MailTemplate,
|
||||
Settings,
|
||||
AdminUser,
|
||||
};
|
||||
|
||||
176
backend/src/public/landing.html
Normal file
176
backend/src/public/landing.html
Normal file
@@ -0,0 +1,176 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="tr">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Güvenlik Farkındalık Testi</title>
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.container {
|
||||
background: white;
|
||||
border-radius: 20px;
|
||||
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
|
||||
max-width: 600px;
|
||||
padding: 60px 40px;
|
||||
text-align: center;
|
||||
animation: slideIn 0.5s ease-out;
|
||||
}
|
||||
|
||||
@keyframes slideIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(30px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
.icon {
|
||||
font-size: 80px;
|
||||
margin-bottom: 20px;
|
||||
animation: bounce 1s ease infinite;
|
||||
}
|
||||
|
||||
@keyframes bounce {
|
||||
0%, 100% { transform: translateY(0); }
|
||||
50% { transform: translateY(-10px); }
|
||||
}
|
||||
|
||||
h1 {
|
||||
color: #2d3748;
|
||||
font-size: 32px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.highlight {
|
||||
color: #e53e3e;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
p {
|
||||
color: #4a5568;
|
||||
font-size: 18px;
|
||||
line-height: 1.8;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.warning-box {
|
||||
background: #fff5f5;
|
||||
border-left: 4px solid #e53e3e;
|
||||
padding: 20px;
|
||||
margin: 30px 0;
|
||||
text-align: left;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.warning-box h2 {
|
||||
color: #e53e3e;
|
||||
font-size: 20px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.tips {
|
||||
background: #f7fafc;
|
||||
border-radius: 10px;
|
||||
padding: 25px;
|
||||
margin-top: 30px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.tips h3 {
|
||||
color: #2d3748;
|
||||
font-size: 20px;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.tips ul {
|
||||
list-style: none;
|
||||
padding-left: 0;
|
||||
}
|
||||
|
||||
.tips li {
|
||||
color: #4a5568;
|
||||
padding: 10px 0;
|
||||
padding-left: 30px;
|
||||
position: relative;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.tips li:before {
|
||||
content: "✓";
|
||||
position: absolute;
|
||||
left: 0;
|
||||
color: #48bb78;
|
||||
font-weight: bold;
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.footer {
|
||||
margin-top: 40px;
|
||||
padding-top: 20px;
|
||||
border-top: 1px solid #e2e8f0;
|
||||
color: #718096;
|
||||
font-size: 14px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="icon">🛡️</div>
|
||||
|
||||
<h1>Bu Bir <span class="highlight">Güvenlik Farkındalık Testi</span>ydi!</h1>
|
||||
|
||||
<p>
|
||||
Az önce tıkladığınız link, <strong>gerçek bir phishing (oltalama) saldırısı değildi</strong>.
|
||||
Bu, güvenlik farkındalığınızı test etmek için düzenlenen bir simülasyondu.
|
||||
</p>
|
||||
|
||||
<div class="warning-box">
|
||||
<h2>⚠️ Önemli Bilgi</h2>
|
||||
<p>
|
||||
Gerçek bir saldırı olsaydı, bu tıklama sonucunda:
|
||||
</p>
|
||||
<ul style="padding-left: 20px; margin-top: 10px;">
|
||||
<li>Kişisel bilgileriniz çalınabilirdi</li>
|
||||
<li>Hesap şifreleriniz ele geçirilebilirdi</li>
|
||||
<li>Cihazınıza zararlı yazılım bulaşabilirdi</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="tips">
|
||||
<h3>🔐 Kendinizi Nasıl Korursunuz?</h3>
|
||||
<ul>
|
||||
<li>E-postaları dikkatlice inceleyin</li>
|
||||
<li>Gönderen adresini kontrol edin</li>
|
||||
<li>Şüpheli linklere tıklamayın</li>
|
||||
<li>İki faktörlü kimlik doğrulama kullanın</li>
|
||||
<li>Düzenli şifre güncellemesi yapın</li>
|
||||
<li>Resmi kanallardan doğrulama yapın</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="footer">
|
||||
<p>Bu test, siber güvenlik farkındalığınızı artırmak amacıyla yapılmıştır.</p>
|
||||
<p><strong>Toplanan bilgiler:</strong> IP adresi, konum, cihaz bilgileri (sadece eğitim amaçlı)</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
17
backend/src/routes/auth.routes.js
Normal file
17
backend/src/routes/auth.routes.js
Normal file
@@ -0,0 +1,17 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const authController = require('../controllers/auth.controller');
|
||||
const { validateLogin } = require('../validators/auth.validator');
|
||||
const { requireAuth } = require('../middlewares/auth');
|
||||
const { authLimiter } = require('../middlewares/rateLimiter');
|
||||
|
||||
// Public routes
|
||||
router.post('/login', authLimiter, validateLogin, authController.login);
|
||||
router.get('/check', authController.checkAuth);
|
||||
|
||||
// Protected routes
|
||||
router.post('/logout', requireAuth, authController.logout);
|
||||
router.get('/me', requireAuth, authController.me);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
22
backend/src/routes/company.routes.js
Normal file
22
backend/src/routes/company.routes.js
Normal file
@@ -0,0 +1,22 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const companyController = require('../controllers/company.controller');
|
||||
const { validateCreateCompany, validateUpdateCompany } = require('../validators/company.validator');
|
||||
const { requireAuth } = require('../middlewares/auth');
|
||||
|
||||
// All company routes require authentication
|
||||
router.use(requireAuth);
|
||||
|
||||
// Company CRUD
|
||||
router.get('/', companyController.getAllCompanies);
|
||||
router.post('/', validateCreateCompany, companyController.createCompany);
|
||||
router.get('/:id', companyController.getCompanyById);
|
||||
router.put('/:id', validateUpdateCompany, companyController.updateCompany);
|
||||
router.delete('/:id', companyController.deleteCompany);
|
||||
|
||||
// Company-specific endpoints
|
||||
router.get('/:id/tokens', companyController.getCompanyTokens);
|
||||
router.get('/:id/stats', companyController.getCompanyStats);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
16
backend/src/routes/settings.routes.js
Normal file
16
backend/src/routes/settings.routes.js
Normal file
@@ -0,0 +1,16 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const settingsController = require('../controllers/settings.controller');
|
||||
const { requireAuth } = require('../middlewares/auth');
|
||||
|
||||
// All settings routes require authentication
|
||||
router.use(requireAuth);
|
||||
|
||||
router.get('/', settingsController.getAllSettings);
|
||||
router.put('/gmail', settingsController.updateGmailSettings);
|
||||
router.put('/telegram', settingsController.updateTelegramSettings);
|
||||
router.post('/test-gmail', settingsController.testGmail);
|
||||
router.post('/test-telegram', settingsController.testTelegram);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
14
backend/src/routes/stats.routes.js
Normal file
14
backend/src/routes/stats.routes.js
Normal file
@@ -0,0 +1,14 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const statsController = require('../controllers/stats.controller');
|
||||
const { requireAuth } = require('../middlewares/auth');
|
||||
|
||||
// All stats routes require authentication
|
||||
router.use(requireAuth);
|
||||
|
||||
router.get('/dashboard', statsController.getDashboardStats);
|
||||
router.get('/recent-clicks', statsController.getRecentClicks);
|
||||
router.get('/by-company', statsController.getCompanyBasedStats);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
14
backend/src/routes/template.routes.js
Normal file
14
backend/src/routes/template.routes.js
Normal file
@@ -0,0 +1,14 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const templateController = require('../controllers/template.controller');
|
||||
const { requireAuth } = require('../middlewares/auth');
|
||||
|
||||
// All template routes require authentication
|
||||
router.use(requireAuth);
|
||||
|
||||
router.get('/', templateController.getAllTemplates);
|
||||
router.get('/:type', templateController.getTemplateByType);
|
||||
router.post('/preview', templateController.previewTemplate);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
23
backend/src/routes/token.routes.js
Normal file
23
backend/src/routes/token.routes.js
Normal file
@@ -0,0 +1,23 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const tokenController = require('../controllers/token.controller');
|
||||
const { validateCreateToken, validateUpdateToken } = require('../validators/token.validator');
|
||||
const { requireAuth } = require('../middlewares/auth');
|
||||
|
||||
// All token routes require authentication
|
||||
router.use(requireAuth);
|
||||
|
||||
// Token CRUD
|
||||
router.get('/', tokenController.getAllTokens);
|
||||
router.post('/create', validateCreateToken, tokenController.createToken);
|
||||
router.post('/create-and-send', validateCreateToken, tokenController.createAndSendToken);
|
||||
router.get('/:id', tokenController.getTokenById);
|
||||
router.put('/:id', validateUpdateToken, tokenController.updateToken);
|
||||
router.delete('/:id', tokenController.deleteToken);
|
||||
|
||||
// Token-specific endpoints
|
||||
router.post('/:id/send', tokenController.sendTokenMail);
|
||||
router.get('/:id/clicks', tokenController.getTokenClicks);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
10
backend/src/routes/tracking.routes.js
Normal file
10
backend/src/routes/tracking.routes.js
Normal file
@@ -0,0 +1,10 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const trackingController = require('../controllers/tracking.controller');
|
||||
const { trackingLimiter } = require('../middlewares/rateLimiter');
|
||||
|
||||
// Public tracking endpoint (no authentication required)
|
||||
router.get('/:token', trackingLimiter, trackingController.trackClick);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
96
backend/src/services/mail.service.js
Normal file
96
backend/src/services/mail.service.js
Normal file
@@ -0,0 +1,96 @@
|
||||
const nodemailer = require('nodemailer');
|
||||
const handlebars = require('handlebars');
|
||||
const logger = require('../config/logger');
|
||||
const { Settings } = require('../models');
|
||||
|
||||
class MailService {
|
||||
constructor() {
|
||||
this.transporter = null;
|
||||
}
|
||||
|
||||
async initializeTransporter() {
|
||||
try {
|
||||
// Get Gmail settings from database
|
||||
const gmailUser = await Settings.findOne({ where: { key: 'gmail_user' } });
|
||||
const gmailPassword = await Settings.findOne({ where: { key: 'gmail_password' } });
|
||||
const gmailFromName = await Settings.findOne({ where: { key: 'gmail_from_name' } });
|
||||
|
||||
// Fallback to env variables
|
||||
const user = gmailUser?.value || process.env.GMAIL_USER;
|
||||
const pass = gmailPassword?.value || process.env.GMAIL_APP_PASSWORD;
|
||||
const fromName = gmailFromName?.value || process.env.GMAIL_FROM_NAME || 'Güvenlik Ekibi';
|
||||
|
||||
if (!user || !pass) {
|
||||
throw new Error('Gmail credentials not configured');
|
||||
}
|
||||
|
||||
this.transporter = nodemailer.createTransport({
|
||||
service: 'gmail',
|
||||
auth: {
|
||||
user,
|
||||
pass,
|
||||
},
|
||||
});
|
||||
|
||||
this.fromAddress = `"${fromName}" <${user}>`;
|
||||
|
||||
// Verify transporter
|
||||
await this.transporter.verify();
|
||||
logger.info('Mail service initialized successfully');
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
logger.error('Failed to initialize mail service:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async sendMail(to, subject, htmlBody) {
|
||||
try {
|
||||
if (!this.transporter) {
|
||||
await this.initializeTransporter();
|
||||
}
|
||||
|
||||
const mailOptions = {
|
||||
from: this.fromAddress,
|
||||
to,
|
||||
subject,
|
||||
html: htmlBody,
|
||||
};
|
||||
|
||||
const info = await this.transporter.sendMail(mailOptions);
|
||||
|
||||
logger.info(`Mail sent to ${to}: ${info.messageId}`);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
messageId: info.messageId,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error(`Failed to send mail to ${to}:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
renderTemplate(templateHtml, data) {
|
||||
try {
|
||||
const template = handlebars.compile(templateHtml);
|
||||
return template(data);
|
||||
} catch (error) {
|
||||
logger.error('Failed to render template:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async testConnection() {
|
||||
try {
|
||||
await this.initializeTransporter();
|
||||
return { success: true, message: 'Gmail connection successful' };
|
||||
} catch (error) {
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new MailService();
|
||||
|
||||
109
backend/src/services/telegram.service.js
Normal file
109
backend/src/services/telegram.service.js
Normal file
@@ -0,0 +1,109 @@
|
||||
const TelegramBot = require('node-telegram-bot-api');
|
||||
const logger = require('../config/logger');
|
||||
const { Settings } = require('../models');
|
||||
|
||||
class TelegramService {
|
||||
constructor() {
|
||||
this.bot = null;
|
||||
this.chatId = null;
|
||||
}
|
||||
|
||||
async initialize() {
|
||||
try {
|
||||
// Get Telegram settings from database
|
||||
const botToken = await Settings.findOne({ where: { key: 'telegram_bot_token' } });
|
||||
const chatId = await Settings.findOne({ where: { key: 'telegram_chat_id' } });
|
||||
|
||||
// Fallback to env variables
|
||||
const token = botToken?.value || process.env.TELEGRAM_BOT_TOKEN;
|
||||
const chat = chatId?.value || process.env.TELEGRAM_CHAT_ID;
|
||||
|
||||
if (!token || !chat) {
|
||||
throw new Error('Telegram credentials not configured');
|
||||
}
|
||||
|
||||
this.bot = new TelegramBot(token, { polling: false });
|
||||
this.chatId = chat;
|
||||
|
||||
logger.info('Telegram service initialized successfully');
|
||||
return true;
|
||||
} catch (error) {
|
||||
logger.error('Failed to initialize Telegram service:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async sendNotification(data) {
|
||||
try {
|
||||
if (!this.bot) {
|
||||
await this.initialize();
|
||||
}
|
||||
|
||||
const {
|
||||
companyName,
|
||||
targetEmail,
|
||||
employeeName,
|
||||
ipAddress,
|
||||
country,
|
||||
city,
|
||||
browser,
|
||||
os,
|
||||
timestamp,
|
||||
clickCount,
|
||||
companyTotalClicks,
|
||||
companyTotalTokens,
|
||||
} = data;
|
||||
|
||||
const message = `
|
||||
🚨 YENİ TIKLAMA ALGILANDI!
|
||||
|
||||
🏢 Şirket: ${companyName}
|
||||
📧 Hedef: ${targetEmail}
|
||||
${employeeName ? `👤 Çalışan: ${employeeName}` : ''}
|
||||
|
||||
🌍 IP: ${ipAddress}
|
||||
📍 Konum: ${city}, ${country}
|
||||
💻 Cihaz: ${browser} (${os})
|
||||
⏰ Zaman: ${timestamp}
|
||||
|
||||
📊 Bu token için toplam tıklama: ${clickCount}
|
||||
📈 Şirket toplam tıklama: ${companyTotalClicks} (${companyTotalTokens} tokenden)
|
||||
`.trim();
|
||||
|
||||
await this.bot.sendMessage(this.chatId, message);
|
||||
|
||||
logger.info(`Telegram notification sent for ${targetEmail}`);
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
logger.error('Failed to send Telegram notification:', error);
|
||||
// Don't throw error - notification failure shouldn't break tracking
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
}
|
||||
|
||||
async sendTestMessage() {
|
||||
try {
|
||||
if (!this.bot) {
|
||||
await this.initialize();
|
||||
}
|
||||
|
||||
const message = `
|
||||
✅ TEST MESAJI
|
||||
|
||||
Telegram bot başarıyla yapılandırıldı!
|
||||
|
||||
⏰ ${new Date().toLocaleString('tr-TR')}
|
||||
`.trim();
|
||||
|
||||
await this.bot.sendMessage(this.chatId, message);
|
||||
|
||||
return { success: true, message: 'Test message sent successfully' };
|
||||
} catch (error) {
|
||||
logger.error('Failed to send test message:', error);
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new TelegramService();
|
||||
|
||||
146
backend/src/services/token.service.js
Normal file
146
backend/src/services/token.service.js
Normal file
@@ -0,0 +1,146 @@
|
||||
const { TrackingToken, Company, MailTemplate } = require('../models');
|
||||
const { generateTrackingToken } = require('../utils/tokenGenerator');
|
||||
const mailService = require('./mail.service');
|
||||
const logger = require('../config/logger');
|
||||
|
||||
class TokenService {
|
||||
async createToken(data) {
|
||||
const { company_id, target_email, employee_name, template_type } = data;
|
||||
|
||||
// Generate unique token
|
||||
let token = generateTrackingToken();
|
||||
let isUnique = false;
|
||||
let attempts = 0;
|
||||
|
||||
// Ensure token is unique
|
||||
while (!isUnique && attempts < 5) {
|
||||
const existing = await TrackingToken.findOne({ where: { token } });
|
||||
if (!existing) {
|
||||
isUnique = true;
|
||||
} else {
|
||||
token = generateTrackingToken();
|
||||
attempts++;
|
||||
}
|
||||
}
|
||||
|
||||
if (!isUnique) {
|
||||
throw new Error('Failed to generate unique token');
|
||||
}
|
||||
|
||||
// Get company and template
|
||||
const company = await Company.findByPk(company_id);
|
||||
if (!company) {
|
||||
throw new Error('Company not found');
|
||||
}
|
||||
|
||||
const template = await MailTemplate.findOne({ where: { template_type } });
|
||||
if (!template) {
|
||||
throw new Error('Mail template not found');
|
||||
}
|
||||
|
||||
// Create tracking token
|
||||
const trackingToken = await TrackingToken.create({
|
||||
token,
|
||||
company_id,
|
||||
target_email,
|
||||
employee_name,
|
||||
template_type,
|
||||
mail_subject: template.subject_template.replace('{{company_name}}', company.name),
|
||||
});
|
||||
|
||||
// Update company stats
|
||||
await company.increment('total_tokens');
|
||||
|
||||
logger.info(`Token created: ${token} for ${target_email}`);
|
||||
|
||||
return trackingToken;
|
||||
}
|
||||
|
||||
async sendMail(tokenId) {
|
||||
const token = await TrackingToken.findByPk(tokenId, {
|
||||
include: [{ model: Company, as: 'company' }],
|
||||
});
|
||||
|
||||
if (!token) {
|
||||
throw new Error('Token not found');
|
||||
}
|
||||
|
||||
if (token.mail_sent) {
|
||||
throw new Error('Mail already sent for this token');
|
||||
}
|
||||
|
||||
// Get mail template
|
||||
const template = await MailTemplate.findOne({
|
||||
where: { template_type: token.template_type },
|
||||
});
|
||||
|
||||
if (!template) {
|
||||
throw new Error('Mail template not found');
|
||||
}
|
||||
|
||||
// Prepare template data
|
||||
const trackingUrl = `${process.env.BASE_URL}/t/${token.token}`;
|
||||
const currentDate = new Date().toLocaleDateString('tr-TR', {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
});
|
||||
const currentYear = new Date().getFullYear();
|
||||
|
||||
const templateData = {
|
||||
company_name: token.company.name,
|
||||
employee_name: token.employee_name,
|
||||
tracking_url: trackingUrl,
|
||||
current_date: currentDate,
|
||||
current_year: currentYear,
|
||||
};
|
||||
|
||||
// Render mail body
|
||||
const htmlBody = mailService.renderTemplate(template.body_html, templateData);
|
||||
const subject = mailService.renderTemplate(template.subject_template, templateData);
|
||||
|
||||
// Send mail
|
||||
await mailService.sendMail(token.target_email, subject, htmlBody);
|
||||
|
||||
// Update token
|
||||
await token.update({
|
||||
mail_sent: true,
|
||||
sent_at: new Date(),
|
||||
});
|
||||
|
||||
logger.info(`Mail sent for token: ${token.token} to ${token.target_email}`);
|
||||
|
||||
return token;
|
||||
}
|
||||
|
||||
async updateCompanyStats(companyId) {
|
||||
const company = await Company.findByPk(companyId);
|
||||
if (!company) return;
|
||||
|
||||
// Count tokens
|
||||
const totalTokens = await TrackingToken.count({
|
||||
where: { company_id: companyId },
|
||||
});
|
||||
|
||||
const clickedTokens = await TrackingToken.count({
|
||||
where: { company_id: companyId, clicked: true },
|
||||
});
|
||||
|
||||
const totalClicks = await TrackingToken.sum('click_count', {
|
||||
where: { company_id: companyId },
|
||||
});
|
||||
|
||||
const clickRate = totalTokens > 0 ? ((clickedTokens / totalTokens) * 100).toFixed(2) : 0;
|
||||
|
||||
await company.update({
|
||||
total_tokens: totalTokens,
|
||||
total_clicks: totalClicks || 0,
|
||||
click_rate: clickRate,
|
||||
});
|
||||
|
||||
logger.info(`Company stats updated for: ${company.name}`);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new TokenService();
|
||||
|
||||
46
backend/src/utils/geoip.js
Normal file
46
backend/src/utils/geoip.js
Normal file
@@ -0,0 +1,46 @@
|
||||
const geoip = require('geoip-lite');
|
||||
|
||||
function getGeoLocation(ip) {
|
||||
try {
|
||||
// Handle localhost
|
||||
if (ip === '::1' || ip === '127.0.0.1' || ip === 'localhost') {
|
||||
return {
|
||||
country: 'Local',
|
||||
city: 'localhost',
|
||||
latitude: null,
|
||||
longitude: null,
|
||||
};
|
||||
}
|
||||
|
||||
const geo = geoip.lookup(ip);
|
||||
|
||||
if (!geo) {
|
||||
return {
|
||||
country: 'Unknown',
|
||||
city: 'Unknown',
|
||||
latitude: null,
|
||||
longitude: null,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
country: geo.country || 'Unknown',
|
||||
city: geo.city || 'Unknown',
|
||||
latitude: geo.ll ? geo.ll[0] : null,
|
||||
longitude: geo.ll ? geo.ll[1] : null,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('GeoIP lookup error:', error);
|
||||
return {
|
||||
country: 'Unknown',
|
||||
city: 'Unknown',
|
||||
latitude: null,
|
||||
longitude: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getGeoLocation,
|
||||
};
|
||||
|
||||
21
backend/src/utils/tokenGenerator.js
Normal file
21
backend/src/utils/tokenGenerator.js
Normal file
@@ -0,0 +1,21 @@
|
||||
const crypto = require('crypto');
|
||||
|
||||
/**
|
||||
* Generate a unique tracking token (32 bytes = 64 hex characters)
|
||||
*/
|
||||
function generateTrackingToken() {
|
||||
return crypto.randomBytes(32).toString('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a secure random string
|
||||
*/
|
||||
function generateSecureString(length = 32) {
|
||||
return crypto.randomBytes(Math.ceil(length / 2)).toString('hex').slice(0, length);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
generateTrackingToken,
|
||||
generateSecureString,
|
||||
};
|
||||
|
||||
33
backend/src/utils/userAgentParser.js
Normal file
33
backend/src/utils/userAgentParser.js
Normal file
@@ -0,0 +1,33 @@
|
||||
const useragent = require('useragent');
|
||||
|
||||
function parseUserAgent(uaString) {
|
||||
try {
|
||||
if (!uaString) {
|
||||
return {
|
||||
browser: 'Unknown',
|
||||
os: 'Unknown',
|
||||
device: 'Unknown',
|
||||
};
|
||||
}
|
||||
|
||||
const agent = useragent.parse(uaString);
|
||||
|
||||
return {
|
||||
browser: `${agent.toAgent()} ${agent.major || ''}`.trim(),
|
||||
os: agent.os.toString(),
|
||||
device: agent.device.toString() || 'Desktop',
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('User-Agent parsing error:', error);
|
||||
return {
|
||||
browser: 'Unknown',
|
||||
os: 'Unknown',
|
||||
device: 'Unknown',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
parseUserAgent,
|
||||
};
|
||||
|
||||
41
backend/src/validators/auth.validator.js
Normal file
41
backend/src/validators/auth.validator.js
Normal file
@@ -0,0 +1,41 @@
|
||||
const Joi = require('joi');
|
||||
|
||||
const loginSchema = Joi.object({
|
||||
username: Joi.string()
|
||||
.min(3)
|
||||
.max(100)
|
||||
.required()
|
||||
.messages({
|
||||
'string.empty': 'Username is required',
|
||||
'string.min': 'Username must be at least 3 characters',
|
||||
'string.max': 'Username must not exceed 100 characters',
|
||||
}),
|
||||
password: Joi.string()
|
||||
.min(6)
|
||||
.required()
|
||||
.messages({
|
||||
'string.empty': 'Password is required',
|
||||
'string.min': 'Password must be at least 6 characters',
|
||||
}),
|
||||
});
|
||||
|
||||
const validate = (schema) => {
|
||||
return (req, res, next) => {
|
||||
const { error } = schema.validate(req.body, { abortEarly: false });
|
||||
|
||||
if (error) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Validation error',
|
||||
details: error.details.map(d => d.message),
|
||||
});
|
||||
}
|
||||
|
||||
next();
|
||||
};
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
validateLogin: validate(loginSchema),
|
||||
};
|
||||
|
||||
67
backend/src/validators/company.validator.js
Normal file
67
backend/src/validators/company.validator.js
Normal file
@@ -0,0 +1,67 @@
|
||||
const Joi = require('joi');
|
||||
|
||||
const createCompanySchema = Joi.object({
|
||||
name: Joi.string()
|
||||
.min(2)
|
||||
.max(255)
|
||||
.required()
|
||||
.messages({
|
||||
'string.empty': 'Company name is required',
|
||||
'string.min': 'Company name must be at least 2 characters',
|
||||
}),
|
||||
description: Joi.string()
|
||||
.max(1000)
|
||||
.allow(null, '')
|
||||
.optional(),
|
||||
logo_url: Joi.string()
|
||||
.uri()
|
||||
.allow(null, '')
|
||||
.optional(),
|
||||
industry: Joi.string()
|
||||
.max(100)
|
||||
.allow(null, '')
|
||||
.optional(),
|
||||
});
|
||||
|
||||
const updateCompanySchema = Joi.object({
|
||||
name: Joi.string()
|
||||
.min(2)
|
||||
.max(255)
|
||||
.optional(),
|
||||
description: Joi.string()
|
||||
.max(1000)
|
||||
.allow(null, '')
|
||||
.optional(),
|
||||
logo_url: Joi.string()
|
||||
.uri()
|
||||
.allow(null, '')
|
||||
.optional(),
|
||||
industry: Joi.string()
|
||||
.max(100)
|
||||
.allow(null, '')
|
||||
.optional(),
|
||||
active: Joi.boolean()
|
||||
.optional(),
|
||||
});
|
||||
|
||||
const validate = (schema) => {
|
||||
return (req, res, next) => {
|
||||
const { error } = schema.validate(req.body, { abortEarly: false });
|
||||
|
||||
if (error) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Validation error',
|
||||
details: error.details.map(d => d.message),
|
||||
});
|
||||
}
|
||||
|
||||
next();
|
||||
};
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
validateCreateCompany: validate(createCompanySchema),
|
||||
validateUpdateCompany: validate(updateCompanySchema),
|
||||
};
|
||||
|
||||
59
backend/src/validators/token.validator.js
Normal file
59
backend/src/validators/token.validator.js
Normal file
@@ -0,0 +1,59 @@
|
||||
const Joi = require('joi');
|
||||
|
||||
const createTokenSchema = Joi.object({
|
||||
company_id: Joi.number()
|
||||
.integer()
|
||||
.positive()
|
||||
.required()
|
||||
.messages({
|
||||
'number.base': 'Company ID must be a number',
|
||||
'any.required': 'Company ID is required',
|
||||
}),
|
||||
target_email: Joi.string()
|
||||
.email()
|
||||
.required()
|
||||
.messages({
|
||||
'string.email': 'Valid email is required',
|
||||
'any.required': 'Target email is required',
|
||||
}),
|
||||
employee_name: Joi.string()
|
||||
.max(255)
|
||||
.allow(null, '')
|
||||
.optional(),
|
||||
template_type: Joi.string()
|
||||
.max(50)
|
||||
.default('bank')
|
||||
.required()
|
||||
.messages({
|
||||
'any.required': 'Template type is required',
|
||||
}),
|
||||
});
|
||||
|
||||
const updateTokenSchema = Joi.object({
|
||||
notes: Joi.string()
|
||||
.max(1000)
|
||||
.allow(null, '')
|
||||
.optional(),
|
||||
});
|
||||
|
||||
const validate = (schema) => {
|
||||
return (req, res, next) => {
|
||||
const { error } = schema.validate(req.body, { abortEarly: false });
|
||||
|
||||
if (error) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Validation error',
|
||||
details: error.details.map(d => d.message),
|
||||
});
|
||||
}
|
||||
|
||||
next();
|
||||
};
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
validateCreateToken: validate(createTokenSchema),
|
||||
validateUpdateToken: validate(updateTokenSchema),
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user