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