summaryrefslogtreecommitdiff
path: root/src/lq/AddAdmin.java
blob: d50e3d0101e64f54402226c30eefc7996cb5b01b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package lq;

import java.io.IOException;
import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AddAdmin extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        resp.setContentType("text/html");
        String email = req.getParameter("email");
        if (UserUtil.isAuthenticated() || UserUtil.hasZeroUsers()) {
            if (addUser(resp, email)) {
                resp.getWriter().println(Strings.escape(email) + " kan nå moderere quotes.");
            }

            String logoutUrl = UserUtil.getLogoutUrl(req.getRequestURI());
            resp.getWriter().println("<a href=\"" + logoutUrl + "\">Logg ut</a><br>");
        }
        else {
            String loginUrl = UserUtil.getLoginUrl(req.getRequestURI());
            resp.getWriter().println("<a href=\"" + loginUrl + "\">Logg inn</a><br>");
        }
    }

    private boolean addUser(HttpServletResponse resp, String email) 
            throws IOException {
        if (Strings.nullOrEmpty(email)) {
            resp.getWriter().println("Feilkode µ (spesifiser email).<br>");
            return false;
        }
        else {
            PersistenceManager pm = PMF.get().getPersistenceManager();
            try {
                if (!UserUtil.userExists(email)) {
                    Administrator newAdmin = new Administrator(email);
                    pm.makePersistent(newAdmin);
                    return true;
                }
                else {
                    resp.getWriter().println("Brukeren " + Strings.escape(email) +
                            " finnes allerede<br>");
                    return false;
                }
            }
            finally {
                pm.close();
            }
        }
    }
}