22Module for encapsulating Geo Engine authentication
33'''
44
5- from typing import ClassVar , Dict , Optional
5+ from typing import ClassVar , Dict , Optional , Tuple
66from uuid import UUID
77
8+ import os
89import requests as req
910from requests .auth import AuthBase
1011
@@ -35,14 +36,25 @@ class Session:
3536
3637 session : ClassVar [req .Session ] = None
3738
38- def __init__ (self , server_url : str ) -> None :
39+ def __init__ (self , server_url : str , credentials : Tuple [ str , str ] = None ) -> None :
3940 '''
4041 Initialize communication between this library and a Geo Engine instance
42+
43+ if credentials are provided, the session will be authenticated
44+
45+ optional arguments: (email, password) as tuple
46+ optional environment variables: GEOENGINE_EMAIL, GEOENGINE_PASSWORD
4147 '''
4248
43- # TODO: username and password for Pro version
49+ session = None
4450
45- session = req .post (f'{ server_url } /anonymous' ).json ()
51+ if credentials is not None :
52+ session = req .post (f'{ server_url } /login' , json = {"email" : credentials [0 ], "password" : credentials [1 ]}).json ()
53+ elif "GEOENGINE_EMAIL" in os .environ and "GEOENGINE_PASSWORD" in os .environ :
54+ session = req .post (f'{ server_url } /login' ,
55+ json = {"email" : os .environ .get ("GEOENGINE_EMAIL" ), "password" : os .environ .get ("GEOENGINE_PASSWORD" )}).json ()
56+ else :
57+ session = req .post (f'{ server_url } /anonymous' ).json ()
4658
4759 if 'error' in session :
4860 raise GeoEngineException (session )
@@ -87,6 +99,13 @@ def requests_bearer_auth(self) -> BearerAuth:
8799
88100 return BearerAuth (self .__id )
89101
102+ def logout (self ):
103+ '''
104+ Logout the current session
105+ '''
106+
107+ req .post (f'{ self .server_url } /logout' , headers = self .auth_header )
108+
90109
91110def get_session () -> Session :
92111 '''
@@ -101,19 +120,25 @@ def get_session() -> Session:
101120 return Session .session
102121
103122
104- def initialize (server_url : str ) -> None :
123+ def initialize (server_url : str , credentials : Tuple [ str , str ] = None ) -> None :
105124 '''
106125 Initialize communication between this library and a Geo Engine instance
126+
127+ if credentials are provided, the session will be authenticated
128+
129+ optional arugments: (email, password) as tuple
130+ optional environment variables: GEOENGINE_EMAIL, GEOENGINE_PASSWORD
107131 '''
108132
109- Session .session = Session (server_url )
133+ Session .session = Session (server_url , credentials )
110134
111135
112- def reset () -> None :
136+ def reset (logout : bool = True ) -> None :
113137 '''
114138 Resets the current session
115139 '''
116140
117- # TODO: active logout for Pro version
141+ if Session .session is not None and logout :
142+ Session .session .logout ()
118143
119144 Session .session = None
0 commit comments