e38a4cd48c16a4257b3d09332bd3d5cf27f82725
[zzz-spline-users.git] / spline / plugins / users / controllers / accounts.py
1 import logging
2 from openid.consumer.consumer import Consumer
3 from openid.extensions.sreg import SRegRequest, SRegResponse
4 from openid.store.filestore import FileOpenIDStore
5 from sqlalchemy.orm.exc import NoResultFound
6
7 from pylons import config, request, response, session, tmpl_context as c, url
8 from pylons.controllers.util import abort, redirect_to
9 from routes import request_config
10
11 from spline import model
12 from spline.model import meta
13 from spline.lib import helpers as h
14 from spline.lib.base import BaseController, render
15
16 log = logging.getLogger(__name__)
17
18 class AccountsController(BaseController):
19
20 openid_store = FileOpenIDStore('/var/tmp')
21
22 def index(self):
23 # Return a rendered template
24 # return render('/template.mako')
25 # or, Return a response
26 return str(request.headers) + request.environ.get('scheme', '')
27
28 def login_begin(self):
29 """Step one of logging in with OpenID; we redirect to the provider"""
30
31 cons = Consumer(session=session, store=self.openid_store)
32 auth_request = cons.begin(request.params['openid'])
33 sreg_req = SRegRequest(optional=['nickname', 'email', 'dob', 'gender',
34 'country', 'language', 'timezone'])
35 auth_request.addExtension(sreg_req)
36
37 host = request.headers['host']
38 protocol = request_config().protocol
39 return_url = url(host=host, controller='accounts', action='login_finish')
40 new_url = auth_request.redirectURL(return_to=return_url,
41 realm=protocol + '://' + host)
42 redirect_to(new_url)
43
44 def login_finish(self):
45 """Step two of logging in; the OpenID provider redirects back here."""
46
47 cons = Consumer(session=session, store=self.openid_store)
48 host = request.headers['host']
49 return_url = url(host=host, controller='accounts', action='login_finish')
50 res = cons.complete(request.params, return_url)
51
52 if res.status != 'success':
53 return 'Error! %s' % res.message
54
55 try:
56 # Grab an existing user record, if one exists
57 q = meta.Session.query(model.User) \
58 .filter(model.User.openids.any(openid=res.identity_url))
59 user = q.one()
60 except NoResultFound:
61 # Try to pull a name out of the SReg response
62 sreg_res = SRegResponse.fromSuccessResponse(res)
63 try:
64 username = sreg_res['nickname']
65 except (KeyError, TypeError):
66 # KeyError if sreg has no nickname; TypeError if sreg is None
67 username = 'Anonymous'
68
69 # Create db records
70 user = model.User(name=username)
71 meta.Session.add(user)
72
73 openid = model.OpenID(openid=res.identity_url)
74 user.openids.append(openid)
75
76 meta.Session.commit()
77
78 # Remember who's logged in, and we're good to go
79 session['user_id'] = user.id
80 session.save()
81
82 h.flash(u"""Hello, {0}!""".format(user.name),
83 icon='user')
84
85 redirect_to('/', _code=303)
86
87 def logout(self):
88 """Logs the user out."""
89
90 if 'user_id' in session:
91 del session['user_id']
92 session.save()
93
94 h.flash(u"""Logged out.""",
95 icon='user-silhouette')
96
97 redirect_to('/', _code=303)