ba2fa26a06d6fa0214e7997b61769daf2f6da500
[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 openid = model.OpenID(openid=res.identity_url)
73 user.openids.append(openid)
74 meta.Session.commit()
75
76 # Remember who's logged in, and we're good to go
77 session['user_id'] = user.id
78 session.save()
79
80 h.flash(u"""Hello, {0}!""".format(user.name),
81 icon='user')
82
83 redirect_to('/', _code=303)
84
85 def logout(self):
86 """Logs the user out."""
87
88 if 'user_id' in session:
89 del session['user_id']
90 session.save()
91
92 h.flash(u"""Logged out.""",
93 icon='user-silhouette')
94
95 redirect_to('/', _code=303)