aboutsummaryrefslogtreecommitdiffstats
path: root/mediagoblin/plugins/oauth/views.py
blob: 1c0d7f86f3d865efd59c793893f767736aec4fc8 (plain)
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
# GNU MediaGoblin -- federated, autonomous media hosting
# Copyright (C) 2011, 2012 MediaGoblin contributors.  See AUTHORS.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import logging
import json

from webob import exc, Response
from urllib import urlencode
from uuid import uuid4
from datetime import datetime

from mediagoblin.tools.response import render_to_response, redirect
from mediagoblin.decorators import require_active_login
from mediagoblin.messages import add_message, SUCCESS, ERROR
from mediagoblin.tools.translate import pass_to_ugettext as _
from mediagoblin.plugins.oauth.models import OAuthCode, OAuthToken, \
        OAuthClient, OAuthUserClient
from mediagoblin.plugins.oauth.forms import ClientRegistrationForm, \
        AuthorizationForm
from mediagoblin.plugins.oauth.tools import require_client_auth
from mediagoblin.plugins.api.tools import json_response

_log = logging.getLogger(__name__)


@require_active_login
def register_client(request):
    '''
    Register an OAuth client
    '''
    form = ClientRegistrationForm(request.POST)

    if request.method == 'POST' and form.validate():
        client = OAuthClient()
        client.name = unicode(request.POST['name'])
        client.description = unicode(request.POST['description'])
        client.type = unicode(request.POST['type'])
        client.owner_id = request.user.id
        client.redirect_uri = unicode(request.POST['redirect_uri'])

        client.generate_identifier()
        client.generate_secret()

        client.save()

        add_message(request, SUCCESS, _('The client {0} has been registered!')\
                .format(
                    client.name))

        return redirect(request, 'mediagoblin.plugins.oauth.list_clients')

    return render_to_response(
            request,
            'oauth/client/register.html',
            {'form': form})


@require_active_login
def list_clients(request):
    clients = request.db.OAuthClient.query.filter(
            OAuthClient.owner_id == request.user.id).all()
    return render_to_response(request, 'oauth/client/list.html',
            {'clients': clients})


@require_active_login
def list_connections(request):
    connections = OAuthUserClient.query.filter(
            OAuthUserClient.user == request.user).all()
    return render_to_response(request, 'oauth/client/connections.html',
            {'connections': connections})


@require_active_login
def authorize_client(request):
    form = AuthorizationForm(request.POST)

    client = OAuthClient.query.filter(OAuthClient.id ==
        form.client_id.data).first()

    if not client:
        _log.error('''No such client id as received from client authorization
                form.''')
        return exc.HTTPBadRequest()

    if form.validate():
        relation = OAuthUserClient()
        relation.user_id = request.user.id
        relation.client_id = form.client_id.data
        if form.allow.data:
            relation.state = u'approved'
        elif form.deny.data:
            relation.state = u'rejected'
        else:
            return exc.HTTPBadRequest

        relation.save()

        return exc.HTTPFound(location=form.next.data)

    return render_to_response(
        request,
        'oauth/authorize.html',
        {'form': form,
            'client': client})


@require_client_auth
@require_active_login
def authorize(request, client):
    # TODO: Get rid of the JSON responses in this view, it's called by the
    # user-agent, not the client.
    user_client_relation = OAuthUserClient.query.filter(
            (OAuthUserClient.user == request.user)
            & (OAuthUserClient.client == client))

    if user_client_relation.filter(OAuthUserClient.state ==
            u'approved').count():
        redirect_uri = None

        if client.type == u'public':
            if not client.redirect_uri:
                return json_response({
                    'status': 400,
                    'errors':
                        [u'Public clients MUST have a redirect_uri pre-set']},
                        _disable_cors=True)

            redirect_uri = client.redirect_uri

        if client.type == u'confidential':
            redirect_uri = request.GET.get('redirect_uri', client.redirect_uri)
            if not redirect_uri:
                return json_response({
                    'status': 400,
                    'errors': [u'Can not find a redirect_uri for client: {0}'\
                            .format(client.name)]}, _disable_cors=True)

        code = OAuthCode()
        code.code = unicode(uuid4())
        code.user = request.user
        code.client = client
        code.save()

        redirect_uri = ''.join([
            redirect_uri,
            '?',
            urlencode({'code': code.code})])

        _log.debug('Redirecting to {0}'.format(redirect_uri))

        return exc.HTTPFound(location=redirect_uri)
    else:
        # Show prompt to allow client to access data
        # - on accept: send the user agent back to the redirect_uri with the
        # code parameter
        # - on deny: send the user agent back to the redirect uri with error
        # information
        form = AuthorizationForm(request.POST)
        form.client_id.data = client.id
        form.next.data = request.url
        return render_to_response(
                request,
                'oauth/authorize.html',
                {'form': form,
                'client': client})


def access_token(request):
    if request.GET.get('code'):
        code = OAuthCode.query.filter(OAuthCode.code ==
                request.GET.get('code')).first()

        if code:
            token = OAuthToken()
            token.token = unicode(uuid4())
            token.user = code.user
            token.client = code.client
            token.save()

            access_token_data = {
                'access_token': token.token,
                'token_type': 'bearer',
                'expires_in':
                (token.expires - datetime.now()).total_seconds()}
            return json_response(access_token_data, _disable_cors=True)

    error_data = {
        'error': 'Incorrect code'}
    return Response(json.dumps(error_data))