11import json
2- import typing
2+ from typing import Any , Dict , Optional , Set
3+
4+ import cachelib
35
46import flask
57import flask .sessions
810import flask_phpbb3
911import flask_phpbb3 .backends .base
1012
11- import cachelib
1213
13- ANONYMOUS_CACHE_TTL = 3600 * 24
14+ ANONYMOUS_CACHE_TTL : int = 3600 * 24
1415
1516
16- class PhpBB3Session (dict , flask .sessions .SessionMixin ):
17- def __init__ (self ):
18- # type: () -> None
17+ class PhpBB3Session (Dict [str , Any ], flask .sessions .SessionMixin ):
18+ def __init__ (self ) -> None :
1919 # Some session related variables
20- self .modified = False
21- self .new = False
22- self ._read_only_properties = set ([]) # type: set
20+ self .modified : bool = False
21+ self .new : bool = False
22+ self ._read_only_properties : Set [ str ] = set ([])
2323
2424 # Some ACL related things
25- self ._acl = None \
26- # type: typing.Optional[flask_phpbb3.backends.base.UserAcl]
25+ self ._acl : Optional [flask_phpbb3 .backends .base .UserAcl ] = None
2726
2827 # Per request cache
2928 # This should not be cached into session, but per
3029 # request should not be executed multiple times
31- self ._request_cache = {} # type: dict
30+ self ._request_cache : Dict [ str , Any ] = {}
3231
33- def __setitem__ (self , key , value ):
34- # type: (str, typing.Union[str, int]) -> None
35- modified = self .get (key ) != value
32+ def __setitem__ (self , key : str , value : str | int ) -> None :
33+ modified : bool = self .get (key ) != value
3634 super (PhpBB3Session , self ).__setitem__ (key , value )
3735 if key not in self ._read_only_properties :
3836 self .modified |= modified
3937
40- def __delitem__ (self , key ):
41- # type: (str) -> None
38+ def __delitem__ (self , key : str ) -> None :
4239 super (PhpBB3Session , self ).__delitem__ (key )
4340 self .modified = True
4441
4542 @property
46- def _phpbb3 (self ):
47- # type: () -> flask_phpbb3.PhpBB3
48- output = flask .current_app .phpbb3 # type: flask_phpbb3.PhpBB3
43+ def _phpbb3 (self ) -> flask_phpbb3 .PhpBB3 :
44+ output : flask_phpbb3 .PhpBB3 = getattr (flask .current_app , 'phpbb3' )
4945 return output
5046
51- def pop (self , * args , ** kwargs ):
52- # type: (*typing.Any, **typing.Any) -> typing.Any
47+ def pop (self , * args : Any , ** kwargs : Any ) -> Any :
5348 """Wrapper to set modified."""
5449 self .modified = True
5550 return super (PhpBB3Session , self ).pop (* args , ** kwargs )
5651
57- def clear (self ):
58- # type: () -> None
52+ def clear (self ) -> None :
5953 self .modified = True
6054 return super (PhpBB3Session , self ).clear ()
6155
6256 @property
63- def is_authenticated (self ):
64- # type: () -> bool
57+ def is_authenticated (self ) -> bool :
6558 """Helper method to test if user is authenticated."""
6659 user_id = int (self .get ('user_id' , 1 ))
6760 return user_id > 1
6861
69- def is_member (self , group ):
70- # type: (typing.Union[int, str]) -> bool
62+ def is_member (self , group : int | str ) -> bool :
7163 """Tests if user is a member of specified group."""
7264 if isinstance (group , int ):
7365 # Try with default group
@@ -90,24 +82,21 @@ def is_member(self, group):
9082 return False
9183 return output
9284
93- def has_privilege (self , option , forum_id = 0 ):
94- # type: (str, int) -> bool
85+ def has_privilege (self , option : str , forum_id : int = 0 ) -> bool :
9586 """Test if user has global or local (if forum_id is set) privileges."""
9687 if not self ._acl :
9788 self ._acl = self ._phpbb3 .get_user_acl (self ['user_permissions' ])
9889
9990 return self ._acl .has_privilege (option , forum_id )
10091
101- def has_privileges (self , * options , ** kwargs ):
102- # type: (*str, **int) -> bool
92+ def has_privileges (self , * options : str , ** kwargs : int ) -> bool :
10393 forum_id = kwargs .get ('forum_id' , 0 )
10494
10595 if not self ._acl :
10696 self ._acl = self ._phpbb3 .get_user_acl (self ['user_permissions' ])
10797 return self ._acl .has_privileges (* options , forum_id = forum_id )
10898
109- def get_link_hash (self , link ):
110- # type: (str) -> str
99+ def get_link_hash (self , link : str ) -> str :
111100 """Returns link hash."""
112101 if not self .is_authenticated :
113102 return ''
@@ -116,8 +105,7 @@ def get_link_hash(self, link):
116105 return hashlib .sha1 (self ['user_form_salt' ] + link ).hexdigest ()[:8 ]
117106
118107 @property
119- def num_unread_notifications (self ):
120- # type: () -> int
108+ def num_unread_notifications (self ) -> int :
121109 """Returns number of unread notifications."""
122110 if 'num_unread_notifications' not in self ._request_cache :
123111 result = self ._phpbb3 .get_unread_notifications_count (
@@ -140,31 +128,41 @@ class PhpBB3SessionInterface(flask.sessions.SessionInterface):
140128 session_class = PhpBB3Session
141129
142130 @classmethod
143- def _cache (cls , app ):
144- # type: (flask.Flask) -> werkzeug.contrib.cache.BaseCache
145- output = app .phpbb3_cache # type: werkzeug.contrib.cache.BaseCache
131+ def _cache (cls , app : flask .Flask ) -> cachelib .BaseCache :
132+ if not hasattr (app , 'phpbb3_cache' ):
133+ raise ValueError (
134+ 'App not properly configured, phpbb3_cache is missing!'
135+ )
136+ output : cachelib .BaseCache = getattr (app , 'phpbb3_cache' )
146137 return output
147138
148- def _is_bot (self , app , request ):
139+ def _is_bot (
140+ self ,
141+ app : flask .Flask ,
142+ request : flask .wrappers .Request
143+ ) -> bool :
149144 for user_agent in app .config ['PHPBB3_BOTLIST' ]:
150145 if request .headers .get ('User-Agent' , '' ).startswith (user_agent ):
151146 return True
152147 return False
153148
154- def open_session (self , app , request ):
155- # type: (flask.Flask, flask.wrappers.Request) -> PhpBB3Session
156- cookie_name = app .config .get ('PHPBB3_COOKIE_NAME' , 'phpbb3_' )
149+ def open_session (
150+ self ,
151+ app : flask .Flask ,
152+ request : flask .wrappers .Request
153+ ) -> PhpBB3Session :
154+ cookie_name : str = app .config .get ('PHPBB3_COOKIE_NAME' , 'phpbb3_' )
157155
158156 if not hasattr (app , 'phpbb3' ):
159157 raise ValueError ('App not properly configured, phpbb3 is missing!' )
160- phpbb3 = app . phpbb3 # type : flask_phpbb3.PhpBB3
158+ phpbb3 : flask_phpbb3 .PhpBB3 = getattr ( app , 'phpbb3' )
161159
162- session_id = request .args .get ('sid' , type = str )\
160+ session_id : Optional [ str ] = request .args .get ('sid' , type = str )\
163161 or request .cookies .get (cookie_name + 'sid' , None )
164162 if not session_id :
165163 session_id = None
166164
167- user = None
165+ user : Optional [ Dict ] = None
168166 if self ._is_bot (app , request ):
169167 user = {'user_id' : 1 , 'username' : 'Anonymous' }
170168 elif session_id :
@@ -181,7 +179,7 @@ def open_session(self, app, request):
181179 )
182180
183181 # Create session
184- session = self .session_class ()
182+ session : PhpBB3Session = self .session_class ()
185183
186184 # Set session data
187185 if isinstance (user , dict ) and user :
@@ -204,8 +202,15 @@ def open_session(self, app, request):
204202
205203 return session
206204
207- def save_session (self , app , session , response ):
208- # type: (flask.Flask, PhpBB3Session, flask.wrappers.Response) -> None
205+ def save_session (
206+ self ,
207+ app : flask .Flask ,
208+ session : flask .sessions .SessionMixin ,
209+ response : flask .wrappers .Response
210+ ) -> None :
211+ if not isinstance (session , PhpBB3Session ):
212+ raise TypeError ('The provided session is not PhpBB3Session!' )
213+
209214 """Currenlty does nothing."""
210215 if session .modified and session ._read_only_properties :
211216 # Store all 'storable' properties
0 commit comments