-
Notifications
You must be signed in to change notification settings - Fork 4
/
models.py
466 lines (401 loc) · 17.3 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
from extensions import db
from flask_login import UserMixin
from datetime import datetime, timedelta
import os
from PIL import Image as PILImage
import smtplib
import boto3
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
from botocore.credentials import Credentials
from botocore.config import Config
import json
import requests
import random
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from urllib.parse import urlencode
class AuthSettings(db.Model):
__tablename__ = 'auth_settings'
id = db.Column(db.Integer, primary_key=True)
regular_auth_enabled = db.Column(db.Boolean, default=True, nullable=False)
google_auth_enabled = db.Column(db.Boolean, default=False, nullable=False)
google_client_id = db.Column(db.String(255))
google_client_secret = db.Column(db.String(255))
created_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
@staticmethod
def get_settings():
"""Get or create auth settings"""
settings = AuthSettings.query.first()
if not settings:
settings = AuthSettings(
regular_auth_enabled=True,
google_auth_enabled=False
)
db.session.add(settings)
db.session.commit()
return settings
class APIProvider(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), unique=True, nullable=False) # e.g. "OpenAI", "Anthropic", "Google Gemini", "Groq"
is_active = db.Column(db.Boolean, default=True)
models = db.relationship('AIModel', backref='provider', lazy=True)
class AIModel(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False) # e.g. "gpt-4o", "claude-3-sonnet", "llama-3.1-8b-instant"
provider_id = db.Column(db.Integer, db.ForeignKey('api_provider.id'), nullable=False)
is_active = db.Column(db.Boolean, default=True)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
class EmailSettings(db.Model):
id = db.Column(db.Integer, primary_key=True)
provider = db.Column(db.String(20), nullable=False) # 'smtp' or 'ses'
is_active = db.Column(db.Boolean, default=False)
# SMTP Settings
smtp_host = db.Column(db.String(255))
smtp_port = db.Column(db.Integer)
smtp_username = db.Column(db.String(255))
smtp_password = db.Column(db.String(255))
smtp_use_tls = db.Column(db.Boolean, default=True)
# Amazon SES Settings
aws_access_key = db.Column(db.String(255))
aws_secret_key = db.Column(db.String(255))
aws_region = db.Column(db.String(50))
# Common Settings
from_email = db.Column(db.String(255))
from_name = db.Column(db.String(255))
# Last test result
last_test_date = db.Column(db.DateTime)
last_test_success = db.Column(db.Boolean)
last_test_message = db.Column(db.Text)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
def _get_ses_endpoint(self):
"""Get the SES endpoint URL for the configured region"""
return f"https://email.{self.aws_region}.amazonaws.com"
def _sign_ses_request(self, request_params):
"""Sign an SES request with AWS Signature Version 4"""
credentials = Credentials(
access_key=self.aws_access_key,
secret_key=self.aws_secret_key
)
endpoint = self._get_ses_endpoint()
request = AWSRequest(
method='POST',
url=endpoint,
data=urlencode(request_params),
headers={
'Content-Type': 'application/x-www-form-urlencoded',
'Host': f"email.{self.aws_region}.amazonaws.com"
}
)
SigV4Auth(credentials, "ses", self.aws_region).add_auth(request)
return dict(request.headers), request.body
def _send_ses_raw(self, request_params):
"""Send a raw SES request with proper v4 signature"""
if not all([self.aws_access_key, self.aws_secret_key, self.aws_region]):
raise ValueError("Missing AWS credentials or region")
headers, body = self._sign_ses_request(request_params)
endpoint = self._get_ses_endpoint()
response = requests.post(
endpoint,
data=body,
headers=headers,
timeout=30
)
if response.status_code != 200:
raise Exception(f"SES request failed: {response.text}")
return response.text
def test_connection(self, test_email):
"""Test email connection with current settings"""
try:
if self.provider == 'smtp':
return self._test_smtp(test_email)
elif self.provider == 'ses':
return self._test_ses(test_email)
return False, "Invalid provider"
except Exception as e:
return False, str(e)
def _test_smtp(self, test_email):
"""Test SMTP connection"""
try:
smtp = smtplib.SMTP(self.smtp_host, self.smtp_port)
if self.smtp_use_tls:
smtp.starttls()
smtp.login(self.smtp_username, self.smtp_password)
msg = MIMEMultipart()
msg['From'] = f"{self.from_name} <{self.from_email}>"
msg['To'] = test_email
msg['Subject'] = "Test Email from Sketch Maker AI"
body = "This is a test email from Sketch Maker AI. If you received this, your email settings are working correctly!"
msg.attach(MIMEText(body, 'plain'))
smtp.send_message(msg)
smtp.quit()
return True, "Test email sent successfully"
except Exception as e:
return False, f"SMTP test failed: {str(e)}"
def _test_ses(self, test_email):
"""Test Amazon SES connection with v4 signature"""
try:
params = {
'Action': 'SendEmail',
'Source': f"{self.from_name} <{self.from_email}>",
'Destination.ToAddresses.member.1': test_email,
'Message.Subject.Data': 'Test Email from Sketch Maker AI',
'Message.Body.Text.Data': 'This is a test email from Sketch Maker AI. If you received this, your SES settings are working correctly!',
'Version': '2010-12-01'
}
response = self._send_ses_raw(params)
return True, "Test email sent successfully"
except Exception as e:
return False, f"SES test failed: {str(e)}"
def send_email(self, to_email, subject, html_content, text_content=None):
"""Send email using configured provider"""
if not self.is_active:
return False, "Email service is not active"
try:
if self.provider == 'smtp':
return self._send_smtp(to_email, subject, html_content, text_content)
elif self.provider == 'ses':
return self._send_ses(to_email, subject, html_content, text_content)
return False, "Invalid provider"
except Exception as e:
return False, str(e)
def _send_smtp(self, to_email, subject, html_content, text_content=None):
"""Send email via SMTP"""
try:
msg = MIMEMultipart('alternative')
msg['From'] = f"{self.from_name} <{self.from_email}>"
msg['To'] = to_email
msg['Subject'] = subject
if text_content:
msg.attach(MIMEText(text_content, 'plain'))
msg.attach(MIMEText(html_content, 'html'))
smtp = smtplib.SMTP(self.smtp_host, self.smtp_port)
if self.smtp_use_tls:
smtp.starttls()
smtp.login(self.smtp_username, self.smtp_password)
smtp.send_message(msg)
smtp.quit()
return True, "Email sent successfully"
except Exception as e:
return False, f"Failed to send email: {str(e)}"
def _send_ses(self, to_email, subject, html_content, text_content=None):
"""Send email via Amazon SES with v4 signature"""
try:
params = {
'Action': 'SendEmail',
'Source': f"{self.from_name} <{self.from_email}>",
'Destination.ToAddresses.member.1': to_email,
'Message.Subject.Data': subject,
'Message.Body.Html.Data': html_content,
'Version': '2010-12-01'
}
if text_content:
params['Message.Body.Text.Data'] = text_content
response = self._send_ses_raw(params)
return True, "Email sent successfully"
except Exception as e:
return False, f"Failed to send email: {str(e)}"
@staticmethod
def get_settings():
"""Get or create email settings"""
settings = EmailSettings.query.first()
if not settings:
settings = EmailSettings(
provider='smtp',
is_active=False,
from_name='Sketch Maker AI',
from_email='[email protected]'
)
db.session.add(settings)
db.session.commit()
return settings
class PasswordResetOTP(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
otp = db.Column(db.String(6), nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
expires_at = db.Column(db.DateTime, nullable=False)
is_used = db.Column(db.Boolean, default=False)
def __init__(self, user_id):
self.user_id = user_id
self.otp = ''.join([str(random.randint(0, 9)) for _ in range(6)])
self.expires_at = datetime.utcnow() + timedelta(minutes=15)
def is_valid(self):
"""Check if OTP is valid and not expired"""
return not self.is_used and datetime.utcnow() <= self.expires_at
def use(self):
"""Mark OTP as used"""
self.is_used = True
db.session.commit()
@staticmethod
def generate_otp(user_id):
"""Generate new OTP for user"""
# Invalidate any existing OTPs
PasswordResetOTP.query.filter_by(
user_id=user_id,
is_used=False
).update({
'is_used': True
})
db.session.commit()
# Create new OTP
otp = PasswordResetOTP(user_id)
db.session.add(otp)
db.session.commit()
return otp
@staticmethod
def verify_otp(user_id, otp_value):
"""Verify OTP for user"""
otp = PasswordResetOTP.query.filter_by(
user_id=user_id,
otp=otp_value,
is_used=False
).first()
if otp and otp.is_valid():
return otp
return None
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password_hash = db.Column(db.String(128), nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
role = db.Column(db.String(20), default='user') # 'superadmin', 'admin' or 'user'
is_active = db.Column(db.Boolean, default=True)
is_approved = db.Column(db.Boolean, default=True) # For manual approval process
images = db.relationship('Image', backref='user', lazy=True)
training_history = db.relationship('TrainingHistory', backref='user', lazy=True)
password_resets = db.relationship('PasswordResetOTP', backref='user', lazy=True)
# API Provider settings
selected_provider_id = db.Column(db.Integer, db.ForeignKey('api_provider.id'))
selected_model_id = db.Column(db.Integer, db.ForeignKey('ai_model.id'))
# API Keys for different providers
openai_api_key = db.Column(db.String(255))
anthropic_api_key = db.Column(db.String(255))
gemini_api_key = db.Column(db.String(255))
groq_api_key = db.Column(db.String(255))
fal_key = db.Column(db.String(255))
# Google OAuth info
google_id = db.Column(db.String(255), unique=True) # For Google OAuth users
def get_api_keys(self):
"""Get user's API keys"""
return {
'openai_api_key': self.openai_api_key,
'anthropic_api_key': self.anthropic_api_key,
'gemini_api_key': self.gemini_api_key,
'groq_api_key': self.groq_api_key,
'fal_key': self.fal_key
}
def get_selected_provider_key(self):
"""Get the API key for the currently selected provider"""
provider = APIProvider.query.get(self.selected_provider_id)
if provider:
if provider.name == 'OpenAI':
return self.openai_api_key
elif provider.name == 'Anthropic':
return self.anthropic_api_key
elif provider.name == 'Google Gemini':
return self.gemini_api_key
elif provider.name == 'Groq':
return self.groq_api_key
return None
def has_required_api_keys(self):
"""Check if user has both required API keys"""
return bool(self.get_selected_provider_key() and self.fal_key)
def is_admin(self):
"""Check if user is an admin or superadmin"""
return self.role in ['admin', 'superadmin']
def is_superadmin(self):
"""Check if user is a superadmin"""
return self.role == 'superadmin'
@staticmethod
def get_first_user():
"""Get the first user in the database"""
return User.query.order_by(User.id.asc()).first()
@staticmethod
def get_total_count():
"""Get total number of users"""
return User.query.count()
@staticmethod
def search_users(query):
"""Search users by username or email"""
return User.query.filter(
(User.username.ilike(f'%{query}%')) |
(User.email.ilike(f'%{query}%'))
).all()
class SystemSettings(db.Model):
id = db.Column(db.Integer, primary_key=True)
require_manual_approval = db.Column(db.Boolean, default=False)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
@staticmethod
def get_settings():
"""Get or create system settings"""
settings = SystemSettings.query.first()
if not settings:
settings = SystemSettings()
db.session.add(settings)
db.session.commit()
return settings
class Image(db.Model):
id = db.Column(db.Integer, primary_key=True)
filename = db.Column(db.String(255), nullable=False)
prompt = db.Column(db.Text, nullable=False)
art_style = db.Column(db.String(100))
width = db.Column(db.Integer)
height = db.Column(db.Integer)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
provider_id = db.Column(db.Integer, db.ForeignKey('api_provider.id'))
model_id = db.Column(db.Integer, db.ForeignKey('ai_model.id'))
@property
def dimensions(self):
return {
'width': self.width,
'height': self.height
}
def get_dimensions(self):
"""Get image dimensions from file if not stored in database"""
if not self.width or not self.height:
try:
filepath = os.path.join('static', 'images', self.filename)
with PILImage.open(filepath) as img:
self.width, self.height = img.size
db.session.commit()
except Exception as e:
print(f"Error getting image dimensions: {str(e)}")
return self.dimensions
@property
def file_path(self):
return os.path.join('static', 'images', self.filename)
def get_url(self, format='png'):
base_filename = os.path.splitext(self.filename)[0]
return f'/static/images/{base_filename}.{format}'
class TrainingHistory(db.Model):
id = db.Column(db.Integer, primary_key=True)
training_id = db.Column(db.String(32), unique=True, nullable=False)
queue_id = db.Column(db.String(100), unique=True) # FAL queue ID
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
trigger_word = db.Column(db.String(100), nullable=False)
status = db.Column(db.String(20), default='pending') # pending, in_progress, completed, failed
logs = db.Column(db.Text)
result = db.Column(db.JSON)
config_url = db.Column(db.String(500))
weights_url = db.Column(db.String(500))
webhook_secret = db.Column(db.String(48)) # For webhook verification
created_at = db.Column(db.DateTime, default=datetime.utcnow)
completed_at = db.Column(db.DateTime)
def to_dict(self):
return {
'training_id': self.training_id,
'queue_id': self.queue_id,
'trigger_word': self.trigger_word,
'status': self.status,
'logs': self.logs,
'config_url': self.config_url,
'weights_url': self.weights_url,
'created_at': self.created_at.isoformat() if self.created_at else None,
'completed_at': self.completed_at.isoformat() if self.completed_at else None,
'result': self.result
}