27ff32b488a20411fc796381ac3072cdc4ea4a88
1 # -*- coding: utf-8 -*-
2 # GNU MediaGoblin -- federated, autonomous media hosting
3 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU Affero General Public License for more details.
15 # You should have received a copy of the GNU Affero General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 from random
import getrandbits
22 from datetime
import datetime
24 from functools
import wraps
26 from mediagoblin
.plugins
.api
.tools
import json_response
29 def require_client_auth(controller
):
33 - Requires the presence of ``?client_id``
35 # Avoid circular import
36 from mediagoblin
.plugins
.oauth
.models
import OAuthClient
39 def wrapper(request
, *args
, **kw
):
40 if not request
.GET
.get('client_id'):
41 return json_response({
43 'errors': [u
'No client identifier in URL']},
46 client
= OAuthClient
.query
.filter(
47 OAuthClient
.identifier
== request
.GET
.get('client_id')).first()
50 return json_response({
52 'errors': [u
'No such client identifier']},
55 return controller(request
, client
)
60 def create_token(client
, user
):
62 Create an OAuthToken and an OAuthRefreshToken entry in the database
64 Returns the data structure expected by the OAuth clients.
66 from mediagoblin
.plugins
.oauth
.models
import OAuthToken
, OAuthRefreshToken
73 refresh_token
= OAuthRefreshToken()
74 refresh_token
.user
= user
75 refresh_token
.client
= client
78 # expire time of token in full seconds
79 # timedelta.total_seconds is python >= 2.7 or we would use that
80 td
= token
.expires
- datetime
.now()
81 exp_in
= 86400*td
.days
+ td
.seconds
# just ignore µsec
83 return {'access_token': token
.token
, 'token_type': 'bearer',
84 'refresh_token': refresh_token
.token
, 'expires_in': exp_in
}
87 def generate_identifier():
88 ''' Generates a ``uuid.uuid4()`` '''
89 return unicode(uuid
.uuid4())
93 ''' Uses generate_identifier '''
94 return generate_identifier()
97 def generate_refresh_token():
98 ''' Uses generate_identifier '''
99 return generate_identifier()
103 ''' Uses generate_identifier '''
104 return generate_identifier()
107 def generate_secret():
109 Generate a long string of pseudo-random characters
111 # XXX: We might not want it to use bcrypt, since bcrypt takes its time to
112 # generate the result.
113 return unicode(getrandbits(192))