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

44 statements  

« prev     ^ index     » next       coverage.py v7.8.0, created at 2025-04-17 01:37 +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 (added in 8.1)""" 

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 self.register_middleware(self.uid, depends_on=['auth']) 

43 

44 ## 

45 

46 def enter_middleware(self, req): 

47 pass 

48 

49 def exit_middleware(self, req, res): 

50 pass 

51 

52 def open_session(self, req): 

53 am = self.root.app.authMgr 

54 credentials = self._parse_header(req) 

55 if not credentials: 

56 return 

57 user = am.authenticate(self, credentials) 

58 if user: 

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

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

61 

62 def close_session(self, req, res): 

63 pass 

64 

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

66 h = req.header(self.header) 

67 if not h: 

68 return 

69 

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

71 

72 if self.prefix: 

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

74 return 

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

76 else: 

77 if len(a) != 1: 

78 return 

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