]>
Commit | Line | Data |
---|---|---|
1 | #!/usr/bin/python | |
2 | ||
3 | import logging | |
4 | import tornado.web | |
5 | ||
6 | from . import handlers_base as base | |
7 | ||
8 | class AuthenticationMixin(object): | |
9 | def login(self, username, password): | |
10 | # Find account | |
11 | account = self.backend.accounts.find_account(username) | |
12 | if not account: | |
13 | raise tornado.web.HTTPError(401, "Unknown user: %s" % username) | |
14 | ||
15 | # Check credentials | |
16 | if not account.check_password(password): | |
17 | raise tornado.web.HTTPError(401, "Invalid password for %s" % account) | |
18 | ||
19 | # User has logged in, create a session | |
20 | session_id, session_expires = self.backend.accounts.create_session( | |
21 | account, self.request.host) | |
22 | ||
23 | # Check if a new session was created | |
24 | if not session_id: | |
25 | raise tornado.web.HTTPError(500, "Could not create session") | |
26 | ||
27 | # Send session cookie to the client | |
28 | self.set_cookie("session_id", session_id, | |
29 | domain=self.request.host, expires=session_expires) | |
30 | ||
31 | def logout(self): | |
32 | session_id = self.get_cookie("session_id") | |
33 | if not session_id: | |
34 | return | |
35 | ||
36 | success = self.backend.accounts.destroy_session(session_id, self.request.host) | |
37 | if success: | |
38 | self.clear_cookie("session_id") | |
39 | ||
40 | ||
41 | class LoginHandler(AuthenticationMixin, base.BaseHandler): | |
42 | def get(self): | |
43 | next = self.get_argument("next", None) | |
44 | ||
45 | self.render("auth/login.html", next=next) | |
46 | ||
47 | def post(self): | |
48 | username = self.get_argument("username") | |
49 | password = self.get_argument("password") | |
50 | ||
51 | with self.db.transaction(): | |
52 | self.login(username, password) | |
53 | ||
54 | # Determine the page we should redirect to | |
55 | next = self.get_argument("next", None) | |
56 | ||
57 | return self.redirect(next or "/") | |
58 | ||
59 | ||
60 | class LogoutHandler(AuthenticationMixin, base.BaseHandler): | |
61 | def get(self): | |
62 | with self.db.transaction(): | |
63 | self.logout() | |
64 | ||
65 | # Get back to the start page | |
66 | self.redirect("/") |