Coverage for gws-app/gws/plugin/auth_method/token/__init__.py: 0%

39 statements  

« prev     ^ index     » next       coverage.py v7.11.0, created at 2025-10-16 23:09 +0200

1"""HTTP Token authorisation method. 

2 

3The token authorization works by passing a token in an HTTP header. 

4For example, with this configuration:: 

5 

6 auth.methods+ { 

7 type "token" 

8 header "X-My-Auth" 

9 prefix "Bearer" 

10 

11 } 

12 

13the application would expect a header like ``X-My-Auth: Bearer <token>``, extract the token value 

14and pass it along to authorization providers. 

15""" 

16 

17import gws 

18import gws.base.auth 

19import gws.base.web 

20 

21 

22gws.ext.new.authMethod('token') 

23 

24 

25class Config(gws.base.auth.method.Config): 

26 """HTTP-token authorization options""" 

27 

28 header: str 

29 """HTTP header name.""" 

30 prefix: str = '' 

31 """Token prefix.""" 

32 

33 

34class Object(gws.base.auth.method.Object): 

35 header: str 

36 prefix: str 

37 

38 def configure(self): 

39 self.uid = 'gws.plugin.auth_method.token' 

40 self.header = self.cfg('header') 

41 self.prefix = self.cfg('prefix', default='') 

42 

43 ## 

44 

45 def open_session(self, req): 

46 am = self.root.app.authMgr 

47 credentials = self._parse_header(req) 

48 if not credentials: 

49 return 

50 user = am.authenticate(self, credentials) 

51 if user: 

52 user.authToken = credentials.get('token') 

53 return am.sessionMgr.create(self, user) 

54 

55 def close_session(self, req, res): 

56 pass 

57 

58 def _parse_header(self, req: gws.WebRequester): 

59 h = req.header(self.header) 

60 if not h: 

61 return 

62 

63 a = h.strip().split() 

64 

65 if self.prefix: 

66 if len(a) != 2 or a[0].lower() != self.prefix.lower(): 

67 return 

68 return gws.Data(token=a[1]) 

69 else: 

70 if len(a) != 1: 

71 return 

72 return gws.Data(token=a[0])