summaryrefslogtreecommitdiffstats
path: root/forum_modules
diff options
context:
space:
mode:
Diffstat (limited to 'forum_modules')
-rwxr-xr-xforum_modules/facebookauth/__init__.py0
-rwxr-xr-xforum_modules/facebookauth/authentication.py85
-rwxr-xr-xforum_modules/facebookauth/settings.py3
-rwxr-xr-xforum_modules/facebookauth/templates/button.html38
-rwxr-xr-xforum_modules/facebookauth/templates/xd_receiver.html1
-rwxr-xr-xforum_modules/facebookauth/urls.py9
-rwxr-xr-xforum_modules/facebookauth/views.py11
-rwxr-xr-xforum_modules/localauth/__init__.py0
-rwxr-xr-xforum_modules/localauth/authentication.py18
-rwxr-xr-xforum_modules/localauth/forms.py77
-rwxr-xr-xforum_modules/localauth/templates/loginform.html31
-rwxr-xr-xforum_modules/localauth/urls.py8
-rwxr-xr-xforum_modules/localauth/views.py31
-rwxr-xr-xforum_modules/oauthauth/__init__.py0
-rwxr-xr-xforum_modules/oauthauth/authentication.py41
-rwxr-xr-xforum_modules/oauthauth/consumer.py87
-rwxr-xr-xforum_modules/oauthauth/lib/__init__.py0
-rwxr-xr-xforum_modules/oauthauth/lib/oauth.py594
-rwxr-xr-xforum_modules/oauthauth/settings.py3
-rwxr-xr-xforum_modules/openidauth/__init__.py0
-rwxr-xr-xforum_modules/openidauth/authentication.py196
-rwxr-xr-xforum_modules/openidauth/consumer.py112
-rwxr-xr-xforum_modules/openidauth/models.py26
-rwxr-xr-xforum_modules/openidauth/settings.py9
-rwxr-xr-xforum_modules/openidauth/store.py79
-rwxr-xr-xforum_modules/openidauth/templates/openidurl.html20
26 files changed, 0 insertions, 1479 deletions
diff --git a/forum_modules/facebookauth/__init__.py b/forum_modules/facebookauth/__init__.py
deleted file mode 100755
index e69de29b..00000000
--- a/forum_modules/facebookauth/__init__.py
+++ /dev/null
diff --git a/forum_modules/facebookauth/authentication.py b/forum_modules/facebookauth/authentication.py
deleted file mode 100755
index 512367a3..00000000
--- a/forum_modules/facebookauth/authentication.py
+++ /dev/null
@@ -1,85 +0,0 @@
-import hashlib
-from time import time
-from datetime import datetime
-from urllib import urlopen, urlencode
-from forum.authentication.base import AuthenticationConsumer, ConsumerTemplateContext, InvalidAuthentication
-from django.utils.translation import ugettext as _
-
-import settings
-
-try:
- from json import load as load_json
-except:
- from django.utils.simplejson import JSONDecoder
-
- def load_json(json):
- decoder = JSONDecoder()
- return decoder.decode(json.read())
-
-class FacebookAuthConsumer(AuthenticationConsumer):
-
- def process_authentication_request(self, request):
- API_KEY = settings.FB_API_KEY
-
- if API_KEY in request.COOKIES:
- if self.check_cookies_signature(request.COOKIES):
- if self.check_session_expiry(request.COOKIES):
- return request.COOKIES[API_KEY + '_user']
- else:
- raise InvalidAuthentication(_('Sorry, your Facebook session has expired, please try again'))
- else:
- raise InvalidAuthentication(_('The authentication with Facebook connect failed due to an invalid signature'))
- else:
- raise InvalidAuthentication(_('The authentication with Facebook connect failed, cannot find authentication tokens'))
-
- def generate_signature(self, values):
- keys = []
-
- for key in sorted(values.keys()):
- keys.append(key)
-
- signature = ''.join(['%s=%s' % (key, values[key]) for key in keys]) + settings.FB_APP_SECRET
- return hashlib.md5(signature).hexdigest()
-
- def check_session_expiry(self, cookies):
- return datetime.fromtimestamp(float(cookies[settings.FB_API_KEY+'_expires'])) > datetime.now()
-
- def check_cookies_signature(self, cookies):
- API_KEY = settings.FB_API_KEY
-
- values = {}
-
- for key in cookies.keys():
- if (key.startswith(API_KEY + '_')):
- values[key.replace(API_KEY + '_', '')] = cookies[key]
-
- return self.generate_signature(values) == cookies[API_KEY]
-
- def get_user_data(self, key):
- request_data = {
- 'method': 'Users.getInfo',
- 'api_key': settings.FB_API_KEY,
- 'call_id': time(),
- 'v': '1.0',
- 'uids': key,
- 'fields': 'name,first_name,last_name,email',
- 'format': 'json',
- }
-
- request_data['sig'] = self.generate_signature(request_data)
- fb_response = load_json(urlopen(settings.REST_SERVER, urlencode(request_data)))[0]
-
- return {
- 'username': fb_response['first_name'] + ' ' + fb_response['last_name'],
- 'email': fb_response['email']
- }
-
-class FacebookAuthContext(ConsumerTemplateContext):
- mode = 'BIGICON'
- type = 'CUSTOM'
- weight = 100
- human_name = 'Facebook'
- code_template = 'modules/facebookauth/button.html'
- extra_css = ["http://www.facebook.com/css/connect/connect_button.css"]
-
- API_KEY = settings.FB_API_KEY \ No newline at end of file
diff --git a/forum_modules/facebookauth/settings.py b/forum_modules/facebookauth/settings.py
deleted file mode 100755
index 67bf80c1..00000000
--- a/forum_modules/facebookauth/settings.py
+++ /dev/null
@@ -1,3 +0,0 @@
-REST_SERVER = 'http://api.facebook.com/restserver.php'
-FB_API_KEY = 'f773fab7be12aea689948208f37ad336'
-FB_APP_SECRET = '894547c1b8db54d77f919b1695ae879c' \ No newline at end of file
diff --git a/forum_modules/facebookauth/templates/button.html b/forum_modules/facebookauth/templates/button.html
deleted file mode 100755
index ceae1fc2..00000000
--- a/forum_modules/facebookauth/templates/button.html
+++ /dev/null
@@ -1,38 +0,0 @@
-<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_US" type="text/javascript"></script>
-<script type="text/javascript">
- var FB_API_KEY = "{{ provider.API_KEY }}";
- var FB_CHANNEL_PATH = "{% url xd_receiver %}";
-
- FB.init(FB_API_KEY, FB_CHANNEL_PATH, {permsToRequestOnConnect : "email"});
-
- function FB_ConnectPostAuthorization() {
- if ($('#validate_email').attr('checked')) {
- FB_RequireFeatures(["Api"], function(){
- var api = FB.Facebook.apiClient;
- var fb_uid = api.get_session().uid;
-
- $.post('{% url facebook_user_is_registered %}', {'fb_uid': fb_uid}, function(response) {
- if (response != "yes") {
- api.users_hasAppPermission("email", function(result) {
- if (!result) {
- FB.Connect.showPermissionDialog("email", redirect_to_done_page);
- } else {
- redirect_to_done_page()
- }
- })
- } else {
- redirect_to_done_page()
- }
- });
- });
- } else {
- redirect_to_done_page();
- }
- }
-
- function redirect_to_done_page() {
- window.location = "{% url auth_provider_done provider=provider.id %}";
- }
-
-</script>
-<fb:login-button v="2" size="medium" onlogin="FB_ConnectPostAuthorization()">Facebook</fb:login-button> \ No newline at end of file
diff --git a/forum_modules/facebookauth/templates/xd_receiver.html b/forum_modules/facebookauth/templates/xd_receiver.html
deleted file mode 100755
index 9c1664d2..00000000
--- a/forum_modules/facebookauth/templates/xd_receiver.html
+++ /dev/null
@@ -1 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <body> <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/XdCommReceiver.js" type="text/javascript"></script> </body> </html>
diff --git a/forum_modules/facebookauth/urls.py b/forum_modules/facebookauth/urls.py
deleted file mode 100755
index cbe3b6c7..00000000
--- a/forum_modules/facebookauth/urls.py
+++ /dev/null
@@ -1,9 +0,0 @@
-from django.conf.urls.defaults import *
-from django.views.generic.simple import direct_to_template
-
-from views import user_is_registered
-
-urlpatterns = patterns('',
- url(r'^xd_receiver.htm$', direct_to_template, {'template': 'modules/facebookauth/xd_receiver.html'}, name='xd_receiver'),
- url(r'^facebook/user_is_registered/', user_is_registered, name="facebook_user_is_registered"),
-) \ No newline at end of file
diff --git a/forum_modules/facebookauth/views.py b/forum_modules/facebookauth/views.py
deleted file mode 100755
index f77c6282..00000000
--- a/forum_modules/facebookauth/views.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from forum.models import AuthKeyUserAssociation
-from django.http import HttpResponse
-
-def user_is_registered(request):
- try:
- fb_uid = request.POST['fb_uid']
- #print fb_uid
- AuthKeyUserAssociation.objects.get(key=fb_uid)
- return HttpResponse('yes')
- except:
- return HttpResponse('no') \ No newline at end of file
diff --git a/forum_modules/localauth/__init__.py b/forum_modules/localauth/__init__.py
deleted file mode 100755
index e69de29b..00000000
--- a/forum_modules/localauth/__init__.py
+++ /dev/null
diff --git a/forum_modules/localauth/authentication.py b/forum_modules/localauth/authentication.py
deleted file mode 100755
index 770ea08f..00000000
--- a/forum_modules/localauth/authentication.py
+++ /dev/null
@@ -1,18 +0,0 @@
-from forum.authentication.base import AuthenticationConsumer, ConsumerTemplateContext, InvalidAuthentication
-from forms import ClassicLoginForm
-
-class LocalAuthConsumer(AuthenticationConsumer):
- def process_authentication_request(self, request):
- form_auth = ClassicLoginForm(request.POST)
-
- if form_auth.is_valid():
- return form_auth.get_user()
- else:
- raise InvalidAuthentication(" ".join(form_auth.errors.values()[0]))
-
-class LocalAuthContext(ConsumerTemplateContext):
- mode = 'STACK_ITEM'
- weight = 1000
- human_name = 'Local authentication'
- stack_item_template = 'modules/localauth/loginform.html'
- show_to_logged_in_user = False \ No newline at end of file
diff --git a/forum_modules/localauth/forms.py b/forum_modules/localauth/forms.py
deleted file mode 100755
index 8afa2b05..00000000
--- a/forum_modules/localauth/forms.py
+++ /dev/null
@@ -1,77 +0,0 @@
-from forum.utils.forms import NextUrlField, UserNameField, UserEmailField, SetPasswordForm
-from forum.models import EmailFeedSetting, Question
-from django.contrib.contenttypes.models import ContentType
-from django.utils.translation import ugettext as _
-from django.contrib.auth import authenticate
-from django import forms
-import logging
-
-class ClassicRegisterForm(SetPasswordForm):
- """ legacy registration form """
-
- next = NextUrlField()
- username = UserNameField()
- email = UserEmailField()
- #fields password1 and password2 are inherited
- #recaptcha = ReCaptchaField()
-
-class ClassicLoginForm(forms.Form):
- """ legacy account signin form """
- next = NextUrlField()
- username = UserNameField(required=False,skip_clean=True)
- password = forms.CharField(max_length=128,
- widget=forms.widgets.PasswordInput(attrs={'class':'required login'}),
- required=False)
-
- def __init__(self, data=None, files=None, auto_id='id_%s',
- prefix=None, initial=None):
- super(ClassicLoginForm, self).__init__(data, files, auto_id,
- prefix, initial)
- self.user_cache = None
-
- def _clean_nonempty_field(self,field):
- value = None
- if field in self.cleaned_data:
- value = str(self.cleaned_data[field]).strip()
- if value == '':
- value = None
- self.cleaned_data[field] = value
- return value
-
- def clean_username(self):
- return self._clean_nonempty_field('username')
-
- def clean_password(self):
- return self._clean_nonempty_field('password')
-
- def clean(self):
- error_list = []
- username = self.cleaned_data['username']
- password = self.cleaned_data['password']
-
- self.user_cache = None
- if username and password:
- self.user_cache = authenticate(username=username, password=password)
-
- if self.user_cache is None:
- del self.cleaned_data['username']
- del self.cleaned_data['password']
- error_list.insert(0,(_("Please enter valid username and password "
- "(both are case-sensitive).")))
- elif self.user_cache.is_active == False:
- error_list.append(_("This account is inactive."))
- if len(error_list) > 0:
- error_list.insert(0,_('Login failed.'))
- elif password == None and username == None:
- error_list.append(_('Please enter username and password'))
- elif password == None:
- error_list.append(_('Please enter your password'))
- elif username == None:
- error_list.append(_('Please enter user name'))
- if len(error_list) > 0:
- self._errors['__all__'] = forms.util.ErrorList(error_list)
- return self.cleaned_data
-
- def get_user(self):
- """ get authenticated user """
- return self.user_cache \ No newline at end of file
diff --git a/forum_modules/localauth/templates/loginform.html b/forum_modules/localauth/templates/loginform.html
deleted file mode 100755
index b1784fb6..00000000
--- a/forum_modules/localauth/templates/loginform.html
+++ /dev/null
@@ -1,31 +0,0 @@
-{% load i18n %}
-
-<fieldset id='local_login_fs'>
- <p><span class='big strong'>Enter your local user name and password</span><br/><span class='grey'>(or select your external provider above)</span></p>
- <table>
- <tr>
- <td>
- <label for="id_username">Login name</label>
- </td>
- <td>
- <input id="id_username" type="text" class="required login" name="username" maxlength="30" />
- </td>
- </tr>
- <tr>
- <td>
- <label for="id_password">Password</label>
- </td>
- <td>
- <input id="id_password" type="password" class="required login" name="password" maxlength="128" />
- </td>
- </tr>
- <tr>
- <td>
- <input id="blogin" name="blogin" type="submit" value="Login" />
- </td>
- <td>
- <a href="{% url auth_local_register %}">Create account</a><span>&nbsp;|&nbsp;</span><a href="{% url auth_request_tempsignin %}">Forgot your password?</a>
- </td>
- </tr>
- </table>
-</fieldset> \ No newline at end of file
diff --git a/forum_modules/localauth/urls.py b/forum_modules/localauth/urls.py
deleted file mode 100755
index aeebc40a..00000000
--- a/forum_modules/localauth/urls.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from django.conf.urls.defaults import *
-from django.views.generic.simple import direct_to_template
-from django.utils.translation import ugettext as _
-import views as app
-
-urlpatterns = patterns('',
- url(r'^%s%s%s$' % (_('account/'), _('local/'), _('register/')), app.register, name='auth_local_register'),
-) \ No newline at end of file
diff --git a/forum_modules/localauth/views.py b/forum_modules/localauth/views.py
deleted file mode 100755
index db71e902..00000000
--- a/forum_modules/localauth/views.py
+++ /dev/null
@@ -1,31 +0,0 @@
-from django.contrib.auth.models import User
-from django.shortcuts import render_to_response
-from django.template import RequestContext
-from django.utils.translation import ugettext as _
-
-from forms import ClassicRegisterForm
-from forum.authentication.forms import SimpleEmailSubscribeForm
-from forum.views.auth import login_and_forward, send_validation_email
-
-def register(request):
- if request.method == 'POST':
- form = ClassicRegisterForm(request.POST)
- email_feeds_form = SimpleEmailSubscribeForm(request.POST)
-
- if form.is_valid() and email_feeds_form.is_valid():
- username = form.cleaned_data['username']
- password = form.cleaned_data['password1']
- email = form.cleaned_data['email']
-
- user_ = User.objects.create_user( username,email,password )
- send_validation_email(user_)
- email_feeds_form.save(user_)
- return login_and_forward(request, user_, None, _("A validation email has been sent to your email address. "))
- else:
- form = ClassicRegisterForm(initial={'next':'/'})
- email_feeds_form = SimpleEmailSubscribeForm()
-
- return render_to_response('auth/signup.html', {
- 'form': form,
- 'email_feeds_form': email_feeds_form
- }, context_instance=RequestContext(request)) \ No newline at end of file
diff --git a/forum_modules/oauthauth/__init__.py b/forum_modules/oauthauth/__init__.py
deleted file mode 100755
index e69de29b..00000000
--- a/forum_modules/oauthauth/__init__.py
+++ /dev/null
diff --git a/forum_modules/oauthauth/authentication.py b/forum_modules/oauthauth/authentication.py
deleted file mode 100755
index 04145461..00000000
--- a/forum_modules/oauthauth/authentication.py
+++ /dev/null
@@ -1,41 +0,0 @@
-from consumer import OAuthAbstractAuthConsumer
-from forum.authentication.base import ConsumerTemplateContext
-
-try:
- import json as simplejson
-except ImportError:
- from django.utils import simplejson
-
-from lib import oauth
-import settings
-
-class TwitterAuthConsumer(OAuthAbstractAuthConsumer):
- def __init__(self):
- OAuthAbstractAuthConsumer.__init__(self,
- settings.TWITTER_CONSUMER_KEY,
- settings.TWITTER_CONSUMER_SECRET,
- "twitter.com",
- "https://twitter.com/oauth/request_token",
- "https://twitter.com/oauth/access_token",
- "https://twitter.com/oauth/authorize",
- )
-
- def get_user_data(self, key):
- json = self.fetch_data(key, "https://twitter.com/account/verify_credentials.json")
-
- if 'screen_name' in json:
- creds = simplejson.loads(json)
-
- return {
- 'username': creds['screen_name']
- }
-
-
- return {}
-
-class TwitterAuthContext(ConsumerTemplateContext):
- mode = 'BIGICON'
- type = 'DIRECT'
- weight = 150
- human_name = 'Twitter'
- icon = '/media/images/openid/twitter.png' \ No newline at end of file
diff --git a/forum_modules/oauthauth/consumer.py b/forum_modules/oauthauth/consumer.py
deleted file mode 100755
index 74734145..00000000
--- a/forum_modules/oauthauth/consumer.py
+++ /dev/null
@@ -1,87 +0,0 @@
-import urllib
-import urllib2
-import httplib
-import time
-
-from forum.authentication.base import AuthenticationConsumer, InvalidAuthentication
-from django.utils.translation import ugettext as _
-
-from lib import oauth
-
-class OAuthAbstractAuthConsumer(AuthenticationConsumer):
-
- def __init__(self, consumer_key, consumer_secret, server_url, request_token_url, access_token_url, authorization_url):
- self.consumer_secret = consumer_secret
- self.consumer_key = consumer_key
-
- self.consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)
- self.signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
-
- self.server_url = server_url
- self.request_token_url = request_token_url
- self.access_token_url = access_token_url
- self.authorization_url = authorization_url
-
- def prepare_authentication_request(self, request, redirect_to):
- request_token = self.fetch_request_token()
- request.session['unauthed_token'] = request_token.to_string()
- return self.authorize_token_url(request_token)
-
- def process_authentication_request(self, request):
- unauthed_token = request.session.get('unauthed_token', None)
- if not unauthed_token:
- raise InvalidAuthentication(_('Error, the oauth token is not on the server'))
-
- token = oauth.OAuthToken.from_string(unauthed_token)
-
- if token.key != request.GET.get('oauth_token', 'no-token'):
- raise InvalidAuthentication(_("Something went wrong! Auth tokens do not match"))
-
- access_token = self.fetch_access_token(token)
-
- return access_token.to_string()
-
- def get_user_data(self, key):
- #token = oauth.OAuthToken.from_string(access_token)
- return {}
-
- def fetch_request_token(self):
- oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer, http_url=self.request_token_url)
- oauth_request.sign_request(self.signature_method, self.consumer, None)
- params = oauth_request.parameters
- data = urllib.urlencode(params)
- full_url='%s?%s'%(self.request_token_url, data)
- response = urllib2.urlopen(full_url)
- return oauth.OAuthToken.from_string(response.read())
-
- def authorize_token_url(self, token, callback_url=None):
- oauth_request = oauth.OAuthRequest.from_token_and_callback(token=token,\
- callback=callback_url, http_url=self.authorization_url)
- params = oauth_request.parameters
- data = urllib.urlencode(params)
- full_url='%s?%s'%(self.authorization_url, data)
- return full_url
-
- def fetch_access_token(self, token):
- oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer, token=token, http_url=self.access_token_url)
- oauth_request.sign_request(self.signature_method, self.consumer, token)
- params = oauth_request.parameters
- data = urllib.urlencode(params)
- full_url='%s?%s'%(self.access_token_url, data)
- response = urllib2.urlopen(full_url)
- return oauth.OAuthToken.from_string(response.read())
-
- def fetch_data(self, token, http_url, parameters=None):
- access_token = oauth.OAuthToken.from_string(token)
- oauth_request = oauth.OAuthRequest.from_consumer_and_token(
- self.consumer, token=access_token, http_method="GET",
- http_url=http_url, parameters=parameters,
- )
- oauth_request.sign_request(self.signature_method, self.consumer, access_token)
-
- url = oauth_request.to_url()
- connection = httplib.HTTPSConnection(self.server_url)
- connection.request(oauth_request.http_method, url)
-
- return connection.getresponse().read()
-
diff --git a/forum_modules/oauthauth/lib/__init__.py b/forum_modules/oauthauth/lib/__init__.py
deleted file mode 100755
index e69de29b..00000000
--- a/forum_modules/oauthauth/lib/__init__.py
+++ /dev/null
diff --git a/forum_modules/oauthauth/lib/oauth.py b/forum_modules/oauthauth/lib/oauth.py
deleted file mode 100755
index 89abf858..00000000
--- a/forum_modules/oauthauth/lib/oauth.py
+++ /dev/null
@@ -1,594 +0,0 @@
-"""
-The MIT License
-
-Copyright (c) 2007 Leah Culver
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
-"""
-
-import cgi
-import urllib
-import time
-import random
-import urlparse
-import hmac
-import binascii
-
-
-VERSION = '1.0' # Hi Blaine!
-HTTP_METHOD = 'GET'
-SIGNATURE_METHOD = 'PLAINTEXT'
-
-
-class OAuthError(RuntimeError):
- """Generic exception class."""
- def __init__(self, message='OAuth error occured.'):
- self.message = message
-
-def build_authenticate_header(realm=''):
- """Optional WWW-Authenticate header (401 error)"""
- return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
-
-def escape(s):
- """Escape a URL including any /."""
- return urllib.quote(s, safe='~')
-
-def _utf8_str(s):
- """Convert unicode to utf-8."""
- if isinstance(s, unicode):
- return s.encode("utf-8")
- else:
- return str(s)
-
-def generate_timestamp():
- """Get seconds since epoch (UTC)."""
- return int(time.time())
-
-def generate_nonce(length=8):
- """Generate pseudorandom number."""
- return ''.join([str(random.randint(0, 9)) for i in range(length)])
-
-
-class OAuthConsumer(object):
- """Consumer of OAuth authentication.
-
- OAuthConsumer is a data type that represents the identity of the Consumer
- via its shared secret with the Service Provider.
-
- """
- key = None
- secret = None
-
- def __init__(self, key, secret):
- self.key = key
- self.secret = secret
-
-
-class OAuthToken(object):
- """OAuthToken is a data type that represents an End User via either an access
- or request token.
-
- key -- the token
- secret -- the token secret
-
- """
- key = None
- secret = None
-
- def __init__(self, key, secret):
- self.key = key
- self.secret = secret
-
- def to_string(self):
- return urllib.urlencode({'oauth_token': self.key,
- 'oauth_token_secret': self.secret})
-
- def from_string(s):
- """ Returns a token from something like:
- oauth_token_secret=xxx&oauth_token=xxx
- """
- params = cgi.parse_qs(s, keep_blank_values=False)
- key = params['oauth_token'][0]
- secret = params['oauth_token_secret'][0]
- return OAuthToken(key, secret)
- from_string = staticmethod(from_string)
-
- def __str__(self):
- return self.to_string()
-
-
-class OAuthRequest(object):
- """OAuthRequest represents the request and can be serialized.
-
- OAuth parameters:
- - oauth_consumer_key
- - oauth_token
- - oauth_signature_method
- - oauth_signature
- - oauth_timestamp
- - oauth_nonce
- - oauth_version
- ... any additional parameters, as defined by the Service Provider.
- """
- parameters = None # OAuth parameters.
- http_method = HTTP_METHOD
- http_url = None
- version = VERSION
-
- def __init__(self, http_method=HTTP_METHOD, http_url=None, parameters=None):
- self.http_method = http_method
- self.http_url = http_url
- self.parameters = parameters or {}
-
- def set_parameter(self, parameter, value):
- self.parameters[parameter] = value
-
- def get_parameter(self, parameter):
- try:
- return self.parameters[parameter]
- except:
- raise OAuthError('Parameter not found: %s' % parameter)
-
- def _get_timestamp_nonce(self):
- return self.get_parameter('oauth_timestamp'), self.get_parameter(
- 'oauth_nonce')
-
- def get_nonoauth_parameters(self):
- """Get any non-OAuth parameters."""
- parameters = {}
- for k, v in self.parameters.iteritems():
- # Ignore oauth parameters.
- if k.find('oauth_') < 0:
- parameters[k] = v
- return parameters
-
- def to_header(self, realm=''):
- """Serialize as a header for an HTTPAuth request."""
- auth_header = 'OAuth realm="%s"' % realm
- # Add the oauth parameters.
- if self.parameters:
- for k, v in self.parameters.iteritems():
- if k[:6] == 'oauth_':
- auth_header += ', %s="%s"' % (k, escape(str(v)))
- return {'Authorization': auth_header}
-
- def to_postdata(self):
- """Serialize as post data for a POST request."""
- return '&'.join(['%s=%s' % (escape(str(k)), escape(str(v))) \
- for k, v in self.parameters.iteritems()])
-
- def to_url(self):
- """Serialize as a URL for a GET request."""
- return '%s?%s' % (self.get_normalized_http_url(), self.to_postdata())
-
- def get_normalized_parameters(self):
- """Return a string that contains the parameters that must be signed."""
- params = self.parameters
- try:
- # Exclude the signature if it exists.
- del params['oauth_signature']
- except:
- pass
- # Escape key values before sorting.
- key_values = [(escape(_utf8_str(k)), escape(_utf8_str(v))) \
- for k,v in params.items()]
- # Sort lexicographically, first after key, then after value.
- key_values.sort()
- # Combine key value pairs into a string.
- return '&'.join(['%s=%s' % (k, v) for k, v in key_values])
-
- def get_normalized_http_method(self):
- """Uppercases the http method."""
- return self.http_method.upper()
-
- def get_normalized_http_url(self):
- """Parses the URL and rebuilds it to be scheme://host/path."""
- parts = urlparse.urlparse(self.http_url)
- scheme, netloc, path = parts[:3]
- # Exclude default port numbers.
- if scheme == 'http' and netloc[-3:] == ':80':
- netloc = netloc[:-3]
- elif scheme == 'https' and netloc[-4:] == ':443':
- netloc = netloc[:-4]
- return '%s://%s%s' % (scheme, netloc, path)
-
- def sign_request(self, signature_method, consumer, token):
- """Set the signature parameter to the result of build_signature."""
- # Set the signature method.
- self.set_parameter('oauth_signature_method',
- signature_method.get_name())
- # Set the signature.
- self.set_parameter('oauth_signature',
- self.build_signature(signature_method, consumer, token))
-
- def build_signature(self, signature_method, consumer, token):
- """Calls the build signature method within the signature method."""
- return signature_method.build_signature(self, consumer, token)
-
- def from_request(http_method, http_url, headers=None, parameters=None,
- query_string=None):
- """Combines multiple parameter sources."""
- if parameters is None:
- parameters = {}
-
- # Headers
- if headers and 'Authorization' in headers:
- auth_header = headers['Authorization']
- # Check that the authorization header is OAuth.
- if auth_header.index('OAuth') > -1:
- auth_header = auth_header.lstrip('OAuth ')
- try:
- # Get the parameters from the header.
- header_params = OAuthRequest._split_header(auth_header)
- parameters.update(header_params)
- except:
- raise OAuthError('Unable to parse OAuth parameters from '
- 'Authorization header.')
-
- # GET or POST query string.
- if query_string:
- query_params = OAuthRequest._split_url_string(query_string)
- parameters.update(query_params)
-
- # URL parameters.
- param_str = urlparse.urlparse(http_url)[4] # query
- url_params = OAuthRequest._split_url_string(param_str)
- parameters.update(url_params)
-
- if parameters:
- return OAuthRequest(http_method, http_url, parameters)
-
- return None
- from_request = staticmethod(from_request)
-
- def from_consumer_and_token(oauth_consumer, token=None,
- http_method=HTTP_METHOD, http_url=None, parameters=None):
- if not parameters:
- parameters = {}
-
- defaults = {
- 'oauth_consumer_key': oauth_consumer.key,
- 'oauth_timestamp': generate_timestamp(),
- 'oauth_nonce': generate_nonce(),
- 'oauth_version': OAuthRequest.version,
- }
-
- defaults.update(parameters)
- parameters = defaults
-
- if token:
- parameters['oauth_token'] = token.key
-
- return OAuthRequest(http_method, http_url, parameters)
- from_consumer_and_token = staticmethod(from_consumer_and_token)
-
- def from_token_and_callback(token, callback=None, http_method=HTTP_METHOD,
- http_url=None, parameters=None):
- if not parameters:
- parameters = {}
-
- parameters['oauth_token'] = token.key
-
- if callback:
- parameters['oauth_callback'] = callback
-
- return OAuthRequest(http_method, http_url, parameters)
- from_token_and_callback = staticmethod(from_token_and_callback)
-
- def _split_header(header):
- """Turn Authorization: header into parameters."""
- params = {}
- parts = header.split(',')
- for param in parts:
- # Ignore realm parameter.
- if param.find('realm') > -1:
- continue
- # Remove whitespace.
- param = param.strip()
- # Split key-value.
- param_parts = param.split('=', 1)
- # Remove quotes and unescape the value.
- params[param_parts[0]] = urllib.unquote(param_parts[1].strip('\"'))
- return params
- _split_header = staticmethod(_split_header)
-
- def _split_url_string(param_str):
- """Turn URL string into parameters."""
- parameters = cgi.parse_qs(param_str, keep_blank_values=False)
- for k, v in parameters.iteritems():
- parameters[k] = urllib.unquote(v[0])
- return parameters
- _split_url_string = staticmethod(_split_url_string)
-
-class OAuthServer(object):
- """A worker to check the validity of a request against a data store."""
- timestamp_threshold = 300 # In seconds, five minutes.
- version = VERSION
- signature_methods = None
- data_store = None
-
- def __init__(self, data_store=None, signature_methods=None):
- self.data_store = data_store
- self.signature_methods = signature_methods or {}
-
- def set_data_store(self, data_store):
- self.data_store = data_store
-
- def get_data_store(self):
- return self.data_store
-
- def add_signature_method(self, signature_method):
- self.signature_methods[signature_method.get_name()] = signature_method
- return self.signature_methods
-
- def fetch_request_token(self, oauth_request):
- """Processes a request_token request and returns the
- request token on success.
- """
- try:
- # Get the request token for authorization.
- token = self._get_token(oauth_request, 'request')
- except OAuthError:
- # No token required for the initial token request.
- version = self._get_version(oauth_request)
- consumer = self._get_consumer(oauth_request)
- self._check_signature(oauth_request, consumer, None)
- # Fetch a new token.
- token = self.data_store.fetch_request_token(consumer)
- return token
-
- def fetch_access_token(self, oauth_request):
- """Processes an access_token request and returns the
- access token on success.
- """
- version = self._get_version(oauth_request)
- consumer = self._get_consumer(oauth_request)
- # Get the request token.
- token = self._get_token(oauth_request, 'request')
- self._check_signature(oauth_request, consumer, token)
- new_token = self.data_store.fetch_access_token(consumer, token)
- return new_token
-
- def verify_request(self, oauth_request):
- """Verifies an api call and checks all the parameters."""
- # -> consumer and token
- version = self._get_version(oauth_request)
- consumer = self._get_consumer(oauth_request)
- # Get the access token.
- token = self._get_token(oauth_request, 'access')
- self._check_signature(oauth_request, consumer, token)
- parameters = oauth_request.get_nonoauth_parameters()
- return consumer, token, parameters
-
- def authorize_token(self, token, user):
- """Authorize a request token."""
- return self.data_store.authorize_request_token(token, user)
-
- def get_callback(self, oauth_request):
- """Get the callback URL."""
- return oauth_request.get_parameter('oauth_callback')
-
- def build_authenticate_header(self, realm=''):
- """Optional support for the authenticate header."""
- return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
-
- def _get_version(self, oauth_request):
- """Verify the correct version request for this server."""
- try:
- version = oauth_request.get_parameter('oauth_version')
- except:
- version = VERSION
- if version and version != self.version:
- raise OAuthError('OAuth version %s not supported.' % str(version))
- return version
-
- def _get_signature_method(self, oauth_request):
- """Figure out the signature with some defaults."""
- try:
- signature_method = oauth_request.get_parameter(
- 'oauth_signature_method')
- except:
- signature_method = SIGNATURE_METHOD
- try:
- # Get the signature method object.
- signature_method = self.signature_methods[signature_method]
- except:
- signature_method_names = ', '.join(self.signature_methods.keys())
- raise OAuthError('Signature method %s not supported try one of the '
- 'following: %s' % (signature_method, signature_method_names))
-
- return signature_method
-
- def _get_consumer(self, oauth_request):
- consumer_key = oauth_request.get_parameter('oauth_consumer_key')
- consumer = self.data_store.lookup_consumer(consumer_key)
- if not consumer:
- raise OAuthError('Invalid consumer.')
- return consumer
-
- def _get_token(self, oauth_request, token_type='access'):
- """Try to find the token for the provided request token key."""
- token_field = oauth_request.get_parameter('oauth_token')
- token = self.data_store.lookup_token(token_type, token_field)
- if not token:
- raise OAuthError('Invalid %s token: %s' % (token_type, token_field))
- return token
-
- def _check_signature(self, oauth_request, consumer, token):
- timestamp, nonce = oauth_request._get_timestamp_nonce()
- self._check_timestamp(timestamp)
- self._check_nonce(consumer, token, nonce)
- signature_method = self._get_signature_method(oauth_request)
- try:
- signature = oauth_request.get_parameter('oauth_signature')
- except:
- raise OAuthError('Missing signature.')
- # Validate the signature.
- valid_sig = signature_method.check_signature(oauth_request, consumer,
- token, signature)
- if not valid_sig:
- key, base = signature_method.build_signature_base_string(
- oauth_request, consumer, token)
- raise OAuthError('Invalid signature. Expected signature base '
- 'string: %s' % base)
- built = signature_method.build_signature(oauth_request, consumer, token)
-
- def _check_timestamp(self, timestamp):
- """Verify that timestamp is recentish."""
- timestamp = int(timestamp)
- now = int(time.time())
- lapsed = now - timestamp
- if lapsed > self.timestamp_threshold:
- raise OAuthError('Expired timestamp: given %d and now %s has a '
- 'greater difference than threshold %d' %
- (timestamp, now, self.timestamp_threshold))
-
- def _check_nonce(self, consumer, token, nonce):
- """Verify that the nonce is uniqueish."""
- nonce = self.data_store.lookup_nonce(consumer, token, nonce)
- if nonce:
- raise OAuthError('Nonce already used: %s' % str(nonce))
-
-
-class OAuthClient(object):
- """OAuthClient is a worker to attempt to execute a request."""
- consumer = None
- token = None
-
- def __init__(self, oauth_consumer, oauth_token):
- self.consumer = oauth_consumer
- self.token = oauth_token
-
- def get_consumer(self):
- return self.consumer
-
- def get_token(self):
- return self.token
-
- def fetch_request_token(self, oauth_request):
- """-> OAuthToken."""
- raise NotImplementedError
-
- def fetch_access_token(self, oauth_request):
- """-> OAuthToken."""
- raise NotImplementedError
-
- def access_resource(self, oauth_request):
- """-> Some protected resource."""
- raise NotImplementedError
-
-
-class OAuthDataStore(object):
- """A database abstraction used to lookup consumers and tokens."""
-
- def lookup_consumer(self, key):
- """-> OAuthConsumer."""
- raise NotImplementedError
-
- def lookup_token(self, oauth_consumer, token_type, token_token):
- """-> OAuthToken."""
- raise NotImplementedError
-
- def lookup_nonce(self, oauth_consumer, oauth_token, nonce):
- """-> OAuthToken."""
- raise NotImplementedError
-
- def fetch_request_token(self, oauth_consumer):
- """-> OAuthToken."""
- raise NotImplementedError
-
- def fetch_access_token(self, oauth_consumer, oauth_token):
- """-> OAuthToken."""
- raise NotImplementedError
-
- def authorize_request_token(self, oauth_token, user):
- """-> OAuthToken."""
- raise NotImplementedError
-
-
-class OAuthSignatureMethod(object):
- """A strategy class that implements a signature method."""
- def get_name(self):
- """-> str."""
- raise NotImplementedError
-
- def build_signature_base_string(self, oauth_request, oauth_consumer, oauth_token):
- """-> str key, str raw."""
- raise NotImplementedError
-
- def build_signature(self, oauth_request, oauth_consumer, oauth_token):
- """-> str."""
- raise NotImplementedError
-
- def check_signature(self, oauth_request, consumer, token, signature):
- built = self.build_signature(oauth_request, consumer, token)
- return built == signature
-
-
-class OAuthSignatureMethod_HMAC_SHA1(OAuthSignatureMethod):
-
- def get_name(self):
- return 'HMAC-SHA1'
-
- def build_signature_base_string(self, oauth_request, consumer, token):
- sig = (
- escape(oauth_request.get_normalized_http_method()),
- escape(oauth_request.get_normalized_http_url()),
- escape(oauth_request.get_normalized_parameters()),
- )
-
- key = '%s&' % escape(consumer.secret)
- if token:
- key += escape(token.secret)
- raw = '&'.join(sig)
- return key, raw
-
- def build_signature(self, oauth_request, consumer, token):
- """Builds the base signature string."""
- key, raw = self.build_signature_base_string(oauth_request, consumer,
- token)
-
- # HMAC object.
- try:
- import hashlib # 2.5
- hashed = hmac.new(key, raw, hashlib.sha1)
- except:
- import sha # Deprecated
- hashed = hmac.new(key, raw, sha)
-
- # Calculate the digest base 64.
- return binascii.b2a_base64(hashed.digest())[:-1]
-
-
-class OAuthSignatureMethod_PLAINTEXT(OAuthSignatureMethod):
-
- def get_name(self):
- return 'PLAINTEXT'
-
- def build_signature_base_string(self, oauth_request, consumer, token):
- """Concatenates the consumer key and secret."""
- sig = '%s&' % escape(consumer.secret)
- if token:
- sig = sig + escape(token.secret)
- return sig, sig
-
- def build_signature(self, oauth_request, consumer, token):
- key, raw = self.build_signature_base_string(oauth_request, consumer,
- token)
- return key \ No newline at end of file
diff --git a/forum_modules/oauthauth/settings.py b/forum_modules/oauthauth/settings.py
deleted file mode 100755
index 67567b63..00000000
--- a/forum_modules/oauthauth/settings.py
+++ /dev/null
@@ -1,3 +0,0 @@
-TWITTER_CONSUMER_KEY = "sAAGwWILliIbgbrG37GztQ"
-TWITTER_CONSUMER_SECRET = "AZv0pHTZQaf4rxxZOrj3Jm1RKgmlV4MnYJAsrY7M0"
-
diff --git a/forum_modules/openidauth/__init__.py b/forum_modules/openidauth/__init__.py
deleted file mode 100755
index e69de29b..00000000
--- a/forum_modules/openidauth/__init__.py
+++ /dev/null
diff --git a/forum_modules/openidauth/authentication.py b/forum_modules/openidauth/authentication.py
deleted file mode 100755
index c04c44b9..00000000
--- a/forum_modules/openidauth/authentication.py
+++ /dev/null
@@ -1,196 +0,0 @@
-from consumer import OpenIdAbstractAuthConsumer
-from forum.authentication.base import ConsumerTemplateContext
-
-class GoogleAuthConsumer(OpenIdAbstractAuthConsumer):
- def get_user_url(self, request):
- return 'https://www.google.com/accounts/o8/id'
-
-class GoogleAuthContext(ConsumerTemplateContext):
- mode = 'BIGICON'
- type = 'DIRECT'
- weight = 200
- human_name = 'Google'
- icon = '/media/images/openid/google.gif'
-
-
-
-class YahooAuthConsumer(OpenIdAbstractAuthConsumer):
- def get_user_url(self, request):
- return 'http://yahoo.com/'
-
-class YahooAuthContext(ConsumerTemplateContext):
- mode = 'BIGICON'
- type = 'DIRECT'
- weight = 300
- human_name = 'Yahoo'
- icon = '/media/images/openid/yahoo.gif'
-
-
-
-class AolAuthConsumer(OpenIdAbstractAuthConsumer):
- def get_user_url(self, request):
- uname = request.POST['input_field']
- return 'http://openid.aol.com/' + uname
-
-class AolAuthContext(ConsumerTemplateContext):
- mode = 'BIGICON'
- type = 'SIMPLE_FORM'
- simple_form_context = {
- 'your_what': 'AOL screen name'
- }
- weight = 400
- human_name = 'AOL'
- icon = '/media/images/openid/aol.gif'
-
-
-class MyOpenIdAuthConsumer(OpenIdAbstractAuthConsumer):
- def get_user_url(self, request):
- blog_name = request.POST['input_field']
- return "http://%s.myopenid.com/" % blog_name
-
-class MyOpenIdAuthContext(ConsumerTemplateContext):
- mode = 'SMALLICON'
- type = 'SIMPLE_FORM'
- simple_form_context = {
- 'your_what': 'MyOpenID user name'
- }
- weight = 200
- human_name = 'MyOpenID'
- icon = '/media/images/openid/myopenid.ico'
-
-
-class FlickrAuthConsumer(OpenIdAbstractAuthConsumer):
- def get_user_url(self, request):
- blog_name = request.POST['input_field']
- return "http://flickr.com/%s/" % blog_name
-
-class FlickrAuthContext(ConsumerTemplateContext):
- mode = 'SMALLICON'
- type = 'SIMPLE_FORM'
- simple_form_context = {
- 'your_what': 'Flickr user name'
- }
- weight = 250
- human_name = 'Flickr'
- icon = '/media/images/openid/flickr.ico'
-
-
-class TechnoratiAuthConsumer(OpenIdAbstractAuthConsumer):
- def get_user_url(self, request):
- blog_name = request.POST['input_field']
- return "http://technorati.com/people/technorati/%s/" % blog_name
-
-class TechnoratiAuthContext(ConsumerTemplateContext):
- mode = 'SMALLICON'
- type = 'SIMPLE_FORM'
- simple_form_context = {
- 'your_what': 'Technorati user name'
- }
- weight = 260
- human_name = 'Technorati'
- icon = '/media/images/openid/technorati.ico'
-
-
-class WordpressAuthConsumer(OpenIdAbstractAuthConsumer):
- def get_user_url(self, request):
- blog_name = request.POST['input_field']
- return "http://%s.wordpress.com/" % blog_name
-
-class WordpressAuthContext(ConsumerTemplateContext):
- mode = 'SMALLICON'
- type = 'SIMPLE_FORM'
- simple_form_context = {
- 'your_what': 'Wordpress blog name'
- }
- weight = 270
- human_name = 'Wordpress'
- icon = '/media/images/openid/wordpress.ico'
-
-
-class BloggerAuthConsumer(OpenIdAbstractAuthConsumer):
- def get_user_url(self, request):
- blog_name = request.POST['input_field']
- return "http://%s.blogspot.com/" % blog_name
-
-class BloggerAuthContext(ConsumerTemplateContext):
- mode = 'SMALLICON'
- type = 'SIMPLE_FORM'
- simple_form_context = {
- 'your_what': 'Blogger blog name'
- }
- weight = 300
- human_name = 'Blogger'
- icon = '/media/images/openid/blogger.ico'
-
-
-class LiveJournalAuthConsumer(OpenIdAbstractAuthConsumer):
- def get_user_url(self, request):
- blog_name = request.POST['input_field']
- return "http://%s.livejournal.com/" % blog_name
-
-class LiveJournalAuthContext(ConsumerTemplateContext):
- mode = 'SMALLICON'
- type = 'SIMPLE_FORM'
- simple_form_context = {
- 'your_what': 'LiveJournal blog name'
- }
- weight = 310
- human_name = 'LiveJournal'
- icon = '/media/images/openid/livejournal.ico'
-
-
-class ClaimIdAuthConsumer(OpenIdAbstractAuthConsumer):
- def get_user_url(self, request):
- blog_name = request.POST['input_field']
- return "http://claimid.com/%s" % blog_name
-
-class ClaimIdAuthContext(ConsumerTemplateContext):
- mode = 'SMALLICON'
- type = 'SIMPLE_FORM'
- simple_form_context = {
- 'your_what': 'ClaimID user name'
- }
- weight = 320
- human_name = 'ClaimID'
- icon = '/media/images/openid/claimid.ico'
-
-class VidoopAuthConsumer(OpenIdAbstractAuthConsumer):
- def get_user_url(self, request):
- blog_name = request.POST['input_field']
- return "http://%s.myvidoop.com/" % blog_name
-
-class VidoopAuthContext(ConsumerTemplateContext):
- mode = 'SMALLICON'
- type = 'SIMPLE_FORM'
- simple_form_context = {
- 'your_what': 'Vidoop user name'
- }
- weight = 330
- human_name = 'Vidoop'
- icon = '/media/images/openid/vidoop.ico'
-
-class VerisignAuthConsumer(OpenIdAbstractAuthConsumer):
- def get_user_url(self, request):
- blog_name = request.POST['input_field']
- return "http://%s.pip.verisignlabs.com/" % blog_name
-
-class VerisignAuthContext(ConsumerTemplateContext):
- mode = 'SMALLICON'
- type = 'SIMPLE_FORM'
- simple_form_context = {
- 'your_what': 'Verisign user name'
- }
- weight = 340
- human_name = 'Verisign'
- icon = '/media/images/openid/verisign.ico'
-
-
-class OpenIdUrlAuthConsumer(OpenIdAbstractAuthConsumer):
- pass
-
-class OpenIdUrlAuthContext(ConsumerTemplateContext):
- mode = 'STACK_ITEM'
- weight = 300
- human_name = 'OpenId url'
- stack_item_template = 'modules/openidauth/openidurl.html'
- icon = '/media/images/openid/openid-inputicon.gif' \ No newline at end of file
diff --git a/forum_modules/openidauth/consumer.py b/forum_modules/openidauth/consumer.py
deleted file mode 100755
index 68035968..00000000
--- a/forum_modules/openidauth/consumer.py
+++ /dev/null
@@ -1,112 +0,0 @@
-from django.utils.html import escape
-from django.http import get_host
-
-from forum.authentication.base import AuthenticationConsumer, InvalidAuthentication
-import settings
-
-from openid.yadis import xri
-from openid.consumer.consumer import Consumer, SUCCESS, CANCEL, FAILURE, SETUP_NEEDED
-from openid.consumer.discover import DiscoveryFailure
-from openid.extensions.sreg import SRegRequest, SRegResponse
-from openid.extensions.ax import FetchRequest as AXFetchRequest, AttrInfo, FetchResponse as AXFetchResponse
-from django.utils.translation import ugettext as _
-
-from store import OsqaOpenIDStore
-
-class OpenIdAbstractAuthConsumer(AuthenticationConsumer):
-
- def get_user_url(self, request):
- try:
- return request.POST['openid_identifier']
- except:
- raise NotImplementedError()
-
- def prepare_authentication_request(self, request, redirect_to):
- if not redirect_to.startswith('http://') or redirect_to.startswith('https://'):
- redirect_to = get_url_host(request) + redirect_to
-
- user_url = self.get_user_url(request)
-
- if xri.identifierScheme(user_url) == 'XRI' and getattr(
- settings, 'OPENID_DISALLOW_INAMES', False
- ):
- raise InvalidAuthentication('i-names are not supported')
-
- consumer = Consumer(request.session, OsqaOpenIDStore())
-
- try:
- auth_request = consumer.begin(user_url)
- except DiscoveryFailure:
- raise InvalidAuthentication(_('Sorry, but your input is not a valid OpenId'))
-
- #sreg = getattr(settings, 'OPENID_SREG', False)
-
- #if sreg:
- # s = SRegRequest()
- # for sarg in sreg:
- # if sarg.lower().lstrip() == "policy_url":
- # s.policy_url = sreg[sarg]
- # else:
- # for v in sreg[sarg].split(','):
- # s.requestField(field_name=v.lower().lstrip(), required=(sarg.lower().lstrip() == "required"))
- # auth_request.addExtension(s)
-
- #auth_request.addExtension(SRegRequest(required=['email']))
-
- if request.session.get('force_email_request', True):
- axr = AXFetchRequest()
- axr.add(AttrInfo("http://axschema.org/contact/email", 1, True, "email"))
- auth_request.addExtension(axr)
-
- trust_root = getattr(
- settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/'
- )
-
-
- return auth_request.redirectURL(trust_root, redirect_to)
-
- def process_authentication_request(self, request):
- consumer = Consumer(request.session, OsqaOpenIDStore())
-
- query_dict = dict([
- (k.encode('utf8'), v.encode('utf8')) for k, v in request.GET.items()
- ])
-
- #for i in query_dict.items():
- # print "%s : %s" % i
-
- url = get_url_host(request) + request.path
- openid_response = consumer.complete(query_dict, url)
-
- if openid_response.status == SUCCESS:
- if request.session.get('force_email_request', True):
- try:
- ax = AXFetchResponse.fromSuccessResponse(openid_response)
- email = ax.getExtensionArgs()['value.ext0.1']
- request.session['auth_email_request'] = email
- except Exception, e:
- pass
-
- return request.GET['openid.identity']
- elif openid_response.status == CANCEL:
- raise InvalidAuthentication(_('The OpenId authentication request was canceled'))
- elif openid_response.status == FAILURE:
- raise InvalidAuthentication(_('The OpenId authentication failed: ') + openid_response.message)
- elif openid_response.status == SETUP_NEEDED:
- raise InvalidAuthentication(_('Setup needed'))
- else:
- raise InvalidAuthentication(_('The OpenId authentication failed with an unknown status: ') + openid_response.status)
-
- def get_user_data(self, key):
- return {}
-
-def get_url_host(request):
- if request.is_secure():
- protocol = 'https'
- else:
- protocol = 'http'
- host = escape(get_host(request))
- return '%s://%s' % (protocol, host)
-
-def get_full_url(request):
- return get_url_host(request) + request.get_full_path() \ No newline at end of file
diff --git a/forum_modules/openidauth/models.py b/forum_modules/openidauth/models.py
deleted file mode 100755
index d76902df..00000000
--- a/forum_modules/openidauth/models.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from django.db import models
-
-class OpenIdNonce(models.Model):
- server_url = models.URLField()
- timestamp = models.IntegerField()
- salt = models.CharField( max_length=50 )
-
- def __unicode__(self):
- return "Nonce: %s" % self.nonce
-
- class Meta:
- app_label = 'forum'
-
-class OpenIdAssociation(models.Model):
- server_url = models.TextField(max_length=2047)
- handle = models.CharField(max_length=255)
- secret = models.TextField(max_length=255) # Stored base64 encoded
- issued = models.IntegerField()
- lifetime = models.IntegerField()
- assoc_type = models.TextField(max_length=64)
-
- def __unicode__(self):
- return "Association: %s, %s" % (self.server_url, self.handle)
-
- class Meta:
- app_label = 'forum'
diff --git a/forum_modules/openidauth/settings.py b/forum_modules/openidauth/settings.py
deleted file mode 100755
index f7c641a1..00000000
--- a/forum_modules/openidauth/settings.py
+++ /dev/null
@@ -1,9 +0,0 @@
-OPENID_SREG = {
- "required": "nickname, email",
- "optional": "postcode, country",
- "policy_url": ""
-}
-OPENID_AX = [
- {"type_uri": "http://axschema.org/contact/email", "count": 1, "required": True, "alias": "email"},
- {"type_uri": "fullname", "count":1 , "required": False, "alias": "fullname"}
- ] \ No newline at end of file
diff --git a/forum_modules/openidauth/store.py b/forum_modules/openidauth/store.py
deleted file mode 100755
index fa61ea6d..00000000
--- a/forum_modules/openidauth/store.py
+++ /dev/null
@@ -1,79 +0,0 @@
-import time, base64, md5
-
-from openid.store import nonce as oid_nonce
-from openid.store.interface import OpenIDStore
-from openid.association import Association as OIDAssociation
-from django.conf import settings
-
-from models import OpenIdNonce as Nonce, OpenIdAssociation as Association
-
-class OsqaOpenIDStore(OpenIDStore):
- def __init__(self):
- self.max_nonce_age = 6 * 60 * 60 # Six hours
-
- def storeAssociation(self, server_url, association):
- assoc = Association(
- server_url = server_url,
- handle = association.handle,
- secret = base64.encodestring(association.secret),
- issued = association.issued,
- lifetime = association.issued,
- assoc_type = association.assoc_type
- )
- assoc.save()
-
- def getAssociation(self, server_url, handle=None):
- assocs = []
- if handle is not None:
- assocs = Association.objects.filter(
- server_url = server_url, handle = handle
- )
- else:
- assocs = Association.objects.filter(
- server_url = server_url
- )
- if not assocs:
- return None
- associations = []
- for assoc in assocs:
- association = OIDAssociation(
- assoc.handle, base64.decodestring(assoc.secret), assoc.issued,
- assoc.lifetime, assoc.assoc_type
- )
- if association.getExpiresIn() == 0:
- self.removeAssociation(server_url, assoc.handle)
- else:
- associations.append((association.issued, association))
- if not associations:
- return None
- return associations[-1][1]
-
- def removeAssociation(self, server_url, handle):
- assocs = list(Association.objects.filter(
- server_url = server_url, handle = handle
- ))
- assocs_exist = len(assocs) > 0
- for assoc in assocs:
- assoc.delete()
- return assocs_exist
-
- def storeNonce(self, nonce):
- nonce, created = Nonce.objects.get_or_create(
- nonce = nonce, defaults={'expires': int(time.time())}
- )
-
- def useNonce(self, server_url, timestamp, salt):
- if abs(timestamp - time.time()) > oid_nonce.SKEW:
- return False
-
- try:
- nonce = Nonce( server_url=server_url, timestamp=timestamp, salt=salt)
- nonce.save()
- except:
- raise
- else:
- return 1
-
- def getAuthKey(self):
- # Use first AUTH_KEY_LEN characters of md5 hash of SECRET_KEY
- return md5.new(settings.SECRET_KEY).hexdigest()[:self.AUTH_KEY_LEN]
diff --git a/forum_modules/openidauth/templates/openidurl.html b/forum_modules/openidauth/templates/openidurl.html
deleted file mode 100755
index cd4e77dc..00000000
--- a/forum_modules/openidauth/templates/openidurl.html
+++ /dev/null
@@ -1,20 +0,0 @@
-{% load i18n %}
-{% load extra_tags %}
-
-<fieldset>
- <table>
- <tr>
- <td><p id="provider_name_slot">{% trans 'Enter your OpenId Url' %}</p></td>
- </tr>
- <tr>
- <td>
- <input id="openid_identifier" class="icon_input" name="openid_identifier" type="text"
- style="width: 500px; background: url('{% media provider.icon %}') no-repeat left center" />
- </td>
- <td>
- <input type="submit" name="ssignin" value="Login" />
- </td>
- </tr>
- </table>
-</fieldset>
-