KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > info > magnolia > cms > security > Authenticator


1 /**
2  *
3  * Magnolia and its source-code is licensed under the LGPL.
4  * You may copy, adapt, and redistribute this file for commercial or non-commercial use.
5  * When copying, adapting, or redistributing this document in keeping with the guidelines above,
6  * you are required to provide proper attribution to obinary.
7  * If you reproduce or distribute the document without making any substantive modifications to its content,
8  * please use the following attribution line:
9  *
10  * Copyright 1993-2005 obinary Ltd. (http://www.obinary.com) All rights reserved.
11  *
12  */

13 package info.magnolia.cms.security;
14
15 import info.magnolia.cms.beans.config.ContentRepository;
16 import info.magnolia.cms.core.Content;
17 import info.magnolia.cms.core.HierarchyManager;
18 import info.magnolia.cms.i18n.MessagesManager;
19
20 import javax.jcr.PathNotFoundException;
21 import javax.jcr.RepositoryException;
22 import javax.servlet.http.HttpServletRequest JavaDoc;
23 import javax.servlet.http.HttpSession JavaDoc;
24
25 import org.apache.commons.codec.binary.Base64;
26 import org.apache.commons.lang.StringUtils;
27 import org.apache.log4j.Logger;
28
29
30 /**
31  * @author Sameer Charles
32  * @version 2.0
33  */

