Fix some bugs when testing opensds ansible
[stor4nfv.git] / src / ceph / src / pybind / mgr / restful / decorators.py
1 from pecan import request, response
2 from base64 import b64decode
3 from functools import wraps
4
5 import traceback
6
7 import module
8
9
10 # Handle authorization
11 def auth(f):
12     @wraps(f)
13     def decorated(*args, **kwargs):
14         if not request.authorization:
15             response.status = 401
16             response.headers['WWW-Authenticate'] = 'Basic realm="Login Required"'
17             return {'message': 'auth: No HTTP username/password'}
18
19         username, password = b64decode(request.authorization[1]).split(':')
20
21         # Check that the username exists
22         if username not in module.instance.keys:
23             response.status = 401
24             response.headers['WWW-Authenticate'] = 'Basic realm="Login Required"'
25             return {'message': 'auth: No such user'}
26
27         # Check the password
28         if module.instance.keys[username] != password:
29             response.status = 401
30             response.headers['WWW-Authenticate'] = 'Basic realm="Login Required"'
31             return {'message': 'auth: Incorrect password'}
32
33         return f(*args, **kwargs)
34     return decorated
35
36
37 # Helper function to lock the function
38 def lock(f):
39     @wraps(f)
40     def decorated(*args, **kwargs):
41         with module.instance.requests_lock:
42             return f(*args, **kwargs)
43     return decorated
44
45
46 # Support ?page=N argument
47 def paginate(f):
48     @wraps(f)
49     def decorated(*args, **kwargs):
50         _out = f(*args, **kwargs)
51
52         # Do not modify anything without a specific request
53         if not 'page' in kwargs:
54             return _out
55
56         # A pass-through for errors, etc
57         if not isinstance(_out, list):
58             return _out
59
60         # Parse the page argument
61         _page = kwargs['page']
62         try:
63             _page = int(_page)
64         except ValueError:
65             response.status = 500
66             return {'message': 'The requested page is not an integer'}
67
68         # Raise _page so that 0 is the first page and -1 is the last
69         _page += 1
70
71         if _page > 0:
72             _page *= 100
73         else:
74             _page = len(_out) - (_page*100)
75
76         return _out[_page - 100: _page]
77     return decorated