Project

General

Profile

Download (6.29 KB) Statistics
| Branch: | Tag: | Revision:

organization_api / ckanext / ozwillo_organization_api / plugin.py @ dca00d04

1
from hashlib import sha1
2
import hmac
3
import requests
4
import logging
5
import json
6

    
7
import ckan.plugins as plugins
8
import ckan.plugins.toolkit as toolkit
9

    
10
import ckan.logic as logic
11

    
12
from pylons import config
13
from ckan.common import request, _
14
from ckan.logic.action.create import _group_or_org_create as group_or_org_create
15
from ckan.logic.action.create import user_create
16
from ckan.logic.action.delete import _group_or_org_purge
17

    
18
plugin_config_prefix = 'ckanext.ozwillo_organization_api.'
19

    
20
log = logging.getLogger(__name__)
21

    
22
def valid_signature_required(func):
23

    
24
    signature_header_name = config.get(plugin_config_prefix + 'signature_header_name',
25
                                       'X-Hub-Signature')
26
    instantiated_secret = config.get(plugin_config_prefix + 'instantiation_secret',
27
                                     'secret')
28

    
29
    def wrapper(context, data):
30
        if signature_header_name in request.headers:
31
            if request.headers[signature_header_name].startswith('sha1='):
32
                algo, received_hmac = request.headers[signature_header_name].rsplit('=')
33
                computed_hmac = hmac.new(instantiated_secret, request.body, sha1).hexdigest()
34
                # the received hmac is uppercase according to
35
                # http://doc.ozwillo.com/#ref-3-2-1
36
                if received_hmac != computed_hmac.upper():
37
                    raise logic.NotAuthorized(_('Invalid HMAC'))
38
            else:
39
                raise logic.ValidationError(_('Invalid HMAC algo'))
40
        else:
41
            raise logic.NotAuthorized(_("No HMAC in the header"))
42
        return func(context, data)
43
    return wrapper
44

    
45
@valid_signature_required
46
def create_organization(context, data_dict):
47
    context['ignore_auth'] = True
48
    model = context['model']
49
    session = context['session']
50

    
51
    destruction_secret = config.get(plugin_config_prefix + 'destruction_secret',
52
                                       'changeme')
53

    
54
    client_id = data_dict.pop('client_id')
55
    client_secret = data_dict.pop('client_secret')
56
    instance_id = data_dict.pop('instance_id')
57

    
58
    # re-mapping received dict
59
    registration_uri = data_dict.pop('instance_registration_uri')
60
    organization = data_dict['organization']
61
    user = data_dict['user']
62
    user_dict = {
63
        'id': user['id'],
64
        'name': user['name'].lower().replace(' ', '').replace('.', ''),
65
        'email': user['email_address'],
66
        'password': user['id']
67
    }
68
    user_obj = model.User.get(user_dict['name'])
69

    
70
    org_dict = {
71
        'type': 'organization',
72
        'name': organization['name'].lower().replace(' ', '-'),
73
        'id': instance_id,
74
        'title': organization['name'],
75
        'user': user_dict['name']
76
    }
77

    
78
    if not user_obj:
79
        user_create(context, user_dict)
80
    context['user'] = user_dict['name']
81

    
82
    try:
83
        delete_uri = toolkit.url_for(host=request.host,
84
                                     controller='api', action='action',
85
                                     logic_function="delete-ozwillo-organization",
86
                                     ver=context['api_version'],
87
                                     qualified=True)
88
        organization_uri = toolkit.url_for(host=request.host,
89
                                           controller='organization',
90
                                           action='read',
91
                                           id=org_dict['name'],
92
                                           qualified=True)
93
        default_icon_url = toolkit.url_for(host=request.host,
94
                                           qualified=True,
95
                                           controller='home',
96
                                           action='index') + 'organization_icon.png'
97

    
98
        group_or_org_create(context, org_dict, is_org=True)
99

    
100
        # setting organization as active explicitely
101
        group = model.Group.get(org_dict['name'])
102
        group.state = 'active'
103
        group.image_url = default_icon_url
104
        group.save()
105
        model.repo.new_revision()
106
        model.GroupExtra(group_id=group.id, key='client_id',
107
                         value=client_id).save()
108
        model.GroupExtra(group_id=group.id, key='client_secret',
109
                         value=client_secret).save()
110
        session.flush()
111

    
112
        # notify about organization creation
113
        services = {'services': [{
114
            'local_id': 'organization',
115
            'name': 'Open Data',
116
            'service_uri': organization_uri + '/sso',
117
            'description': 'Organization ' + org_dict['name'] + ' on CKAN',
118
            'tos_uri': organization_uri,
119
            'policy_uri': organization_uri,
120
            'icon': group.image_url,
121
            'payment_option': 'FREE',
122
            'target_audience': ['PUBLIC_BODIES'],
123
            'contacts': [organization_uri],
124
            'redirect_uris': [organization_uri + '/callback'],
125
            'post_logout_redirect_uris': [organization_uri + '/logout'],
126
            'visible': False}],
127
            'instance_id': instance_id,
128
            'destruction_uri': delete_uri,
129
            'destruction_secret': destruction_secret,
130
            'needed_scopes': [{
131
                'scope_id': 'profile',
132
                'motivation': 'Used to link user to the organization'
133
            }]
134
        }
135
        headers = {'Content-type': 'application/json',
136
                   'Accept': 'application/json'}
137
        requests.post(registration_uri,
138
                      data=json.dumps(services),
139
                      auth=(client_id, client_secret),
140
                      headers=headers
141
                  )
142
    except logic.ValidationError, e:
143
        log.debug('Validation error "%s" occured while creating organization' % e)
144
        raise
145

    
146
@valid_signature_required
147
def delete_organization(context, data_dict):
148
    data_dict['id'] = data_dict.pop('instance_id')
149
    context['ignore_auth'] = True
150
    _group_or_org_purge(context, data_dict, is_org=True)
151

    
152

    
153
class OzwilloOrganizationApiPlugin(plugins.SingletonPlugin):
154
    """
155
    API for OASIS to create and delete an organization
156
    """
157
    plugins.implements(plugins.IActions)
158
    plugins.implements(plugins.IConfigurer)
159

    
160
    def update_config(self, config):
161
        toolkit.add_public_directory(config, 'public')
162

    
163
    def get_actions(self):
164
        return {
165
            'create-ozwillo-organization': create_organization,
166
            'delete-ozwillo-organization': delete_organization
167
        }
(2-2/2)