Display the last login in the web client.
[pithos] / src / gr / ebs / gss / server / rest / UserHandler.java
1 /*
2  * Copyright 2008, 2009 Electronic Business Systems Ltd.
3  *
4  * This file is part of GSS.
5  *
6  * GSS is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * GSS is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with GSS.  If not, see <http://www.gnu.org/licenses/>.
18  */
19 package gr.ebs.gss.server.rest;
20
21 import static gr.ebs.gss.server.configuration.GSSConfigurationFactory.getConfiguration;
22 import gr.ebs.gss.client.exceptions.InsufficientPermissionsException;
23 import gr.ebs.gss.client.exceptions.ObjectNotFoundException;
24 import gr.ebs.gss.client.exceptions.RpcException;
25 import gr.ebs.gss.server.Login;
26 import gr.ebs.gss.server.domain.User;
27 import gr.ebs.gss.server.domain.dto.StatsDTO;
28 import gr.ebs.gss.server.ejb.TransactionHelper;
29
30 import java.io.IOException;
31 import java.util.concurrent.Callable;
32
33 import javax.servlet.http.Cookie;
34 import javax.servlet.http.HttpServletRequest;
35 import javax.servlet.http.HttpServletResponse;
36
37 import org.apache.commons.logging.Log;
38 import org.apache.commons.logging.LogFactory;
39 import org.json.JSONException;
40 import org.json.JSONObject;
41
42
43 /**
44  * A class that handles operations on the user's root namespace.
45  *
46  * @author past
47  */
48 public class UserHandler extends RequestHandler {
49
50         /**
51          * The reset WebDAV password parameter name.
52          */
53         protected static final String RESET_WEBDAV_PARAMETER = "resetWebDAV";
54
55         /**
56          * The logger.
57          */
58         private static Log logger = LogFactory.getLog(UserHandler.class);
59
60     /**
61      * Serve the root namespace for the user.
62      *
63      * @param req The servlet request we are processing
64      * @param resp The servlet response we are processing
65      * @throws IOException if an input/output error occurs
66          */
67         void serveUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
68         String parentUrl = getContextPath(req, false);
69
70         User user = getUser(req);
71         User owner = getOwner(req);
72         if (!owner.equals(user)) {
73                 resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
74                 return;
75         }
76
77         JSONObject json = new JSONObject();
78         try {
79                 StatsDTO stats = getService().getUserStatistics(owner.getId());
80                 JSONObject statistics = new JSONObject();
81                 statistics.put("totalFiles", stats.getFileCount()).put("totalBytes", stats.getFileSize()).
82                                 put("bytesRemaining", stats.getQuotaLeftSize());
83                         json.put("name", owner.getName()).put("firstname", owner.getFirstname()).
84                                         put("lastname", owner.getLastname()).put("username", owner.getUsername()).
85                                         put("creationDate", owner.getAuditInfo().getCreationDate().getTime()).
86                                         put("modificationDate", owner.getAuditInfo().getModificationDate().getTime()).
87                                         put("email", owner.getEmail()).put("fileroot", parentUrl + PATH_FILES).
88                                         put("groups", parentUrl + PATH_GROUPS).put("trash", parentUrl + PATH_TRASH).
89                                         put("shared", parentUrl + PATH_SHARED).put("others", parentUrl + PATH_OTHERS).
90                                         put("quota", statistics).put("tags", parentUrl + PATH_TAGS);
91                         String announcement = getConfiguration().getString("announcement");
92                         if (announcement != null && !announcement.isEmpty())
93                                 json.put("announcement", announcement);
94                         if (owner.getLastLogin() != null)
95                                 json.put("lastLogin", owner.getLastLogin().getTime());
96                 } catch (JSONException e) {
97                         logger.error("", e);
98                         resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
99                         return;
100                 } catch (ObjectNotFoundException e) {
101                         resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
102                         return;
103                 } catch (RpcException e) {
104                         logger.error("", e);
105                         resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
106                         return;
107                 }
108
109         sendJson(req, resp, json.toString());
110         }
111
112
113         /**
114          * Handle POST requests in the users namespace.
115          *
116      * @param req The servlet request we are processing
117      * @param resp The servlet response we are processing
118      * @throws IOException if an input/output error occurs
119          */
120         void postUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
121                 try {
122                 final User user = getUser(req);
123                 User owner = getOwner(req);
124                 if (!owner.equals(user))
125                         throw new InsufficientPermissionsException("User " + user.getUsername()
126                                                 + " does not have permission to modify "
127                                                 + owner.getUsername());
128                 boolean hasResetWebDAVParam = req.getParameterMap().containsKey(RESET_WEBDAV_PARAMETER);
129                 if (hasResetWebDAVParam) {
130                         String newPassword = new TransactionHelper<String>().tryExecute(new Callable<String>() {
131                                         @Override
132                                         public String call() throws Exception {
133                                                 return getService().resetWebDAVPassword(user.getId());
134                                         }
135                                 });
136
137                         // Set the cookie again to send new value
138                         Cookie cookie = new Cookie(Login.WEBDAV_COOKIE, newPassword);
139                         cookie.setMaxAge(-1);
140                         String domain = req.getRemoteHost();
141                         String path = req.getContextPath();
142                         cookie.setDomain(domain);
143                         cookie.setPath(path);
144                     resp.addCookie(cookie);
145                 }
146                 // Workaround for IE's broken caching behavior.
147                         resp.setHeader("Expires", "-1");
148                 } catch (ObjectNotFoundException e) {
149                         resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
150                 } catch (RpcException e) {
151                         logger.error("", e);
152                         resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
153                 } catch (InsufficientPermissionsException e) {
154                         resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, e.getMessage());
155                 } catch (Exception e) {
156                         logger.error("", e);
157                         resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
158                 }
159         }
160
161 }