aboutsummaryrefslogtreecommitdiffstats
path: root/mediagoblin/plugins
diff options
context:
space:
mode:
Diffstat (limited to 'mediagoblin/plugins')
-rw-r--r--mediagoblin/plugins/api/__init__.py4
-rw-r--r--mediagoblin/plugins/api/tools.py24
-rw-r--r--mediagoblin/plugins/api/views.py97
-rw-r--r--mediagoblin/plugins/basic_auth/README.rst24
-rw-r--r--mediagoblin/plugins/basic_auth/__init__.py119
-rw-r--r--mediagoblin/plugins/basic_auth/forms.py76
-rw-r--r--mediagoblin/plugins/basic_auth/static/js/autofilledin_password.js25
-rw-r--r--mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/change_fp.html43
-rw-r--r--mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/change_pass.html52
-rw-r--r--mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/create_account_link.html27
-rw-r--r--mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/edit_link.html25
-rw-r--r--mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/forgot_password.html38
-rw-r--r--mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/fp_head.html20
-rw-r--r--mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/fp_link.html25
-rw-r--r--mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/fp_verification_email.txt30
-rw-r--r--mediagoblin/plugins/basic_auth/tools.py121
-rw-r--r--mediagoblin/plugins/basic_auth/views.py223
-rw-r--r--mediagoblin/plugins/httpapiauth/__init__.py10
-rw-r--r--mediagoblin/plugins/ldap/README.rst64
-rw-r--r--mediagoblin/plugins/ldap/__init__.py59
-rw-r--r--mediagoblin/plugins/ldap/forms.py40
-rw-r--r--mediagoblin/plugins/ldap/templates/mediagoblin/plugins/ldap/create_account_link.html25
-rw-r--r--mediagoblin/plugins/ldap/tools.py65
-rw-r--r--mediagoblin/plugins/ldap/views.py104
-rw-r--r--mediagoblin/plugins/oauth/__init__.py12
-rw-r--r--mediagoblin/plugins/oauth/tools.py2
-rw-r--r--mediagoblin/plugins/oauth/views.py3
-rw-r--r--mediagoblin/plugins/openid/README.rst34
-rw-r--r--mediagoblin/plugins/openid/__init__.py125
-rw-r--r--mediagoblin/plugins/openid/forms.py41
-rw-r--r--mediagoblin/plugins/openid/models.py65
-rw-r--r--mediagoblin/plugins/openid/store.py127
-rw-r--r--mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/add.html44
-rw-r--r--mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/delete.html43
-rw-r--r--mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/edit_link.html24
-rw-r--r--mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/login.html66
-rw-r--r--mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/login_link.html27
-rw-r--r--mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/register_link.html27
-rw-r--r--mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/request_form.html24
-rw-r--r--mediagoblin/plugins/openid/views.py404
-rw-r--r--mediagoblin/plugins/persona/README.rst41
-rw-r--r--mediagoblin/plugins/persona/__init__.py116
-rw-r--r--mediagoblin/plugins/persona/forms.py41
-rw-r--r--mediagoblin/plugins/persona/models.py36
-rw-r--r--mediagoblin/plugins/persona/static/js/persona.js59
-rw-r--r--mediagoblin/plugins/persona/templates/mediagoblin/plugins/persona/edit.html43
-rw-r--r--mediagoblin/plugins/persona/templates/mediagoblin/plugins/persona/edit_link.html24
-rw-r--r--mediagoblin/plugins/persona/templates/mediagoblin/plugins/persona/login_link.html25
-rw-r--r--mediagoblin/plugins/persona/templates/mediagoblin/plugins/persona/persona.html38
-rw-r--r--mediagoblin/plugins/persona/templates/mediagoblin/plugins/persona/persona_js_end.html21
-rw-r--r--mediagoblin/plugins/persona/templates/mediagoblin/plugins/persona/register_link.html25
-rw-r--r--mediagoblin/plugins/persona/views.py194
-rw-r--r--mediagoblin/plugins/piwigo/__init__.py5
-rw-r--r--mediagoblin/plugins/piwigo/forms.py16
-rw-r--r--mediagoblin/plugins/piwigo/tools.py63
-rw-r--r--mediagoblin/plugins/piwigo/views.py119
56 files changed, 3154 insertions, 120 deletions
diff --git a/mediagoblin/plugins/api/__init__.py b/mediagoblin/plugins/api/__init__.py
index d3fdf2ef..1eddd9e0 100644
--- a/mediagoblin/plugins/api/__init__.py
+++ b/mediagoblin/plugins/api/__init__.py
@@ -23,11 +23,11 @@ _log = logging.getLogger(__name__)
PLUGIN_DIR = os.path.dirname(__file__)
-config = pluginapi.get_config(__name__)
-
def setup_plugin():
_log.info('Setting up API...')
+ config = pluginapi.get_config(__name__)
+
_log.debug('API config: {0}'.format(config))
routes = [
diff --git a/mediagoblin/plugins/api/tools.py b/mediagoblin/plugins/api/tools.py
index 92411f4b..d1b3ebb1 100644
--- a/mediagoblin/plugins/api/tools.py
+++ b/mediagoblin/plugins/api/tools.py
@@ -51,30 +51,6 @@ class Auth(object):
def __call__(self, request, *args, **kw):
raise NotImplemented()
-
-def json_response(serializable, _disable_cors=False, *args, **kw):
- '''
- Serializes a json objects and returns a werkzeug Response object with the
- serialized value as the response body and Content-Type: application/json.
-
- :param serializable: A json-serializable object
-
- Any extra arguments and keyword arguments are passed to the
- Response.__init__ method.
- '''
- response = Response(json.dumps(serializable), *args, content_type='application/json', **kw)
-
- if not _disable_cors:
- cors_headers = {
- 'Access-Control-Allow-Origin': '*',
- 'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
- 'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With'}
- for key, value in cors_headers.iteritems():
- response.headers.set(key, value)
-
- return response
-
-
def get_entry_serializable(entry, urlgen):
'''
Returns a serializable dict() of a MediaEntry instance.
diff --git a/mediagoblin/plugins/api/views.py b/mediagoblin/plugins/api/views.py
index fde76fe4..69fae7bb 100644
--- a/mediagoblin/plugins/api/views.py
+++ b/mediagoblin/plugins/api/views.py
@@ -17,17 +17,19 @@
import json
import logging
-from os.path import splitext
-from werkzeug.exceptions import BadRequest, Forbidden
+from werkzeug.exceptions import BadRequest
from werkzeug.wrappers import Response
+from mediagoblin.tools.translate import pass_to_ugettext as _
+from mediagoblin.tools.response import json_response
from mediagoblin.decorators import require_active_login
from mediagoblin.meddleware.csrf import csrf_exempt
-from mediagoblin.media_types import sniff_media
-from mediagoblin.plugins.api.tools import api_auth, get_entry_serializable, \
- json_response
-from mediagoblin.submit.lib import check_file_field, prepare_queue_task, \
- run_process_media
+from mediagoblin.media_types import \
+ InvalidFileType, FileTypeNotSupported
+from mediagoblin.plugins.api.tools import api_auth, get_entry_serializable
+from mediagoblin.submit.lib import \
+ check_file_field, submit_media, get_upload_file_limits, \
+ FileUploadLimit, UserUploadLimit, UserPastUploadLimit
_log = logging.getLogger(__name__)
@@ -49,47 +51,46 @@ def post_entry(request):
_log.debug('File field not found')
raise BadRequest()
- media_file = request.files['file']
-
- media_type, media_manager = sniff_media(media_file)
-
- entry = request.db.MediaEntry()
- entry.media_type = unicode(media_type)
- entry.title = unicode(request.form.get('title')
- or splitext(media_file.filename)[0])
-
- entry.description = unicode(request.form.get('description'))
- entry.license = unicode(request.form.get('license', ''))
-
- entry.uploader = request.user.id
-
- entry.generate_slug()
-
- # queue appropriately
- queue_file = prepare_queue_task(request.app, entry, media_file.filename)
-
- with queue_file:
- queue_file.write(request.files['file'].stream.read())
-
- # Save now so we have this data before kicking off processing
- entry.save()
-
- if request.form.get('callback_url'):
- metadata = request.db.ProcessingMetaData()
- metadata.media_entry = entry
- metadata.callback_url = unicode(request.form['callback_url'])
- metadata.save()
-
- # Pass off to processing
- #
- # (... don't change entry after this point to avoid race
- # conditions with changes to the document via processing code)
- feed_url = request.urlgen(
- 'mediagoblin.user_pages.atom_feed',
- qualified=True, user=request.user.username)
- run_process_media(entry, feed_url)
-
- return json_response(get_entry_serializable(entry, request.urlgen))
+ upload_limit, max_file_size = get_upload_file_limits(request.user)
+
+ callback_url = request.form.get('callback_url')
+ if callback_url:
+ callback_url = unicode(callback_url)
+ try:
+ entry = submit_media(
+ mg_app=request.app, user=request.user,
+ submitted_file=request.files['file'],
+ filename=request.files['file'].filename,
+ title=unicode(request.form.get('title')),
+ description=unicode(request.form.get('description')),
+ license=unicode(request.form.get('license', '')),
+ upload_limit=upload_limit, max_file_size=max_file_size,
+ callback_url=callback_url)
+
+ return json_response(get_entry_serializable(entry, request.urlgen))
+
+ # Handle upload limit issues
+ except FileUploadLimit:
+ raise BadRequest(
+ _(u'Sorry, the file size is too big.'))
+ except UserUploadLimit:
+ raise BadRequest(
+ _('Sorry, uploading this file will put you over your'
+ ' upload limit.'))
+ except UserPastUploadLimit:
+ raise BadRequest(
+ _('Sorry, you have reached your upload limit.'))
+
+ except Exception as e:
+ '''
+ This section is intended to catch exceptions raised in
+ mediagoblin.media_types
+ '''
+ if isinstance(e, InvalidFileType) or \
+ isinstance(e, FileTypeNotSupported):
+ raise BadRequest(unicode(e))
+ else:
+ raise
@api_auth
diff --git a/mediagoblin/plugins/basic_auth/README.rst b/mediagoblin/plugins/basic_auth/README.rst
new file mode 100644
index 00000000..82f247ed
--- /dev/null
+++ b/mediagoblin/plugins/basic_auth/README.rst
@@ -0,0 +1,24 @@
+.. _basic_auth-chapter:
+
+===================
+ basic_auth plugin
+===================
+
+The basic_auth plugin is enabled by default in mediagoblin.ini. This plugin
+provides basic username and password authentication for GNU Mediagoblin.
+
+This plugin can be enabled alongside :ref:`openid-chapter` and
+:ref:`persona-chapter`.
+
+Set up the basic_auth plugin
+============================
+
+1. Add the following to your MediaGoblin .ini file in the ``[plugins]`` section::
+
+ [[mediagoblin.plugins.basic_auth]]
+
+2. Run::
+
+ gmg assetlink
+
+ in order to link basic_auth's static assets
diff --git a/mediagoblin/plugins/basic_auth/__init__.py b/mediagoblin/plugins/basic_auth/__init__.py
new file mode 100644
index 00000000..64564c7f
--- /dev/null
+++ b/mediagoblin/plugins/basic_auth/__init__.py
@@ -0,0 +1,119 @@
+# 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/>.
+from pkg_resources import resource_filename
+import os
+
+from mediagoblin.plugins.basic_auth import forms as auth_forms
+from mediagoblin.plugins.basic_auth import tools as auth_tools
+from mediagoblin.auth.tools import create_basic_user
+from mediagoblin.db.models import User
+from mediagoblin.tools import pluginapi
+from sqlalchemy import or_
+from mediagoblin.tools.staticdirect import PluginStatic
+
+
+PLUGIN_DIR = os.path.dirname(__file__)
+
+
+def setup_plugin():
+ config = pluginapi.get_config('mediagoblin.plugins.basic_auth')
+
+ routes = [
+ ('mediagoblin.plugins.basic_auth.edit.pass',
+ '/edit/password/',
+ 'mediagoblin.plugins.basic_auth.views:change_pass'),
+ ('mediagoblin.plugins.basic_auth.forgot_password',
+ '/auth/forgot_password/',
+ 'mediagoblin.plugins.basic_auth.views:forgot_password'),
+ ('mediagoblin.plugins.basic_auth.verify_forgot_password',
+ '/auth/forgot_password/verify/',
+ 'mediagoblin.plugins.basic_auth.views:verify_forgot_password')]
+
+ pluginapi.register_routes(routes)
+ pluginapi.register_template_path(os.path.join(PLUGIN_DIR, 'templates'))
+
+ pluginapi.register_template_hooks(
+ {'edit_link': 'mediagoblin/plugins/basic_auth/edit_link.html',
+ 'fp_link': 'mediagoblin/plugins/basic_auth/fp_link.html',
+ 'fp_head': 'mediagoblin/plugins/basic_auth/fp_head.html',
+ 'create_account':
+ 'mediagoblin/plugins/basic_auth/create_account_link.html'})
+
+
+def get_user(**kwargs):
+ username = kwargs.pop('username', None)
+ if username:
+ user = User.query.filter(
+ or_(
+ User.username == username,
+ User.email == username,
+ )).first()
+ return user
+
+
+def create_user(registration_form):
+ user = get_user(username=registration_form.username.data)
+ if not user and 'password' in registration_form:
+ user = create_basic_user(registration_form)
+ user.pw_hash = gen_password_hash(
+ registration_form.password.data)
+ user.save()
+ return user
+
+
+def get_login_form(request):
+ return auth_forms.LoginForm(request.form)
+
+
+def get_registration_form(request):
+ return auth_forms.RegistrationForm(request.form)
+
+
+def gen_password_hash(raw_pass, extra_salt=None):
+ return auth_tools.bcrypt_gen_password_hash(raw_pass, extra_salt)
+
+
+def check_password(raw_pass, stored_hash, extra_salt=None):
+ if stored_hash:
+ return auth_tools.bcrypt_check_password(raw_pass,
+ stored_hash, extra_salt)
+ return None
+
+
+def auth():
+ return True
+
+
+def append_to_global_context(context):
+ context['pass_auth'] = True
+ return context
+
+
+hooks = {
+ 'setup': setup_plugin,
+ 'authentication': auth,
+ 'auth_get_user': get_user,
+ 'auth_create_user': create_user,
+ 'auth_get_login_form': get_login_form,
+ 'auth_get_registration_form': get_registration_form,
+ 'auth_gen_password_hash': gen_password_hash,
+ 'auth_check_password': check_password,
+ 'auth_fake_login_attempt': auth_tools.fake_login_attempt,
+ 'template_global_context': append_to_global_context,
+ 'static_setup': lambda: PluginStatic(
+ 'coreplugin_basic_auth',
+ resource_filename('mediagoblin.plugins.basic_auth', 'static'))
+}
diff --git a/mediagoblin/plugins/basic_auth/forms.py b/mediagoblin/plugins/basic_auth/forms.py
new file mode 100644
index 00000000..c10496f8
--- /dev/null
+++ b/mediagoblin/plugins/basic_auth/forms.py
@@ -0,0 +1,76 @@
+# 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 wtforms
+
+from mediagoblin.tools.translate import lazy_pass_to_ugettext as _
+from mediagoblin.auth.tools import normalize_user_or_email_field
+
+
+class RegistrationForm(wtforms.Form):
+ username = wtforms.TextField(
+ _('Username'),
+ [wtforms.validators.Required(),
+ normalize_user_or_email_field(allow_email=False)])
+ password = wtforms.PasswordField(
+ _('Password'),
+ [wtforms.validators.Required(),
+ wtforms.validators.Length(min=5, max=1024)])
+ email = wtforms.TextField(
+ _('Email address'),
+ [wtforms.validators.Required(),
+ normalize_user_or_email_field(allow_user=False)])
+
+
+class LoginForm(wtforms.Form):
+ username = wtforms.TextField(
+ _('Username or Email'),
+ [wtforms.validators.Required(),
+ normalize_user_or_email_field()])
+ password = wtforms.PasswordField(
+ _('Password'))
+ stay_logged_in = wtforms.BooleanField(
+ label='',
+ description=_('Stay logged in'))
+
+
+class ForgotPassForm(wtforms.Form):
+ username = wtforms.TextField(
+ _('Username or email'),
+ [wtforms.validators.Required(),
+ normalize_user_or_email_field()])
+
+
+class ChangeForgotPassForm(wtforms.Form):
+ password = wtforms.PasswordField(
+ 'Password',
+ [wtforms.validators.Required(),
+ wtforms.validators.Length(min=5, max=1024)])
+ token = wtforms.HiddenField(
+ '',
+ [wtforms.validators.Required()])
+
+
+class ChangePassForm(wtforms.Form):
+ old_password = wtforms.PasswordField(
+ _('Old password'),
+ [wtforms.validators.Required()],
+ description=_(
+ "Enter your old password to prove you own this account."))
+ new_password = wtforms.PasswordField(
+ _('New password'),
+ [wtforms.validators.Required(),
+ wtforms.validators.Length(min=6, max=30)],
+ id="password")
diff --git a/mediagoblin/plugins/basic_auth/static/js/autofilledin_password.js b/mediagoblin/plugins/basic_auth/static/js/autofilledin_password.js
new file mode 100644
index 00000000..45e867fe
--- /dev/null
+++ b/mediagoblin/plugins/basic_auth/static/js/autofilledin_password.js
@@ -0,0 +1,25 @@
+/**
+ * GNU MediaGoblin -- federated, autonomous media hosting
+ * Copyright (C) 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/>.
+ */
+
+$(document).ready(function(){
+ $('#forgot_password').click(function(event){
+ event.preventDefault();
+ window.location.pathname = $(this).attr('href') + '?username=' +
+ $('#username').val();
+ });
+});
diff --git a/mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/change_fp.html b/mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/change_fp.html
new file mode 100644
index 00000000..47cd591e
--- /dev/null
+++ b/mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/change_fp.html
@@ -0,0 +1,43 @@
+{#
+# GNU MediaGoblin -- federated, autonomous media hosting
+# Copyright (C) 2011 Free Software Foundation, Inc
+#
+# 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/>.
+#}
+{% extends "mediagoblin/base.html" %}
+
+{% import "/mediagoblin/utils/wtforms.html" as wtforms_util %}
+
+{% block mediagoblin_head %}
+ <script type="text/javascript"
+ src="{{ request.staticdirect('/js/show_password.js') }}"></script>
+{% endblock mediagoblin_head %}
+
+{% block title -%}
+ {% trans %}Set your new password{% endtrans %} &mdash; {{ super() }}
+{%- endblock %}
+
+{% block mediagoblin_content %}
+ <form action="{{ request.urlgen('mediagoblin.plugins.basic_auth.verify_forgot_password') }}"
+ method="POST" enctype="multipart/form-data">
+ {{ csrf_token }}
+ <div class="form_box">
+ <h1>{% trans %}Set your new password{% endtrans %}</h1>
+ {{ wtforms_util.render_divs(cp_form, True) }}
+ <div class="form_submit_buttons">
+ <input type="submit" value="{% trans %}Set password{% endtrans %}" class="button_form"/>
+ </div>
+ </div>
+{% endblock %}
+
diff --git a/mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/change_pass.html b/mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/change_pass.html
new file mode 100644
index 00000000..596a4def
--- /dev/null
+++ b/mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/change_pass.html
@@ -0,0 +1,52 @@
+{#
+# 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/>.
+#}
+{% extends "mediagoblin/base.html" %}
+
+{% import "/mediagoblin/utils/wtforms.html" as wtforms_util %}
+
+{% block mediagoblin_head %}
+ <script type="text/javascript"
+ src="{{ request.staticdirect('/js/show_password.js') }}"></script>
+{% endblock mediagoblin_head %}
+
+{% block title -%}
+ {% trans username=user.username -%}
+ Changing {{ username }}'s password
+ {%- endtrans %} &mdash; {{ super() }}
+{%- endblock %}
+
+{% block mediagoblin_content %}
+ <form action="{{ request.urlgen('mediagoblin.plugins.basic_auth.edit.pass') }}"
+ method="POST" enctype="multipart/form-data">
+ <div class="form_box edit_box">
+ <h1>
+ {%- trans username=user.username -%}
+ Changing {{ username }}'s password
+ {%- endtrans -%}
+ </h1>
+ {{ wtforms_util.render_divs(form, True) }}
+ {{ csrf_token }}
+ <div class="form_submit_buttons">
+ <input type="submit" value="{% trans %}Save{% endtrans %}"
+ class="button_form" />
+ </div>
+ </div>
+ </form>
+{% endblock %}
+
+
diff --git a/mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/create_account_link.html b/mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/create_account_link.html
new file mode 100644
index 00000000..7425630b
--- /dev/null
+++ b/mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/create_account_link.html
@@ -0,0 +1,27 @@
+{#
+# 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/>.
+#}
+
+{% block create_account %}
+ {% if allow_registration %}
+ <p>
+ {% trans %}Don't have an account yet?{% endtrans %}
+ <a href="{{ request.urlgen('mediagoblin.auth.register') }}">
+ {%- trans %}Create one here!{% endtrans %}</a>
+ </p>
+ {% endif %}
+{% endblock %}
diff --git a/mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/edit_link.html b/mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/edit_link.html
new file mode 100644
index 00000000..9fd09ab1
--- /dev/null
+++ b/mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/edit_link.html
@@ -0,0 +1,25 @@
+{#
+# 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/>.
+#}
+
+{% block change_pass_link %}
+ <p>
+ <a href="{{ request.urlgen('mediagoblin.plugins.basic_auth.edit.pass') }}">
+ {% trans %}Change your password.{% endtrans %}
+ </a>
+ </p>
+{% endblock %}
diff --git a/mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/forgot_password.html b/mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/forgot_password.html
new file mode 100644
index 00000000..b0028ab6
--- /dev/null
+++ b/mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/forgot_password.html
@@ -0,0 +1,38 @@
+{#
+# GNU MediaGoblin -- federated, autonomous media hosting
+# Copyright (C) 2011 Free Software Foundation, Inc
+#
+# 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/>.
+#}
+{% extends "mediagoblin/base.html" %}
+
+{% import "/mediagoblin/utils/wtforms.html" as wtforms_util %}
+
+{% block title -%}
+ {% trans %}Recover password{% endtrans %} &mdash; {{ super() }}
+{%- endblock %}
+
+{% block mediagoblin_content %}
+ <form action="{{ request.urlgen('mediagoblin.plugins.basic_auth.forgot_password') }}"
+ method="POST" enctype="multipart/form-data">
+ {{ csrf_token }}
+ <div class="form_box">
+ <h1>{% trans %}Recover password{% endtrans %}</h1>
+ {{ wtforms_util.render_divs(fp_form, True) }}
+ <div class="form_submit_buttons">
+ <input type="submit" value="{% trans %}Send instructions{% endtrans %}" class="button_form"/>
+ </div>
+ </div>
+ </form>
+{% endblock %}
diff --git a/mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/fp_head.html b/mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/fp_head.html
new file mode 100644
index 00000000..292dce28
--- /dev/null
+++ b/mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/fp_head.html
@@ -0,0 +1,20 @@
+{#
+# 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/>.
+#}
+
+<script type="text/javascript"
+ src="{{ request.staticdirect('/js/autofilledin_password.js', 'coreplugin_basic_auth') }}"></script>
diff --git a/mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/fp_link.html b/mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/fp_link.html
new file mode 100644
index 00000000..404358d8
--- /dev/null
+++ b/mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/fp_link.html
@@ -0,0 +1,25 @@
+{#
+# 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/>.
+#}
+
+{% block fp_link %}
+ <p>
+ <a href="{{ request.urlgen('mediagoblin.plugins.basic_auth.forgot_password') }}" id="forgot_password">
+ {% trans %}Forgot your password?{% endtrans %}</a>
+ </p>
+{% endblock %}
+
diff --git a/mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/fp_verification_email.txt b/mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/fp_verification_email.txt
new file mode 100644
index 00000000..fb5e1674
--- /dev/null
+++ b/mediagoblin/plugins/basic_auth/templates/mediagoblin/plugins/basic_auth/fp_verification_email.txt
@@ -0,0 +1,30 @@
+{#
+# GNU MediaGoblin -- federated, autonomous media hosting
+# Copyright (C) 2011 Free Software Foundation, Inc
+#
+# 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/>.
+#}
+
+{% trans username=username, verification_url=verification_url|safe -%}
+Hi {{ username }},
+
+to change your GNU MediaGoblin password, open the following URL in
+your web browser:
+
+{{ verification_url }}
+
+If you think this is an error, just ignore this email and continue being
+a happy goblin!
+{%- endtrans %}
+
diff --git a/mediagoblin/plugins/basic_auth/tools.py b/mediagoblin/plugins/basic_auth/tools.py
new file mode 100644
index 00000000..f943bf39
--- /dev/null
+++ b/mediagoblin/plugins/basic_auth/tools.py
@@ -0,0 +1,121 @@
+# 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 bcrypt
+import random
+
+from mediagoblin import mg_globals
+from mediagoblin.tools.crypto import get_timed_signer_url
+from mediagoblin.tools.mail import send_email
+from mediagoblin.tools.template import render_template
+
+
+def bcrypt_check_password(raw_pass, stored_hash, extra_salt=None):
+ """
+ Check to see if this password matches.
+
+ Args:
+ - raw_pass: user submitted password to check for authenticity.
+ - stored_hash: The hash of the raw password (and possibly extra
+ salt) to check against
+ - extra_salt: (optional) If this password is with stored with a
+ non-database extra salt (probably in the config file) for extra
+ security, factor this into the check.
+
+ Returns:
+ True or False depending on success.
+ """
+ if extra_salt:
+ raw_pass = u"%s:%s" % (extra_salt, raw_pass)
+
+ hashed_pass = bcrypt.hashpw(raw_pass.encode('utf-8'), stored_hash)
+
+ # Reduce risk of timing attacks by hashing again with a random
+ # number (thx to zooko on this advice, which I hopefully
+ # incorporated right.)
+ #
+ # See also:
+ rand_salt = bcrypt.gensalt(5)
+ randplus_stored_hash = bcrypt.hashpw(stored_hash, rand_salt)
+ randplus_hashed_pass = bcrypt.hashpw(hashed_pass, rand_salt)
+
+ return randplus_stored_hash == randplus_hashed_pass
+
+
+def bcrypt_gen_password_hash(raw_pass, extra_salt=None):
+ """
+ Generate a salt for this new password.
+
+ Args:
+ - raw_pass: user submitted password
+ - extra_salt: (optional) If this password is with stored with a
+ non-database extra salt
+ """
+ if extra_salt:
+ raw_pass = u"%s:%s" % (extra_salt, raw_pass)
+
+ return unicode(
+ bcrypt.hashpw(raw_pass.encode('utf-8'), bcrypt.gensalt()))
+
+
+def fake_login_attempt():
+ """
+ Pretend we're trying to login.
+
+ Nothing actually happens here, we're just trying to take up some
+ time, approximately the same amount of time as
+ bcrypt_check_password, so as to avoid figuring out what users are
+ on the system by intentionally faking logins a bunch of times.
+ """
+ rand_salt = bcrypt.gensalt(5)
+
+ hashed_pass = bcrypt.hashpw(str(random.random()), rand_salt)
+
+ randplus_stored_hash = bcrypt.hashpw(str(random.random()), rand_salt)
+ randplus_hashed_pass = bcrypt.hashpw(hashed_pass, rand_salt)
+
+ randplus_stored_hash == randplus_hashed_pass
+
+
+EMAIL_FP_VERIFICATION_TEMPLATE = (
+ u"{uri}?"
+ u"token={fp_verification_key}")
+
+
+def send_fp_verification_email(user, request):
+ """
+ Send the verification email to users to change their password.
+
+ Args:
+ - user: a user object
+ - request: the request
+ """
+ fp_verification_key = get_timed_signer_url('mail_verification_token') \
+ .dumps(user.id)
+
+ rendered_email = render_template(
+ request, 'mediagoblin/plugins/basic_auth/fp_verification_email.txt',
+ {'username': user.username,
+ 'verification_url': EMAIL_FP_VERIFICATION_TEMPLATE.format(
+ uri=request.urlgen('mediagoblin.plugins.basic_auth.verify_forgot_password',
+ qualified=True),
+ fp_verification_key=fp_verification_key)})
+
+ # TODO: There is no error handling in place
+ send_email(
+ mg_globals.app_config['email_sender_address'],
+ [user.email],
+ 'GNU MediaGoblin - Change forgotten password!',
+ rendered_email)
diff --git a/mediagoblin/plugins/basic_auth/views.py b/mediagoblin/plugins/basic_auth/views.py
new file mode 100644
index 00000000..02d370f0
--- /dev/null
+++ b/mediagoblin/plugins/basic_auth/views.py
@@ -0,0 +1,223 @@
+# 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/>.
+from itsdangerous import BadSignature
+
+from mediagoblin import messages
+from mediagoblin.db.models import User
+from mediagoblin.decorators import require_active_login
+from mediagoblin.plugins.basic_auth import forms, tools
+from mediagoblin.tools.crypto import get_timed_signer_url
+from mediagoblin.tools.mail import email_debug_message
+from mediagoblin.tools.response import redirect, render_to_response, render_404
+from mediagoblin.tools.translate import pass_to_ugettext as _
+
+
+def forgot_password(request):
+ """
+ Forgot password view
+
+ Sends an email with an url to renew forgotten password.
+ Use GET querystring parameter 'username' to pre-populate the input field
+ """
+ fp_form = forms.ForgotPassForm(request.form,
+ username=request.args.get('username'))
+
+ if not (request.method == 'POST' and fp_form.validate()):
+ # Either GET request, or invalid form submitted. Display the template
+ return render_to_response(request,
+ 'mediagoblin/plugins/basic_auth/forgot_password.html',
+ {'fp_form': fp_form})
+
+ # If we are here: method == POST and form is valid. username casing
+ # has been sanitized. Store if a user was found by email. We should
+ # not reveal if the operation was successful then as we don't want to
+ # leak if an email address exists in the system.
+ found_by_email = '@' in fp_form.username.data
+
+ if found_by_email:
+ user = User.query.filter_by(
+ email=fp_form.username.data).first()
+ # Don't reveal success in case the lookup happened by email address.
+ success_message = _("If that email address (case sensitive!) is "
+ "registered an email has been sent with "
+ "instructions on how to change your password.")
+
+ else: # found by username
+ user = User.query.filter_by(
+ username=fp_form.username.data).first()
+
+ if user is None:
+ messages.add_message(request,
+ messages.WARNING,
+ _("Couldn't find someone with that username."))
+ return redirect(request, 'mediagoblin.auth.forgot_password')
+
+ success_message = _("An email has been sent with instructions "
+ "on how to change your password.")
+
+ if user and user.has_privilege(u'active') is False:
+ # Don't send reminder because user is inactive or has no verified email
+ messages.add_message(request,
+ messages.WARNING,
+ _("Could not send password recovery email as your username is in"
+ "active or your account's email address has not been verified."))
+
+ return redirect(request, 'mediagoblin.user_pages.user_home',
+ user=user.username)
+
+ # SUCCESS. Send reminder and return to login page
+ if user:
+ email_debug_message(request)
+ tools.send_fp_verification_email(user, request)
+
+ messages.add_message(request, messages.INFO, success_message)
+ return redirect(request, 'mediagoblin.auth.login')
+
+
+def verify_forgot_password(request):
+ """
+ Check the forgot-password verification and possibly let the user
+ change their password because of it.
+ """
+ # get form data variables, and specifically check for presence of token
+ formdata = _process_for_token(request)
+ if not formdata['has_token']:
+ return render_404(request)
+
+ formdata_vars = formdata['vars']
+
+ # Catch error if token is faked or expired
+ try:
+ token = get_timed_signer_url("mail_verification_token") \
+ .loads(formdata_vars['token'], max_age=10*24*3600)
+ except BadSignature:
+ messages.add_message(
+ request,
+ messages.ERROR,
+ _('The verification key or user id is incorrect.'))
+
+ return redirect(
+ request,
+ 'index')
+
+ # check if it's a valid user id
+ user = User.query.filter_by(id=int(token)).first()
+
+ # no user in db
+ if not user:
+ messages.add_message(
+ request, messages.ERROR,
+ _('The user id is incorrect.'))
+ return redirect(
+ request, 'index')
+
+ # check if user active and has email verified
+ if user.has_privilege(u'active'):
+ cp_form = forms.ChangeForgotPassForm(formdata_vars)
+
+ if request.method == 'POST' and cp_form.validate():
+ user.pw_hash = tools.bcrypt_gen_password_hash(
+ cp_form.password.data)
+ user.save()
+
+ messages.add_message(
+ request,
+ messages.INFO,
+ _("You can now log in using your new password."))
+ return redirect(request, 'mediagoblin.auth.login')
+ else:
+ return render_to_response(
+ request,
+ 'mediagoblin/plugins/basic_auth/change_fp.html',
+ {'cp_form': cp_form})
+
+ ## Commenting this out temporarily because I'm checking into
+ ## what's going on with user.email_verified.
+ ##
+ ## ... if this commit lasts long enough for anyone but me (cwebber) to
+ ## notice it, they should pester me to remove this or remove it
+ ## themselves ;)
+ #
+ # if not user.email_verified:
+ # messages.add_message(
+ # request, messages.ERROR,
+ # _('You need to verify your email before you can reset your'
+ # ' password.'))
+
+ if not user.status == 'active':
+ messages.add_message(
+ request, messages.ERROR,
+ _('You are no longer an active user. Please contact the system'
+ ' admin to reactivate your account.'))
+
+ return redirect(
+ request, 'index')
+
+
+def _process_for_token(request):
+ """
+ Checks for tokens in formdata without prior knowledge of request method
+
+ For now, returns whether the userid and token formdata variables exist, and
+ the formdata variables in a hash. Perhaps an object is warranted?
+ """
+ # retrieve the formdata variables
+ if request.method == 'GET':
+ formdata_vars = request.GET
+ else:
+ formdata_vars = request.form
+
+ formdata = {
+ 'vars': formdata_vars,
+ 'has_token': 'token' in formdata_vars}
+
+ return formdata
+
+
+@require_active_login
+def change_pass(request):
+ form = forms.ChangePassForm(request.form)
+ user = request.user
+
+ if request.method == 'POST' and form.validate():
+
+ if not tools.bcrypt_check_password(
+ form.old_password.data, user.pw_hash):
+ form.old_password.errors.append(
+ _('Wrong password'))
+
+ return render_to_response(
+ request,
+ 'mediagoblin/plugins/basic_auth/change_pass.html',
+ {'form': form,
+ 'user': user})
+
+ # Password matches
+ user.pw_hash = tools.bcrypt_gen_password_hash(
+ form.new_password.data)
+ user.save()
+
+ messages.add_message(
+ request, messages.SUCCESS,
+ _('Your password was changed successfully'))
+
+ return redirect(request, 'mediagoblin.edit.account')
+
+ return render_to_response(
+ request,
+ 'mediagoblin/plugins/basic_auth/change_pass.html',
+ {'form': form,
+ 'user': user})
diff --git a/mediagoblin/plugins/httpapiauth/__init__.py b/mediagoblin/plugins/httpapiauth/__init__.py
index 081b590e..2b2d593c 100644
--- a/mediagoblin/plugins/httpapiauth/__init__.py
+++ b/mediagoblin/plugins/httpapiauth/__init__.py
@@ -15,10 +15,10 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
-import base64
-from werkzeug.exceptions import BadRequest, Unauthorized
+from werkzeug.exceptions import Unauthorized
+from mediagoblin.auth.tools import check_login_simple
from mediagoblin.plugins.api.tools import Auth
_log = logging.getLogger(__name__)
@@ -40,10 +40,10 @@ class HTTPAuth(Auth):
if not request.authorization:
return False
- user = request.db.User.query.filter_by(
- username=unicode(request.authorization['username'])).first()
+ user = check_login_simple(unicode(request.authorization['username']),
+ request.authorization['password'])
- if user.check_login(request.authorization['password']):
+ if user:
request.user = user
return True
else:
diff --git a/mediagoblin/plugins/ldap/README.rst b/mediagoblin/plugins/ldap/README.rst
new file mode 100644
index 00000000..ea9a34b3
--- /dev/null
+++ b/mediagoblin/plugins/ldap/README.rst
@@ -0,0 +1,64 @@
+.. MediaGoblin Documentation
+
+ Written in 2012 by MediaGoblin contributors
+
+ To the extent possible under law, the author(s) have dedicated all
+ copyright and related and neighboring rights to this software to
+ the public domain worldwide. This software is distributed without
+ any warranty.
+
+ You should have received a copy of the CC0 Public Domain
+ Dedication along with this software. If not, see
+ <http://creativecommons.org/publicdomain/zero/1.0/>.
+
+.. _ldap-plugin:
+
+=============
+ ldap plugin
+=============
+
+.. Warning::
+ This plugin is not compatible with the other authentication plugins.
+
+This plugin allow your GNU Mediagoblin instance to authenticate against an
+LDAP server.
+
+Set up the ldap plugin
+======================
+
+1. Install the ``python-ldap`` package.
+
+2. Add the following to your MediaGoblin .ini file in the ``[plugins]`` section::
+
+ [[mediagoblin.plugins.ldap]]
+
+Configuring the ldap plugin
+===========================
+
+This plugin allows you to use multiple ldap servers for authentication.
+
+In order to configure a server, add the following to you MediaGoblin .ini file
+under the ldap plugin::
+
+ [[mediagoblin.plugins.ldap]]
+ [[[server1]]]
+ LDAP_SERVER_URI = 'ldap://ldap.testathon.net:389'
+ LDAP_USER_DN_TEMPLATE = 'cn={username},ou=users,dc=testathon,dc=net'
+ [[[server2]]]
+ ...
+
+Make any necessary changes to the above to work with your sever. Make sure
+``{username}`` is where the username should be in LDAP_USER_DN_TEMPLATE.
+
+If you would like to fetch the users email from the ldap server upon account
+registration, add ``LDAP_SEARCH_BASE = 'ou=users,dc=testathon,dc=net'`` and
+``EMAIL_SEARCH_FIELD = 'mail'`` under you server configuration in your
+MediaGoblin .ini file.
+
+.. Warning::
+ By default, this plugin provides no encryption when communicating with the
+ ldap servers. If you would like to use an SSL connection, change
+ LDAP_SERVER_URI to use ``ldaps://`` and whichever port you use. Default ldap
+ port for SSL connections is 636. If you would like to use a TLS connection,
+ add ``LDAP_START_TLS = 'true'`` under your server configuration in your
+ MediaGoblin .ini file.
diff --git a/mediagoblin/plugins/ldap/__init__.py b/mediagoblin/plugins/ldap/__init__.py
new file mode 100644
index 00000000..4673acee
--- /dev/null
+++ b/mediagoblin/plugins/ldap/__init__.py
@@ -0,0 +1,59 @@
+# 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 os
+
+from mediagoblin.auth.tools import create_basic_user
+from mediagoblin.tools import pluginapi
+
+PLUGIN_DIR = os.path.dirname(__file__)
+
+
+def setup_plugin():
+ config = pluginapi.get_config('mediagoblin.plugins.ldap')
+
+ routes = [
+ ('mediagoblin.plugins.ldap.register',
+ '/auth/ldap/register/',
+ 'mediagoblin.plugins.ldap.views:register'),
+ ('mediagoblin.plugins.ldap.login',
+ '/auth/ldap/login/',
+ 'mediagoblin.plugins.ldap.views:login')]
+
+ pluginapi.register_routes(routes)
+ pluginapi.register_template_path(os.path.join(PLUGIN_DIR, 'templates'))
+
+ pluginapi.register_template_hooks(
+ {'create_account': 'mediagoblin/plugins/ldap/create_account_link.html'})
+
+
+def create_user(register_form):
+ if 'username' in register_form and 'password' not in register_form:
+ return create_basic_user(register_form)
+
+
+def no_pass_redirect():
+ return 'ldap'
+
+
+def auth():
+ return True
+
+hooks = {
+ 'setup': setup_plugin,
+ 'authentication': auth,
+ 'auth_no_pass_redirect': no_pass_redirect,
+ 'auth_create_user': create_user,
+}
diff --git a/mediagoblin/plugins/ldap/forms.py b/mediagoblin/plugins/ldap/forms.py
new file mode 100644
index 00000000..7ec1479e
--- /dev/null
+++ b/mediagoblin/plugins/ldap/forms.py
@@ -0,0 +1,40 @@
+# 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 wtforms
+
+from mediagoblin.tools.translate import lazy_pass_to_ugettext as _
+from mediagoblin.auth.tools import normalize_user_or_email_field
+
+
+class RegisterForm(wtforms.Form):
+ username = wtforms.HiddenField(
+ '',
+ [wtforms.validators.Required(),
+ normalize_user_or_email_field(allow_email=False)])
+ email = wtforms.TextField(
+ _('Email address'),
+ [wtforms.validators.Required(),
+ normalize_user_or_email_field(allow_user=False)])
+
+
+class LoginForm(wtforms.Form):
+ username = wtforms.TextField(
+ _('Username'),
+ [wtforms.validators.Required(),
+ normalize_user_or_email_field()])
+ password = wtforms.PasswordField(
+ _('Password'),
+ [wtforms.validators.Required()])
diff --git a/mediagoblin/plugins/ldap/templates/mediagoblin/plugins/ldap/create_account_link.html b/mediagoblin/plugins/ldap/templates/mediagoblin/plugins/ldap/create_account_link.html
new file mode 100644
index 00000000..947e4ae2
--- /dev/null
+++ b/mediagoblin/plugins/ldap/templates/mediagoblin/plugins/ldap/create_account_link.html
@@ -0,0 +1,25 @@
+{#
+# 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/>.
+#}
+
+{% block create_account %}
+ {% if allow_registration %}
+ <p>
+ {% trans %}Sign in to create an account!{% endtrans %}
+ </p>
+ {% endif %}
+{% endblock %}
diff --git a/mediagoblin/plugins/ldap/tools.py b/mediagoblin/plugins/ldap/tools.py
new file mode 100644
index 00000000..1c436792
--- /dev/null
+++ b/mediagoblin/plugins/ldap/tools.py
@@ -0,0 +1,65 @@
+# 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 ldap
+import logging
+
+from mediagoblin.tools import pluginapi
+
+_log = logging.getLogger(__name__)
+
+
+class LDAP(object):
+ def __init__(self):
+ self.ldap_settings = pluginapi.get_config('mediagoblin.plugins.ldap')
+
+ def _connect(self, server):
+ _log.info('Connecting to {0}.'.format(server['LDAP_SERVER_URI']))
+ self.conn = ldap.initialize(server['LDAP_SERVER_URI'])
+
+ if server['LDAP_START_TLS'] == 'true':
+ _log.info('Initiating TLS')
+ self.conn.start_tls_s()
+
+ def _get_email(self, server, username):
+ try:
+ results = self.conn.search_s(server['LDAP_SEARCH_BASE'],
+ ldap.SCOPE_SUBTREE, 'uid={0}'
+ .format(username),
+ [server['EMAIL_SEARCH_FIELD']])
+
+ email = results[0][1][server['EMAIL_SEARCH_FIELD']][0]
+ except KeyError:
+ email = None
+
+ return email
+
+ def login(self, username, password):
+ for k, v in self.ldap_settings.iteritems():
+ try:
+ self._connect(v)
+ user_dn = v['LDAP_USER_DN_TEMPLATE'].format(username=username)
+ self.conn.simple_bind_s(user_dn, password.encode('utf8'))
+ email = self._get_email(v, username)
+ return username, email
+
+ except ldap.LDAPError, e:
+ _log.info(e)
+
+ finally:
+ _log.info('Unbinding {0}.'.format(v['LDAP_SERVER_URI']))
+ self.conn.unbind()
+
+ return False, None
diff --git a/mediagoblin/plugins/ldap/views.py b/mediagoblin/plugins/ldap/views.py
new file mode 100644
index 00000000..aef1bf56
--- /dev/null
+++ b/mediagoblin/plugins/ldap/views.py
@@ -0,0 +1,104 @@
+# 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/>.
+from mediagoblin import mg_globals, messages
+from mediagoblin.auth.tools import register_user
+from mediagoblin.db.models import User
+from mediagoblin.decorators import allow_registration, auth_enabled
+from mediagoblin.plugins.ldap import forms
+from mediagoblin.plugins.ldap.tools import LDAP
+from mediagoblin.tools.translate import pass_to_ugettext as _
+from mediagoblin.tools.response import redirect, render_to_response
+
+
+@auth_enabled
+def login(request):
+ login_form = forms.LoginForm(request.form)
+
+ login_failed = False
+
+ if request.method == 'POST' and login_form.validate():
+ l = LDAP()
+ username, email = l.login(login_form.username.data,
+ login_form.password.data)
+
+ if username:
+ user = User.query.filter_by(
+ username=username).first()
+
+ if user:
+ # set up login in session
+ request.session['user_id'] = unicode(user.id)
+ request.session.save()
+
+ if request.form.get('next'):
+ return redirect(request, location=request.form['next'])
+ else:
+ return redirect(request, "index")
+ else:
+ if not mg_globals.app.auth:
+ messages.add_message(
+ request,
+ messages.WARNING,
+ _('Sorry, authentication is disabled on this '
+ 'instance.'))
+ return redirect(request, 'index')
+
+ register_form = forms.RegisterForm(username=username,
+ email=email)
+
+ return render_to_response(
+ request,
+ 'mediagoblin/auth/register.html',
+ {'register_form': register_form,
+ 'post_url': request.urlgen('mediagoblin.plugins.ldap.register')})
+
+ login_failed = True
+
+ return render_to_response(
+ request,
+ 'mediagoblin/auth/login.html',
+ {'login_form': login_form,
+ 'next': request.GET.get('next') or request.form.get('next'),
+ 'login_failed': login_failed,
+ 'post_url': request.urlgen('mediagoblin.plugins.ldap.login'),
+ 'allow_registration': mg_globals.app_config["allow_registration"]})
+
+
+@allow_registration
+@auth_enabled
+def register(request):
+ if request.method == 'GET':
+ return redirect(
+ request,
+ 'mediagoblin.plugins.ldap.login')
+
+ register_form = forms.RegisterForm(request.form)
+
+ if register_form.validate():
+ user = register_user(request, register_form)
+
+ if user:
+ # redirect the user to their homepage... there will be a
+ # message waiting for them to verify their email
+ return redirect(
+ request, 'mediagoblin.user_pages.user_home',
+ user=user.username)
+
+ return render_to_response(
+ request,
+ 'mediagoblin/auth/register.html',
+ {'register_form': register_form,
+ 'post_url': request.urlgen('mediagoblin.plugins.ldap.register')})
diff --git a/mediagoblin/plugins/oauth/__init__.py b/mediagoblin/plugins/oauth/__init__.py
index 5762379d..82c1f380 100644
--- a/mediagoblin/plugins/oauth/__init__.py
+++ b/mediagoblin/plugins/oauth/__init__.py
@@ -35,22 +35,22 @@ def setup_plugin():
routes = [
('mediagoblin.plugins.oauth.authorize',
- '/oauth/authorize',
+ '/oauth-2/authorize',
'mediagoblin.plugins.oauth.views:authorize'),
('mediagoblin.plugins.oauth.authorize_client',
- '/oauth/client/authorize',
+ '/oauth-2/client/authorize',
'mediagoblin.plugins.oauth.views:authorize_client'),
('mediagoblin.plugins.oauth.access_token',
- '/oauth/access_token',
+ '/oauth-2/access_token',
'mediagoblin.plugins.oauth.views:access_token'),
('mediagoblin.plugins.oauth.list_connections',
- '/oauth/client/connections',
+ '/oauth-2/client/connections',
'mediagoblin.plugins.oauth.views:list_connections'),
('mediagoblin.plugins.oauth.register_client',
- '/oauth/client/register',
+ '/oauth-2/client/register',
'mediagoblin.plugins.oauth.views:register_client'),
('mediagoblin.plugins.oauth.list_clients',
- '/oauth/client/list',
+ '/oauth-2/client/list',
'mediagoblin.plugins.oauth.views:list_clients')]
pluginapi.register_routes(routes)
diff --git a/mediagoblin/plugins/oauth/tools.py b/mediagoblin/plugins/oauth/tools.py
index 27ff32b4..af0a3305 100644
--- a/mediagoblin/plugins/oauth/tools.py
+++ b/mediagoblin/plugins/oauth/tools.py
@@ -23,7 +23,7 @@ from datetime import datetime
from functools import wraps
-from mediagoblin.plugins.api.tools import json_response
+from mediagoblin.tools.response import json_response
def require_client_auth(controller):
diff --git a/mediagoblin/plugins/oauth/views.py b/mediagoblin/plugins/oauth/views.py
index d6fd314f..de637d6b 100644
--- a/mediagoblin/plugins/oauth/views.py
+++ b/mediagoblin/plugins/oauth/views.py
@@ -21,7 +21,7 @@ from urllib import urlencode
from werkzeug.exceptions import BadRequest
-from mediagoblin.tools.response import render_to_response, redirect
+from mediagoblin.tools.response import render_to_response, redirect, json_response
from mediagoblin.decorators import require_active_login
from mediagoblin.messages import add_message, SUCCESS
from mediagoblin.tools.translate import pass_to_ugettext as _
@@ -31,7 +31,6 @@ from mediagoblin.plugins.oauth.forms import ClientRegistrationForm, \
AuthorizationForm
from mediagoblin.plugins.oauth.tools import require_client_auth, \
create_token
-from mediagoblin.plugins.api.tools import json_response
_log = logging.getLogger(__name__)
diff --git a/mediagoblin/plugins/openid/README.rst b/mediagoblin/plugins/openid/README.rst
new file mode 100644
index 00000000..870a2b58
--- /dev/null
+++ b/mediagoblin/plugins/openid/README.rst
@@ -0,0 +1,34 @@
+.. _openid-chapter:
+
+===================
+ openid plugin
+===================
+
+The openid plugin allows user to login to your GNU Mediagoblin instance using
+their openid url.
+
+This plugin can be enabled alongside :ref:`basic_auth-chapter` and
+:ref:`persona-chapter`.
+
+.. note::
+ When :ref:`basic_auth-chapter` is enabled alongside this openid plugin, and
+ a user creates an account using their openid. If they would like to add a
+ password to their account, they can use the forgot password feature to do
+ so.
+
+
+Set up the openid plugin
+============================
+
+1. Install the ``python-openid`` package.
+
+2. Add the following to your MediaGoblin .ini file in the ``[plugins]`` section::
+
+ [[mediagoblin.plugins.openid]]
+
+3. Run::
+
+ gmg dbupdate
+
+ in order to create and apply migrations to any database tables that the
+ plugin requires.
diff --git a/mediagoblin/plugins/openid/__init__.py b/mediagoblin/plugins/openid/__init__.py
new file mode 100644
index 00000000..ca17a7e8
--- /dev/null
+++ b/mediagoblin/plugins/openid/__init__.py
@@ -0,0 +1,125 @@
+# 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 os
+import uuid
+
+from sqlalchemy import or_
+
+from mediagoblin.auth.tools import create_basic_user
+from mediagoblin.db.models import User
+from mediagoblin.plugins.openid.models import OpenIDUserURL
+from mediagoblin.tools import pluginapi
+from mediagoblin.tools.translate import lazy_pass_to_ugettext as _
+
+PLUGIN_DIR = os.path.dirname(__file__)
+
+
+def setup_plugin():
+ config = pluginapi.get_config('mediagoblin.plugins.openid')
+
+ routes = [
+ ('mediagoblin.plugins.openid.register',
+ '/auth/openid/register/',
+ 'mediagoblin.plugins.openid.views:register'),
+ ('mediagoblin.plugins.openid.login',
+ '/auth/openid/login/',
+ 'mediagoblin.plugins.openid.views:login'),
+ ('mediagoblin.plugins.openid.finish_login',
+ '/auth/openid/login/finish/',
+ 'mediagoblin.plugins.openid.views:finish_login'),
+ ('mediagoblin.plugins.openid.edit',
+ '/edit/openid/',
+ 'mediagoblin.plugins.openid.views:start_edit'),
+ ('mediagoblin.plugins.openid.finish_edit',
+ '/edit/openid/finish/',
+ 'mediagoblin.plugins.openid.views:finish_edit'),
+ ('mediagoblin.plugins.openid.delete',
+ '/edit/openid/delete/',
+ 'mediagoblin.plugins.openid.views:delete_openid'),
+ ('mediagoblin.plugins.openid.finish_delete',
+ '/edit/openid/delete/finish/',
+ 'mediagoblin.plugins.openid.views:finish_delete')]
+
+ pluginapi.register_routes(routes)
+ pluginapi.register_template_path(os.path.join(PLUGIN_DIR, 'templates'))
+
+ pluginapi.register_template_hooks(
+ {'register_link': 'mediagoblin/plugins/openid/register_link.html',
+ 'login_link': 'mediagoblin/plugins/openid/login_link.html',
+ 'edit_link': 'mediagoblin/plugins/openid/edit_link.html'})
+
+
+def create_user(register_form):
+ if 'openid' in register_form:
+ username = register_form.username.data
+ user = User.query.filter(
+ or_(
+ User.username == username,
+ User.email == username,
+ )).first()
+
+ if not user:
+ user = create_basic_user(register_form)
+
+ new_entry = OpenIDUserURL()
+ new_entry.openid_url = register_form.openid.data
+ new_entry.user_id = user.id
+ new_entry.save()
+
+ return user
+
+
+def extra_validation(register_form):
+ openid = register_form.openid.data if 'openid' in \
+ register_form else None
+ if openid:
+ openid_url_exists = OpenIDUserURL.query.filter_by(
+ openid_url=openid
+ ).count()
+
+ extra_validation_passes = True
+
+ if openid_url_exists:
+ register_form.openid.errors.append(
+ _('Sorry, an account is already registered to that OpenID.'))
+ extra_validation_passes = False
+
+ return extra_validation_passes
+
+
+def no_pass_redirect():
+ return 'openid'
+
+
+def add_to_form_context(context):
+ context['openid_link'] = True
+ return context
+
+
+def Auth():
+ return True
+
+hooks = {
+ 'setup': setup_plugin,
+ 'authentication': Auth,
+ 'auth_extra_validation': extra_validation,
+ 'auth_create_user': create_user,
+ 'auth_no_pass_redirect': no_pass_redirect,
+ ('mediagoblin.auth.register',
+ 'mediagoblin/auth/register.html'): add_to_form_context,
+ ('mediagoblin.auth.login',
+ 'mediagoblin/auth/login.html'): add_to_form_context
+}
diff --git a/mediagoblin/plugins/openid/forms.py b/mediagoblin/plugins/openid/forms.py
new file mode 100644
index 00000000..f26024bd
--- /dev/null
+++ b/mediagoblin/plugins/openid/forms.py
@@ -0,0 +1,41 @@
+# 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 wtforms
+
+from mediagoblin.tools.translate import lazy_pass_to_ugettext as _
+from mediagoblin.auth.tools import normalize_user_or_email_field
+
+
+class RegistrationForm(wtforms.Form):
+ openid = wtforms.HiddenField(
+ '',
+ [wtforms.validators.Required()])
+ username = wtforms.TextField(
+ _('Username'),
+ [wtforms.validators.Required(),
+ normalize_user_or_email_field(allow_email=False)])
+ email = wtforms.TextField(
+ _('Email address'),
+ [wtforms.validators.Required(),
+ normalize_user_or_email_field(allow_user=False)])
+
+
+class LoginForm(wtforms.Form):
+ openid = wtforms.TextField(
+ _('OpenID'),
+ [wtforms.validators.Required(),
+ # Can openid's only be urls?
+ wtforms.validators.URL(message='Please enter a valid url.')])
diff --git a/mediagoblin/plugins/openid/models.py b/mediagoblin/plugins/openid/models.py
new file mode 100644
index 00000000..6773f0ad
--- /dev/null
+++ b/mediagoblin/plugins/openid/models.py
@@ -0,0 +1,65 @@
+# 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/>.
+from sqlalchemy import Column, Integer, Unicode, ForeignKey
+from sqlalchemy.orm import relationship, backref
+
+from mediagoblin.db.models import User
+from mediagoblin.db.base import Base
+
+
+class OpenIDUserURL(Base):
+ __tablename__ = "openid__user_urls"
+
+ id = Column(Integer, primary_key=True)
+ openid_url = Column(Unicode, nullable=False)
+ user_id = Column(Integer, ForeignKey(User.id), nullable=False)
+
+ # OpenID's are owned by their user, so do the full thing.
+ user = relationship(User, backref=backref('openid_urls',
+ cascade='all, delete-orphan'))
+
+
+# OpenID Store Models
+class Nonce(Base):
+ __tablename__ = "openid__nonce"
+
+ server_url = Column(Unicode, primary_key=True)
+ timestamp = Column(Integer, primary_key=True)
+ salt = Column(Unicode, primary_key=True)
+
+ def __unicode__(self):
+ return u'Nonce: %r, %r' % (self.server_url, self.salt)
+
+
+class Association(Base):
+ __tablename__ = "openid__association"
+
+ server_url = Column(Unicode, primary_key=True)
+ handle = Column(Unicode, primary_key=True)
+ secret = Column(Unicode)
+ issued = Column(Integer)
+ lifetime = Column(Integer)
+ assoc_type = Column(Unicode)
+
+ def __unicode__(self):
+ return u'Association: %r, %r' % (self.server_url, self.handle)
+
+
+MODELS = [
+ OpenIDUserURL,
+ Nonce,
+ Association
+]
diff --git a/mediagoblin/plugins/openid/store.py b/mediagoblin/plugins/openid/store.py
new file mode 100644
index 00000000..8f9a7012
--- /dev/null
+++ b/mediagoblin/plugins/openid/store.py
@@ -0,0 +1,127 @@
+# 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 base64
+import time
+
+from openid.association import Association as OIDAssociation
+from openid.store.interface import OpenIDStore
+from openid.store import nonce
+
+from mediagoblin.plugins.openid.models import Association, Nonce
+
+
+class SQLAlchemyOpenIDStore(OpenIDStore):
+ def __init__(self):
+ self.max_nonce_age = 6 * 60 * 60
+
+ def storeAssociation(self, server_url, association):
+ assoc = Association.query.filter_by(
+ server_url=server_url, handle=association.handle
+ ).first()
+
+ if not assoc:
+ assoc = Association()
+ assoc.server_url = unicode(server_url)
+ assoc.handle = association.handle
+
+ # django uses base64 encoding, python-openid uses a blob field for
+ # secret
+ assoc.secret = unicode(base64.encodestring(association.secret))
+ assoc.issued = association.issued
+ assoc.lifetime = association.lifetime
+ assoc.assoc_type = association.assoc_type
+ assoc.save()
+
+ def getAssociation(self, server_url, handle=None):
+ assocs = []
+ if handle is not None:
+ assocs = Association.query.filter_by(
+ server_url=server_url, handle=handle
+ )
+ else:
+ assocs = Association.query.filter_by(
+ server_url=server_url
+ )
+
+ if assocs.count() == 0:
+ return None
+ else:
+ associations = []
+ for assoc in assocs:
+ association = OIDAssociation(
+ assoc.handle, base64.decodestring(assoc.secret),
+ assoc.issued, assoc.lifetime, assoc.assoc_type
+ )
+ if association.getExpiresIn() == 0:
+ assoc.delete()
+ else:
+ associations.append((association.issued, association))
+
+ if not associations:
+ return None
+ associations.sort()
+ return associations[-1][1]
+
+ def removeAssociation(self, server_url, handle):
+ assocs = Association.query.filter_by(
+ server_url=server_url, handle=handle
+ ).first()
+
+ assoc_exists = True if assocs else False
+ for assoc in assocs:
+ assoc.delete()
+ return assoc_exists
+
+ def useNonce(self, server_url, timestamp, salt):
+ if abs(timestamp - time.time()) > nonce.SKEW:
+ return False
+
+ ononce = Nonce.query.filter_by(
+ server_url=server_url,
+ timestamp=timestamp,
+ salt=salt
+ ).first()
+
+ if ononce:
+ return False
+ else:
+ ononce = Nonce()
+ ononce.server_url = server_url
+ ononce.timestamp = timestamp
+ ononce.salt = salt
+ ononce.save()
+ return True
+
+ def cleanupNonces(self, _now=None):
+ if _now is None:
+ _now = int(time.time())
+ expired = Nonce.query.filter(
+ Nonce.timestamp < (_now - nonce.SKEW)
+ )
+ count = expired.count()
+ for each in expired:
+ each.delete()
+ return count
+
+ def cleanupAssociations(self):
+ now = int(time.time())
+ assoc = Association.query.all()
+ count = 0
+ for each in assoc:
+ if (each.lifetime + each.issued) <= now:
+ each.delete()
+ count = count + 1
+ return count
diff --git a/mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/add.html b/mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/add.html
new file mode 100644
index 00000000..8d308c81
--- /dev/null
+++ b/mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/add.html
@@ -0,0 +1,44 @@
+{#
+# 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/>.
+#}
+{% extends "mediagoblin/base.html" %}
+
+{% import "/mediagoblin/utils/wtforms.html" as wtforms_util %}
+
+{% block title -%}
+ {% trans %}Add an OpenID{% endtrans %} &mdash; {{ super() }}
+{%- endblock %}
+
+{% block mediagoblin_content %}
+ <form action="{{ request.urlgen('mediagoblin.plugins.openid.edit') }}"
+ method="POST" enctype="multipart/form-data">
+ {{ csrf_token }}
+ <div class="form_box">
+ <h1>{% trans %}Add an OpenID{% endtrans %}</h1>
+ <p>
+ <a href="{{ request.urlgen('mediagoblin.plugins.openid.delete') }}">
+ {% trans %}Delete an OpenID{% endtrans %}
+ </a>
+ </p>
+ {{ wtforms_util.render_divs(form, True) }}
+ <div class="form_submit_buttons">
+ <input type="submit" value="{% trans %}Add{% endtrans %}" class="button_form"/>
+ </div>
+ </div>
+ </form>
+{% endblock %}
+
diff --git a/mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/delete.html b/mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/delete.html
new file mode 100644
index 00000000..84301b9e
--- /dev/null
+++ b/mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/delete.html
@@ -0,0 +1,43 @@
+{#
+# 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/>.
+#}
+{% extends "mediagoblin/base.html" %}
+
+{% import "/mediagoblin/utils/wtforms.html" as wtforms_util %}
+
+{% block title -%}
+ {% trans %}Delete an OpenID{% endtrans %} &mdash; {{ super() }}
+{%- endblock %}
+
+{% block mediagoblin_content %}
+ <form action="{{ request.urlgen('mediagoblin.plugins.openid.delete') }}"
+ method="POST" enctype="multipart/form-data">
+ {{ csrf_token }}
+ <div class="form_box">
+ <h1>{% trans %}Delete an OpenID{% endtrans %}</h1>
+ <p>
+ <a href="{{ request.urlgen('mediagoblin.plugins.openid.edit') }}">
+ {% trans %}Add an OpenID{% endtrans %}
+ </a>
+ </p>
+ {{ wtforms_util.render_divs(form, True) }}
+ <div class="form_submit_buttons">
+ <input type="submit" value="{% trans %}Delete{% endtrans %}" class="button_form"/>
+ </div>
+ </div>
+ </form>
+{% endblock %}
diff --git a/mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/edit_link.html b/mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/edit_link.html
new file mode 100644
index 00000000..88b232f8
--- /dev/null
+++ b/mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/edit_link.html
@@ -0,0 +1,24 @@
+{#
+# 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/>.
+#}
+
+{% block openid_edit_link %}
+ <a href="{{ request.urlgen('mediagoblin.plugins.openid.edit') }}">
+ {% trans %}OpenID's{% endtrans %}
+ </a>
+ &middot;
+{% endblock %}
diff --git a/mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/login.html b/mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/login.html
new file mode 100644
index 00000000..193a3b2d
--- /dev/null
+++ b/mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/login.html
@@ -0,0 +1,66 @@
+{#
+# 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/>.
+#}
+{% extends "mediagoblin/base.html" %}
+
+{% import "/mediagoblin/utils/wtforms.html" as wtforms_util %}
+
+{% block mediagoblin_head %}
+ {{ super() }}
+ {% template_hook("fp_head") %}
+{% endblock %}
+
+{% block title -%}
+ {% trans %}Log in{% endtrans %} &mdash; {{ super() }}
+{%- endblock %}
+
+{% block mediagoblin_content %}
+ <form action="{{ post_url }}"
+ method="POST" enctype="multipart/form-data">
+ {{ csrf_token }}
+ <div class="form_box">
+ <h1>{% trans %}Log in{% endtrans %}</h1>
+ {% if login_failed %}
+ <div class="form_field_error">
+ {% trans %}Logging in failed!{% endtrans %}
+ </div>
+ {% endif %}
+ {% if allow_registration %}
+ <p>
+ {% trans %}Log in to create an account!{% endtrans %}
+ </p>
+ {% endif %}
+ {% template_hook('login_link') %}
+ {% if pass_auth is defined %}
+ <p>
+ <a href="{{ request.urlgen('mediagoblin.auth.login') }}?{{ request.query_string }}">
+ {%- trans %}Or login with a password!{% endtrans %}
+ </a>
+ </p>
+ {% endif %}
+ {{ wtforms_util.render_divs(login_form, True) }}
+ <div class="form_submit_buttons">
+ <input type="submit" value="{% trans %}Log in{% endtrans %}" class="button_form"/>
+ </div>
+ {% if next %}
+ <input type="hidden" name="next" value="{{ next }}" class="button_form"
+ style="display: none;"/>
+ {% endif %}
+ </div>
+ </form>
+{% endblock %}
+
diff --git a/mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/login_link.html b/mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/login_link.html
new file mode 100644
index 00000000..fa4d5e85
--- /dev/null
+++ b/mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/login_link.html
@@ -0,0 +1,27 @@
+{#
+# 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/>.
+#}
+
+{% block openid_login_link %}
+ {% if openid_link is defined %}
+ <p>
+ <a href="{{ request.urlgen('mediagoblin.plugins.openid.login') }}?{{ request.query_string }}">
+ {%- trans %}Or login with OpenID!{% endtrans %}
+ </a>
+ </p>
+ {% endif %}
+{% endblock %}
diff --git a/mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/register_link.html b/mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/register_link.html
new file mode 100644
index 00000000..9bccb4d8
--- /dev/null
+++ b/mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/register_link.html
@@ -0,0 +1,27 @@
+{#
+# 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/>.
+#}
+
+{% block openid_register_link %}
+ {% if openid_link is defined %}
+ <p>
+ <a href="{{ request.urlgen('mediagoblin.plugins.openid.login') }}">
+ {%- trans %}Or register with OpenID!{% endtrans %}
+ </a>
+ </p>
+ {% endif %}
+{% endblock %}
diff --git a/mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/request_form.html b/mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/request_form.html
new file mode 100644
index 00000000..68d028d0
--- /dev/null
+++ b/mediagoblin/plugins/openid/templates/mediagoblin/plugins/openid/request_form.html
@@ -0,0 +1,24 @@
+{#
+# 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/>.
+#}
+{% extends "mediagoblin/base.html" %}
+
+{% block mediagoblin_content %}
+ <div onload="document.getElementById('openid_message').submit()">
+ {{ html|safe }}
+ </div>
+{% endblock %}
diff --git a/mediagoblin/plugins/openid/views.py b/mediagoblin/plugins/openid/views.py
new file mode 100644
index 00000000..bb2de7ab
--- /dev/null
+++ b/mediagoblin/plugins/openid/views.py
@@ -0,0 +1,404 @@
+# 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/>.
+from openid.consumer import consumer
+from openid.consumer.discover import DiscoveryFailure
+from openid.extensions.sreg import SRegRequest, SRegResponse
+
+from mediagoblin import mg_globals, messages
+from mediagoblin.db.models import User
+from mediagoblin.decorators import (auth_enabled, allow_registration,
+ require_active_login)
+from mediagoblin.tools.response import redirect, render_to_response
+from mediagoblin.tools.translate import pass_to_ugettext as _
+from mediagoblin.plugins.openid import forms as auth_forms
+from mediagoblin.plugins.openid.models import OpenIDUserURL
+from mediagoblin.plugins.openid.store import SQLAlchemyOpenIDStore
+from mediagoblin.auth.tools import register_user
+
+
+def _start_verification(request, form, return_to, sreg=True):
+ """
+ Start OpenID Verification.
+
+ Returns False if verification fails, otherwise, will return either a
+ redirect or render_to_response object
+ """
+ openid_url = form.openid.data
+ c = consumer.Consumer(request.session, SQLAlchemyOpenIDStore())
+
+ # Try to discover provider
+ try:
+ auth_request = c.begin(openid_url)
+ except DiscoveryFailure:
+ # Discovery failed, return to login page
+ form.openid.errors.append(
+ _('Sorry, the OpenID server could not be found'))
+
+ return False
+
+ host = 'http://' + request.host
+
+ if sreg:
+ # Ask provider for email and nickname
+ auth_request.addExtension(SRegRequest(required=['email', 'nickname']))
+
+ # Do we even need this?
+ if auth_request is None:
+ form.openid.errors.append(
+ _('No OpenID service was found for %s' % openid_url))
+
+ elif auth_request.shouldSendRedirect():
+ # Begin the authentication process as a HTTP redirect
+ redirect_url = auth_request.redirectURL(
+ host, return_to)
+
+ return redirect(
+ request, location=redirect_url)
+
+ else:
+ # Send request as POST
+ form_html = auth_request.htmlMarkup(
+ host, host + return_to,
+ # Is this necessary?
+ form_tag_attrs={'id': 'openid_message'})
+
+ # Beware: this renders a template whose content is a form
+ # and some javascript to submit it upon page load. Non-JS
+ # users will have to click the form submit button to
+ # initiate OpenID authentication.
+ return render_to_response(
+ request,
+ 'mediagoblin/plugins/openid/request_form.html',
+ {'html': form_html})
+
+ return False
+
+
+def _finish_verification(request):
+ """
+ Complete OpenID Verification Process.
+
+ If the verification failed, will return false, otherwise, will return
+ the response
+ """
+ c = consumer.Consumer(request.session, SQLAlchemyOpenIDStore())
+
+ # Check the response from the provider
+ response = c.complete(request.args, request.base_url)
+ if response.status == consumer.FAILURE:
+ messages.add_message(
+ request,
+ messages.WARNING,
+ _('Verification of %s failed: %s' %
+ (response.getDisplayIdentifier(), response.message)))
+
+ elif response.status == consumer.SUCCESS:
+ # Verification was successfull
+ return response
+
+ elif response.status == consumer.CANCEL:
+ # Verification canceled
+ messages.add_message(
+ request,
+ messages.WARNING,
+ _('Verification cancelled'))
+
+ return False
+
+
+def _response_email(response):
+ """ Gets the email from the OpenID providers response"""
+ sreg_response = SRegResponse.fromSuccessResponse(response)
+ if sreg_response and 'email' in sreg_response:
+ return sreg_response.data['email']
+ return None
+
+
+def _response_nickname(response):
+ """ Gets the nickname from the OpenID providers response"""
+ sreg_response = SRegResponse.fromSuccessResponse(response)
+ if sreg_response and 'nickname' in sreg_response:
+ return sreg_response.data['nickname']
+ return None
+
+
+@auth_enabled
+def login(request):
+ """OpenID Login View"""
+ login_form = auth_forms.LoginForm(request.form)
+ allow_registration = mg_globals.app_config["allow_registration"]
+
+ # Can't store next in request.GET because of redirects to OpenID provider
+ # Store it in the session
+ next = request.GET.get('next')
+ request.session['next'] = next
+
+ login_failed = False
+
+ if request.method == 'POST' and login_form.validate():
+ return_to = request.urlgen(
+ 'mediagoblin.plugins.openid.finish_login')
+
+ success = _start_verification(request, login_form, return_to)
+
+ if success:
+ return success
+
+ login_failed = True
+
+ return render_to_response(
+ request,
+ 'mediagoblin/plugins/openid/login.html',
+ {'login_form': login_form,
+ 'next': request.session.get('next'),
+ 'login_failed': login_failed,
+ 'post_url': request.urlgen('mediagoblin.plugins.openid.login'),
+ 'allow_registration': allow_registration})
+
+
+@auth_enabled
+def finish_login(request):
+ """Complete OpenID Login Process"""
+ response = _finish_verification(request)
+
+ if not response:
+ # Verification failed, redirect to login page.
+ return redirect(request, 'mediagoblin.plugins.openid.login')
+
+ # Verification was successfull
+ query = OpenIDUserURL.query.filter_by(
+ openid_url=response.identity_url,
+ ).first()
+ user = query.user if query else None
+
+ if user:
+ # Set up login in session
+ request.session['user_id'] = unicode(user.id)
+ request.session.save()
+
+ if request.session.get('next'):
+ return redirect(request, location=request.session.pop('next'))
+ else:
+ return redirect(request, "index")
+ else:
+ # No user, need to register
+ if not mg_globals.app_config['allow_registration']:
+ messages.add_message(
+ request,
+ messages.WARNING,
+ _('Sorry, registration is disabled on this instance.'))
+ return redirect(request, 'index')
+
+ # Get email and nickname from response
+ email = _response_email(response)
+ username = _response_nickname(response)
+
+ register_form = auth_forms.RegistrationForm(request.form,
+ openid=response.identity_url,
+ email=email,
+ username=username)
+ return render_to_response(
+ request,
+ 'mediagoblin/auth/register.html',
+ {'register_form': register_form,
+ 'post_url': request.urlgen('mediagoblin.plugins.openid.register')})
+
+
+@allow_registration
+@auth_enabled
+def register(request):
+ """OpenID Registration View"""
+ if request.method == 'GET':
+ # Need to connect to openid provider before registering a user to
+ # get the users openid url. If method is 'GET', then this page was
+ # acessed without logging in first.
+ return redirect(request, 'mediagoblin.plugins.openid.login')
+
+ register_form = auth_forms.RegistrationForm(request.form)
+
+ if register_form.validate():
+ user = register_user(request, register_form)
+
+ if user:
+ # redirect the user to their homepage... there will be a
+ # message waiting for them to verify their email
+ return redirect(
+ request, 'mediagoblin.user_pages.user_home',
+ user=user.username)
+
+ return render_to_response(
+ request,
+ 'mediagoblin/auth/register.html',
+ {'register_form': register_form,
+ 'post_url': request.urlgen('mediagoblin.plugins.openid.register')})
+
+
+@require_active_login
+def start_edit(request):
+ """Starts the process of adding an openid url to a users account"""
+ form = auth_forms.LoginForm(request.form)
+
+ if request.method == 'POST' and form.validate():
+ query = OpenIDUserURL.query.filter_by(
+ openid_url=form.openid.data
+ ).first()
+ user = query.user if query else None
+
+ if not user:
+ return_to = request.urlgen('mediagoblin.plugins.openid.finish_edit')
+ success = _start_verification(request, form, return_to, False)
+
+ if success:
+ return success
+ else:
+ form.openid.errors.append(
+ _('Sorry, an account is already registered to that OpenID.'))
+
+ return render_to_response(
+ request,
+ 'mediagoblin/plugins/openid/add.html',
+ {'form': form,
+ 'post_url': request.urlgen('mediagoblin.plugins.openid.edit')})
+
+
+@require_active_login
+def finish_edit(request):
+ """Finishes the process of adding an openid url to a user"""
+ response = _finish_verification(request)
+
+ if not response:
+ # Verification failed, redirect to add openid page.
+ return redirect(request, 'mediagoblin.plugins.openid.edit')
+
+ # Verification was successfull
+ query = OpenIDUserURL.query.filter_by(
+ openid_url=response.identity_url,
+ ).first()
+ user_exists = query.user if query else None
+
+ if user_exists:
+ # user exists with that openid url, redirect back to edit page
+ messages.add_message(
+ request,
+ messages.WARNING,
+ _('Sorry, an account is already registered to that OpenID.'))
+ return redirect(request, 'mediagoblin.plugins.openid.edit')
+
+ else:
+ # Save openid to user
+ user = User.query.filter_by(
+ id=request.session['user_id']
+ ).first()
+
+ new_entry = OpenIDUserURL()
+ new_entry.openid_url = response.identity_url
+ new_entry.user_id = user.id
+ new_entry.save()
+
+ messages.add_message(
+ request,
+ messages.SUCCESS,
+ _('Your OpenID url was saved successfully.'))
+
+ return redirect(request, 'mediagoblin.edit.account')
+
+
+@require_active_login
+def delete_openid(request):
+ """View to remove an openid from a users account"""
+ form = auth_forms.LoginForm(request.form)
+
+ if request.method == 'POST' and form.validate():
+ # Check if a user has this openid
+ query = OpenIDUserURL.query.filter_by(
+ openid_url=form.openid.data
+ )
+ user = query.first().user if query.first() else None
+
+ if user and user.id == int(request.session['user_id']):
+ count = len(user.openid_urls)
+ if not count > 1 and not user.pw_hash:
+ # Make sure the user has a pw or another OpenID
+ messages.add_message(
+ request,
+ messages.WARNING,
+ _("You can't delete your only OpenID URL unless you"
+ " have a password set"))
+ elif user:
+ # There is a user, but not the same user who is logged in
+ form.openid.errors.append(
+ _('That OpenID is not registered to this account.'))
+
+ if not form.errors and not request.session.get('messages'):
+ # Okay to continue with deleting openid
+ return_to = request.urlgen(
+ 'mediagoblin.plugins.openid.finish_delete')
+ success = _start_verification(request, form, return_to, False)
+
+ if success:
+ return success
+
+ return render_to_response(
+ request,
+ 'mediagoblin/plugins/openid/delete.html',
+ {'form': form,
+ 'post_url': request.urlgen('mediagoblin.plugins.openid.delete')})
+
+
+@require_active_login
+def finish_delete(request):
+ """Finishes the deletion of an OpenID from an user's account"""
+ response = _finish_verification(request)
+
+ if not response:
+ # Verification failed, redirect to delete openid page.
+ return redirect(request, 'mediagoblin.plugins.openid.delete')
+
+ query = OpenIDUserURL.query.filter_by(
+ openid_url=response.identity_url
+ )
+ user = query.first().user if query.first() else None
+
+ # Need to check this again because of generic openid urls such as google's
+ if user and user.id == int(request.session['user_id']):
+ count = len(user.openid_urls)
+ if count > 1 or user.pw_hash:
+ # User has more then one openid or also has a password.
+ query.first().delete()
+
+ messages.add_message(
+ request,
+ messages.SUCCESS,
+ _('OpenID was successfully removed.'))
+
+ return redirect(request, 'mediagoblin.edit.account')
+
+ elif not count > 1:
+ messages.add_message(
+ request,
+ messages.WARNING,
+ _("You can't delete your only OpenID URL unless you have a "
+ "password set"))
+
+ return redirect(request, 'mediagoblin.plugins.openid.delete')
+
+ else:
+ messages.add_message(
+ request,
+ messages.WARNING,
+ _('That OpenID is not registered to this account.'))
+
+ return redirect(request, 'mediagoblin.plugins.openid.delete')
diff --git a/mediagoblin/plugins/persona/README.rst b/mediagoblin/plugins/persona/README.rst
new file mode 100644
index 00000000..ef19ac5d
--- /dev/null
+++ b/mediagoblin/plugins/persona/README.rst
@@ -0,0 +1,41 @@
+.. _persona-chapter:
+
+================
+ persona plugin
+================
+
+The persona plugin allows users to login to you GNU MediaGoblin instance using
+`Mozilla Persona`_.
+
+This plugin can be enabled alongside :ref:`openid-chapter` and
+:ref:`basic_auth-chapter`.
+
+.. note::
+ When :ref:`basic_auth-chapter` is enabled alongside this persona plugin, and
+ a user creates an account using their persona. If they would like to add a
+ password to their account, they can use the forgot password feature to do
+ so.
+
+.. _Mozilla Persona: https://www.mozilla.org/en-US/persona/
+
+Set up the persona plugin
+=========================
+
+1. Install the ``requests`` package.
+
+2. Add the following to your MediaGoblin .ini file in the ``[plugins]`` section::
+
+ [[mediagoblin.plugins.persona]]
+
+3. Run::
+
+ gmg dbupdate
+
+ in order to create and apply migrations to any database tables that the
+ plugin requires.
+
+4. Run::
+
+ gmg assetlink
+
+ in order to persona's static assets.
diff --git a/mediagoblin/plugins/persona/__init__.py b/mediagoblin/plugins/persona/__init__.py
new file mode 100644
index 00000000..700c18e2
--- /dev/null
+++ b/mediagoblin/plugins/persona/__init__.py
@@ -0,0 +1,116 @@
+# 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/>.
+from pkg_resources import resource_filename
+import os
+
+from sqlalchemy import or_
+
+from mediagoblin.auth.tools import create_basic_user
+from mediagoblin.db.models import User
+from mediagoblin.plugins.persona.models import PersonaUserEmails
+from mediagoblin.tools import pluginapi
+from mediagoblin.tools.staticdirect import PluginStatic
+from mediagoblin.tools.translate import pass_to_ugettext as _
+
+PLUGIN_DIR = os.path.dirname(__file__)
+
+
+def setup_plugin():
+ config = pluginapi.get_config('mediagoblin.plugins.persona')
+
+ routes = [
+ ('mediagoblin.plugins.persona.login',
+ '/auth/persona/login/',
+ 'mediagoblin.plugins.persona.views:login'),
+ ('mediagoblin.plugins.persona.register',
+ '/auth/persona/register/',
+ 'mediagoblin.plugins.persona.views:register'),
+ ('mediagoblin.plugins.persona.edit',
+ '/edit/persona/',
+ 'mediagoblin.plugins.persona.views:edit'),
+ ('mediagoblin.plugins.persona.add',
+ '/edit/persona/add/',
+ 'mediagoblin.plugins.persona.views:add')]
+
+ pluginapi.register_routes(routes)
+ pluginapi.register_template_path(os.path.join(PLUGIN_DIR, 'templates'))
+ pluginapi.register_template_hooks(
+ {'persona_end': 'mediagoblin/plugins/persona/persona_js_end.html',
+ 'persona_form': 'mediagoblin/plugins/persona/persona.html',
+ 'edit_link': 'mediagoblin/plugins/persona/edit_link.html',
+ 'login_link': 'mediagoblin/plugins/persona/login_link.html',
+ 'register_link': 'mediagoblin/plugins/persona/register_link.html'})
+
+
+def create_user(register_form):
+ if 'persona_email' in register_form:
+ username = register_form.username.data
+ user = User.query.filter(
+ or_(
+ User.username == username,
+ User.email == username,
+ )).first()
+
+ if not user:
+ user = create_basic_user(register_form)
+
+ new_entry = PersonaUserEmails()
+ new_entry.persona_email = register_form.persona_email.data
+ new_entry.user_id = user.id
+ new_entry.save()
+
+ return user
+
+
+def extra_validation(register_form):
+ persona_email = register_form.persona_email.data if 'persona_email' in \
+ register_form else None
+ if persona_email:
+ persona_email_exists = PersonaUserEmails.query.filter_by(
+ persona_email=persona_email
+ ).count()
+
+ extra_validation_passes = True
+
+ if persona_email_exists:
+ register_form.persona_email.errors.append(
+ _('Sorry, an account is already registered to that Persona'
+ ' email.'))
+ extra_validation_passes = False
+
+ return extra_validation_passes
+
+
+def Auth():
+ return True
+
+
+def add_to_global_context(context):
+ if len(pluginapi.hook_runall('authentication')) == 1:
+ context['persona_auth'] = True
+ context['persona'] = True
+ return context
+
+hooks = {
+ 'setup': setup_plugin,
+ 'authentication': Auth,
+ 'auth_extra_validation': extra_validation,
+ 'auth_create_user': create_user,
+ 'template_global_context': add_to_global_context,
+ 'static_setup': lambda: PluginStatic(
+ 'coreplugin_persona',
+ resource_filename('mediagoblin.plugins.persona', 'static'))
+}
diff --git a/mediagoblin/plugins/persona/forms.py b/mediagoblin/plugins/persona/forms.py
new file mode 100644
index 00000000..608be0c7
--- /dev/null
+++ b/mediagoblin/plugins/persona/forms.py
@@ -0,0 +1,41 @@
+# 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 wtforms
+
+from mediagoblin.tools.translate import lazy_pass_to_ugettext as _
+from mediagoblin.auth.tools import normalize_user_or_email_field
+
+
+class RegistrationForm(wtforms.Form):
+ username = wtforms.TextField(
+ _('Username'),
+ [wtforms.validators.Required(),
+ normalize_user_or_email_field(allow_email=False)])
+ email = wtforms.TextField(
+ _('Email address'),
+ [wtforms.validators.Required(),
+ normalize_user_or_email_field(allow_user=False)])
+ persona_email = wtforms.HiddenField(
+ '',
+ [wtforms.validators.Required(),
+ normalize_user_or_email_field(allow_user=False)])
+
+
+class EditForm(wtforms.Form):
+ email = wtforms.TextField(
+ _('Email address'),
+ [wtforms.validators.Required(),
+ normalize_user_or_email_field(allow_user=False)])
diff --git a/mediagoblin/plugins/persona/models.py b/mediagoblin/plugins/persona/models.py
new file mode 100644
index 00000000..ff3c525a
--- /dev/null
+++ b/mediagoblin/plugins/persona/models.py
@@ -0,0 +1,36 @@
+# 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/>.
+from sqlalchemy import Column, Integer, Unicode, ForeignKey
+from sqlalchemy.orm import relationship, backref
+
+from mediagoblin.db.models import User
+from mediagoblin.db.base import Base
+
+
+class PersonaUserEmails(Base):
+ __tablename__ = "persona__user_emails"
+
+ id = Column(Integer, primary_key=True)
+ persona_email = Column(Unicode, nullable=False)
+ user_id = Column(Integer, ForeignKey(User.id), nullable=False)
+
+ # Persona's are owned by their user, so do the full thing.
+ user = relationship(User, backref=backref('persona_emails',
+ cascade='all, delete-orphan'))
+
+MODELS = [
+ PersonaUserEmails
+]
diff --git a/mediagoblin/plugins/persona/static/js/persona.js b/mediagoblin/plugins/persona/static/js/persona.js
new file mode 100644
index 00000000..76a7757a
--- /dev/null
+++ b/mediagoblin/plugins/persona/static/js/persona.js
@@ -0,0 +1,59 @@
+/**
+ * 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/>.
+ */
+
+$(document).ready(function () {
+ var requestParams = {
+ backgroundColor: "#171717",
+ siteName: "GNU MediaGoblin",
+ siteLogo: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAA0IklEQVR4XuSYS2gUSRyHq6ofk8kDZXycRTwEcfGgboIgBOMTFoxZ8LYXwcWDd/HoRUFPHvbg47gXQeMugqC7iiIeoht0IeDFg+ID8RBNYpKZ6e4qPyYVu5meBhkmSU9S8PHvamro6v76V93TUuSkHdz3q7z7701Tt6+b0gnr4SfYBptgM6yDEvSADwIq8BUmLK/gDbyE/2AKZjjOdNaxl5tlFXJgcFhJKR1EBAkJ/ZRdlu2wFdwWedcwDi9gDEYRMZoQ41Ei9ulVJWT/3qNSKeUuiEDCDspJOAxroQuSzTQ/5+zfJtL0yBhz4d79kXF7o/iUgL5ZNQlBQokyBOdhIwgIQFmWYm4aInBBwns4i5wbyPi8YhNCAhzSENntn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FWCu9/S/MSDzJVUJTVH/bwBvBW4A7PPEFtPEwJ8B39Ra3xOrpGmAU6il/38Bkq5IwFFKmTiWCZqqKJdblnUFsAHYBCxKRitQBHJNwWcI1IASUAaOA8PAXuAZrfWLMQD7m+ImN3kOSCQR9v8H5P8FdKdwLi9BNikAAAAASUVORK5CYII="
+ };
+
+ var signinLink = document.getElementById('persona_login');
+ if (signinLink) {
+ signinLink.onclick = function() { navigator.id.request(requestParams); };
+ }
+
+ var signinLink1 = document.getElementById('persona_login1');
+ if (signinLink1) {
+ signinLink1.onclick = function() { navigator.id.request(requestParams); };
+ }
+
+ var signoutLink = document.getElementById('logout');
+ if (signoutLink) {
+ signoutLink.onclick = function() { navigator.id.logout(); };
+ }
+
+ var logout_url = document.getElementById('_logout_url').value;
+ var persona_user = document.getElementById('_persona_user').value;
+
+ navigator.id.watch({
+ loggedInUser: persona_user || null,
+ onlogin: function(assertion) {
+ document.getElementById('_assertion').value = assertion;
+ document.getElementById('_persona_login').submit();
+ },
+ onlogout: function() {
+ $.ajax({
+ type: 'GET',
+ url: logout_url,
+ success: function(res, status, xhr) { window.location.reload(); },
+ error: function(xhr, status, err) { alert("Logout failure: " + err); }
+ });
+ }
+ });
+});
diff --git a/mediagoblin/plugins/persona/templates/mediagoblin/plugins/persona/edit.html b/mediagoblin/plugins/persona/templates/mediagoblin/plugins/persona/edit.html
new file mode 100644
index 00000000..be62b8cc
--- /dev/null
+++ b/mediagoblin/plugins/persona/templates/mediagoblin/plugins/persona/edit.html
@@ -0,0 +1,43 @@
+{#
+# 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/>.
+#}
+{% extends "mediagoblin/base.html" %}
+
+{% import "/mediagoblin/utils/wtforms.html" as wtforms_util %}
+
+{% block title -%}
+ {% trans %}Add an OpenID{% endtrans %} &mdash; {{ super() }}
+{%- endblock %}
+
+{% block mediagoblin_content %}
+ <form action="{{ request.urlgen('mediagoblin.plugins.persona.edit') }}"
+ method="POST" enctype="multipart/form-data">
+ {{ csrf_token }}
+ <div class="form_box">
+ <h1>{% trans %}Delete a Persona email address{% endtrans %}</h1>
+ <p>
+ <a href="javascript:;" id="persona_login">
+ {% trans %}Add a Persona email address{% endtrans %}
+ </a>
+ </p>
+ {{ wtforms_util.render_divs(form, True) }}
+ <div class="form_submit_buttons">
+ <input type="submit" value="{% trans %}Delete{% endtrans %}" class="button_form"/>
+ </div>
+ </div>
+ </form>
+{% endblock %}
diff --git a/mediagoblin/plugins/persona/templates/mediagoblin/plugins/persona/edit_link.html b/mediagoblin/plugins/persona/templates/mediagoblin/plugins/persona/edit_link.html
new file mode 100644
index 00000000..a022c62a
--- /dev/null
+++ b/mediagoblin/plugins/persona/templates/mediagoblin/plugins/persona/edit_link.html
@@ -0,0 +1,24 @@
+{#
+# 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/>.
+#}
+
+{% block persona_edit_link %}
+ <a href="{{ request.urlgen('mediagoblin.plugins.persona.edit') }}">
+ {% trans %}Persona's{% endtrans %}
+ </a>
+ &middot;
+{% endblock %}
diff --git a/mediagoblin/plugins/persona/templates/mediagoblin/plugins/persona/login_link.html b/mediagoblin/plugins/persona/templates/mediagoblin/plugins/persona/login_link.html
new file mode 100644
index 00000000..975683da
--- /dev/null
+++ b/mediagoblin/plugins/persona/templates/mediagoblin/plugins/persona/login_link.html
@@ -0,0 +1,25 @@
+{#
+# 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/>.
+#}
+
+{% block person_login_link %}
+ <p>
+ <a href="javascript:;" id="persona_login">
+ {% trans %}Or login with Persona!{% endtrans %}
+ </a>
+ </p>
+{% endblock %}
diff --git a/mediagoblin/plugins/persona/templates/mediagoblin/plugins/persona/persona.html b/mediagoblin/plugins/persona/templates/mediagoblin/plugins/persona/persona.html
new file mode 100644
index 00000000..03d63aae
--- /dev/null
+++ b/mediagoblin/plugins/persona/templates/mediagoblin/plugins/persona/persona.html
@@ -0,0 +1,38 @@
+{#
+# 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/>.
+#}
+{% block persona %}
+ <form id="_persona_login"
+ action=
+ {%- if edit_persona is defined -%}
+ "{{ request.urlgen('mediagoblin.plugins.persona.add') }}"
+ {%- else -%}
+ "{{ request.urlgen('mediagoblin.plugins.persona.login') }}"
+ {%- endif %}
+ method="POST">
+ {{ csrf_token }}
+ <input type="hidden" name="assertion" type="text" id="_assertion"/>
+ <input type="hidden" name="_logout_url" type="text" id="_logout_url"
+ value="{{ request.urlgen('mediagoblin.auth.logout') }}"/>
+ <input type="hidden" type="text" id="_persona_user"
+ {% if request.session.get('persona_login_email', False) %}
+ value="{{ request.session['persona_login_email'] }}"/>
+ {% else %}
+ value=""/>
+ {% endif %}
+ </form>
+{% endblock %}
diff --git a/mediagoblin/plugins/persona/templates/mediagoblin/plugins/persona/persona_js_end.html b/mediagoblin/plugins/persona/templates/mediagoblin/plugins/persona/persona_js_end.html
new file mode 100644
index 00000000..8c0d72d5
--- /dev/null
+++ b/mediagoblin/plugins/persona/templates/mediagoblin/plugins/persona/persona_js_end.html
@@ -0,0 +1,21 @@
+{#
+# 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/>.
+#}
+
+<script src="https://login.persona.org/include.js"></script>
+<script type="text/javascript"
+ src="{{ request.staticdirect('/js/persona.js', 'coreplugin_persona') }}"></script>
diff --git a/mediagoblin/plugins/persona/templates/mediagoblin/plugins/persona/register_link.html b/mediagoblin/plugins/persona/templates/mediagoblin/plugins/persona/register_link.html
new file mode 100644
index 00000000..bcd9ae2b
--- /dev/null
+++ b/mediagoblin/plugins/persona/templates/mediagoblin/plugins/persona/register_link.html
@@ -0,0 +1,25 @@
+{#
+# 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/>.
+#}
+
+{% block persona_register_link %}
+ <p>
+ <a href="javascript:;" id="persona_login">
+ {% trans %}Or register with Persona!{% endtrans %}
+ </a>
+ </p>
+{% endblock %}
diff --git a/mediagoblin/plugins/persona/views.py b/mediagoblin/plugins/persona/views.py
new file mode 100644
index 00000000..1bba3b8c
--- /dev/null
+++ b/mediagoblin/plugins/persona/views.py
@@ -0,0 +1,194 @@
+# 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 json
+import logging
+import requests
+
+from werkzeug.exceptions import BadRequest
+
+from mediagoblin import messages, mg_globals
+from mediagoblin.auth.tools import register_user
+from mediagoblin.decorators import (auth_enabled, allow_registration,
+ require_active_login)
+from mediagoblin.tools.response import render_to_response, redirect
+from mediagoblin.tools.translate import pass_to_ugettext as _
+from mediagoblin.plugins.persona import forms
+from mediagoblin.plugins.persona.models import PersonaUserEmails
+
+_log = logging.getLogger(__name__)
+
+
+def _get_response(request):
+ if 'assertion' not in request.form:
+ _log.debug('assertion not in request.form')
+ raise BadRequest()
+
+ data = {'assertion': request.form['assertion'],
+ 'audience': request.urlgen('index', qualified=True)}
+ resp = requests.post('https://verifier.login.persona.org/verify',
+ data=data, verify=True)
+
+ if resp.ok:
+ verification_data = json.loads(resp.content)
+
+ if verification_data['status'] == 'okay':
+ return verification_data['email']
+
+ return None
+
+
+@auth_enabled
+def login(request):
+ if request.method == 'GET':
+ return redirect(request, 'mediagoblin.auth.login')
+
+ email = _get_response(request)
+ if email:
+ query = PersonaUserEmails.query.filter_by(
+ persona_email=email
+ ).first()
+ user = query.user if query else None
+
+ if user:
+ request.session['user_id'] = unicode(user.id)
+ request.session['persona_login_email'] = email
+ request.session.save()
+
+ return redirect(request, "index")
+
+ else:
+ if not mg_globals.app.auth:
+ messages.add_message(
+ request,
+ messages.WARNING,
+ _('Sorry, authentication is disabled on this instance.'))
+
+ return redirect(request, 'index')
+
+ register_form = forms.RegistrationForm(email=email,
+ persona_email=email)
+ return render_to_response(
+ request,
+ 'mediagoblin/auth/register.html',
+ {'register_form': register_form,
+ 'post_url': request.urlgen(
+ 'mediagoblin.plugins.persona.register')})
+
+ return redirect(request, 'mediagoblin.auth.login')
+
+
+@allow_registration
+@auth_enabled
+def register(request):
+ if request.method == 'GET':
+ # Need to connect to persona before registering a user. If method is
+ # 'GET', then this page was acessed without logging in first.
+ return redirect(request, 'mediagoblin.auth.login')
+ register_form = forms.RegistrationForm(request.form)
+
+ if register_form.validate():
+ user = register_user(request, register_form)
+
+ if user:
+ # redirect the user to their homepage... there will be a
+ # message waiting for them to verify their email
+ return redirect(
+ request, 'mediagoblin.user_pages.user_home',
+ user=user.username)
+
+ return render_to_response(
+ request,
+ 'mediagoblin/auth/register.html',
+ {'register_form': register_form,
+ 'post_url': request.urlgen('mediagoblin.plugins.persona.register')})
+
+
+@require_active_login
+def edit(request):
+ form = forms.EditForm(request.form)
+
+ if request.method == 'POST' and form.validate():
+ query = PersonaUserEmails.query.filter_by(
+ persona_email=form.email.data)
+ user = query.first().user if query.first() else None
+
+ if user and user.id == int(request.user.id):
+ count = len(user.persona_emails)
+
+ if count > 1 or user.pw_hash:
+ # User has more then one Persona email or also has a password.
+ query.first().delete()
+
+ messages.add_message(
+ request,
+ messages.SUCCESS,
+ _('The Persona email address was successfully removed.'))
+
+ return redirect(request, 'mediagoblin.edit.account')
+
+ elif not count > 1:
+ form.email.errors.append(
+ _("You can't delete your only Persona email address unless"
+ " you have a password set."))
+
+ else:
+ form.email.errors.append(
+ _('That Persona email address is not registered to this'
+ ' account.'))
+
+ return render_to_response(
+ request,
+ 'mediagoblin/plugins/persona/edit.html',
+ {'form': form,
+ 'edit_persona': True})
+
+
+@require_active_login
+def add(request):
+ if request.method == 'GET':
+ return redirect(request, 'mediagoblin.plugins.persona.edit')
+
+ email = _get_response(request)
+
+ if email:
+ query = PersonaUserEmails.query.filter_by(
+ persona_email=email
+ ).first()
+ user_exists = query.user if query else None
+
+ if user_exists:
+ messages.add_message(
+ request,
+ messages.WARNING,
+ _('Sorry, an account is already registered with that Persona'
+ ' email address.'))
+ return redirect(request, 'mediagoblin.plugins.persona.edit')
+
+ else:
+ # Save the Persona Email to the user
+ new_entry = PersonaUserEmails()
+ new_entry.persona_email = email
+ new_entry.user_id = request.user.id
+ new_entry.save()
+
+ request.session['persona_login_email'] = email
+
+ messages.add_message(
+ request,
+ messages.SUCCESS,
+ _('Your Persona email address was saved successfully.'))
+
+ return redirect(request, 'mediagoblin.edit.account')
diff --git a/mediagoblin/plugins/piwigo/__init__.py b/mediagoblin/plugins/piwigo/__init__.py
index 73326e9e..c4da708a 100644
--- a/mediagoblin/plugins/piwigo/__init__.py
+++ b/mediagoblin/plugins/piwigo/__init__.py
@@ -17,6 +17,8 @@
import logging
from mediagoblin.tools import pluginapi
+from mediagoblin.tools.session import SessionManager
+from .tools import PWGSession
_log = logging.getLogger(__name__)
@@ -32,6 +34,9 @@ def setup_plugin():
pluginapi.register_routes(routes)
+ PWGSession.session_manager = SessionManager("pwg_id", "plugins.piwigo")
+
+
hooks = {
'setup': setup_plugin
}
diff --git a/mediagoblin/plugins/piwigo/forms.py b/mediagoblin/plugins/piwigo/forms.py
index 5bb12e62..fb04aa6a 100644
--- a/mediagoblin/plugins/piwigo/forms.py
+++ b/mediagoblin/plugins/piwigo/forms.py
@@ -26,3 +26,19 @@ class AddSimpleForm(wtforms.Form):
# tags = wtforms.FieldList(wtforms.TextField())
category = wtforms.IntegerField()
level = wtforms.IntegerField()
+
+
+_md5_validator = wtforms.validators.Regexp(r"^[0-9a-fA-F]{32}$")
+
+
+class AddForm(wtforms.Form):
+ original_sum = wtforms.TextField(None,
+ [_md5_validator,
+ wtforms.validators.Required()])
+ thumbnail_sum = wtforms.TextField(None,
+ [wtforms.validators.Optional(),
+ _md5_validator])
+ file_sum = wtforms.TextField(None, [_md5_validator])
+ name = wtforms.TextField()
+ date_creation = wtforms.TextField()
+ categories = wtforms.TextField()
diff --git a/mediagoblin/plugins/piwigo/tools.py b/mediagoblin/plugins/piwigo/tools.py
index 4d2e985a..484ea531 100644
--- a/mediagoblin/plugins/piwigo/tools.py
+++ b/mediagoblin/plugins/piwigo/tools.py
@@ -14,18 +14,23 @@
# 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/>.
+from collections import namedtuple
import logging
import six
import lxml.etree as ET
-from werkzeug.exceptions import MethodNotAllowed
+from werkzeug.exceptions import MethodNotAllowed, BadRequest
+from mediagoblin.tools.request import setup_user_in_request
from mediagoblin.tools.response import Response
_log = logging.getLogger(__name__)
+PwgError = namedtuple("PwgError", ["code", "msg"])
+
+
class PwgNamedArray(list):
def __init__(self, l, item_name, as_attrib=()):
self.item_name = item_name
@@ -73,9 +78,18 @@ def _fill_element(el, data):
def response_xml(result):
r = ET.Element("rsp")
r.set("stat", "ok")
- _fill_element(r, result)
+ status = None
+ if isinstance(result, PwgError):
+ r.set("stat", "fail")
+ err = ET.SubElement(r, "err")
+ err.set("code", str(result.code))
+ err.set("msg", result.msg)
+ if result.code >= 100 and result.code < 600:
+ status = result.code
+ else:
+ _fill_element(r, result)
return Response(ET.tostring(r, encoding="utf-8", xml_declaration=True),
- mimetype='text/xml')
+ mimetype='text/xml', status=status)
class CmdTable(object):
@@ -106,3 +120,46 @@ class CmdTable(object):
_log.warn("Method %s only allowed for POST", cmd_name)
raise MethodNotAllowed()
return func
+
+
+def check_form(form):
+ if not form.validate():
+ _log.error("form validation failed for form %r", form)
+ for f in form:
+ if len(f.errors):
+ _log.error("Errors for %s: %r", f.name, f.errors)
+ raise BadRequest()
+ dump = []
+ for f in form:
+ dump.append("%s=%r" % (f.name, f.data))
+ _log.debug("form: %s", " ".join(dump))
+
+
+class PWGSession(object):
+ session_manager = None
+
+ def __init__(self, request):
+ self.request = request
+ self.in_pwg_session = False
+
+ def __enter__(self):
+ # Backup old state
+ self.old_session = self.request.session
+ self.old_user = self.request.user
+ # Load piwigo session into state
+ self.request.session = self.session_manager.load_session_from_cookie(
+ self.request)
+ setup_user_in_request(self.request)
+ self.in_pwg_session = True
+ return self
+
+ def __exit__(self, *args):
+ # Restore state
+ self.request.session = self.old_session
+ self.request.user = self.old_user
+ self.in_pwg_session = False
+
+ def save_to_cookie(self, response):
+ assert self.in_pwg_session
+ self.session_manager.save_session_to_cookie(self.request.session,
+ self.request, response)
diff --git a/mediagoblin/plugins/piwigo/views.py b/mediagoblin/plugins/piwigo/views.py
index bd3f9320..f913a730 100644
--- a/mediagoblin/plugins/piwigo/views.py
+++ b/mediagoblin/plugins/piwigo/views.py
@@ -20,11 +20,20 @@ import re
from werkzeug.exceptions import MethodNotAllowed, BadRequest, NotImplemented
from werkzeug.wrappers import BaseResponse
-from mediagoblin import mg_globals
+from mediagoblin.tools.translate import pass_to_ugettext as _
from mediagoblin.meddleware.csrf import csrf_exempt
-from mediagoblin.submit.lib import check_file_field
-from .tools import CmdTable, PwgNamedArray, response_xml
-from .forms import AddSimpleForm
+from mediagoblin.auth.tools import check_login_simple
+from mediagoblin.submit.lib import \
+ submit_media, check_file_field, get_upload_file_limits, \
+ FileUploadLimit, UserUploadLimit, UserPastUploadLimit
+
+
+from mediagoblin.user_pages.lib import add_media_to_collection
+from mediagoblin.db.models import Collection
+
+from .tools import CmdTable, response_xml, check_form, \
+ PWGSession, PwgNamedArray, PwgError
+from .forms import AddSimpleForm, AddForm
_log = logging.getLogger(__name__)
@@ -34,13 +43,18 @@ _log = logging.getLogger(__name__)
def pwg_login(request):
username = request.form.get("username")
password = request.form.get("password")
- _log.info("Login for %r/%r...", username, password)
+ user = check_login_simple(username, password)
+ if not user:
+ return PwgError(999, 'Invalid username/password')
+ request.session["user_id"] = user.id
+ request.session.save()
return True
@CmdTable("pwg.session.logout")
def pwg_logout(request):
_log.info("Logout")
+ request.session.delete()
return True
@@ -51,14 +65,30 @@ def pwg_getversion(request):
@CmdTable("pwg.session.getStatus")
def pwg_session_getStatus(request):
- return {'username': "fake_user"}
+ if request.user:
+ username = request.user.username
+ else:
+ username = "guest"
+ return {'username': username}
@CmdTable("pwg.categories.getList")
def pwg_categories_getList(request):
- catlist = ({'id': -29711,
+ catlist = [{'id': -29711,
'uppercats': "-29711",
- 'name': "All my images"},)
+ 'name': "All my images"}]
+
+ if request.user:
+ collections = Collection.query.filter_by(
+ get_creator=request.user).order_by(Collection.title)
+
+ for c in collections:
+ catlist.append({'id': c.id,
+ 'uppercats': str(c.id),
+ 'name': c.title,
+ 'comment': c.description
+ })
+
return {
'categories': PwgNamedArray(
catlist,
@@ -90,16 +120,51 @@ def pwg_images_addSimple(request):
dump = []
for f in form:
dump.append("%s=%r" % (f.name, f.data))
- _log.info("addimple: %r %s %r", request.form, " ".join(dump), request.files)
+ _log.info("addSimple: %r %s %r", request.form, " ".join(dump),
+ request.files)
if not check_file_field(request, 'image'):
raise BadRequest()
- return {'image_id': 123456, 'url': ''}
+ upload_limit, max_file_size = get_upload_file_limits(request.user)
+
+ try:
+ entry = submit_media(
+ mg_app=request.app, user=request.user,
+ submitted_file=request.files['image'],
+ filename=request.files['image'].filename,
+ title=unicode(form.name.data),
+ description=unicode(form.comment.data),
+ upload_limit=upload_limit, max_file_size=max_file_size)
+
+ collection_id = form.category.data
+ if collection_id > 0:
+ collection = Collection.query.get(collection_id)
+ if collection is not None and collection.creator == request.user.id:
+ add_media_to_collection(collection, entry, "")
+
+ return {
+ 'image_id': entry.id,
+ 'url': entry.url_for_self(
+ request.urlgen,
+ qualified=True)}
+
+ # Handle upload limit issues
+ except FileUploadLimit:
+ raise BadRequest(
+ _(u'Sorry, the file size is too big.'))
+ except UserUploadLimit:
+ raise BadRequest(
+ _('Sorry, uploading this file will put you over your'
+ ' upload limit.'))
+ except UserPastUploadLimit:
+ raise BadRequest(
+ _('Sorry, you have reached your upload limit.'))
+
-
md5sum_matcher = re.compile(r"^[0-9a-fA-F]{32}$")
+
def fetch_md5(request, parm_name, optional_parm=False):
val = request.form.get(parm_name)
if (val is None) and (not optional_parm):
@@ -133,17 +198,13 @@ def pwg_images_addChunk(request):
return True
-def possibly_add_cookie(request, response):
- # TODO: We should only add a *real* cookie, if
- # authenticated. And if there is no cookie already.
- if True:
- response.set_cookie(
- 'pwg_id',
- "some_fake_for_now",
- path=request.environ['SCRIPT_NAME'],
- domain=mg_globals.app_config.get('csrf_cookie_domain'),
- secure=(request.scheme.lower() == 'https'),
- httponly=True)
+@CmdTable("pwg.images.add", True)
+def pwg_images_add(request):
+ _log.info("add: %r", request.form)
+ form = AddForm(request.form)
+ check_form(form)
+
+ return {'image_id': 123456, 'url': ''}
@csrf_exempt
@@ -158,13 +219,13 @@ def ws_php(request):
request.args, request.form)
raise NotImplemented()
- result = func(request)
-
- if isinstance(result, BaseResponse):
- return result
+ with PWGSession(request) as session:
+ result = func(request)
- response = response_xml(result)
+ if isinstance(result, BaseResponse):
+ return result
- possibly_add_cookie(request, response)
+ response = response_xml(result)
+ session.save_to_cookie(response)
- return response
+ return response