b0ed6e69397dcaa4cd313752eed3e473c405f643
[gigi.git] / src / club / wpia / gigi / pages / LoginPage.java
1 package club.wpia.gigi.pages;
2
3 import static club.wpia.gigi.Gigi.*;
4
5 import java.io.IOException;
6 import java.io.PrintWriter;
7 import java.math.BigInteger;
8 import java.security.cert.X509Certificate;
9 import java.util.Map;
10
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13 import javax.servlet.http.HttpSession;
14
15 import club.wpia.gigi.GigiApiException;
16 import club.wpia.gigi.database.GigiPreparedStatement;
17 import club.wpia.gigi.database.GigiResultSet;
18 import club.wpia.gigi.dbObjects.CertificateOwner;
19 import club.wpia.gigi.dbObjects.Group;
20 import club.wpia.gigi.dbObjects.User;
21 import club.wpia.gigi.localisation.Language;
22 import club.wpia.gigi.output.template.Form;
23 import club.wpia.gigi.output.template.TranslateCommand;
24 import club.wpia.gigi.pages.main.RegisterPage;
25 import club.wpia.gigi.util.AuthorizationContext;
26 import club.wpia.gigi.util.PasswordHash;
27 import club.wpia.gigi.util.RateLimit;
28 import club.wpia.gigi.util.RateLimit.RateLimitException;
29 import club.wpia.gigi.util.ServerConstants;
30 import club.wpia.gigi.util.ServerConstants.Host;
31
32 public class LoginPage extends Page {
33
34     public static final RateLimit RATE_LIMIT = new RateLimit(10, 5 * 60 * 1000);
35
36     public class LoginForm extends Form {
37
38         public LoginForm(HttpServletRequest hsr) {
39             super(hsr);
40         }
41
42         @Override
43         public RedirectResult submit(HttpServletRequest req) throws GigiApiException {
44             if (RegisterPage.RATE_LIMIT.isLimitExceeded(req.getRemoteAddr())) {
45                 throw new RateLimitException();
46             }
47             tryAuthWithUnpw(req);
48             return new RedirectResult(redirectPath(req));
49         }
50
51         @Override
52         protected void outputContent(PrintWriter out, Language l, Map<String, Object> vars) {
53             getDefaultTemplate().output(out, l, vars);
54         }
55
56     }
57
58     public static final String LOGIN_RETURNPATH = "login-returnpath";
59
60     public LoginPage() {
61         super("Password Login");
62     }
63
64     @Override
65     public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
66         if (req.getHeader("Host").equals(ServerConstants.getHostNamePortSecure(Host.SECURE))) {
67             resp.getWriter().println(getLanguage(req).getTranslation("Authentication with certificate failed. Try another certificate or use a password."));
68         } else {
69             new LoginForm(req).output(resp.getWriter(), getLanguage(req), getDefaultVars(req));
70         }
71     }
72
73     @Override
74     public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
75         if (Form.printFormErrors(req, resp.getWriter())) {
76             Form.getForm(req, LoginForm.class).output(resp.getWriter(), getLanguage(req), getDefaultVars(req));
77         }
78     }
79
80     @Override
81     public boolean beforeTemplate(HttpServletRequest req, HttpServletResponse resp) throws IOException {
82         if (req.getSession().getAttribute("loggedin") == null) {
83             X509Certificate cert = getCertificateFromRequest(req);
84             if (cert != null) {
85                 tryAuthWithCertificate(req, cert);
86             }
87             if (req.getMethod().equals("POST")) {
88                 return Form.getForm(req, LoginForm.class).submitExceptionProtected(req, resp);
89             }
90         }
91
92         if (req.getSession().getAttribute("loggedin") != null) {
93             resp.sendRedirect(redirectPath(req));
94             return true;
95         }
96         return false;
97     }
98
99     private static String redirectPath(HttpServletRequest req) {
100         String redir = (String) req.getAttribute(LOGIN_RETURNPATH);
101         String s = redir;
102         if (s != null) {
103             if ( !s.startsWith("/")) {
104                 s = "/" + s;
105             }
106             return s;
107         } else {
108             return "/";
109         }
110     }
111
112     @Override
113     public boolean needsLogin() {
114         return false;
115     }
116
117     private void tryAuthWithUnpw(HttpServletRequest req) throws GigiApiException {
118         String un = req.getParameter("username");
119         String pw = req.getParameter("password");
120         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `password`, `id` FROM `users` WHERE `email`=? AND verified='1'")) {
121             ps.setString(1, un);
122             GigiResultSet rs = ps.executeQuery();
123             if (rs.next()) {
124                 String dbHash = rs.getString(1);
125                 String hash = PasswordHash.verifyHash(pw, dbHash);
126                 if (hash != null) {
127                     if ( !hash.equals(dbHash)) {
128                         try (GigiPreparedStatement gps = new GigiPreparedStatement("UPDATE `users` SET `password`=? WHERE `email`=?")) {
129                             gps.setString(1, hash);
130                             gps.setString(2, un);
131                             gps.executeUpdate();
132                         }
133                     }
134                     loginSession(req, User.getById(rs.getInt(2)));
135                     req.getSession().setAttribute(LOGIN_METHOD, new TranslateCommand("Password"));
136                     return;
137                 }
138             }
139         }
140         throw new GigiApiException("Username and password didn't match.");
141     }
142
143     public static User getUser(HttpServletRequest req) {
144         AuthorizationContext ac = getAuthorizationContext(req);
145         if (ac == null) {
146             return null;
147         }
148         return ac.getActor();
149     }
150
151     public static AuthorizationContext getAuthorizationContext(HttpServletRequest req) {
152         return ((AuthorizationContext) req.getSession().getAttribute(AUTH_CONTEXT));
153     }
154
155     private void tryAuthWithCertificate(HttpServletRequest req, X509Certificate x509Certificate) {
156         BigInteger serial = extractSerialFormCert(x509Certificate);
157         User user = fetchUserBySerial(serial);
158         if (user == null) {
159             return;
160         }
161         loginSession(req, user);
162         req.getSession().setAttribute(CERT_SERIAL, serial);
163         req.getSession().setAttribute(CERT_ISSUER, x509Certificate.getIssuerDN());
164         req.getSession().setAttribute(LOGIN_METHOD, new TranslateCommand("Certificate"));
165     }
166
167     public static BigInteger extractSerialFormCert(X509Certificate x509Certificate) {
168         return x509Certificate.getSerialNumber();
169     }
170
171     public static User fetchUserBySerial(BigInteger serial) {
172         CertificateOwner o = CertificateOwner.getByEnabledSerial(serial);
173         if (o == null || !(o instanceof User)) {
174             return null;
175         }
176         return (User) o;
177     }
178
179     public static X509Certificate getCertificateFromRequest(HttpServletRequest req) {
180         X509Certificate[] cert = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
181         X509Certificate uc = null;
182         if (cert != null && cert[0] != null) {
183             uc = cert[0];
184         }
185         return uc;
186     }
187
188     private static final Group LOGIN_BLOCKED = Group.BLOCKED_LOGIN;
189
190     private void loginSession(HttpServletRequest req, User user) {
191         if (user.isInGroup(LOGIN_BLOCKED)) {
192             return;
193         }
194         req.setAttribute(LOGIN_RETURNPATH, req.getSession().getAttribute(LOGIN_RETURNPATH));
195         req.getSession().invalidate();
196         HttpSession hs = req.getSession();
197         hs.setAttribute(LOGGEDIN, true);
198         hs.setAttribute(Language.SESSION_ATTRIB_NAME, user.getPreferredLocale());
199         hs.setAttribute(AUTH_CONTEXT, new AuthorizationContext(user, user));
200     }
201
202     @Override
203     public boolean isPermitted(AuthorizationContext ac) {
204         return ac == null;
205     }
206 }