Files
@ c9d859a89a88
Branch filter:
Location: kallithea/kallithea/lib/auth_modules/auth_crowd.py
c9d859a89a88
9.7 KiB
text/x-python
auth: move 'active' handling out of the individual auth modules
The 'active' flag in the Kallithea user database is very fundamental and should
not be specific to auth modules. Modules should only care about whether the
user is active in the external authentication system.
user_activation_state is thus removed, and 'hg.extern_activate.auto' is now
consistently checked for all kinds of external authentication.
The 'active' flag in the Kallithea user database is very fundamental and should
not be specific to auth modules. Modules should only care about whether the
user is active in the external authentication system.
user_activation_state is thus removed, and 'hg.extern_activate.auto' is now
consistently checked for all kinds of external authentication.
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 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 | # -*- coding: utf-8 -*-
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
kallithea.lib.auth_modules.auth_crowd
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Kallithea authentication plugin for Atlassian CROWD
This file was forked by the Kallithea project in July 2014.
Original author and date, and relevant copyright and licensing information is below:
:created_on: Created on Nov 17, 2012
:author: marcink
:copyright: (c) 2013 RhodeCode GmbH, and others.
:license: GPLv3, see LICENSE.md for more details.
"""
import base64
import logging
import urllib2
from kallithea.lib import auth_modules
from kallithea.lib.compat import json, formatted_json, hybrid_property
from kallithea.model.db import User
log = logging.getLogger(__name__)
class CrowdServer(object):
def __init__(self, *args, **kwargs):
"""
Create a new CrowdServer object that points to IP/Address 'host',
on the given port, and using the given method (https/http). user and
passwd can be set here or with set_credentials. If unspecified,
"version" defaults to "latest".
example::
cserver = CrowdServer(host="127.0.0.1",
port="8095",
user="some_app",
passwd="some_passwd",
version="1")
"""
if "port" not in kwargs:
kwargs["port"] = "8095"
self._logger = kwargs.get("logger", logging.getLogger(__name__))
self._uri = "%s://%s:%s/crowd" % (kwargs.get("method", "http"),
kwargs.get("host", "127.0.0.1"),
kwargs.get("port", "8095"))
self.set_credentials(kwargs.get("user", ""),
kwargs.get("passwd", ""))
self._version = kwargs.get("version", "latest")
self._url_list = None
self._appname = "crowd"
def set_credentials(self, user, passwd):
self.user = user
self.passwd = passwd
self._make_opener()
def _make_opener(self):
mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
mgr.add_password(None, self._uri, self.user, self.passwd)
handler = urllib2.HTTPBasicAuthHandler(mgr)
self.opener = urllib2.build_opener(handler)
def _request(self, url, body=None, headers=None,
method=None, noformat=False,
empty_response_ok=False):
_headers = {"Content-type": "application/json",
"Accept": "application/json"}
if self.user and self.passwd:
authstring = base64.b64encode("%s:%s" % (self.user, self.passwd))
_headers["Authorization"] = "Basic %s" % authstring
if headers:
_headers.update(headers)
log.debug("Sent crowd: \n%s",
formatted_json({"url": url, "body": body,
"headers": _headers}))
req = urllib2.Request(url, body, _headers)
if method:
req.get_method = lambda: method
global msg
msg = ""
try:
rdoc = self.opener.open(req)
msg = "".join(rdoc.readlines())
if not msg and empty_response_ok:
rval = {}
rval["status"] = True
rval["error"] = "Response body was empty"
elif not noformat:
rval = json.loads(msg)
rval["status"] = True
else:
rval = "".join(rdoc.readlines())
except Exception as e:
if not noformat:
rval = {"status": False,
"body": body,
"error": str(e) + "\n" + msg}
else:
rval = None
return rval
def user_auth(self, username, password):
"""Authenticate a user against crowd. Returns brief information about
the user."""
url = ("%s/rest/usermanagement/%s/authentication?username=%s"
% (self._uri, self._version, urllib2.quote(username)))
body = json.dumps({"value": password})
return self._request(url, body)
def user_groups(self, username):
"""Retrieve a list of groups to which this user belongs."""
url = ("%s/rest/usermanagement/%s/user/group/nested?username=%s"
% (self._uri, self._version, urllib2.quote(username)))
return self._request(url)
class KallitheaAuthPlugin(auth_modules.KallitheaExternalAuthPlugin):
def __init__(self):
self._protocol_values = ["http", "https"]
@hybrid_property
def name(self):
return "crowd"
def settings(self):
settings = [
{
"name": "method",
"validator": self.validators.OneOf(self._protocol_values),
"type": "select",
"values": self._protocol_values,
"description": "The protocol used to connect to the Atlassian CROWD server.",
"formname": "Protocol"
},
{
"name": "host",
"validator": self.validators.UnicodeString(strip=True),
"type": "string",
"description": "The FQDN or IP of the Atlassian CROWD Server",
"default": "127.0.0.1",
"formname": "Host"
},
{
"name": "port",
"validator": self.validators.Number(strip=True),
"type": "int",
"description": "The Port in use by the Atlassian CROWD Server",
"default": 8095,
"formname": "Port"
},
{
"name": "app_name",
"validator": self.validators.UnicodeString(strip=True),
"type": "string",
"description": "The Application Name to authenticate to CROWD",
"default": "",
"formname": "Application Name"
},
{
"name": "app_password",
"validator": self.validators.UnicodeString(strip=True),
"type": "string",
"description": "The password to authenticate to CROWD",
"default": "",
"formname": "Application Password"
},
{
"name": "admin_groups",
"validator": self.validators.UnicodeString(strip=True),
"type": "string",
"description": "A comma separated list of group names that identify users as Kallithea Administrators",
"formname": "Admin Groups"
}
]
return settings
def use_fake_password(self):
return True
def auth(self, userobj, username, password, settings, **kwargs):
"""
Given a user object (which may be null), username, a plaintext password,
and a settings object (containing all the keys needed as listed in settings()),
authenticate this user's login attempt.
Return None on failure. On success, return a dictionary of the form:
see: KallitheaAuthPluginBase.auth_func_attrs
This is later validated for correctness
"""
if not username or not password:
log.debug('Empty username or password skipping...')
return None
log.debug("Crowd settings: \n%s", formatted_json(settings))
server = CrowdServer(**settings)
server.set_credentials(settings["app_name"], settings["app_password"])
crowd_user = server.user_auth(username, password)
log.debug("Crowd returned: \n%s", formatted_json(crowd_user))
if not crowd_user["status"]:
log.error('Crowd authentication as %s returned no status', username)
return None
if not crowd_user.get('active'):
log.error('Crowd authentication as %s returned in-active user', username)
return None
res = server.user_groups(crowd_user["name"])
log.debug("Crowd groups: \n%s", formatted_json(res))
crowd_user["groups"] = [x["name"] for x in res["groups"]]
# old attrs fetched from Kallithea database
admin = getattr(userobj, 'admin', False)
email = getattr(userobj, 'email', '')
firstname = getattr(userobj, 'firstname', '')
lastname = getattr(userobj, 'lastname', '')
user_data = {
'username': crowd_user["name"] or username,
'firstname': crowd_user["first-name"] or firstname,
'lastname': crowd_user["last-name"] or lastname,
'groups': crowd_user["groups"],
'email': crowd_user["email"] or email,
'admin': admin,
'extern_name': crowd_user["name"],
}
# set an admin if we're in admin_groups of crowd
for group in settings["admin_groups"].split(","):
if group in user_data["groups"]:
user_data["admin"] = True
log.debug("Final crowd user object: \n%s", formatted_json(user_data))
log.info('user %s authenticated correctly', user_data['username'])
return user_data
def get_managed_fields(self):
return ['username', 'firstname', 'lastname', 'email', 'password']
|