1
+ import sqlite3
2
+ import os
3
+ import sys
4
+ from colorama import Fore , Style , init
5
+ from config import get_config
6
+
7
+ # Initialize colorama
8
+ init ()
9
+
10
+ # Define emoji and color constants
11
+ EMOJI = {
12
+ 'DB' : '🗄️' ,
13
+ 'UPDATE' : '🔄' ,
14
+ 'SUCCESS' : '✅' ,
15
+ 'ERROR' : '❌' ,
16
+ 'WARN' : '⚠️' ,
17
+ 'INFO' : 'ℹ️' ,
18
+ 'FILE' : '📄' ,
19
+ 'KEY' : '🔐'
20
+ }
21
+
22
+ class CursorAuth :
23
+ def __init__ (self , translator = None ):
24
+ self .translator = translator
25
+
26
+ # Get configuration
27
+ config = get_config (translator )
28
+ if not config :
29
+ print (f"{ Fore .RED } { EMOJI ['ERROR' ]} { self .translator .get ('auth.config_error' ) if self .translator else 'Failed to load configuration' } { Style .RESET_ALL } " )
30
+ sys .exit (1 )
31
+
32
+ # Get path based on operating system
33
+ try :
34
+ if sys .platform == "win32" : # Windows
35
+ if not config .has_section ('WindowsPaths' ):
36
+ raise ValueError ("Windows paths not configured" )
37
+ self .db_path = config .get ('WindowsPaths' , 'sqlite_path' )
38
+
39
+ elif sys .platform == 'linux' : # Linux
40
+ if not config .has_section ('LinuxPaths' ):
41
+ raise ValueError ("Linux paths not configured" )
42
+ self .db_path = config .get ('LinuxPaths' , 'sqlite_path' )
43
+
44
+ elif sys .platform == 'darwin' : # macOS
45
+ if not config .has_section ('MacPaths' ):
46
+ raise ValueError ("macOS paths not configured" )
47
+ self .db_path = config .get ('MacPaths' , 'sqlite_path' )
48
+
49
+ else :
50
+ print (f"{ Fore .RED } { EMOJI ['ERROR' ]} { self .translator .get ('auth.unsupported_platform' ) if self .translator else 'Unsupported platform' } { Style .RESET_ALL } " )
51
+ sys .exit (1 )
52
+
53
+ # Verify if the path exists
54
+ if not os .path .exists (os .path .dirname (self .db_path )):
55
+ raise FileNotFoundError (f"Database directory not found: { os .path .dirname (self .db_path )} " )
56
+
57
+ except Exception as e :
58
+ print (f"{ Fore .RED } { EMOJI ['ERROR' ]} { self .translator .get ('auth.path_error' , error = str (e )) if self .translator else f'Error getting database path: { str (e )} ' } { Style .RESET_ALL } " )
59
+ sys .exit (1 )
60
+
61
+ # Check if the database file exists
62
+ if not os .path .exists (self .db_path ):
63
+ print (f"{ Fore .RED } { EMOJI ['ERROR' ]} { self .translator .get ('auth.db_not_found' , path = self .db_path )} { Style .RESET_ALL } " )
64
+ return
65
+
66
+ # Check file permissions
67
+ if not os .access (self .db_path , os .R_OK | os .W_OK ):
68
+ print (f"{ Fore .RED } { EMOJI ['ERROR' ]} { self .translator .get ('auth.db_permission_error' )} { Style .RESET_ALL } " )
69
+ return
70
+
71
+ try :
72
+ self .conn = sqlite3 .connect (self .db_path )
73
+ print (f"{ Fore .GREEN } { EMOJI ['SUCCESS' ]} { self .translator .get ('auth.connected_to_database' )} { Style .RESET_ALL } " )
74
+ except sqlite3 .Error as e :
75
+ print (f"{ Fore .RED } { EMOJI ['ERROR' ]} { self .translator .get ('auth.db_connection_error' , error = str (e ))} { Style .RESET_ALL } " )
76
+ return
77
+
78
+ def update_auth (self , email = None , access_token = None , refresh_token = None ):
79
+ conn = None
80
+ try :
81
+ # Ensure the directory exists and set the correct permissions
82
+ db_dir = os .path .dirname (self .db_path )
83
+ if not os .path .exists (db_dir ):
84
+ os .makedirs (db_dir , mode = 0o755 , exist_ok = True )
85
+
86
+ # If the database file does not exist, create a new one
87
+ if not os .path .exists (self .db_path ):
88
+ conn = sqlite3 .connect (self .db_path )
89
+ cursor = conn .cursor ()
90
+ cursor .execute ('''
91
+ CREATE TABLE IF NOT EXISTS ItemTable (
92
+ key TEXT PRIMARY KEY,
93
+ value TEXT
94
+ )
95
+ ''' )
96
+ conn .commit ()
97
+ if sys .platform != "win32" :
98
+ os .chmod (self .db_path , 0o644 )
99
+ conn .close ()
100
+
101
+ # Reconnect to the database
102
+ conn = sqlite3 .connect (self .db_path )
103
+ print (f"{ EMOJI ['INFO' ]} { Fore .GREEN } { self .translator .get ('auth.connected_to_database' )} { Style .RESET_ALL } " )
104
+ cursor = conn .cursor ()
105
+
106
+ # Add timeout and other optimization settings
107
+ conn .execute ("PRAGMA busy_timeout = 5000" )
108
+ conn .execute ("PRAGMA journal_mode = WAL" )
109
+ conn .execute ("PRAGMA synchronous = NORMAL" )
110
+
111
+ # Set the key-value pairs to update
112
+ updates = []
113
+
114
+ updates .append (("cursorAuth/cachedSignUpType" , "Auth_0" ))
115
+
116
+ if email is not None :
117
+ updates .append (("cursorAuth/cachedEmail" , email ))
118
+ if access_token is not None :
119
+ updates .append (("cursorAuth/accessToken" , access_token ))
120
+ if refresh_token is not None :
121
+ updates .append (("cursorAuth/refreshToken" , refresh_token ))
122
+
123
+
124
+ # Use transactions to ensure data integrity
125
+ cursor .execute ("BEGIN TRANSACTION" )
126
+ try :
127
+ for key , value in updates :
128
+ # Check if the key exists
129
+ cursor .execute ("SELECT COUNT(*) FROM ItemTable WHERE key = ?" , (key ,))
130
+ if cursor .fetchone ()[0 ] == 0 :
131
+ cursor .execute ("""
132
+ INSERT INTO ItemTable (key, value)
133
+ VALUES (?, ?)
134
+ """ , (key , value ))
135
+ else :
136
+ cursor .execute ("""
137
+ UPDATE ItemTable SET value = ?
138
+ WHERE key = ?
139
+ """ , (value , key ))
140
+ print (f"{ EMOJI ['INFO' ]} { Fore .CYAN } { self .translator .get ('auth.updating_pair' )} { key .split ('/' )[- 1 ]} ...{ Style .RESET_ALL } " )
141
+
142
+ cursor .execute ("COMMIT" )
143
+ print (f"{ EMOJI ['SUCCESS' ]} { Fore .GREEN } { self .translator .get ('auth.database_updated_successfully' )} { Style .RESET_ALL } " )
144
+ return True
145
+
146
+ except Exception as e :
147
+ cursor .execute ("ROLLBACK" )
148
+ raise e
149
+
150
+ except sqlite3 .Error as e :
151
+ print (f"\n { EMOJI ['ERROR' ]} { Fore .RED } { self .translator .get ('auth.database_error' , error = str (e ))} { Style .RESET_ALL } " )
152
+ return False
153
+ except Exception as e :
154
+ print (f"\n { EMOJI ['ERROR' ]} { Fore .RED } { self .translator .get ('auth.an_error_occurred' , error = str (e ))} { Style .RESET_ALL } " )
155
+ return False
156
+ finally :
157
+ if conn :
158
+ conn .close ()
159
+ print (f"{ EMOJI ['DB' ]} { Fore .CYAN } { self .translator .get ('auth.database_connection_closed' )} { Style .RESET_ALL } " )
0 commit comments