@@ -8,13 +8,13 @@ API
Starting from RhodeCode version 1.2 a simple API was implemented.
There's a single schema for calling all api methods. API is implemented
with JSON protocol both ways. An url to send API request in RhodeCode is
<your_server>/_admin/api
All clients need to send JSON data in such format::
All clients are required to send JSON-RPC spec JSON data::
{
"api_key":"<api_key>",
"method":"<method_name>",
"args":{"<arg_key>":"<arg_val>"}
}
@@ -29,13 +29,13 @@ Simply provide
.. note::
api_key can be found in your user account page
RhodeCode API will return always a JSON formatted answer::
RhodeCode API will return always a JSON-RPC response::
"result": "<result>",
"error": null
@@ -217,14 +217,14 @@ OUTPUT::
result: {
"id": "<newusersgroupid>",
"msg": "created new users group <name>"
error: null
add_user_to_users_groups
------------------------
add_user_to_users_group
-----------------------
Adds a user to a users group. This command can be executed only using api_key
belonging to user with admin rights
INPUT::
@@ -296,20 +296,20 @@ OUTPUT::
"firstname": "<firstname>",
"lastname" : "<lastname>",
"email" : "<email>",
"active" : "<bool>",
"admin" : "<bool>",
"ldap" : "<ldap_dn>",
"permission" : "repository_(read|write|admin)"
"permission" : "repository.(read|write|admin)"
},
…
"id" : "<usersgroupid>",
"name" : "<usersgroupname>",
"active": "<bool>",
]
@@ -350,13 +350,30 @@ INPUT::
api_key : "<api_key>"
method : "add_user_to_repo"
args: {
"repo_name" : "<reponame>",
"user_name" : "<username>",
"perm" : "(None|repository_(read|write|admin))",
"perm" : "(None|repository.(read|write|admin))",
OUTPUT::
result: None
add_users_group_to_repo
Add a users group to a repository. This command can be executed only using
api_key belonging to user with admin rights. If "perm" is None, group will
be removed from the repository.
method : "add_users_group_to_repo"
"group_name" : "<groupname>",
\ No newline at end of file
# -*- coding: utf-8 -*-
"""
rhodecode.controllers.api
~~~~~~~~~~~~~~~~~~~~~~~~~
JSON RPC controller
:created_on: Aug 20, 2011
:author: marcink
:copyright: (C) 2009-2010 Marcin Kuzminski <marcin@python-works.com>
:license: GPLv3, see COPYING for more details.
# This program is free software; you can redistribute it and/or
@@ -33,49 +33,56 @@ import traceback
from rhodecode.lib.compat import izip_longest, json
from paste.response import replace_header
from pylons.controllers import WSGIController
from pylons.controllers.util import Response
from webob.exc import HTTPNotFound, HTTPForbidden, HTTPInternalServerError, \
HTTPBadRequest, HTTPError
from rhodecode.model.db import User
from rhodecode.lib.auth import AuthUser
log = logging.getLogger('JSONRPC')
class JSONRPCError(BaseException):
def __init__(self, message):
self.message = message
super(JSONRPCError, self).__init__()
def __str__(self):
return str(self.message)
def jsonrpc_error(message, code=None):
"""Generate a Response object with a JSON-RPC error body"""
return Response(body=json.dumps(dict(result=None,
error=message)))
Generate a Response object with a JSON-RPC error body
resp = Response(body=json.dumps(dict(result=None, error=message)),
status=code,
content_type='application/json')
return resp
class JSONRPCController(WSGIController):
A WSGI-speaking JSON-RPC controller class
See the specification:
<http://json-rpc.org/wiki/specification>`.
Valid controller return values should be json-serializable objects.
Sub-classes should catch their exceptions and raise JSONRPCError
if they want to pass meaningful errors to the client.
def _get_method_args(self):
Return `self._rpc_args` to dispatched controller method
chosen by __call__
@@ -101,30 +108,33 @@ class JSONRPCController(WSGIController):
raw_body = environ['wsgi.input'].read(length)
try:
json_body = json.loads(urllib.unquote_plus(raw_body))
except ValueError, e:
#catch JSON errors Here
# catch JSON errors Here
return jsonrpc_error(message="JSON parse error ERR:%s RAW:%r" \
% (e, urllib.unquote_plus(raw_body)))
#check AUTH based on API KEY
# check AUTH based on API KEY
self._req_api_key = json_body['api_key']
self._req_id = json_body['id']
self._req_method = json_body['method']
self._req_params = json_body['args']
self._request_params = json_body['args']
log.debug('method: %s, params: %s',
self._req_method,
self._req_params)
self._request_params)
except KeyError, e:
return jsonrpc_error(message='Incorrect JSON query missing %s' % e)
#check if we can find this session using api_key
# check if we can find this session using api_key
u = User.get_by_api_key(self._req_api_key)
if u is None:
return jsonrpc_error(message='Invalid API KEY')
auth_u = AuthUser(u.user_id, self._req_api_key)
except Exception, e:
self._error = None
@@ -133,19 +143,20 @@ class JSONRPCController(WSGIController):
return jsonrpc_error(message=str(e))
# now that we have a method, add self._req_params to
# self.kargs and dispatch control to WGIController
argspec = inspect.getargspec(self._func)
arglist = argspec[0][1:]
defaults = argspec[3] or []
defaults = map(type, argspec[3] or [])
default_empty = types.NotImplementedType
kwarglist = list(izip_longest(reversed(arglist), reversed(defaults),
fillvalue=default_empty))
# kw arguments required by this method
func_kwargs = dict(izip_longest(reversed(arglist), reversed(defaults),
# this is little trick to inject logged in user for
# perms decorators to work they expect the controller class to have
# rhodecode_user attribute set
self.rhodecode_user = auth_u
# This attribute will need to be first param of a method that uses
# api_key, which is translated to instance of user at that name
@@ -154,35 +165,38 @@ class JSONRPCController(WSGIController):
if USER_SESSION_ATTR not in arglist:
return jsonrpc_error(message='This method [%s] does not support '
'authentication (missing %s param)' %
(self._func.__name__, USER_SESSION_ATTR))
# get our arglist and check if we provided them as args
for arg, default in kwarglist:
for arg, default in func_kwargs.iteritems():
if arg == USER_SESSION_ATTR:
# USER_SESSION_ATTR is something translated from api key and
# this is checked before so we don't need validate it
continue
# skip the required param check if it's default value is
# NotImplementedType (default_empty)
if not self._req_params or (type(default) == default_empty
and arg not in self._req_params):
return jsonrpc_error(message=('Missing non optional %s arg '
'in JSON DATA') % arg)
if (default == default_empty and arg not in self._request_params):
return jsonrpc_error(
message=(
'Missing non optional `%s` arg in JSON DATA' % arg
)
self._rpc_args = {USER_SESSION_ATTR:u}
self._rpc_args.update(self._req_params)
self._rpc_args = {USER_SESSION_ATTR: u}
self._rpc_args.update(self._request_params)
self._rpc_args['action'] = self._req_method
self._rpc_args['environ'] = environ
self._rpc_args['start_response'] = start_response
status = []
headers = []
exc_info = []
def change_content(new_status, new_headers, new_exc_info=None):
status.append(new_status)
headers.extend(new_headers)
exc_info.append(new_exc_info)
output = WSGIController.__call__(self, environ, change_content)
@@ -209,13 +223,14 @@ class JSONRPCController(WSGIController):
json_exc = JSONRPCError('Internal server error')
self._error = str(json_exc)
if self._error is not None:
raw_response = None
response = dict(result=raw_response, error=self._error)
response = dict(result=raw_response,
error=self._error)
return json.dumps(response)
except TypeError, e:
log.debug('Error encoding response: %s', e)
return json.dumps(dict(result=None,
@@ -3,14 +3,15 @@
rhodecode.model.users_group
~~~~~~~~~~~~~~~~~~~~~~~~~~~
repository permission model for RhodeCode
:created_on: Oct 1, 2011
:author: nvinot
:author: nvinot, marcink
:copyright: (C) 2011-2011 Nicolas Vinot <aeris@imirhil.fr>
:copyright: (C) 2009-2011 Marcin Kuzminski <marcin@python-works.com>
# 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.
@@ -21,17 +22,19 @@
# 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/>.
import logging
from rhodecode.model.db import BaseModel, RepoToPerm, Permission
from rhodecode.model.db import BaseModel, RepoToPerm, Permission,\
UsersGroupRepoToPerm
from rhodecode.model.meta import Session
log = logging.getLogger(__name__)
class RepositoryPermissionModel(BaseModel):
def get_user_permission(self, repository, user):
return RepoToPerm.query() \
.filter(RepoToPerm.user == user) \
.filter(RepoToPerm.repository == repository) \
.scalar()
@@ -53,11 +56,46 @@ class RepositoryPermissionModel(BaseMode
def delete_user_permission(self, repository, user):
current = self.get_user_permission(repository, user)
if current:
Session.delete(current)
Session.commit()
def get_users_group_permission(self, repository, users_group):
return UsersGroupRepoToPerm.query() \
.filter(UsersGroupRepoToPerm.users_group == users_group) \
.filter(UsersGroupRepoToPerm.repository == repository) \
def update_users_group_permission(self, repository, users_group,
permission):
permission = Permission.get_by_key(permission)
current = self.get_users_group_permission(repository, users_group)
if not current.permission is permission:
current.permission = permission
else:
p = UsersGroupRepoToPerm()
p.users_group = users_group
p.repository = repository
p.permission = permission
self.sa.add(p)
def delete_users_group_permission(self, repository, users_group):
self.sa.delete(current)
def update_or_delete_user_permission(self, repository, user, permission):
if permission:
self.update_user_permission(repository, user, permission)
self.delete_user_permission(repository, user)
def update_or_delete_users_group_permission(self, repository, user_group,
self.update_users_group_permission(repository, user_group,
permission)
self.delete_users_group_permission(repository, user_group)
Status change: