comparison rhodecode/lib/auth_modules/auth_crowd.py @ 4116:ffd45b185016 rhodecode-2.2.5-gpl

Imported some of the GPLv3'd changes from RhodeCode v2.2.5. This imports changes between changesets 21af6c4eab3d and 6177597791c2 in RhodeCode's original repository, including only changes to Python files and HTML. RhodeCode clearly licensed its changes to these files under GPLv3 in their /LICENSE file, which states the following: The Python code and integrated HTML are licensed under the GPLv3 license. (See: https://code.rhodecode.com/rhodecode/files/v2.2.5/LICENSE or http://web.archive.org/web/20140512193334/https://code.rhodecode.com/rhodecode/files/f3b123159901f15426d18e3dc395e8369f70ebe0/LICENSE for an online copy of that LICENSE file) Conservancy reviewed these changes and confirmed that they can be licensed as a whole to the Kallithea project under GPLv3-only. While some of the contents committed herein are clearly licensed GPLv3-or-later, on the whole we must assume the are GPLv3-only, since the statement above from RhodeCode indicates that they intend GPLv3-only as their license, per GPLv3ยง14 and other relevant sections of GPLv3.
author Bradley M. Kuhn <bkuhn@sfconservancy.org>
date Wed, 02 Jul 2014 19:03:13 -0400
parents
children 7e5f8c12a3fc
comparison
equal deleted inserted replaced
4115:8b7294a804a0 4116:ffd45b185016
1 # -*- coding: utf-8 -*-
2 # This program is free software: you can redistribute it and/or modify
3 # it under the terms of the GNU General Public License as published by
4 # the Free Software Foundation, either version 3 of the License, or
5 # (at your option) any later version.
6 #
7 # This program is distributed in the hope that it will be useful,
8 # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 # GNU General Public License for more details.
11 #
12 # You should have received a copy of the GNU General Public License
13 # along with this program. If not, see <http://www.gnu.org/licenses/>.
14 """
15 rhodecode.lib.auth_modules.auth_crowd
16 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
17
18 RhodeCode authentication plugin for Atlassian CROWD
19
20 :created_on: Created on Nov 17, 2012
21 :author: marcink
22 :copyright: (c) 2013 RhodeCode GmbH.
23 :license: GPLv3, see LICENSE for more details.
24 """
25
26
27 import base64
28 import logging
29 import urllib2
30 from rhodecode.lib import auth_modules
31 from rhodecode.lib.compat import json, formatted_json, hybrid_property
32 from rhodecode.model.db import User
33
34 log = logging.getLogger(__name__)
35
36
37 class CrowdServer(object):
38 def __init__(self, *args, **kwargs):
39 """
40 Create a new CrowdServer object that points to IP/Address 'host',
41 on the given port, and using the given method (https/http). user and
42 passwd can be set here or with set_credentials. If unspecified,
43 "version" defaults to "latest".
44
45 example::
46
47 cserver = CrowdServer(host="127.0.0.1",
48 port="8095",
49 user="some_app",
50 passwd="some_passwd",
51 version="1")
52 """
53 if not "port" in kwargs:
54 kwargs["port"] = "8095"
55 self._logger = kwargs.get("logger", logging.getLogger(__name__))
56 self._uri = "%s://%s:%s/crowd" % (kwargs.get("method", "http"),
57 kwargs.get("host", "127.0.0.1"),
58 kwargs.get("port", "8095"))
59 self.set_credentials(kwargs.get("user", ""),
60 kwargs.get("passwd", ""))
61 self._version = kwargs.get("version", "latest")
62 self._url_list = None
63 self._appname = "crowd"
64
65 def set_credentials(self, user, passwd):
66 self.user = user
67 self.passwd = passwd
68 self._make_opener()
69
70 def _make_opener(self):
71 mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
72 mgr.add_password(None, self._uri, self.user, self.passwd)
73 handler = urllib2.HTTPBasicAuthHandler(mgr)
74 self.opener = urllib2.build_opener(handler)
75
76 def _request(self, url, body=None, headers=None,
77 method=None, noformat=False,
78 empty_response_ok=False):
79 _headers = {"Content-type": "application/json",
80 "Accept": "application/json"}
81 if self.user and self.passwd:
82 authstring = base64.b64encode("%s:%s" % (self.user, self.passwd))
83 _headers["Authorization"] = "Basic %s" % authstring
84 if headers:
85 _headers.update(headers)
86 log.debug("Sent crowd: \n%s"
87 % (formatted_json({"url": url, "body": body,
88 "headers": _headers})))
89 request = urllib2.Request(url, body, _headers)
90 if method:
91 request.get_method = lambda: method
92
93 global msg
94 msg = ""
95 try:
96 rdoc = self.opener.open(request)
97 msg = "".join(rdoc.readlines())
98 if not msg and empty_response_ok:
99 rval = {}
100 rval["status"] = True
101 rval["error"] = "Response body was empty"
102 elif not noformat:
103 rval = json.loads(msg)
104 rval["status"] = True
105 else:
106 rval = "".join(rdoc.readlines())
107 except Exception, e:
108 if not noformat:
109 rval = {"status": False,
110 "body": body,
111 "error": str(e) + "\n" + msg}
112 else:
113 rval = None
114 return rval
115
116 def user_auth(self, username, password):
117 """Authenticate a user against crowd. Returns brief information about
118 the user."""
119 url = ("%s/rest/usermanagement/%s/authentication?username=%s"
120 % (self._uri, self._version, username))
121 body = json.dumps({"value": password})
122 return self._request(url, body)
123
124 def user_groups(self, username):
125 """Retrieve a list of groups to which this user belongs."""
126 url = ("%s/rest/usermanagement/%s/user/group/nested?username=%s"
127 % (self._uri, self._version, username))
128 return self._request(url)
129
130
131 class RhodeCodeAuthPlugin(auth_modules.RhodeCodeExternalAuthPlugin):
132
133 @hybrid_property
134 def name(self):
135 return "crowd"
136
137 def settings(self):
138 settings = [
139 {
140 "name": "host",
141 "validator": self.validators.UnicodeString(strip=True),
142 "type": "string",
143 "description": "The FQDN or IP of the Atlassian CROWD Server",
144 "default": "127.0.0.1",
145 "formname": "Host"
146 },
147 {
148 "name": "port",
149 "validator": self.validators.Number(strip=True),
150 "type": "int",
151 "description": "The Port in use by the Atlassian CROWD Server",
152 "default": 8095,
153 "formname": "Port"
154 },
155 {
156 "name": "app_name",
157 "validator": self.validators.UnicodeString(strip=True),
158 "type": "string",
159 "description": "The Application Name to authenticate to CROWD",
160 "default": "",
161 "formname": "Application Name"
162 },
163 {
164 "name": "app_password",
165 "validator": self.validators.UnicodeString(strip=True),
166 "type": "string",
167 "description": "The password to authenticate to CROWD",
168 "default": "",
169 "formname": "Application Password"
170 },
171 {
172 "name": "admin_groups",
173 "validator": self.validators.UnicodeString(strip=True),
174 "type": "string",
175 "description": "A comma separated list of group names that identify users as RhodeCode Administrators",
176 "formname": "Admin Groups"
177 }
178 ]
179 return settings
180
181 def use_fake_password(self):
182 return True
183
184 def user_activation_state(self):
185 def_user_perms = User.get_default_user().AuthUser.permissions['global']
186 return 'hg.extern_activate.auto' in def_user_perms
187
188 def auth(self, userobj, username, password, settings, **kwargs):
189 """
190 Given a user object (which may be null), username, a plaintext password,
191 and a settings object (containing all the keys needed as listed in settings()),
192 authenticate this user's login attempt.
193
194 Return None on failure. On success, return a dictionary of the form:
195
196 see: RhodeCodeAuthPluginBase.auth_func_attrs
197 This is later validated for correctness
198 """
199 if not username or not password:
200 log.debug('Empty username or password skipping...')
201 return None
202
203 log.debug("Crowd settings: \n%s" % (formatted_json(settings)))
204 server = CrowdServer(**settings)
205 server.set_credentials(settings["app_name"], settings["app_password"])
206 crowd_user = server.user_auth(username, password)
207 log.debug("Crowd returned: \n%s" % (formatted_json(crowd_user)))
208 if not crowd_user["status"]:
209 return None
210
211 res = server.user_groups(crowd_user["name"])
212 log.debug("Crowd groups: \n%s" % (formatted_json(res)))
213 crowd_user["groups"] = [x["name"] for x in res["groups"]]
214
215 # old attrs fetched from RhodeCode database
216 admin = getattr(userobj, 'admin', False)
217 active = getattr(userobj, 'active', True)
218 email = getattr(userobj, 'email', '')
219 firstname = getattr(userobj, 'firstname', '')
220 lastname = getattr(userobj, 'lastname', '')
221 extern_type = getattr(userobj, 'extern_type', '')
222
223 user_attrs = {
224 'username': username,
225 'firstname': crowd_user["first-name"] or firstname,
226 'lastname': crowd_user["last-name"] or lastname,
227 'groups': crowd_user["groups"],
228 'email': crowd_user["email"] or email,
229 'admin': admin,
230 'active': active,
231 'active_from_extern': crowd_user.get('active'),
232 'extern_name': crowd_user["name"],
233 'extern_type': extern_type,
234 }
235
236 # set an admin if we're in admin_groups of crowd
237 for group in settings["admin_groups"]:
238 if group in user_attrs["groups"]:
239 user_attrs["admin"] = True
240 log.debug("Final crowd user object: \n%s" % (formatted_json(user_attrs)))
241 log.info('user %s authenticated correctly' % user_attrs['username'])
242 return user_attrs