Oranblock commited on
Commit
1868937
·
verified ·
1 Parent(s): fb780d9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -93
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  from flask import Flask, render_template, request, jsonify, session
2
  import sqlite3
3
  from datetime import datetime
@@ -14,73 +15,10 @@ logging.basicConfig(level=logging.DEBUG)
14
  otp_code = None
15
  otp_expiration = None
16
 
17
- def init_db():
18
- with sqlite3.connect('database.db') as conn:
19
- cursor = conn.cursor()
20
- cursor.execute('''
21
- CREATE TABLE IF NOT EXISTS sessions (
22
- id INTEGER PRIMARY KEY AUTOINCREMENT,
23
- user_id INTEGER,
24
- start_time TEXT,
25
- end_time TEXT,
26
- script_code TEXT,
27
- rating INTEGER,
28
- comments TEXT,
29
- session_type TEXT,
30
- duration INTEGER
31
- )
32
- ''')
33
- cursor.execute('''
34
- CREATE TABLE IF NOT EXISTS users (
35
- id INTEGER PRIMARY KEY AUTOINCREMENT,
36
- username TEXT UNIQUE,
37
- password TEXT,
38
- is_admin INTEGER DEFAULT 0
39
- )
40
- ''')
41
- cursor.execute('''
42
- CREATE TABLE IF NOT EXISTS tasks (
43
- id INTEGER PRIMARY KEY AUTOINCREMENT,
44
- user_id INTEGER,
45
- description TEXT,
46
- completed INTEGER DEFAULT 0
47
- )
48
- ''')
49
- cursor.execute('''
50
- CREATE TABLE IF NOT EXISTS settings (
51
- id INTEGER PRIMARY KEY AUTOINCREMENT,
52
- user_id INTEGER,
53
- setting_name TEXT,
54
- setting_value TEXT,
55
- UNIQUE(user_id, setting_name)
56
- )
57
- ''')
58
- cursor.execute('''
59
- CREATE TABLE IF NOT EXISTS admin_settings (
60
- setting_name TEXT PRIMARY KEY,
61
- setting_value INTEGER
62
- )
63
- ''')
64
- default_settings = [
65
- ('sound_enabled', 1),
66
- ('notifications_enabled', 1),
67
- ('dark_mode_enabled', 1),
68
- ('task_manager_enabled', 1),
69
- ('statistics_enabled', 1)
70
- ]
71
- cursor.executemany('INSERT OR IGNORE INTO admin_settings (setting_name, setting_value) VALUES (?, ?)', default_settings)
72
- conn.commit()
73
-
74
- def generate_otp():
75
- global otp_code, otp_expiration
76
- otp_code = ''.join(random.choices(string.digits, k=6))
77
- otp_expiration = datetime.now().timestamp() + 300 # OTP valid for 5 minutes
78
-
79
- def validate_otp(input_otp):
80
- global otp_code, otp_expiration
81
- if otp_code and otp_expiration and datetime.now().timestamp() < otp_expiration:
82
- return input_otp == otp_code
83
- return False
84
 
85
  @app.route('/')
86
  def index():
@@ -92,7 +30,7 @@ def start_session():
92
  session_type = request.json.get('session_type')
93
  duration = request.json.get('duration')
94
  user_id = session.get('user_id')
95
- with sqlite3.connect('database.db') as conn:
96
  cursor = conn.cursor()
97
  cursor.execute('INSERT INTO sessions (user_id, start_time, session_type, duration) VALUES (?, ?, ?, ?)',
98
  (user_id, start_time, session_type, duration))
@@ -104,7 +42,7 @@ def start_session():
104
  def end_session():
105
  session_id = request.json.get('session_id')
106
  end_time = datetime.now().isoformat()
107
- with sqlite3.connect('database.db') as conn:
108
  cursor = conn.cursor()
109
  cursor.execute('UPDATE sessions SET end_time = ? WHERE id = ?', (end_time, session_id))
110
  conn.commit()
@@ -114,7 +52,7 @@ def end_session():
114
  def save_script():
115
  session_id = request.json.get('session_id')
116
  script_code = request.json.get('script_code')
117
- with sqlite3.connect('database.db') as conn:
118
  cursor = conn.cursor()
119
  cursor.execute('UPDATE sessions SET script_code = ? WHERE id = ?', (script_code, session_id))
120
  conn.commit()
