a32583ce8f597cf7d17edcbee304ff5a0b1957e9
[zzz-floof.git] / floof / controllers / account.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 request, response, session, tmpl_context as c
8 from pylons.controllers.util import abort, redirect_to
9 from routes import url_for, request_config
10
11 from floof import model
12 from floof.model.meta import Session
13 from floof.lib.base import BaseController, render
14
15 log = logging.getLogger(__name__)
16
17 class AccountController(BaseController):
18
19 openid_store = FileOpenIDStore('/var/tmp')
20
21 def login(self):
22 return render('/login.mako')
23
24 def login_begin(self):
25 """Step one of logging in with OpenID; we redirect to the provider"""
26
27 cons = Consumer(session=session, store=self.openid_store)
28 auth_request = cons.begin(request.params['identity_url'])
29 sreg_req = SRegRequest(optional=['nickname', 'email', 'dob', 'gender',
30 'country', 'language', 'timezone'])
31 auth_request.addExtension(sreg_req)
32
33 host = request.headers['host']
34 protocol = request_config().protocol
35 return_url = url_for(host=host, controller='account', action='login_finish')
36 new_url = auth_request.redirectURL(return_to=return_url,
37 realm=protocol + '://' + host)
38 redirect_to(new_url)
39
40 def login_finish(self):
41 """Step two of logging in; the OpenID provider redirects back here."""
42
43 cons = Consumer(session=session, store=self.openid_store)
44 host = request.headers['host']
45 return_url = url_for(host=host, controller='account', action='login_finish')
46 res = cons.complete(request.params, return_url)
47
48 if res.status != 'success':
49 return 'Error! %s' % res.message
50
51 try:
52 # Grab an existing user record, if one exists
53 q = Session.query(model.User) \
54 .filter(model.User.identity_urls.any(url=res.identity_url))
55 user = q.one()
56 except NoResultFound:
57 # Try to pull a name out of the SReg response
58 sreg_res = SRegResponse.fromSuccessResponse(res)
59 try:
60 username = sreg_res['nickname']
61 except:
62 username = 'Anonymous'
63
64 # Create db records
65 user = model.User(name=username)
66 Session.add(user)
67 identity_url = model.IdentityURL(url=res.identity_url)
68 user.identity_urls.append(identity_url)
69 Session.commit()
70
71 # Remember who's logged in, and we're good to go
72 session['user_id'] = user.id
73 session.save()
74
75 return "Hello, %s from %s" % (user.name, res.identity_url)