Revision bda47e03 snf-django-lib/snf_django/lib/api/__init__.py

b/snf-django-lib/snf_django/lib/api/__init__.py
250 250
    Wrapper to enable jsonp responses.
251 251
    """
252 252
    def wrapper(func):
253
        @wraps(func)
253 254
        def view_wrapper(request, *args, **kwargs):
254 255
            response = func(request, *args, **kwargs)
255 256
            if 'content-type' in response._headers and \
......
263 264
            return response
264 265
        return view_wrapper
265 266
    return wrapper
267

  
268

  
269
def user_in_groups(permitted_groups, logger=None):
270
    """Check that the request user belongs to one of permitted groups.
271

  
272
    Django view wrapper to check that the already identified request user
273
    belongs to one of the allowed groups.
274

  
275
    """
276
    if not logger:
277
        logger = log
278

  
279
    def decorator(func):
280
        @wraps(func)
281
        def wrapper(request, *args, **kwargs):
282
            if hasattr(request, "user") and request.user is not None:
283
                groups = request.user["access"]["user"]["roles"]
284
                groups = [g["name"] for g in groups]
285
            else:
286
                raise faults.Forbidden
287

  
288
            common_groups = set(groups) & set(permitted_groups)
289

  
290
            if not common_groups:
291
                msg = ("Not allowing access to '%s' by user '%s'. User does"
292
                       " not belong to a valid group. User groups: %s,"
293
                       " Required groups %s"
294
                       % (request.path, request.user, groups,
295
                          permitted_groups))
296
                logger.error(msg)
297
                raise faults.Forbidden
298

  
299
            logger.info("User '%s' in groups '%s' accessed view '%s'",
300
                        request.user_uniq, groups, request.path)
301

  
302
            return func(request, *args, **kwargs)
303
        return wrapper
304
    return decorator

Also available in: Unified diff