11import enum
2+ import warnings
23from aiohttp import web
34from aiohttp_security .abc import (AbstractIdentityPolicy ,
45 AbstractAuthorizationPolicy )
@@ -86,6 +87,15 @@ async def is_anonymous(request):
8687 return False
8788
8889
90+ async def check_authorized (request ):
91+ """Checker that raises HTTPUnauthorized for anonymous users.
92+ """
93+ userid = await authorized_userid (request )
94+ if userid is None :
95+ raise web .HTTPUnauthorized ()
96+ return userid
97+
98+
8999def login_required (fn ):
90100 """Decorator that restrict access only for authorized users.
91101
@@ -101,21 +111,34 @@ async def wrapped(*args, **kwargs):
101111 "or `def handler(self, request)`." )
102112 raise RuntimeError (msg )
103113
104- userid = await authorized_userid (request )
105- if userid is None :
106- raise web .HTTPUnauthorized
107-
108- ret = await fn (* args , ** kwargs )
109- return ret
114+ await check_authorized (request )
115+ return await fn (* args , ** kwargs )
110116
117+ warnings .warn ("login_required decorator is deprecated, "
118+ "use check_authorized instead" ,
119+ DeprecationWarning )
111120 return wrapped
112121
113122
123+ async def check_permission (request , permission , context = None ):
124+ """Checker that passes only to authoraised users with given permission.
125+
126+ If user is not authorized - raises HTTPUnauthorized,
127+ if user is authorized and does not have permission -
128+ raises HTTPForbidden.
129+ """
130+
131+ await check_authorized (request )
132+ allowed = await permits (request , permission , context )
133+ if not allowed :
134+ raise web .HTTPForbidden ()
135+
136+
114137def has_permission (
115138 permission ,
116139 context = None ,
117140):
118- """Decorator that restrict access only for authorized users
141+ """Decorator that restricts access only for authorized users
119142 with correct permissions.
120143
121144 If user is not authorized - raises HTTPUnauthorized,
@@ -132,18 +155,14 @@ async def wrapped(*args, **kwargs):
132155 "or `def handler(self, request)`." )
133156 raise RuntimeError (msg )
134157
135- userid = await authorized_userid (request )
136- if userid is None :
137- raise web .HTTPUnauthorized
138-
139- allowed = await permits (request , permission , context )
140- if not allowed :
141- raise web .HTTPForbidden
142- ret = await fn (* args , ** kwargs )
143- return ret
158+ await check_permission (request , permission , context )
159+ return await fn (* args , ** kwargs )
144160
145161 return wrapped
146162
163+ warnings .warn ("has_permission decorator is deprecated, "
164+ "use check_permission instead" ,
165+ DeprecationWarning )
147166 return wrapper
148167
149168
0 commit comments