You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AuthenticationManager.java 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  1. /*
  2. * Copyright 2013 gitblit.com.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.gitblit.manager;
  17. import java.nio.charset.Charset;
  18. import java.security.Principal;
  19. import java.text.MessageFormat;
  20. import java.util.*;
  21. import java.util.concurrent.TimeUnit;
  22. import javax.servlet.http.Cookie;
  23. import javax.servlet.http.HttpServletRequest;
  24. import javax.servlet.http.HttpServletResponse;
  25. import javax.servlet.http.HttpSession;
  26. import org.slf4j.Logger;
  27. import org.slf4j.LoggerFactory;
  28. import com.gitblit.Constants;
  29. import com.gitblit.Constants.AccountType;
  30. import com.gitblit.Constants.AuthenticationType;
  31. import com.gitblit.Constants.Role;
  32. import com.gitblit.IStoredSettings;
  33. import com.gitblit.Keys;
  34. import com.gitblit.auth.AuthenticationProvider;
  35. import com.gitblit.auth.AuthenticationProvider.UsernamePasswordAuthenticationProvider;
  36. import com.gitblit.auth.HtpasswdAuthProvider;
  37. import com.gitblit.auth.HttpHeaderAuthProvider;
  38. import com.gitblit.auth.LdapAuthProvider;
  39. import com.gitblit.auth.PAMAuthProvider;
  40. import com.gitblit.auth.RedmineAuthProvider;
  41. import com.gitblit.auth.SalesforceAuthProvider;
  42. import com.gitblit.auth.WindowsAuthProvider;
  43. import com.gitblit.models.TeamModel;
  44. import com.gitblit.models.UserModel;
  45. import com.gitblit.transport.ssh.SshKey;
  46. import com.gitblit.utils.Base64;
  47. import com.gitblit.utils.HttpUtils;
  48. import com.gitblit.utils.PasswordHash;
  49. import com.gitblit.utils.StringUtils;
  50. import com.gitblit.utils.X509Utils.X509Metadata;
  51. import com.google.inject.Inject;
  52. import com.google.inject.Singleton;
  53. /**
  54. * The authentication manager handles user login & logout.
  55. *
  56. * @author James Moger
  57. *
  58. */
  59. @Singleton
  60. public class AuthenticationManager implements IAuthenticationManager {
  61. private final Logger logger = LoggerFactory.getLogger(getClass());
  62. private final IStoredSettings settings;
  63. private final IRuntimeManager runtimeManager;
  64. private final IUserManager userManager;
  65. private final List<AuthenticationProvider> authenticationProviders;
  66. private final Map<String, Class<? extends AuthenticationProvider>> providerNames;
  67. private final Map<String, String> legacyRedirects;
  68. @Inject
  69. public AuthenticationManager(
  70. IRuntimeManager runtimeManager,
  71. IUserManager userManager) {
  72. this.settings = runtimeManager.getSettings();
  73. this.runtimeManager = runtimeManager;
  74. this.userManager = userManager;
  75. this.authenticationProviders = new ArrayList<AuthenticationProvider>();
  76. // map of shortcut provider names
  77. providerNames = new HashMap<String, Class<? extends AuthenticationProvider>>();
  78. providerNames.put("htpasswd", HtpasswdAuthProvider.class);
  79. providerNames.put("httpheader", HttpHeaderAuthProvider.class);
  80. providerNames.put("ldap", LdapAuthProvider.class);
  81. providerNames.put("pam", PAMAuthProvider.class);
  82. providerNames.put("redmine", RedmineAuthProvider.class);
  83. providerNames.put("salesforce", SalesforceAuthProvider.class);
  84. providerNames.put("windows", WindowsAuthProvider.class);
  85. // map of legacy external user services
  86. legacyRedirects = new HashMap<String, String>();
  87. legacyRedirects.put("com.gitblit.HtpasswdUserService", "htpasswd");
  88. legacyRedirects.put("com.gitblit.LdapUserService", "ldap");
  89. legacyRedirects.put("com.gitblit.PAMUserService", "pam");
  90. legacyRedirects.put("com.gitblit.RedmineUserService", "redmine");
  91. legacyRedirects.put("com.gitblit.SalesforceUserService", "salesforce");
  92. legacyRedirects.put("com.gitblit.WindowsUserService", "windows");
  93. }
  94. @Override
  95. public AuthenticationManager start() {
  96. // automatically adjust legacy configurations
  97. String realm = settings.getString(Keys.realm.userService, "${baseFolder}/users.conf");
  98. if (legacyRedirects.containsKey(realm)) {
  99. logger.warn("");
  100. logger.warn(Constants.BORDER2);
  101. logger.warn(" IUserService '{}' is obsolete!", realm);
  102. logger.warn(" Please set '{}={}'", "realm.authenticationProviders", legacyRedirects.get(realm));
  103. logger.warn(Constants.BORDER2);
  104. logger.warn("");
  105. // conditionally override specified authentication providers
  106. if (StringUtils.isEmpty(settings.getString(Keys.realm.authenticationProviders, null))) {
  107. settings.overrideSetting(Keys.realm.authenticationProviders, legacyRedirects.get(realm));
  108. }
  109. }
  110. // instantiate and setup specified authentication providers
  111. List<String> providers = settings.getStrings(Keys.realm.authenticationProviders);
  112. if (providers.isEmpty()) {
  113. logger.info("External authentication disabled.");
  114. } else {
  115. for (String provider : providers) {
  116. try {
  117. Class<?> authClass;
  118. if (providerNames.containsKey(provider)) {
  119. // map the name -> class
  120. authClass = providerNames.get(provider);
  121. } else {
  122. // reflective lookup
  123. authClass = Class.forName(provider);
  124. }
  125. logger.info("setting up {}", authClass.getName());
  126. AuthenticationProvider authImpl = (AuthenticationProvider) authClass.newInstance();
  127. authImpl.setup(runtimeManager, userManager);
  128. authenticationProviders.add(authImpl);
  129. } catch (Exception e) {
  130. logger.error("", e);
  131. }
  132. }
  133. }
  134. return this;
  135. }
  136. @Override
  137. public AuthenticationManager stop() {
  138. for (AuthenticationProvider provider : authenticationProviders) {
  139. try {
  140. provider.stop();
  141. } catch (Exception e) {
  142. logger.error("Failed to stop " + provider.getClass().getSimpleName(), e);
  143. }
  144. }
  145. return this;
  146. }
  147. public void addAuthenticationProvider(AuthenticationProvider prov) {
  148. authenticationProviders.add(prov);
  149. }
  150. /**
  151. * Used to handle authentication for page requests.
  152. *
  153. * This allows authentication to occur based on the contents of the request
  154. * itself. If no configured @{AuthenticationProvider}s authenticate succesffully,
  155. * a request for login will be shown.
  156. *
  157. * Authentication by X509Certificate is tried first and then by cookie.
  158. *
  159. * @param httpRequest
  160. * @return a user object or null
  161. */
  162. @Override
  163. public UserModel authenticate(HttpServletRequest httpRequest) {
  164. return authenticate(httpRequest, false);
  165. }
  166. /**
  167. * Authenticate a user based on HTTP request parameters.
  168. *
  169. * Authentication by custom HTTP header, servlet container principal, X509Certificate, cookie,
  170. * and finally BASIC header.
  171. *
  172. * @param httpRequest
  173. * @param requiresCertificate
  174. * @return a user object or null
  175. */
  176. @Override
  177. public UserModel authenticate(HttpServletRequest httpRequest, boolean requiresCertificate) {
  178. // Check if this request has already been authenticated, and trust that instead of re-processing
  179. String reqAuthUser = (String) httpRequest.getAttribute(Constants.ATTRIB_AUTHUSER);
  180. if (!StringUtils.isEmpty(reqAuthUser)) {
  181. logger.debug("Called servlet authenticate when request is already authenticated.");
  182. return userManager.getUserModel(reqAuthUser);
  183. }
  184. // try to authenticate by servlet container principal
  185. if (!requiresCertificate) {
  186. Principal principal = httpRequest.getUserPrincipal();
  187. if (principal != null) {
  188. String username = principal.getName();
  189. if (!StringUtils.isEmpty(username)) {
  190. boolean internalAccount = userManager.isInternalAccount(username);
  191. UserModel user = userManager.getUserModel(username);
  192. if (user != null) {
  193. // existing user
  194. flagRequest(httpRequest, AuthenticationType.CONTAINER, user.username);
  195. logger.debug(MessageFormat.format("{0} authenticated by servlet container principal from {1}",
  196. user.username, httpRequest.getRemoteAddr()));
  197. return validateAuthentication(user, AuthenticationType.CONTAINER);
  198. } else if (settings.getBoolean(Keys.realm.container.autoCreateAccounts, false)
  199. && !internalAccount) {
  200. // auto-create user from an authenticated container principal
  201. user = new UserModel(username.toLowerCase());
  202. user.displayName = username;
  203. user.password = Constants.EXTERNAL_ACCOUNT;
  204. user.accountType = AccountType.CONTAINER;
  205. // Try to extract user's informations for the session
  206. // it uses "realm.container.autoAccounts.*" as the attribute name to look for
  207. HttpSession session = httpRequest.getSession();
  208. String emailAddress = resolveAttribute(session, Keys.realm.container.autoAccounts.emailAddress);
  209. if(emailAddress != null) {
  210. user.emailAddress = emailAddress;
  211. }
  212. String displayName = resolveAttribute(session, Keys.realm.container.autoAccounts.displayName);
  213. if(displayName != null) {
  214. user.displayName = displayName;
  215. }
  216. String userLocale = resolveAttribute(session, Keys.realm.container.autoAccounts.locale);
  217. if(userLocale != null) {
  218. user.getPreferences().setLocale(userLocale);
  219. }
  220. String adminRole = settings.getString(Keys.realm.container.autoAccounts.adminRole, null);
  221. if(adminRole != null && ! adminRole.isEmpty()) {
  222. if(httpRequest.isUserInRole(adminRole)) {
  223. user.canAdmin = true;
  224. }
  225. }
  226. userManager.updateUserModel(user);
  227. flagRequest(httpRequest, AuthenticationType.CONTAINER, user.username);
  228. logger.debug(MessageFormat.format("{0} authenticated and created by servlet container principal from {1}",
  229. user.username, httpRequest.getRemoteAddr()));
  230. return validateAuthentication(user, AuthenticationType.CONTAINER);
  231. } else if (!internalAccount) {
  232. logger.warn(MessageFormat.format("Failed to find UserModel for {0}, attempted servlet container authentication from {1}",
  233. principal.getName(), httpRequest.getRemoteAddr()));
  234. }
  235. }
  236. }
  237. }
  238. // try to authenticate by certificate
  239. boolean checkValidity = settings.getBoolean(Keys.git.enforceCertificateValidity, true);
  240. String [] oids = settings.getStrings(Keys.git.certificateUsernameOIDs).toArray(new String[0]);
  241. UserModel model = HttpUtils.getUserModelFromCertificate(httpRequest, checkValidity, oids);
  242. if (model != null) {
  243. // grab real user model and preserve certificate serial number
  244. UserModel user = userManager.getUserModel(model.username);
  245. X509Metadata metadata = HttpUtils.getCertificateMetadata(httpRequest);
  246. if (user != null) {
  247. flagRequest(httpRequest, AuthenticationType.CERTIFICATE, user.username);
  248. logger.debug(MessageFormat.format("{0} authenticated by client certificate {1} from {2}",
  249. user.username, metadata.serialNumber, httpRequest.getRemoteAddr()));
  250. return validateAuthentication(user, AuthenticationType.CERTIFICATE);
  251. } else {
  252. logger.warn(MessageFormat.format("Failed to find UserModel for {0}, attempted client certificate ({1}) authentication from {2}",
  253. model.username, metadata.serialNumber, httpRequest.getRemoteAddr()));
  254. }
  255. }
  256. if (requiresCertificate) {
  257. // caller requires client certificate authentication (e.g. git servlet)
  258. return null;
  259. }
  260. UserModel user = null;
  261. // try to authenticate by cookie
  262. String cookie = getCookie(httpRequest);
  263. if (!StringUtils.isEmpty(cookie)) {
  264. user = userManager.getUserModel(cookie.toCharArray());
  265. if (user != null) {
  266. flagRequest(httpRequest, AuthenticationType.COOKIE, user.username);
  267. logger.debug(MessageFormat.format("{0} authenticated by cookie from {1}",
  268. user.username, httpRequest.getRemoteAddr()));
  269. return validateAuthentication(user, AuthenticationType.COOKIE);
  270. }
  271. }
  272. // try to authenticate by BASIC
  273. final String authorization = httpRequest.getHeader("Authorization");
  274. if (authorization != null && authorization.startsWith("Basic")) {
  275. // Authorization: Basic base64credentials
  276. String base64Credentials = authorization.substring("Basic".length()).trim();
  277. String credentials = new String(Base64.decode(base64Credentials),
  278. Charset.forName("UTF-8"));
  279. // credentials = username:password
  280. final String[] values = credentials.split(":", 2);
  281. if (values.length == 2) {
  282. String username = values[0];
  283. char[] password = values[1].toCharArray();
  284. user = authenticate(username, password, httpRequest.getRemoteAddr());
  285. if (user != null) {
  286. flagRequest(httpRequest, AuthenticationType.CREDENTIALS, user.username);
  287. logger.debug(MessageFormat.format("{0} authenticated by BASIC request header from {1}",
  288. user.username, httpRequest.getRemoteAddr()));
  289. return validateAuthentication(user, AuthenticationType.CREDENTIALS);
  290. }
  291. }
  292. }
  293. // Check each configured AuthenticationProvider
  294. for (AuthenticationProvider ap : authenticationProviders) {
  295. UserModel authedUser = ap.authenticate(httpRequest);
  296. if (null != authedUser) {
  297. flagRequest(httpRequest, ap.getAuthenticationType(), authedUser.username);
  298. logger.debug(MessageFormat.format("{0} authenticated by {1} from {2} for {3}",
  299. authedUser.username, ap.getServiceName(), httpRequest.getRemoteAddr(),
  300. httpRequest.getPathInfo()));
  301. return validateAuthentication(authedUser, ap.getAuthenticationType());
  302. }
  303. }
  304. return null;
  305. }
  306. /**
  307. * Extract given attribute from the session and return it's content
  308. * it return null if attributeMapping is empty, or if the value is
  309. * empty
  310. *
  311. * @param session The user session
  312. * @param attributeMapping
  313. * @return
  314. */
  315. private String resolveAttribute(HttpSession session, String attributeMapping) {
  316. String attributeName = settings.getString(attributeMapping, null);
  317. if(StringUtils.isEmpty(attributeName)) {
  318. return null;
  319. }
  320. Object attributeValue = session.getAttribute(attributeName);
  321. if(attributeValue == null) {
  322. return null;
  323. }
  324. String value = attributeValue.toString();
  325. if(value.isEmpty()) {
  326. return null;
  327. }
  328. return value;
  329. }
  330. /**
  331. * Authenticate a user based on a public key.
  332. *
  333. * This implementation assumes that the authentication has already take place
  334. * (e.g. SSHDaemon) and that this is a validation/verification of the user.
  335. *
  336. * @param username
  337. * @param key
  338. * @return a user object or null
  339. */
  340. @Override
  341. public UserModel authenticate(String username, SshKey key) {
  342. if (username != null) {
  343. if (!StringUtils.isEmpty(username)) {
  344. UserModel user = userManager.getUserModel(username);
  345. if (user != null) {
  346. // existing user
  347. logger.debug(MessageFormat.format("{0} authenticated by {1} public key",
  348. user.username, key.getAlgorithm()));
  349. return validateAuthentication(user, AuthenticationType.PUBLIC_KEY);
  350. }
  351. logger.warn(MessageFormat.format("Failed to find UserModel for {0} during public key authentication",
  352. username));
  353. }
  354. } else {
  355. logger.warn("Empty user passed to AuthenticationManager.authenticate!");
  356. }
  357. return null;
  358. }
  359. /**
  360. * Return the UserModel for already authenticated user.
  361. *
  362. * This implementation assumes that the authentication has already take place
  363. * (e.g. SSHDaemon) and that this is a validation/verification of the user.
  364. *
  365. * @param username
  366. * @return a user object or null
  367. */
  368. @Override
  369. public UserModel authenticate(String username) {
  370. if (username != null) {
  371. if (!StringUtils.isEmpty(username)) {
  372. UserModel user = userManager.getUserModel(username);
  373. if (user != null) {
  374. // existing user
  375. logger.debug(MessageFormat.format("{0} authenticated externally", user.username));
  376. return validateAuthentication(user, AuthenticationType.CONTAINER);
  377. }
  378. logger.warn(MessageFormat.format("Failed to find UserModel for {0} during external authentication",
  379. username));
  380. }
  381. } else {
  382. logger.warn("Empty user passed to AuthenticationManager.authenticate!");
  383. }
  384. return null;
  385. }
  386. /**
  387. * This method allows the authentication manager to reject authentication
  388. * attempts. It is called after the username/secret have been verified to
  389. * ensure that the authentication technique has been logged.
  390. *
  391. * @param user
  392. * @return
  393. */
  394. protected UserModel validateAuthentication(UserModel user, AuthenticationType type) {
  395. if (user == null) {
  396. return null;
  397. }
  398. if (user.disabled) {
  399. // user has been disabled
  400. logger.warn("Rejected {} authentication attempt by disabled account \"{}\"",
  401. type, user.username);
  402. return null;
  403. }
  404. return user;
  405. }
  406. protected void flagRequest(HttpServletRequest httpRequest, AuthenticationType authenticationType, String authedUsername) {
  407. httpRequest.setAttribute(Constants.ATTRIB_AUTHUSER, authedUsername);
  408. httpRequest.setAttribute(Constants.ATTRIB_AUTHTYPE, authenticationType);
  409. }
  410. /**
  411. * Authenticate a user based on a username and password.
  412. *
  413. * @see IUserService.authenticate(String, char[])
  414. * @param username
  415. * @param password
  416. * @return a user object or null
  417. */
  418. @Override
  419. public UserModel authenticate(String username, char[] password, String remoteIP) {
  420. if (StringUtils.isEmpty(username)) {
  421. // can not authenticate empty username
  422. return null;
  423. }
  424. if (username.equalsIgnoreCase(Constants.FEDERATION_USER)) {
  425. // can not authenticate internal FEDERATION_USER at this point
  426. // it must be routed to FederationManager
  427. return null;
  428. }
  429. String usernameDecoded = StringUtils.decodeUsername(username);
  430. String pw = new String(password);
  431. if (StringUtils.isEmpty(pw)) {
  432. // can not authenticate empty password
  433. return null;
  434. }
  435. UserModel user = userManager.getUserModel(usernameDecoded);
  436. // try local authentication
  437. if (user != null && user.isLocalAccount()) {
  438. UserModel returnedUser = authenticateLocal(user, password);
  439. if (returnedUser != null) {
  440. // user authenticated
  441. return returnedUser;
  442. }
  443. } else {
  444. // try registered external authentication providers
  445. for (AuthenticationProvider provider : authenticationProviders) {
  446. if (provider instanceof UsernamePasswordAuthenticationProvider) {
  447. UserModel returnedUser = provider.authenticate(usernameDecoded, password);
  448. if (returnedUser != null) {
  449. // user authenticated
  450. returnedUser.accountType = provider.getAccountType();
  451. return validateAuthentication(returnedUser, AuthenticationType.CREDENTIALS);
  452. }
  453. }
  454. }
  455. }
  456. // could not authenticate locally or with a provider
  457. logger.warn(MessageFormat.format("Failed login attempt for {0}, invalid credentials from {1}", username,
  458. remoteIP != null ? remoteIP : "unknown"));
  459. return null;
  460. }
  461. /**
  462. * Returns a UserModel if local authentication succeeds.
  463. *
  464. * @param user
  465. * @param password
  466. * @return a UserModel if local authentication succeeds, null otherwise
  467. */
  468. protected UserModel authenticateLocal(UserModel user, char [] password) {
  469. UserModel returnedUser = null;
  470. // Create a copy of the password that we can use to rehash to upgrade to a more secure hashing method.
  471. // This is done to be independent from the implementation of the PasswordHash, which might already clear out
  472. // the password it gets passed in. This looks a bit stupid, as we could simply clean up the mess, but this
  473. // falls under "better safe than sorry".
  474. char[] pwdToUpgrade = Arrays.copyOf(password, password.length);
  475. try {
  476. PasswordHash pwdHash = PasswordHash.instanceFor(user.password);
  477. if (pwdHash != null) {
  478. if (pwdHash.matches(user.password, password, user.username)) {
  479. returnedUser = user;
  480. }
  481. } else if (user.password.equals(new String(password))) {
  482. // plain-text password
  483. returnedUser = user;
  484. }
  485. // validate user
  486. returnedUser = validateAuthentication(returnedUser, AuthenticationType.CREDENTIALS);
  487. // try to upgrade the stored password hash to a stronger hash, if necessary
  488. upgradeStoredPassword(returnedUser, pwdToUpgrade, pwdHash);
  489. }
  490. finally {
  491. // Now we make sure that the password is zeroed out in any case.
  492. Arrays.fill(password, Character.MIN_VALUE);
  493. Arrays.fill(pwdToUpgrade, Character.MIN_VALUE);
  494. }
  495. return returnedUser;
  496. }
  497. /**
  498. * Upgrade stored password to a strong hash if configured.
  499. *
  500. * @param user the user to be updated
  501. * @param password the password
  502. * @param pwdHash
  503. * Instance of PasswordHash for the stored password entry. If null, no current hashing is assumed.
  504. */
  505. private void upgradeStoredPassword(UserModel user, char[] password, PasswordHash pwdHash) {
  506. // check if user has successfully authenticated i.e. is not null
  507. if (user == null) return;
  508. // check if strong hash algorithm is configured
  509. String algorithm = settings.getString(Keys.realm.passwordStorage, PasswordHash.getDefaultType().name());
  510. if (pwdHash == null || pwdHash.needsUpgradeTo(algorithm)) {
  511. // rehash the provided correct password and update the user model
  512. pwdHash = PasswordHash.instanceOf(algorithm);
  513. if (pwdHash != null) { // necessary since the algorithm name could be something not supported.
  514. user.password = pwdHash.toHashedEntry(password, user.username);
  515. userManager.updateUserModel(user);
  516. }
  517. }
  518. }
  519. /**
  520. * Returns the Gitlbit cookie in the request.
  521. *
  522. * @param request
  523. * @return the Gitblit cookie for the request or null if not found
  524. */
  525. @Override
  526. public String getCookie(HttpServletRequest request) {
  527. if (settings.getBoolean(Keys.web.allowCookieAuthentication, true)) {
  528. Cookie[] cookies = request.getCookies();
  529. if (cookies != null && cookies.length > 0) {
  530. for (Cookie cookie : cookies) {
  531. if (cookie.getName().equals(Constants.NAME)) {
  532. String value = cookie.getValue();
  533. return value;
  534. }
  535. }
  536. }
  537. }
  538. return null;
  539. }
  540. /**
  541. * Sets a cookie for the specified user.
  542. *
  543. * @param response
  544. * @param user
  545. */
  546. @Override
  547. @Deprecated
  548. public void setCookie(HttpServletResponse response, UserModel user) {
  549. setCookie(null, response, user);
  550. }
  551. /**
  552. * Sets a cookie for the specified user.
  553. *
  554. * @param request
  555. * @param response
  556. * @param user
  557. */
  558. @Override
  559. public void setCookie(HttpServletRequest request, HttpServletResponse response, UserModel user) {
  560. if (settings.getBoolean(Keys.web.allowCookieAuthentication, true)) {
  561. boolean standardLogin = true;
  562. if (null != request) {
  563. // Pull the auth type from the request, it is set there if container managed
  564. AuthenticationType authenticationType = (AuthenticationType) request.getAttribute(Constants.ATTRIB_AUTHTYPE);
  565. if (null != authenticationType)
  566. standardLogin = authenticationType.isStandard();
  567. }
  568. if (standardLogin) {
  569. Cookie userCookie;
  570. if (user == null) {
  571. // clear cookie for logout
  572. userCookie = new Cookie(Constants.NAME, "");
  573. } else {
  574. // set cookie for login
  575. String cookie = userManager.getCookie(user);
  576. if (StringUtils.isEmpty(cookie)) {
  577. // create empty cookie
  578. userCookie = new Cookie(Constants.NAME, "");
  579. } else {
  580. // create real cookie
  581. userCookie = new Cookie(Constants.NAME, cookie);
  582. // expire the cookie in 7 days
  583. userCookie.setMaxAge((int) TimeUnit.DAYS.toSeconds(7));
  584. // Set cookies HttpOnly so they are not accessible to JavaScript engines
  585. userCookie.setHttpOnly(true);
  586. // Set secure cookie if only HTTPS is used
  587. userCookie.setSecure(httpsOnly());
  588. }
  589. }
  590. String path = "/";
  591. if (request != null) {
  592. if (!StringUtils.isEmpty(request.getContextPath())) {
  593. path = request.getContextPath();
  594. }
  595. }
  596. userCookie.setPath(path);
  597. response.addCookie(userCookie);
  598. }
  599. }
  600. }
  601. private boolean httpsOnly() {
  602. int port = settings.getInteger(Keys.server.httpPort, 0);
  603. int tlsPort = settings.getInteger(Keys.server.httpsPort, 0);
  604. return (port <= 0 && tlsPort > 0) ||
  605. (port > 0 && tlsPort > 0 && settings.getBoolean(Keys.server.redirectToHttpsPort, true) );
  606. }
  607. /**
  608. * Logout a user.
  609. *
  610. * @param response
  611. * @param user
  612. */
  613. @Override
  614. @Deprecated
  615. public void logout(HttpServletResponse response, UserModel user) {
  616. setCookie(null, response, null);
  617. }
  618. /**
  619. * Logout a user.
  620. *
  621. * @param request
  622. * @param response
  623. * @param user
  624. */
  625. @Override
  626. public void logout(HttpServletRequest request, HttpServletResponse response, UserModel user) {
  627. setCookie(request, response, null);
  628. }
  629. /**
  630. * Returns true if the user's credentials can be changed.
  631. *
  632. * @param user
  633. * @return true if the user service supports credential changes
  634. */
  635. @Override
  636. public boolean supportsCredentialChanges(UserModel user) {
  637. return (user != null && user.isLocalAccount()) || findProvider(user).supportsCredentialChanges();
  638. }
  639. /**
  640. * Returns true if the user's display name can be changed.
  641. *
  642. * @param user
  643. * @return true if the user service supports display name changes
  644. */
  645. @Override
  646. public boolean supportsDisplayNameChanges(UserModel user) {
  647. return (user != null && user.isLocalAccount()) || findProvider(user).supportsDisplayNameChanges();
  648. }
  649. /**
  650. * Returns true if the user's email address can be changed.
  651. *
  652. * @param user
  653. * @return true if the user service supports email address changes
  654. */
  655. @Override
  656. public boolean supportsEmailAddressChanges(UserModel user) {
  657. return (user != null && user.isLocalAccount()) || findProvider(user).supportsEmailAddressChanges();
  658. }
  659. /**
  660. * Returns true if the user's team memberships can be changed.
  661. *
  662. * @param user
  663. * @return true if the user service supports team membership changes
  664. */
  665. @Override
  666. public boolean supportsTeamMembershipChanges(UserModel user) {
  667. return (user != null && user.isLocalAccount()) || findProvider(user).supportsTeamMembershipChanges();
  668. }
  669. /**
  670. * Returns true if the team memberships can be changed.
  671. *
  672. * @param user
  673. * @return true if the team membership can be changed
  674. */
  675. @Override
  676. public boolean supportsTeamMembershipChanges(TeamModel team) {
  677. return (team != null && team.isLocalTeam()) || findProvider(team).supportsTeamMembershipChanges();
  678. }
  679. /**
  680. * Returns true if the user's role can be changed.
  681. *
  682. * @param user
  683. * @return true if the user's role can be changed
  684. */
  685. @Override
  686. public boolean supportsRoleChanges(UserModel user, Role role) {
  687. return (user != null && user.isLocalAccount()) || findProvider(user).supportsRoleChanges(user, role);
  688. }
  689. /**
  690. * Returns true if the team's role can be changed.
  691. *
  692. * @param user
  693. * @return true if the team's role can be changed
  694. */
  695. @Override
  696. public boolean supportsRoleChanges(TeamModel team, Role role) {
  697. return (team != null && team.isLocalTeam()) || findProvider(team).supportsRoleChanges(team, role);
  698. }
  699. protected AuthenticationProvider findProvider(UserModel user) {
  700. for (AuthenticationProvider provider : authenticationProviders) {
  701. if (provider.getAccountType().equals(user.accountType)) {
  702. return provider;
  703. }
  704. }
  705. return AuthenticationProvider.NULL_PROVIDER;
  706. }
  707. protected AuthenticationProvider findProvider(TeamModel team) {
  708. for (AuthenticationProvider provider : authenticationProviders) {
  709. if (provider.getAccountType().equals(team.accountType)) {
  710. return provider;
  711. }
  712. }
  713. return AuthenticationProvider.NULL_PROVIDER;
  714. }
  715. }