]> git.ipfire.org Git - ipfire.org.git/blame - src/web/auth.py
accounts: Don't rely on objects being of class posixAccount
[ipfire.org.git] / src / web / auth.py
CommitLineData
08df6527
MT
1#!/usr/bin/python
2
3import logging
4import tornado.web
5
124a8404 6from . import base
08df6527
MT
7
8class 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
08df6527 41class LoginHandler(AuthenticationMixin, base.BaseHandler):
cfe7d74c 42 @base.blacklisted
08df6527
MT
43 def get(self):
44 next = self.get_argument("next", None)
45
46 self.render("auth/login.html", next=next)
47
cfe7d74c 48 @base.blacklisted
08df6527
MT
49 def post(self):
50 username = self.get_argument("username")
51 password = self.get_argument("password")
52
53 with self.db.transaction():
54 self.login(username, password)
55
56 # Determine the page we should redirect to
57 next = self.get_argument("next", None)
58
59 return self.redirect(next or "/")
60
61
62class LogoutHandler(AuthenticationMixin, base.BaseHandler):
63 def get(self):
64 with self.db.transaction():
65 self.logout()
66
67 # Get back to the start page
68 self.redirect("/")
9b8ff27d
MT
69
70
71class CacheMixin(object):
72 def prepare(self):
73 # Mark this as private when someone is logged in
74 if self.current_user:
75 self.add_header("Cache-Control", "private")
76
77 self.add_header("Vary", "Cookie")