1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
|
# -*- coding: utf-8 -*-
import http.cookies
import json
import logging
import sys
from typing import Optional
import cherrypy
from .. import mgr
from ..exceptions import InvalidCredentialsError, UserDoesNotExist
from ..services.auth import AuthManager, AuthType, BaseAuth, JwtManager, OAuth2
from ..services.cluster import ClusterModel
from ..settings import Settings
from . import APIDoc, APIRouter, ControllerAuthMixin, EndpointDoc, RESTController, allow_empty_body
# Python 3.8 introduced `samesite` attribute:
# https://docs.python.org/3/library/http.cookies.html#morsel-objects
if sys.version_info < (3, 8):
http.cookies.Morsel._reserved["samesite"] = "SameSite" # type: ignore # pylint: disable=W0212
logger = logging.getLogger('controllers.auth')
AUTH_CHECK_SCHEMA = {
"username": (str, "Username"),
"permissions": ({
"cephfs": ([str], "")
}, "List of permissions acquired"),
"sso": (bool, "Uses single sign on?"),
"pwdUpdateRequired": (bool, "Is password update required?")
}
AUTH_SCHEMA = {
"token": (str, "Authentication Token"),
"username": (str, "Username"),
"permissions": ({
"cephfs": ([str], "")
}, "List of permissions acquired"),
"pwdExpirationDate": (str, "Password expiration date"),
"sso": (bool, "Uses single sign on?"),
"pwdUpdateRequired": (bool, "Is password update required?")
}
@APIRouter('/auth', secure=False)
@APIDoc("Initiate a session with Ceph", "Auth")
class Auth(RESTController, ControllerAuthMixin):
"""
Provide authenticates and returns JWT token.
"""
@EndpointDoc("Dashboard Authentication",
parameters={
'username': (str, 'Username'),
'password': (str, 'Password'),
'ttl': (int, 'Token Time to Live (in hours)')
},
responses={201: AUTH_SCHEMA})
def create(self, username, password, ttl: Optional[int] = None):
# pylint: disable=R0912
user_data = AuthManager.authenticate(username, password)
user_perms, pwd_expiration_date, pwd_update_required = None, None, None
max_attempt = Settings.ACCOUNT_LOCKOUT_ATTEMPTS
origin = cherrypy.request.headers.get('Origin', None)
try:
fsid = mgr.get('config')['fsid']
except KeyError:
fsid = ''
if max_attempt == 0 or mgr.ACCESS_CTRL_DB.get_attempt(username) < max_attempt: # pylint: disable=R1702,line-too-long # noqa: E501
if user_data:
user_perms = user_data.get('permissions')
pwd_expiration_date = user_data.get('pwdExpirationDate', None)
pwd_update_required = user_data.get('pwdUpdateRequired', False)
if user_perms is not None:
url_prefix = 'https' if mgr.get_localized_module_option('ssl') else 'http'
logger.info('Login successful: %s', username)
mgr.ACCESS_CTRL_DB.reset_attempt(username)
mgr.ACCESS_CTRL_DB.save()
token = JwtManager.gen_token(username, ttl=ttl)
# For backward-compatibility: PyJWT versions < 2.0.0 return bytes.
token = token.decode('utf-8') if isinstance(token, bytes) else token
self._set_token_cookie(url_prefix, token)
if isinstance(Settings.MULTICLUSTER_CONFIG, str):
try:
item_to_dict = json.loads(Settings.MULTICLUSTER_CONFIG)
except json.JSONDecodeError:
item_to_dict = {}
multicluster_config = item_to_dict.copy()
else:
multicluster_config = Settings.MULTICLUSTER_CONFIG.copy()
try:
if fsid in multicluster_config['config']:
cluster_configurations = multicluster_config['config'][fsid]
for config_item in cluster_configurations:
if config_item['user'] == username or config_item['cluster_alias'] == 'local-cluster': # noqa E501 #pylint: disable=line-too-long
config_item['token'] = token # Update token
break
else:
cluster_configurations.append({
"name": fsid,
"url": origin,
"cluster_alias": "local-cluster",
"user": username,
"token": token
})
else:
multicluster_config['config'][fsid] = [{
"name": fsid,
"url": origin,
"cluster_alias": "local-cluster",
"user": username,
"token": token
}]
except KeyError:
multicluster_config = {
'current_url': origin,
'current_user': username,
'hub_url': origin,
'config': {
fsid: [
{
"name": fsid,
"url": origin,
"cluster_alias": "local-cluster",
"user": username,
"token": token
}
]
}
}
Settings.MULTICLUSTER_CONFIG = json.dumps(multicluster_config)
return {
'token': token,
'username': username,
'permissions': user_perms,
'pwdExpirationDate': pwd_expiration_date,
'sso': BaseAuth.from_protocol(mgr.SSO_DB.protocol).sso,
'pwdUpdateRequired': pwd_update_required
}
mgr.ACCESS_CTRL_DB.increment_attempt(username)
mgr.ACCESS_CTRL_DB.save()
else:
try:
user = mgr.ACCESS_CTRL_DB.get_user(username)
user.enabled = False
mgr.ACCESS_CTRL_DB.save()
logging.warning('Maximum number of unsuccessful log-in attempts '
'(%d) reached for '
'username "%s" so the account was blocked. '
'An administrator will need to re-enable the account',
max_attempt, username)
raise InvalidCredentialsError
except UserDoesNotExist:
raise InvalidCredentialsError
logger.info('Login failed: %s', username)
raise InvalidCredentialsError
@RESTController.Collection('POST')
@allow_empty_body
def logout(self):
logger.debug('Logout started')
token = JwtManager.get_token(cherrypy.request)
JwtManager.blocklist_token(token)
self._delete_token_cookie(token)
return {
'redirect_url': BaseAuth.from_db(mgr.SSO_DB).LOGOUT_URL,
'protocol': BaseAuth.from_db(mgr.SSO_DB).get_auth_name()
}
@RESTController.Collection('POST', query_params=['token'])
@EndpointDoc("Check token Authentication",
parameters={'token': (str, 'Authentication Token')},
responses={201: AUTH_CHECK_SCHEMA})
def check(self, token):
if token:
if mgr.SSO_DB.protocol == AuthType.OAUTH2:
user = OAuth2.get_user(token)
else:
user = JwtManager.get_user(token)
if user:
return {
'username': user.username,
'permissions': user.permissions_dict(),
'sso': BaseAuth.from_db(mgr.SSO_DB).sso,
'pwdUpdateRequired': user.pwd_update_required
}
return {
'login_url': BaseAuth.from_db(mgr.SSO_DB).LOGIN_URL,
'cluster_status': ClusterModel.from_db().dict()['status']
}
|