Automated merge with https://gss.googlecode.com/hg/
[pithos] / src / gr / ebs / gss / server / webdav / milton / GssSecurityManager.java
1 /*
2  * Copyright 2011 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.webdav.milton;
20
21 import static gr.ebs.gss.server.configuration.GSSConfigurationFactory.getConfiguration;
22 import gr.ebs.gss.client.exceptions.RpcException;
23 import gr.ebs.gss.server.domain.User;
24 import gr.ebs.gss.server.ejb.ExternalAPI;
25 import gr.ebs.gss.server.ejb.TransactionHelper;
26
27 import java.io.UnsupportedEncodingException;
28 import java.util.Map;
29 import java.util.concurrent.Callable;
30
31 import javax.naming.Context;
32 import javax.naming.InitialContext;
33 import javax.naming.NamingException;
34 import javax.rmi.PortableRemoteObject;
35 import javax.security.auth.login.FailedLoginException;
36 import javax.security.auth.login.LoginException;
37
38 import org.apache.commons.codec.binary.Base64;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 import com.bradmcevoy.http.Auth;
43 import com.bradmcevoy.http.Request;
44 import com.bradmcevoy.http.Resource;
45 import com.bradmcevoy.http.Request.Method;
46 import com.bradmcevoy.http.http11.auth.DigestGenerator;
47 import com.bradmcevoy.http.http11.auth.DigestResponse;
48 import com.ettrema.http.fs.SimpleSecurityManager;
49
50
51 /**
52  * @author kman
53  *
54  */
55 public class GssSecurityManager  implements com.bradmcevoy.http.SecurityManager{
56
57         private static final Logger log = LoggerFactory.getLogger(SimpleSecurityManager.class);
58
59     private String realm;
60     private DigestGenerator digestGenerator;
61
62     public GssSecurityManager() {
63         digestGenerator = new DigestGenerator();
64     }
65
66     public GssSecurityManager( DigestGenerator digestGenerator ) {
67         this.digestGenerator = digestGenerator;
68     }
69
70    
71     public GssSecurityManager( String realm) {
72         this.realm = realm;
73         
74     }
75     /*
76     public Object getUserByName( String name ) {
77         String actualPassword = nameAndPasswords.get( name );
78         if( actualPassword != null ) return name;
79         return null;
80     }*/
81
82
83
84     public Object authenticate( String user, String password ) {
85         log.debug( "authenticate: " + user + " - " + password);
86         // user name will include domain when coming form ftp. we just strip it off
87         if( user.contains( "@")) {
88             user = user.substring( 0, user.indexOf( "@"));
89         }
90         String actualPassword=null;
91                 try {
92                         actualPassword = getUsersPassword( user );
93                 } catch (Exception e) {
94                         // TODO Auto-generated catch block
95                         e.printStackTrace();
96                         return null;
97                 }
98         if( actualPassword == null ) {
99             log.debug( "user not found: " + user);
100             return null;
101         } else {
102             boolean ok;
103             if( actualPassword == null ) {
104                 ok = password == null || password.length()==0;
105             } else {
106                 ok = actualPassword.equals( password);
107             }
108             return ok ? user : null;
109         }
110     }
111
112     public Object authenticate( DigestResponse digestRequest ) {
113         String actualPassword=null;
114                 try {
115                         actualPassword = getUsersPassword( digestRequest.getUser() );
116                 } catch (Exception e) {
117                         // TODO Auto-generated catch block
118                         e.printStackTrace();
119                         return null;
120                 }
121                 
122         String serverResponse = digestGenerator.generateDigest( digestRequest, actualPassword );
123         String clientResponse = digestRequest.getResponseDigest();
124
125         if( serverResponse.equals( clientResponse ) ) {
126             try {
127                                 return getService().getUserByUserName(digestRequest.getUser());
128                         } catch (RpcException e) {
129                                 // TODO Auto-generated catch block
130                                 e.printStackTrace();
131                                 return null;
132                         }
133         } else {
134             return null;
135         }
136     }
137
138
139
140     public boolean authorise( Request request, Method method, Auth auth, Resource resource ) {
141         return auth != null && auth.getTag() != null;
142     }
143
144     public String getRealm(String host) {
145         return realm;
146     }
147
148     /**
149      * @param realm the realm to set
150      */
151     public void setRealm( String realm ) {
152         this.realm = realm;
153     }
154     
155     private ExternalAPI getService() throws RpcException {
156                 try {
157                         final Context ctx = new InitialContext();
158                         final Object ref = ctx.lookup(getConfiguration().getString("externalApiPath"));
159                         return (ExternalAPI) PortableRemoteObject.narrow(ref, ExternalAPI.class);
160                 } catch (final NamingException e) {
161                         log.error("Unable to retrieve the ExternalAPI EJB", e);
162                         throw new RpcException("An error occurred while contacting the naming service");
163                 }
164         }
165
166         
167         protected String getUsersPassword(String username) throws Exception {
168                 
169                 try {
170                         final User user = getService().findUser(username);
171                         if (user == null) throw new FailedLoginException("User '" + username + "' not found.");
172                         if (!user.isActive()) throw new FailedLoginException("User '" + username + "' is disabled.");
173                         if (user.getWebDAVPassword() != null && user.getWebDAVPassword().length() > 0)
174                                 return user.getWebDAVPassword();
175                         // If no password has ever been generated, use token instead
176                         String tokenEncoded = new String(Base64.encodeBase64(user.getAuthToken()), "US-ASCII");
177                         user.setWebDAVPassword(tokenEncoded);
178                         new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
179                                 @Override
180                                 public Void call() throws Exception {
181                                         getService().updateUser(user);
182                                         return null;
183                                 }
184                         });
185                         return tokenEncoded;
186                 } catch (RpcException e) {
187                         String error = "An error occurred while communicating with the service";
188                         log.error(error, e);
189                         throw new Exception(e.getMessage());
190                 } catch (UnsupportedEncodingException e) {
191             log.error("", e);
192             throw new Exception(e.getMessage());
193                 } catch (Exception e) {
194             log.error("", e);
195                         throw new Exception(e.getMessage());
196                 }
197         }
198
199     
200
201
202 }