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
9+ from dotenv import load_dotenv
810import requests as req
911from requests .auth import AuthBase
1012
@@ -35,14 +37,26 @@ class Session:
3537
3638 session : ClassVar [req .Session ] = None
3739
38- def __init__ (self , server_url : str ) -> None :
40+ def __init__ (self , server_url : str , credentials : Tuple [ str , str ] = None ) -> None :
3941 '''
4042 Initialize communication between this library and a Geo Engine instance
43+
44+ if credentials are provided, the session will be authenticated
45+
46+ optional arguments: (email, password) as tuple
47+ optional environment variables: GEOENGINE_EMAIL, GEOENGINE_PASSWORD
4148 '''
4249
43- # TODO: username and password for Pro version
50+ session = None
4451
45- session = req .post (f'{ server_url } /anonymous' ).json ()
52+ if credentials is not None :
53+ session = req .post (f'{ server_url } /login' , json = {"email" : credentials [0 ], "password" : credentials [1 ]}).json ()
54+ elif "GEOENGINE_EMAIL" in os .environ and "GEOENGINE_PASSWORD" in os .environ :
55+ session = req .post (f'{ server_url } /login' ,
56+ json = {"email" : os .environ .get ("GEOENGINE_EMAIL" ),
57+ "password" : os .environ .get ("GEOENGINE_PASSWORD" )}).json ()
58+ else :
59+ session = req .post (f'{ server_url } /anonymous' ).json ()
4660
4761 if 'error' in session :
4862 raise GeoEngineException (session )
@@ -87,6 +101,13 @@ def requests_bearer_auth(self) -> BearerAuth:
87101
88102 return BearerAuth (self .__id )
89103
104+ def logout (self ):
105+ '''
106+ Logout the current session
107+ '''
108+
109+ req .post (f'{ self .server_url } /logout' , headers = self .auth_header )
110+
90111
91112def get_session () -> Session :
92113 '''
@@ -101,19 +122,28 @@ def get_session() -> Session:
101122 return Session .session
102123
103124
104- def initialize (server_url : str ) -> None :
125+ def initialize (server_url : str , credentials : Tuple [ str , str ] = None ) -> None :
105126 '''
106127 Initialize communication between this library and a Geo Engine instance
128+
129+ if credentials are provided, the session will be authenticated
130+
131+ optional arugments: (email, password) as tuple
132+ optional environment variables: GEOENGINE_EMAIL, GEOENGINE_PASSWORD
133+ optional .env file defining: GEOENGINE_EMAIL, GEOENGINE_PASSWORD
107134 '''
108135
109- Session .session = Session (server_url )
136+ load_dotenv ()
137+
138+ Session .session = Session (server_url , credentials )
110139
111140
112- def reset () -> None :
141+ def reset (logout : bool = True ) -> None :
113142 '''
114143 Resets the current session
115144 '''
116145
117- # TODO: active logout for Pro version
146+ if Session .session is not None and logout :
147+ Session .session .logout ()
118148
119149 Session .session = None
0 commit comments