34 public final class Authenticator {
35
36     /**
37      * Logger.
38      */

39     private static Logger log = Logger.getLogger(Authenticator.class);
40
41     /**
42      * Session attribute holding the magnolia user id.
43      */

44     private static final String JavaDoc ATTRIBUTE_USER_ID = "mgnlUserId"; //$NON-NLS-1$
45

46     /**
47      * Session attribute holding the magnolia user password.
48      */

49     private static final String JavaDoc ATTRIBUTE_PSWD = "mgnlUserPSWD"; //$NON-NLS-1$
50

51     /**
52      * Session attribute holding the magnolia user node from the jcr repository.
53      */

54     private static final String JavaDoc ATTRIBUTE_USER_NODE = "mgnlUserNode"; //$NON-NLS-1$
55

56     /**
57      * Utility class, don't instantiate.
58      */

59     private Authenticator() {
60         // unused
61
}
62
63     /**
64      * Authenticate authorization request with the usersRepository.
65      * @param req as received by the servlet engine
66      * @return boolean
67      */

68     public static boolean authenticate(HttpServletRequest JavaDoc req) {
69         String JavaDoc credentials = req.getHeader("Authorization"); //$NON-NLS-1$
70
if (StringUtils.isEmpty(credentials) || credentials.length() <= 6) {
71             return false;
72         }
73         credentials = getDecodedCredentials(credentials.substring(6).trim());
74         Authenticator.setUserId(credentials, req);
75         Authenticator.setPassword(credentials, req);
76         boolean isValid = isValidUser(req);
77         if (!isValid) {
78             req.getSession().invalidate();
79         }
80         return isValid;
81     }
82
83     /**
84      * checks is the credentials exist in the repository
85      * @param request current HttpServletRequest
86      * @return boolean
87      */

88     private static boolean isValidUser(HttpServletRequest JavaDoc request) {
89         HierarchyManager hm = ContentRepository.getHierarchyManager(ContentRepository.USERS);
90         try {
91             String JavaDoc userid = Authenticator.getUserId(request);
92             if (StringUtils.isEmpty(userid)) {
93                 return false;
94             }
95             Content userPage = hm.getContent(userid);
96             String JavaDoc encodedPassword = new String JavaDoc(Base64.encodeBase64(Authenticator
97                 .getPasswordAsString(request)
98                 .getBytes()));
99             String JavaDoc fromRepository = userPage.getNodeData("pswd").getString().trim(); //$NON-NLS-1$
100
String JavaDoc fromBrowser = encodedPassword.trim();
101             if (fromRepository.equalsIgnoreCase(fromBrowser)) {
102                 request.getSession().setAttribute(ATTRIBUTE_USER_NODE, userPage);
103
104                 // we must set the language because the JSTL will not use our classes
105
String JavaDoc lang = userPage.getNodeData("language").getString(); //$NON-NLS-1$
106
if (StringUtils.isEmpty(lang)) {
107                     lang = MessagesManager.getDefaultLocale().getLanguage();
108                 }
109                 MessagesManager.setUserLanguage(lang, request.getSession());
110                 return true;
111             }
112         }
113         catch (PathNotFoundException e) {
114             log.info("Unable to locate user [" + Authenticator.getUserId(request) + "], authentication failed"); //$NON-NLS-1$ //$NON-NLS-2$
115
}
116         catch (RepositoryException e) {
117             log.error("Unable to locate user [" //$NON-NLS-1$
118
+ Authenticator.getUserId(request) + "], authentication failed due to a " //$NON-NLS-1$
119
+ e.getClass().getName(), e);
120         }
121         return false;
122     }
123
124     /**
125      * @param credentials to be decoded
126      * @return String decoded credentials <b>name:password </b>
127      */

128     private static String JavaDoc getDecodedCredentials(String JavaDoc credentials) {
129         return (new String JavaDoc(Base64.decodeBase64(credentials.getBytes())));
130     }
131
132     /**
133      * @param decodedCredentials , BASE64Decoded credentials from the request
134      * @param request current HttpServletRequest
135      */

136     private static void setUserId(String JavaDoc decodedCredentials, HttpServletRequest JavaDoc request) {
137         request.getSession().setAttribute(ATTRIBUTE_USER_ID, StringUtils.substringBefore(decodedCredentials, ":")); //$NON-NLS-1$
138
}
139
140     /**
141      * @param request current HttpServletRequest
142      * @param decodedCredentials , BASE64Decoded credentials from the request
143      */

144     private static void setPassword(String JavaDoc decodedCredentials, HttpServletRequest JavaDoc request) {
145         request.getSession().setAttribute(ATTRIBUTE_PSWD, StringUtils.substringAfter(decodedCredentials, ":")); //$NON-NLS-1$
146
}
147
148     /**
149      * @param request current HttpServletRequest
150      * @return String , current logged in user
151      */

152     public static String JavaDoc getUserId(HttpServletRequest JavaDoc request) {
153         Object JavaDoc userId = request.getSession().getAttribute(ATTRIBUTE_USER_ID);
154         if (userId == null) {
155             String JavaDoc credentials = request.getHeader("Authorization"); //$NON-NLS-1$
156
if (credentials == null) {
157                 return "superuser"; //$NON-NLS-1$
158
}
159
160             credentials = getDecodedCredentials(credentials.substring(6).trim());
161             Authenticator.setUserId(credentials, request);
162             userId = request.getSession().getAttribute(ATTRIBUTE_USER_ID);
163         }
164         return (String JavaDoc) userId;
165     }
166
167     /**
168      * @param request current HttpServletRequest
169      * @return char[] , decoded current user password
170      */

171     public static char[] getPassword(HttpServletRequest JavaDoc request) {
172         Object JavaDoc pswd = request.getSession().getAttribute(ATTRIBUTE_PSWD);
173         if (pswd == null) {
174             return StringUtils.EMPTY.toCharArray();
175         }
176         return ((String JavaDoc) pswd).toCharArray();
177     }
178
179     /**
180      * @param request current HttpServletRequest
181      * @return String password
182      */

183     private static String JavaDoc getPasswordAsString(HttpServletRequest JavaDoc request) {
184         return ((String JavaDoc) request.getSession().getAttribute(ATTRIBUTE_PSWD));
185     }
186
187     /**
188      * @param request current HttpServletRequest
189      * @return credentials , as received from the servlet request
190      */

191     public static String JavaDoc getCredentials(HttpServletRequest JavaDoc request) {
192         return request.getHeader("Authorization"); //$NON-NLS-1$
193
}
194
195     /**
196      * @param request current HttpServletRequest
197      * @return current logged in user page
198      */

199     public static Content getUserPage(HttpServletRequest JavaDoc request) {
200         return (Content) request.getSession().getAttribute(ATTRIBUTE_USER_NODE);
201     }
202
203     /**
204      * @param request current HttpServletRequest
205      * @return the current user object
206      */

207     public static User getUser(HttpServletRequest JavaDoc request) {
208         return new User(getUserPage(request));
209     }
210
211     /**
212      * checks user session for attribute "user node"
213      * @param request current HttpServletRequest
214      * @return <code>true</code> if the user is authenticated, <code>false</code> otherwise
215      */

216     public static boolean isAuthenticated(HttpServletRequest JavaDoc request) {
217         // don't force a creation of a new session
218
HttpSession JavaDoc session = request.getSession(false);
219         if (session != null) {
220             try {
221                 return session.getAttribute(ATTRIBUTE_USER_NODE) != null;
222             }
223             catch (IllegalStateException JavaDoc e) {
224                 // can happen if the session has just been invalidated
225
log.debug("IllegalStateException caught"); //$NON-NLS-1$
226
return false;
227             }
228         }
229
230         return false;
231     }
232 }
Popular Tags