1919"""
2020
2121def check_apikey (KEY = "" ):
22+ '''
23+ Checks if a given API key is valid and has writing permissions.
24+ If yes it fetches and returns the full name of the user to whom
25+ the key belongs. If not it raises errors accordingly.
26+ '''
2227 # No sense proceeding if the user somehow submitted an empty key...
2328 if KEY == "" :
2429 raise Exception ('You submitted an empty key.' )
@@ -28,11 +33,18 @@ def check_apikey(KEY=""):
2833 "Authorization" : KEY ,
2934 "Content-Type" : "application/json"
3035 }
31- response = requests .get (
32- url = endpoint ,
33- headers = header ,
34- verify = ssl_verification ,
35- )
36+ try :
37+ response = requests .get (
38+ url = endpoint ,
39+ headers = header ,
40+ verify = ssl_verification ,
41+ )
42+ except requests .exceptions .ConnectionError as ce :
43+ if "NewConnectionError" in str (ce ):
44+ raise ConnectionError ("Your eLabFTW server might currently be down." )
45+ else :
46+ raise Exception ("General connection error." )
47+
3648 # Check zero: is the request not accepted by the server?
3749 if response .status_code // 100 == 5 :
3850 raise Exception ("There's a problem on the server. Try asking the sysadmin." )
@@ -48,14 +60,17 @@ def check_apikey(KEY=""):
4860 key_can_write = last_used ['rw' ]
4961 # Last check: is the key read only?
5062 if key_can_write == 0 :
51- raise Exception (f"API key is read-only, not read/write.<br>Please use (eventually create) one with read/write permissions." )
63+ raise PermissionError (f"API key is read-only, not read/write.<br>Please use (eventually create) one with read/write permissions." )
5264
5365 # If AND ONLY IF the key exists, is valid and is not read-only, return user's full name:
5466 endpoint = f"{ API_URL } api/v2/users/me/"
5567 response = requests .get (
5668 url = endpoint ,
5769 headers = header ,
5870 verify = ssl_verification ,
59- )
60- user = response .json ()['fullname' ]
71+ ).json ()
72+ user = {
73+ "fullname" : response .get ("fullname" ),
74+ "userid" : response .get ("userid" )
75+ }
6176 return user
0 commit comments