wcs/wcs/api.py

192 lines
7.2 KiB
Python

# w.c.s. - web application for online forms
# Copyright (C) 2005-2013 Entr'ouvert
#
# 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 2 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/>.
import base64
import hmac
import hashlib
import json
import datetime
import urllib
import urllib2
import urlparse
import random
from quixote import get_request, get_publisher, get_response
from quixote.directory import Directory
from qommon.errors import AccessForbiddenError, QueryError, TraversalError
from wcs.formdef import FormDef
from wcs.roles import Role
def is_url_signed():
query_string = get_request().get_query()
if not query_string:
return False
signature = get_request().form.get('signature')
if not isinstance(signature, basestring):
return False
# verify signature
orig = get_request().form.get('orig')
if not isinstance(orig, basestring):
raise AccessForbiddenError('missing/multiple orig field')
key = get_publisher().get_site_option(orig, 'api-secrets')
if not key:
raise AccessForbiddenError('invalid orig')
algo = get_request().form.get('algo')
if not isinstance(algo, basestring):
raise AccessForbiddenError('missing/multiple algo field')
try:
algo = getattr(hashlib, algo)
except AttributeError:
raise AccessForbiddenError('invalid algo')
if signature != base64.standard_b64encode(hmac.new(key,
query_string[:query_string.find('&signature=')],
algo).digest()):
raise AccessForbiddenError('invalid signature')
timestamp = get_request().form.get('timestamp')
if not isinstance(timestamp, basestring):
raise AccessForbiddenError('missing/multiple timestamp field')
delta = (datetime.datetime.utcnow().replace(tzinfo=None) -
datetime.datetime.strptime(timestamp,
'%Y-%m-%dT%H:%M:%SZ'))
MAX_DELTA = 30
if abs(delta) > datetime.timedelta(seconds=MAX_DELTA):
raise AccessForbiddenError('timestamp delta is more '
'than %s seconds: %s seconds' % (MAX_DELTA, delta))
return True
def get_user_from_api_query_string():
if not is_url_signed():
return None
# Signature is good. Now looking for the user, by email/NameID.
# If email or NameID exist but are empty, return None
user = None
if get_request().form.get('email'):
email = get_request().form.get('email')
if not isinstance(email, basestring):
raise AccessForbiddenError('multiple email field')
users = list(get_publisher().user_class.get_users_with_email(email))
if users:
user = users[0]
else:
raise AccessForbiddenError('unknown email')
elif get_request().form.get('NameID'):
ni = get_request().form.get('NameID')
if not isinstance(ni, basestring):
raise AccessForbiddenError('multiple NameID field')
users = list(get_publisher().user_class.get_users_with_name_identifier(ni))
if users:
user = users[0]
else:
raise AccessForbiddenError('unknown NameID')
return user
def sign_url(url, key, algo='sha256', timestamp=None, nonce=None):
parsed = urlparse.urlparse(url)
new_query = sign_query(parsed.query, key, algo, timestamp, nonce)
return urlparse.urlunparse(parsed[:4] + (new_query,) + parsed[5:])
def sign_query(query, key, algo='sha256', timestamp=None, nonce=None):
if timestamp is None:
timestamp = datetime.datetime.utcnow()
timestamp = timestamp.strftime('%Y-%m-%dT%H:%M:%SZ')
if nonce is None:
nonce = hex(random.getrandbits(128))[2:-1]
new_query = query
if new_query:
new_query += '&'
new_query += urllib.urlencode((
('algo', algo),
('timestamp', timestamp),
('nonce', nonce)))
signature = base64.b64encode(sign_string(new_query, key, algo=algo))
new_query += '&signature=' + urllib.quote(signature)
return new_query
def sign_string(s, key, algo='sha256', timedelta=30):
digestmod = getattr(hashlib, algo)
hash = hmac.HMAC(key, digestmod=digestmod, msg=s)
return hash.digest()
# import backoffice.root.FormPage after get_user_from_api_query_string
# to avoid circular dependencies
from backoffice.management import FormPage as BackofficeFormPage
class ApiFormPage(BackofficeFormPage):
_q_exports = [('list', 'json')] # same as backoffice but restricted to json export
def __init__(self, component):
try:
self.formdef = FormDef.get_by_urlname(component)
except KeyError:
raise TraversalError()
api_user = get_user_from_api_query_string()
if not api_user:
if get_request().user and get_request().user.is_admin:
return # grant access to admins, to ease debug
raise AccessForbiddenError()
if not self.formdef.is_of_concern_for_user(api_user):
raise AccessForbiddenError()
class ApiFormsDirectory(Directory):
def _q_lookup(self, component):
api_user = get_user_from_api_query_string()
if not api_user:
# grant access to admins, to ease debug
if not (get_request().user and get_request().user.is_admin):
raise AccessForbiddenError()
return ApiFormPage(component)
class ApiDirectory(Directory):
_q_exports = ['forms', 'roles', ('reverse-geocoding', 'reverse_geocoding')]
forms = ApiFormsDirectory()
def reverse_geocoding(self):
try:
lat = get_request().form['lat']
lon = get_request().form['lon']
except KeyError:
raise QueryError
nominatim_url = get_publisher().get_site_option('nominatim_url')
if not nominatim_url:
nominatim_url = 'http://nominatim.openstreetmap.org'
get_response().set_content_type('application/json')
return urllib2.urlopen('%s/reverse?format=json&zoom=18&addressdetails=1&lat=%s&lon=%s' % (
nominatim_url, lat, lon)).read()
def roles(self):
get_response().set_content_type('application/json')
if not (get_request().user and get_request().user.can_go_in_admin()) and \
not get_user_from_api_query_string():
raise AccessForbiddenError()
list_roles = []
charset = get_publisher().site_charset
for role in Role.select():
list_roles.append({'text': unicode(role.name, charset),
'allows_backoffice_access': role.allows_backoffice_access,
'slug': role.slug,
'id': role.id})
get_response().set_content_type('application/json')
return json.dumps({'data': list_roles})