-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.py
200 lines (167 loc) · 5.65 KB
/
database.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
import sqlite3
import bcrypt
from datetime import datetime
DATABASE = 'startup_platform.db'
def get_db_connection():
try:
conn = sqlite3.connect(DATABASE)
conn.row_factory = sqlite3.Row
return conn
except sqlite3.Error as e:
print(f"Ошибка подключения к БД {e}")
return None
def create_table():
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
nickname TEXT NOT NULL,
email TEXT NOT NULL,
password TEXT NOT NULL,
registration_date DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
role TEXT DEFAULT 'user',
last_active DATETIME,
ip_address TEXT,
city TEXT,
country TEXT,
provider TEXT
)
''')
conn.commit()
conn.close()
def create_startup_table():
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS startups(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
description TEXT NOT NULL,
image_path TEXT,
submission_date DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
user_id INTEGER,
FOREIGN KEY (user_id) REFERENCES users(id)
)
''')
conn.commit()
conn.close()
def create_logs_table():
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
action TEXT,
details TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
''')
conn.commit()
conn.close()
def create_startup_submission_table():
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS startup_submissions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
startup_id INTEGER,
user_id INTEGER,
moderation_status TEXT DEFAULT 'На модерации',
FOREIGN KEY (startup_id) REFERENCES startups(id),
FOREIGN KEY (user_id) REFERENCES users(id)
)
''')
conn.commit()
conn.close()
def log_action(user_id, action, details):
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('''
INSERT INTO logs (user_id, action, details)
VALUES (?, ?, ?)
''', (user_id, action, details))
conn.commit()
conn.close()
def add_user(nickname, email, password, role='user'):
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("SELECT * FROM users where nickname = ?", (nickname,))
existing_nickname = cursor.fetchall()
if existing_nickname:
print("Пользователь с таким ником уже существует.")
conn.close()
return False
cursor.execute("SELECT * FROM users WHERE email = ?", (email,))
existing_email = cursor.fetchone()
if existing_email:
print("Пользователь с таким адресом электронной почты уже существует.")
conn.close()
return False
hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
cursor.execute('''
INSERT INTO users (nickname, email, password, role) VALUES (?, ?, ?, ?)
''', (nickname, email, hashed_password.decode('utf-8'), role))
conn.commit()
conn.close()
return True
def get_user(nickname, password):
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('''
SELECT * FROM users WHERE nickname = ?
''', (nickname,))
user = cursor.fetchone()
conn.close()
if user and bcrypt.checkpw(password.encode('utf-8'), user['password'].encode('utf-8')):
return user
return None
def update_user(user_id, new_nickname=None, new_email=None, new_role=None):
conn = get_db_connection()
cursor = conn.cursor()
update_data = []
query = 'UPDATE users SET'
if new_nickname:
query += ' nickname = ?, '
update_data.append(new_nickname)
if new_email:
query += 'email = ?,'
update_data.append(new_email)
if new_role:
query += 'role = ?,'
update_data.append(new_role)
query = query.rstrip(',')
query += ' WHERE id = ?'
update_data.append(user_id)
cursor.execute(query, tuple(update_data))
conn.commit()
conn.close()
def delete_user(user_id):
try:
user_id = int(user_id)
except ValueError:
print("Ошибка: user_id должен быть целым числом.")
return
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('''
DELETE FROM users
WHERE id = ?
''', (user_id,))
conn.close()
def is_admin(user_id):
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('SELECT role FROM users WHERE id = ?', (user_id,))
user = cursor.fetchone()
conn.close()
return user and user['role'] == 'admin'
def main():
get_db_connection()
create_table()
create_startup_table()
create_logs_table()
create_startup_submission_table()
if __name__ == '__main__':
main()