@@ -123,17 +61,17 @@ def save_script():
123
  @app.route('/scripts', methods=['GET'])
124
  def get_scripts():
125
  user_id = session.get('user_id')
126
- with sqlite3.connect('database.db') as conn:
127
  cursor = conn.cursor()
128
  cursor.execute('SELECT id, start_time, end_time, script_code, rating, comments, session_type, duration FROM sessions WHERE user_id = ?', (user_id,))
129
  scripts = cursor.fetchall()
130
- return jsonify(scripts)
131
 
132
  @app.route('/rate_script', methods=['POST'])
133
  def rate_script():
134
  session_id = request.json.get('session_id')
135
  rating = request.json.get('rating')
136
- with sqlite3.connect('database.db') as conn:
137
  cursor = conn.cursor()
138
  cursor.execute('UPDATE sessions SET rating = ? WHERE id = ?', (rating, session_id))
139
  conn.commit()
@@ -143,7 +81,7 @@ def rate_script():
143
  def comment_script():
144
  session_id = request.json.get('session_id')
145
  comments = request.json.get('comments')
146
- with sqlite3.connect('database.db') as conn:
147
  cursor = conn.cursor()
148
  cursor.execute('UPDATE sessions SET comments = ? WHERE id = ?', (comments, session_id))
149
  conn.commit()
@@ -158,7 +96,7 @@ def generate_otp_route():
158
  def reset_database():
159
  input_otp = request.json.get('otp')
160
  if validate_otp(input_otp):
161
- with sqlite3.connect('database.db') as conn:
162
  cursor = conn.cursor()
163
  cursor.execute('DROP TABLE IF EXISTS sessions')
164
  cursor.execute('DROP TABLE IF EXISTS users')
@@ -177,7 +115,7 @@ def register():
177
  password = request.json.get('password')
178
  hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
179
 
180
- with sqlite3.connect('database.db') as conn:
181
  cursor = conn.cursor()
182
  try:
183
  cursor.execute('INSERT INTO users (username, password) VALUES (?, ?)', (username, hashed_password))
@@ -191,15 +129,15 @@ def login():
191
  username = request.json.get('username')
192
  password = request.json.get('password')
193
 
194
- with sqlite3.connect('database.db') as conn:
195
  cursor = conn.cursor()
196
  cursor.execute('SELECT id, password, is_admin FROM users WHERE username = ?', (username,))
197
  user = cursor.fetchone()
198
 
199
- if user and bcrypt.checkpw(password.encode('utf-8'), user[1]):
200
- session['user_id'] = user[0]
201
- session['is_admin'] = user[2]
202
- return jsonify({'message': 'Login successful', 'is_admin': user[2]}), 200
203
  else:
204
  return jsonify({'error': 'Invalid username or password'}), 401
205
 
@@ -213,7 +151,7 @@ def add_task():
213
  user_id = session.get('user_id')
214
  description = request.json.get('description')
215
 
216
- with sqlite3.connect('database.db') as conn:
217
  cursor = conn.cursor()
218
  cursor.execute('INSERT INTO tasks (user_id, description) VALUES (?, ?)', (user_id, description))
219
  conn.commit()
@@ -225,19 +163,19 @@ def add_task():
225
  def get_tasks():
226
  user_id = session.get('user_id')
227
 
228
- with sqlite3.connect('database.db') as conn:
229
  cursor = conn.cursor()
230
  cursor.execute('SELECT id, description, completed FROM tasks WHERE user_id = ?', (user_id,))
231
  tasks = cursor.fetchall()
232
 
233
- return jsonify([{'id': task[0], 'description': task[1], 'completed': bool(task[2])} for task in tasks])
234
 
235
  @app.route('/update_task', methods=['POST'])
236
  def update_task():
237
  task_id = request.json.get('task_id')
238
  completed = request.json.get('completed')
239
 
240
- with sqlite3.connect('database.db') as conn:
241
  cursor = conn.cursor()
242
  cursor.execute('UPDATE tasks SET completed = ? WHERE id = ?', (completed, task_id))
243
  conn.commit()
@@ -247,7 +185,7 @@ def update_task():
247
  @app.route('/get_settings', methods=['GET'])
248
  def get_settings():
249
  user_id = session.get('user_id')
250
- with sqlite3.connect('database.db') as conn:
251
  cursor = conn.cursor()
252
  cursor.execute('SELECT setting_name, setting_value FROM settings WHERE user_id = ?', (user_id,))
