Skip to content
This repository has been archived by the owner on Jul 11, 2019. It is now read-only.

Allows the user to login only via email without reseting the password #426

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/adhocracy/config/routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ def make_map(config):
action='dashboard_pages')
map.connect('/welcome/{id}/{token}', controller='user',
action='welcome')
map.connect('/emaillogin/{id}/{token}', controller='user',
action='emaillogin')
map.resource('user', 'user', member={'votes': 'GET',
'delegations': 'GET',
'votes': 'GET',
Expand Down
30 changes: 29 additions & 1 deletion src/adhocracy/controllers/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from pylons.decorators import validate
from pylons.i18n import _
from babel import Locale

from adhocracy.lib.session.session import get_secret
from webob.exc import HTTPFound

from repoze.who.api import get_api
Expand All @@ -23,6 +23,7 @@
from adhocracy.lib.auth.csrf import RequireInternalRequest, token_id
from adhocracy.lib.auth.welcome import (welcome_enabled, can_welcome,
welcome_url)
from adhocracy.lib.auth.emaillogin import (create_token, email_url)
from adhocracy.lib.base import BaseController
from adhocracy.lib.instance import RequireInstance
import adhocracy.lib.mail as libmail
Expand Down Expand Up @@ -562,6 +563,33 @@ def nopassword(self):
_("Sorry, registration has been disabled by administrator."),
category='error', code=403)

@RequireInternalRequest(methods=['POST'])
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of abandoning the nopassword target, it should simply call here if required.

@validate(schema=NoPasswordForm(), post_only=True)
def perform_email_login(self):
assert config.get('adhocracy.login_style') == 'alternate'
if config.get('adhocracy.login_style') == 'alternate' and self.form_result.get('have_password') == 'false':
user = model.User.find_by_email(self.form_result.get('login'))
if user:
login_code = create_token(user.email, config)
url = email_url(user, login_code)
body = (
_("you have requested to authenticate you as a user via email address."
"to proceed, please open the "
"link below in your browser:") +
"\n\n " + url + "\n")
libmail.to_user(user,
_("Login for %s") % h.site.name(),
body)
return render("/user/login_email.html")
return self.nopassword()

def emaillogin(self, id, token):
# Intercepted by EmailLoginRepozeWho, only errors go in here
h.flash(_('The login request was not valid, please try again'),
'error')
return redirect(h.base_url('/login'))


def dashboard(self, id):
'''Render a personalized dashboard for users'''

Expand Down
5 changes: 3 additions & 2 deletions src/adhocracy/lib/auth/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

import adhocracy.model as model
from . import welcome
from . import emaillogin
from authorization import InstanceGroupSourceAdapter
from instance_auth_tkt import InstanceAuthTktCookiePlugin

Expand Down Expand Up @@ -92,7 +93,7 @@ def identify(self, environ):
request = Request(environ, charset=self.charset)
form = dict(request.POST)
if form.get('have_password') == 'false':
environ['PATH_INFO'] = '/user/nopassword'
environ['PATH_INFO'] = '/user/perform_email_login'
login = form.get('login')
environ['_adhocracy_nopassword_user'] = self._get_user(login)
return None
Expand Down Expand Up @@ -150,7 +151,7 @@ def setup_auth(app, config):
mdproviders = [('sql_user_md', sql_user_md)]

welcome.setup_auth(config, identifiers, authenticators)

emaillogin.setup_auth(config, identifiers, authenticators)
log_stream = None
#log_stream = sys.stdout

Expand Down
97 changes: 97 additions & 0 deletions src/adhocracy/lib/auth/emaillogin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
""" Logs in user via email """

import re
import adhocracy.model as model
from adhocracy.lib.auth.authorization import has
from paste.deploy.converters import asbool
import pylons
from repoze.who.interfaces import IAuthenticator, IIdentifier
from webob.exc import HTTPFound
from zope.interface import implements
import time
import hashlib
import base64
from adhocracy.lib.session.session import get_secret


def email_url(user, code):
from adhocracy.lib.helpers import base_url
return base_url("/emaillogin/%s/%s" % (user.user_name, code),
absolute=True)


def create_token(email, config):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should definitely use the new crypto functions.

secret = get_secret(config)
timestamp = str(int(time.time()))
message = timestamp + "_" + create_hash(email, timestamp, config)
return base64.urlsafe_b64encode(message.encode("utf-8"))


def create_hash(email, time, config):
secret = get_secret(config)
value = secret + email + time
return hashlib.sha256(value).hexdigest()


def validate_token(user_token, email, config):
try:
decoded = base64.urlsafe_b64decode(user_token)
user_time = decoded.split('_')[0]
user_hash = decoded.split('_')[1]
time_dif = int(time.time()) - int(user_time)
except (TypeError, ValueError):
return False
correct_value = create_hash(email, user_time, config)
if (user_hash == correct_value) and (time_dif < 3600):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of 3600, we should use a configuration option here, and default it to 3600.

return True
return False


class EmailLoginRepozeWho(object):
implements(IAuthenticator, IIdentifier)

def __init__(self, config, rememberer_name, prefix='/emaillogin/'):
self.config = config
self.rememberer_name = rememberer_name
self.url_rex = re.compile(r'^' + re.escape(prefix) +
r'(?P<id>[^/]+)/(?P<code>[^/]+)$')

def identify(self, environ):
path_info = environ['PATH_INFO']
m = self.url_rex.match(path_info)
if not m:
return None
u = model.User.find(m.group('id'))
if not u:
return None

if not validate_token(m.group('code'), u.email, self.config):
return None

from adhocracy.lib.helpers import base_url
root_url = base_url('/', instance=None, config=self.config)
environ['repoze.who.application'] = HTTPFound(location=root_url)
return {
'repoze.who.plugins.emaillogin.userid': u.user_name,
}

def forget(self, environ, identity):
rememberer = environ['repoze.who.plugins'][self.rememberer_name]
return rememberer.forget(environ, identity)

def remember(self, environ, identity):
rememberer = environ['repoze.who.plugins'][self.rememberer_name]
return rememberer.remember(environ, identity)

def authenticate(self, environ, identity):
userid = identity.get('repoze.who.plugins.emaillogin.userid')
if userid is None:
return None
identity['repoze.who.userid'] = userid
return userid


def setup_auth(config, idenitifiers, authenticators):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should name the second variable identifiers

email_rwho = EmailLoginRepozeWho(config, 'auth_tkt')
idenitifiers.append(('emaillogin', email_rwho))
authenticators.append(('emaillogin', email_rwho))
17 changes: 17 additions & 0 deletions src/adhocracy/templates/user/login_email.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<%inherit file="/template.html" />
<%def name="title()">${_("Email login request sent")}</%def>

<%block name="headline">
<h1 class="page_title">${_("Email login request sent")}</h1>
</%block>

<%block name="main_content">
<div class="sidebar">
&nbsp;
</div>
<div class="mainbar">
<div class="infobox">
${_("You will be sent an link to your email address. that, when opened will authenticate you automatically.")}
</div>
</div>
</%block>