1   /**
2    * Copyright (c) 2000-2007 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portal.security.auth;
24  
25  import com.liferay.portal.NoSuchUserException;
26  import com.liferay.portal.kernel.util.StringPool;
27  import com.liferay.portal.model.User;
28  import com.liferay.portal.service.UserLocalServiceUtil;
29  import com.liferay.portal.theme.ThemeDisplay;
30  import com.liferay.portal.util.PortalUtil;
31  import com.liferay.portal.util.PrefsPropsUtil;
32  import com.liferay.portal.util.PropsUtil;
33  import com.liferay.portal.util.WebKeys;
34  import com.liferay.util.HttpUtil;
35  import com.liferay.util.PwdGenerator;
36  
37  import java.io.BufferedReader;
38  import java.io.InputStream;
39  import java.io.InputStreamReader;
40  
41  import java.net.URL;
42  import java.net.URLConnection;
43  
44  import java.util.Calendar;
45  import java.util.HashMap;
46  import java.util.Locale;
47  import java.util.Map;
48  
49  import javax.servlet.http.HttpServletRequest;
50  import javax.servlet.http.HttpServletResponse;
51  import javax.servlet.http.HttpSession;
52  
53  import org.apache.commons.logging.Log;
54  import org.apache.commons.logging.LogFactory;
55  
56  /**
57   * <a href="OpenSSOAutoLogin.java.html"><b><i>View Source</i></b></a>
58   *
59   * @author Brian Wing Shun Chan
60   *
61   */
62  public class OpenSSOAutoLogin implements AutoLogin {
63  
64      public String[] login(HttpServletRequest req, HttpServletResponse res)
65          throws AutoLoginException {
66  
67          String[] credentials = null;
68  
69          try {
70              long companyId = PortalUtil.getCompanyId(req);
71  
72              if (!PrefsPropsUtil.getBoolean(
73                      companyId, PropsUtil.OPEN_SSO_AUTH_ENABLED)) {
74  
75                  return credentials;
76              }
77  
78              HttpSession ses = req.getSession();
79  
80              String subjectId = (String)ses.getAttribute(WebKeys.OPEN_SSO_LOGIN);
81  
82              if (subjectId == null) {
83                  return credentials;
84              }
85  
86              Map nameValues = new HashMap();
87  
88              String serviceUrl = PrefsPropsUtil.getString(
89                  companyId, PropsUtil.OPEN_SSO_SERVICE_URL);
90  
91              String url =
92                  serviceUrl + "/attributes?subjectid=" +
93                      HttpUtil.encodeURL(subjectId);
94  
95              URL urlObj = new URL(url);
96  
97              URLConnection con = urlObj.openConnection();
98  
99              BufferedReader reader = new BufferedReader(
100                 new InputStreamReader((InputStream)con.getContent()));
101 
102             String line = null;
103 
104             while ((line = reader.readLine()) != null) {
105                 String[] parts = line.split("=");
106 
107                 if ((parts == null) || (parts.length != 2)) {
108                     continue;
109                 }
110 
111                 String attrName = null;
112                 String attrValue = null;
113 
114                 if (parts[0].endsWith("name")) {
115                     attrName = parts[1];
116 
117                     line = reader.readLine();
118 
119                     if (line == null) {
120 
121                         // Name must be followed by value
122 
123                         throw new AutoLoginException(
124                             "Error reading user attributes");
125                     }
126 
127                     parts = line.split("=");
128 
129                     if ((parts == null) || (parts.length != 2) ||
130                         (!parts[0].endsWith("value"))) {
131 
132                         attrValue = null;
133                     }
134                     else {
135                         attrValue = parts[1];
136                     }
137 
138                     nameValues.put(attrName, attrValue);
139                 }
140             }
141 
142             String firstName = (String)nameValues.get("cn");
143             String lastName = (String)nameValues.get("sn");
144             String screenName = (String)nameValues.get("givenname");
145             String emailAddress = (String)nameValues.get("mail");
146 
147             User user = null;
148 
149             try {
150                 user = UserLocalServiceUtil.getUserByEmailAddress(
151                     companyId, emailAddress);
152             }
153             catch (NoSuchUserException nsue) {
154                 ThemeDisplay themeDisplay =
155                     (ThemeDisplay)req.getAttribute(WebKeys.THEME_DISPLAY);
156 
157                 user = addUser(
158                     companyId, firstName, lastName, emailAddress, screenName,
159                     themeDisplay.getLocale());
160             }
161 
162             credentials = new String[3];
163 
164             credentials[0] = String.valueOf(user.getUserId());
165             credentials[1] = user.getPassword();
166             credentials[2] = Boolean.TRUE.toString();
167         }
168         catch (Exception e) {
169             _log.error(e.getMessage());
170         }
171 
172         return credentials;
173     }
174 
175     protected User addUser(
176             long companyId, String firstName, String lastName,
177             String emailAddress, String screenName, Locale locale)
178         throws Exception {
179 
180         long creatorUserId = 0;
181         boolean autoPassword = false;
182         String password1 = PwdGenerator.getPassword();
183         String password2 = password1;
184         boolean autoScreenName = false;
185         String middleName = StringPool.BLANK;
186         int prefixId = 0;
187         int suffixId = 0;
188         boolean male = true;
189         int birthdayMonth = Calendar.JANUARY;
190         int birthdayDay = 1;
191         int birthdayYear = 1970;
192         String jobTitle = StringPool.BLANK;
193         long organizationId = 0;
194         long locationId = 0;
195         boolean sendEmail = false;
196 
197         return UserLocalServiceUtil.addUser(
198             creatorUserId, companyId, autoPassword, password1, password2,
199             autoScreenName, screenName, emailAddress, locale, firstName,
200             middleName, lastName, prefixId, suffixId, male, birthdayMonth,
201             birthdayDay, birthdayYear, jobTitle, organizationId, locationId,
202             sendEmail);
203     }
204 
205     private static Log _log = LogFactory.getLog(OpenSSOAutoLogin.class);
206 
207 }