253
  settings = dict(cursor.fetchall())
@@ -259,7 +197,7 @@ def update_settings():
259
  user_id = session.get('user_id')
260
  new_settings = request.json
261
 
262
- with sqlite3.connect('database.db') as conn:
263
  cursor = conn.cursor()
264
  for setting, value in new_settings.items():
265
  cursor.execute('INSERT OR REPLACE INTO settings (user_id, setting_name, setting_value) VALUES (?, ?, ?)',
@@ -272,7 +210,7 @@ def update_settings():
272
  def get_statistics():
273
  user_id = session.get('user_id')
274
 
275
- with sqlite3.connect('database.db') as conn:
276
  cursor = conn.cursor()
277
  cursor.execute('''
278
  SELECT
@@ -285,9 +223,9 @@ def get_statistics():
285
  stats = cursor.fetchone()
286
 
287
  return jsonify({
288
- 'total_sessions': stats[0],
289
- 'total_work_time': stats[1],
290
- 'average_rating': stats[2]
291
  })
292
 
293
  @app.route('/update_admin_settings', methods=['POST'])
@@ -297,7 +235,7 @@ def update_admin_settings():
297
 
298
  settings = request.json
299
 
300
- with sqlite3.connect('database.db') as conn:
301
  cursor = conn.cursor()
302
  for setting, value in settings.items():
303
  cursor.execute('INSERT OR REPLACE INTO admin_settings (setting_name, setting_value) VALUES (?, ?)', (setting, int(value)))
@@ -310,7 +248,7 @@ def get_admin_settings():
310
  if not session.get('is_admin'):
311
  return jsonify({'error': 'Unauthorized'}), 403
312
 
313
- with sqlite3.connect('database.db') as conn:
314
  cursor = conn.cursor()
315
  cursor.execute('SELECT setting_name, setting_value FROM admin_settings')
316
  settings = dict(cursor.fetchall())
 
1
+ import os
2
  from flask import Flask, render_template, request, jsonify, session
3
  import sqlite3
4
  from datetime import datetime
 
15
  otp_code = None
16
  otp_expiration = None
17
 
18
+ def get_db():
19
+ db = sqlite3.connect('database.db')
20
+ db.row_factory = sqlite3.Row
21
+ return db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
  @app.route('/')
24
  def index():
 
30
  session_type = request.json.get('session_type')
31
  duration = request.json.get('duration')
32
  user_id = session.get('user_id')
33
+ with get_db() as conn:
34
  cursor = conn.cursor()
35
  cursor.execute('INSERT INTO sessions (user_id, start_time, session_type, duration) VALUES (?, ?, ?, ?)',
36
  (user_id, start_time, session_type, duration))
 
42
  def end_session():
43
  session_id = request.json.get('session_id')
44
  end_time = datetime.now().isoformat()
45
+ with get_db() as conn:
46
  cursor = conn.cursor()
47
  cursor.execute('UPDATE sessions SET end_time = ? WHERE id = ?', (end_time, session_id))
48
  conn.commit()
 
52
  def save_script():
53
  session_id = request.json.get('session_id')
54
  script_code = request.json.get('script_code')
55
+ with get_db() as conn:
56
  cursor = conn.cursor()
57
  cursor.execute('UPDATE sessions SET script_code = ? WHERE id = ?', (script_code, session_id))
58
  conn.commit()
 
61
  @app.route('/scripts', methods=['GET'])
62
  def get_scripts():
63
  user_id = session.get('user_id')
64
+ with get_db() as conn:
65
  cursor = conn.cursor()
66
  cursor.execute('SELECT id, start_time, end_time, script_code, rating, comments, session_type, duration FROM sessions WHERE user_id = ?', (user_id,))
67
  scripts = cursor.fetchall()
68
+ return jsonify([dict(row) for row in scripts])
69
 
70
  @app.route('/rate_script', methods=['POST'])
71
  def rate_script():
72
  session_id = request.json.get('session_id')
73
  rating = request.json.get('rating')
74
+ with get_db() as conn:
75
  cursor = conn.cursor()
76
  cursor.execute('UPDATE sessions SET rating = ? WHERE id = ?', (rating, session_id))
77
  conn.commit()
 
81
  def comment_script():
82
  session_id = request.json.get('session_id')
83
  comments = request.json.get('comments')
84
+ with get_db() as conn:
85
  cursor = conn.cursor()
86
  cursor.execute('UPDATE sessions SET comments = ? WHERE id = ?', (comments, session_id))
87
  conn.commit()
 
96
  def reset_database():
97
  input_otp = request.json.get('otp')
98
  if validate_otp(input_otp):
99
+ with get_db() as conn:
100
  cursor = conn.cursor()
101
  cursor.execute('DROP TABLE IF EXISTS sessions')
102
  cursor.execute('DROP TABLE IF EXISTS users')
 
115
  password = request.json.get('password')
116
  hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
117
 
118
+ with get_db() as conn:
119
  cursor = conn.cursor()
120
  try:
121
  cursor.execute('INSERT INTO users (username, password) VALUES (?, ?)', (username, hashed_password))
 
129
  username = request.json.get('username')
130
  password = request.json.get('password')
131
 
132
+ with get_db() as conn:
133
  cursor = conn.cursor()
134
  cursor.execute('SELECT id, password, is_admin FROM users WHERE username = ?', (username,))
135
  user = cursor.fetchone()
136
 
137
+ if user and bcrypt.checkpw(password.encode('utf-8'), user['password']):
138
+ session['user_id'] = user['id']
139
+ session['is_admin'] = user['is_admin']
140
+ return jsonify({'message': 'Login successful', 'is_admin': user['is_admin']}), 200
141
  else:
142
  return jsonify({'error': 'Invalid username or password'}), 401
143
 
 
151
  user_id = session.get('user_id')
152
  description = request.json.get('description')
153
 
154
+ with get_db() as conn:
155
  cursor = conn.cursor()
156
  cursor.execute('INSERT INTO tasks (user_id, description) VALUES (?, ?)', (user_id, description))
157
  conn.commit()
 
163
  def get_tasks():
164
  user_id = session.get('user_id')
165
 
166
+ with get_db() as conn:
167
  cursor = conn.cursor()
168
  cursor.execute('SELECT id, description, completed FROM tasks WHERE user_id = ?', (user_id,))
169
  tasks = cursor.fetchall()
170
 
171
+ return jsonify([dict(row) for row in tasks])
172
 
173
  @app.route('/update_task', methods=['POST'])
174
  def update_task():
175
  task_id = request.json.get('task_id')
176
  completed = request.json.get('completed')
177
 
178
+ with get_db() as conn:
179
  cursor = conn.cursor()
180
  cursor.execute('UPDATE tasks SET completed = ? WHERE id = ?', (completed, task_id))
181
  conn.commit()
 
185
  @app.route('/get_settings', methods=['GET'])
186
  def get_settings():
187
  user_id = session.get('user_id')
188
+ with get_db() as conn:
189
  cursor = conn.cursor()
190
  cursor.execute('SELECT setting_name, setting_value FROM settings WHERE user_id = ?', (user_id,))
191
  settings = dict(cursor.fetchall())
 
197
  user_id = session.get('user_id')
198
  new_settings = request.json
199
 
200
+ with get_db() as conn:
201
  cursor = conn.cursor()
202
  for setting, value in new_settings.items():
203
  cursor.execute('INSERT OR REPLACE INTO settings (user_id, setting_name, setting_value) VALUES (?, ?, ?)',
 
210
  def get_statistics():
211
  user_id = session.get('user_id')
212
 
213
+ with get_db() as conn:
214
  cursor = conn.cursor()
215
  cursor.execute('''
216
  SELECT
 
223
  stats = cursor.fetchone()
224
 
225
  return jsonify({
226
+ 'total_sessions': stats['total_sessions'],
227
+ 'total_work_time': stats['total_work_time'],
228
+ 'average_rating': stats['average_rating']
229
  })
230
 
231
  @app.route('/update_admin_settings', methods=['POST'])
 
235
 
236
  settings = request.json
237
 
238
+ with get_db() as conn:
239
  cursor = conn.cursor()
240
  for setting, value in settings.items():
241
  cursor.execute('INSERT OR REPLACE INTO admin_settings (setting_name, setting_value) VALUES (?, ?)', (setting, int(value)))
 
248
  if not session.get('is_admin'):
249
  return jsonify({'error': 'Unauthorized'}), 403
250
 
251
+ with get_db() as conn:
252
  cursor = conn.cursor()
253
  cursor.execute('SELECT setting_name, setting_value FROM admin_settings')
254
  settings = dict(cursor.fetchall())