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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  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. * @param username
  414. * @param password
  415. * @return a user object or null
  416. */
  417. @Override
  418. public UserModel authenticate(String username, char[] password, String remoteIP) {
  419. if (StringUtils.isEmpty(username)) {
  420. // can not authenticate empty username
  421. return null;
  422. }
  423. if (username.equalsIgnoreCase(Constants.FEDERATION_USER)) {
  424. // can not authenticate internal FEDERATION_USER at this point
  425. // it must be routed to FederationManager
  426. return null;
  427. }
  428. String usernameDecoded = StringUtils.decodeUsername(username);
  429. if (StringUtils.isEmpty(password)) {
  430. // can not authenticate empty password
  431. return null;
  432. }
  433. UserModel user = userManager.getUserModel(usernameDecoded);
  434. try {
  435. // try local authentication
  436. if (user != null && user.isLocalAccount()) {
  437. UserModel returnedUser = authenticateLocal(user, password);
  438. if (returnedUser != null) {
  439. // user authenticated
  440. return returnedUser;
  441. }
  442. } else {
  443. // try registered external authentication providers
  444. for (AuthenticationProvider provider : authenticationProviders) {
  445. if (provider instanceof UsernamePasswordAuthenticationProvider) {
  446. UserModel returnedUser = provider.authenticate(usernameDecoded, password);
  447. if (returnedUser != null) {
  448. // user authenticated
  449. returnedUser.accountType = provider.getAccountType();
  450. return validateAuthentication(returnedUser, AuthenticationType.CREDENTIALS);
  451. }
  452. }
  453. }
  454. }
  455. }
  456. finally {
  457. // Zero out password array to delete password from memory
  458. Arrays.fill(password, Character.MIN_VALUE);
  459. }
  460. // could not authenticate locally or with a provider
  461. logger.warn(MessageFormat.format("Failed login attempt for {0}, invalid credentials from {1}", username,
  462. remoteIP != null ? remoteIP : "unknown"));
  463. return null;
  464. }
  465. /**
  466. * Returns a UserModel if local authentication succeeds.
  467. *
  468. * @param user
  469. * @param password
  470. * @return a UserModel if local authentication succeeds, null otherwise
  471. */
  472. protected UserModel authenticateLocal(UserModel user, char [] password) {
  473. UserModel returnedUser = null;
  474. // Create a copy of the password that we can use to rehash to upgrade to a more secure hashing method.
  475. // This is done to be independent from the implementation of the PasswordHash, which might already clear out
  476. // the password it gets passed in. This looks a bit stupid, as we could simply clean up the mess, but this
  477. // falls under "better safe than sorry".
  478. char[] pwdToUpgrade = Arrays.copyOf(password, password.length);
  479. try {
  480. PasswordHash pwdHash = PasswordHash.instanceFor(user.password);
  481. if (pwdHash != null) {
  482. if (pwdHash.matches(user.password, password, user.username)) {
  483. returnedUser = user;
  484. }
  485. } else if (user.password.equals(new String(password))) {
  486. // plain-text password
  487. returnedUser = user;
  488. }
  489. // validate user
  490. returnedUser = validateAuthentication(returnedUser, AuthenticationType.CREDENTIALS);
  491. // try to upgrade the stored password hash to a stronger hash, if necessary
  492. upgradeStoredPassword(returnedUser, pwdToUpgrade, pwdHash);
  493. }
  494. finally {
  495. // Now we make sure that the password is zeroed out in any case.
  496. Arrays.fill(password, Character.MIN_VALUE);
  497. Arrays.fill(pwdToUpgrade, Character.MIN_VALUE);
  498. }
  499. return returnedUser;
  500. }
  501. /**
  502. * Upgrade stored password to a strong hash if configured.
  503. *
  504. * @param user the user to be updated
  505. * @param password the password
  506. * @param pwdHash
  507. * Instance of PasswordHash for the stored password entry. If null, no current hashing is assumed.
  508. */
  509. private void upgradeStoredPassword(UserModel user, char[] password, PasswordHash pwdHash) {
  510. // check if user has successfully authenticated i.e. is not null
  511. if (user == null) return;
  512. // check if strong hash algorithm is configured
  513. String algorithm = settings.getString(Keys.realm.passwordStorage, PasswordHash.getDefaultType().name());
  514. if (pwdHash == null || pwdHash.needsUpgradeTo(algorithm)) {
  515. // rehash the provided correct password and update the user model
  516. pwdHash = PasswordHash.instanceOf(algorithm);
  517. if (pwdHash != null) { // necessary since the algorithm name could be something not supported.
  518. user.password = pwdHash.toHashedEntry(password, user.username);
  519. userManager.updateUserModel(user);
  520. }
  521. }
  522. }
  523. /**
  524. * Returns the Gitlbit cookie in the request.
  525. *
  526. * @param request
  527. * @return the Gitblit cookie for the request or null if not found
  528. */
  529. @Override
  530. public String getCookie(HttpServletRequest request) {
  531. if (settings.getBoolean(Keys.web.allowCookieAuthentication, true)) {
  532. Cookie[] cookies = request.getCookies();
  533. if (cookies != null && cookies.length > 0) {
  534. for (Cookie cookie : cookies) {
  535. if (cookie.getName().equals(Constants.NAME)) {
  536. String value = cookie.getValue();
  537. return value;
  538. }
  539. }
  540. }
  541. }
  542. return null;
  543. }
  544. /**
  545. * Sets a cookie for the specified user.
  546. *
  547. * @param response
  548. * @param user
  549. */
  550. @Override
  551. @Deprecated
  552. public void setCookie(HttpServletResponse response, UserModel user) {
  553. setCookie(null, response, user);
  554. }
  555. /**
  556. * Sets a cookie for the specified user.
  557. *
  558. * @param request
  559. * @param response
  560. * @param user
  561. */
  562. @Override
  563. public void setCookie(HttpServletRequest request, HttpServletResponse response, UserModel user) {
  564. if (settings.getBoolean(Keys.web.allowCookieAuthentication, true)) {
  565. boolean standardLogin = true;
  566. if (null != request) {
  567. // Pull the auth type from the request, it is set there if container managed
  568. AuthenticationType authenticationType = (AuthenticationType) request.getAttribute(Constants.ATTRIB_AUTHTYPE);
  569. if (null != authenticationType)
  570. standardLogin = authenticationType.isStandard();
  571. }
  572. if (standardLogin) {
  573. Cookie userCookie;
  574. if (user == null) {
  575. // clear cookie for logout
  576. userCookie = new Cookie(Constants.NAME, "");
  577. } else {
  578. // set cookie for login
  579. String cookie = userManager.getCookie(user);
  580. if (StringUtils.isEmpty(cookie)) {
  581. // create empty cookie
  582. userCookie = new Cookie(Constants.NAME, "");
  583. } else {
  584. // create real cookie
  585. userCookie = new Cookie(Constants.NAME, cookie);
  586. // expire the cookie in 7 days
  587. userCookie.setMaxAge((int) TimeUnit.DAYS.toSeconds(7));
  588. // Set cookies HttpOnly so they are not accessible to JavaScript engines
  589. userCookie.setHttpOnly(true);
  590. // Set secure cookie if only HTTPS is used
  591. userCookie.setSecure(httpsOnly());
  592. }
  593. }
  594. String path = "/";
  595. if (request != null) {
  596. if (!StringUtils.isEmpty(request.getContextPath())) {
  597. path = request.getContextPath();
  598. }
  599. }
  600. userCookie.setPath(path);
  601. response.addCookie(userCookie);
  602. }
  603. }
  604. }
  605. private boolean httpsOnly() {
  606. int port = settings.getInteger(Keys.server.httpPort, 0);
  607. int tlsPort = settings.getInteger(Keys.server.httpsPort, 0);
  608. return (port <= 0 && tlsPort > 0) ||
  609. (port > 0 && tlsPort > 0 && settings.getBoolean(Keys.server.redirectToHttpsPort, true) );
  610. }
  611. /**
  612. * Logout a user.
  613. *
  614. * @param response
  615. * @param user
  616. */
  617. @Override
  618. @Deprecated
  619. public void logout(HttpServletResponse response, UserModel user) {
  620. setCookie(null, response, null);
  621. }
  622. /**
  623. * Logout a user.
  624. *
  625. * @param request
  626. * @param response
  627. * @param user
  628. */
  629. @Override
  630. public void logout(HttpServletRequest request, HttpServletResponse response, UserModel user) {
  631. setCookie(request, response, null);
  632. }
  633. /**
  634. * Returns true if the user's credentials can be changed.
  635. *
  636. * @param user
  637. * @return true if the user service supports credential changes
  638. */
  639. @Override
  640. public boolean supportsCredentialChanges(UserModel user) {
  641. return (user != null && user.isLocalAccount()) || findProvider(user).supportsCredentialChanges();
  642. }
  643. /**
  644. * Returns true if the user's display name can be changed.
  645. *
  646. * @param user
  647. * @return true if the user service supports display name changes
  648. */
  649. @Override
  650. public boolean supportsDisplayNameChanges(UserModel user) {
  651. return (user != null && user.isLocalAccount()) || findProvider(user).supportsDisplayNameChanges();
  652. }
  653. /**
  654. * Returns true if the user's email address can be changed.
  655. *
  656. * @param user
  657. * @return true if the user service supports email address changes
  658. */
  659. @Override
  660. public boolean supportsEmailAddressChanges(UserModel user) {
  661. return (user != null && user.isLocalAccount()) || findProvider(user).supportsEmailAddressChanges();
  662. }
  663. /**
  664. * Returns true if the user's team memberships can be changed.
  665. *
  666. * @param user
  667. * @return true if the user service supports team membership changes
  668. */
  669. @Override
  670. public boolean supportsTeamMembershipChanges(UserModel user) {
  671. return (user != null && user.isLocalAccount()) || findProvider(user).supportsTeamMembershipChanges();
  672. }
  673. /**
  674. * Returns true if the team memberships can be changed.
  675. *
  676. * @param user
  677. * @return true if the team membership can be changed
  678. */
  679. @Override
  680. public boolean supportsTeamMembershipChanges(TeamModel team) {
  681. return (team != null && team.isLocalTeam()) || findProvider(team).supportsTeamMembershipChanges();
  682. }
  683. /**
  684. * Returns true if the user's role can be changed.
  685. *
  686. * @param user
  687. * @return true if the user's role can be changed
  688. */
  689. @Override
  690. public boolean supportsRoleChanges(UserModel user, Role role) {
  691. return (user != null && user.isLocalAccount()) || findProvider(user).supportsRoleChanges(user, role);
  692. }
  693. /**
  694. * Returns true if the team's role can be changed.
  695. *
  696. * @param user
  697. * @return true if the team's role can be changed
  698. */
  699. @Override
  700. public boolean supportsRoleChanges(TeamModel team, Role role) {
  701. return (team != null && team.isLocalTeam()) || findProvider(team).supportsRoleChanges(team, role);
  702. }
  703. protected AuthenticationProvider findProvider(UserModel user) {
  704. for (AuthenticationProvider provider : authenticationProviders) {
  705. if (provider.getAccountType().equals(user.accountType)) {
  706. return provider;
  707. }
  708. }
  709. return AuthenticationProvider.NULL_PROVIDER;
  710. }
  711. protected AuthenticationProvider findProvider(TeamModel team) {
  712. for (AuthenticationProvider provider : authenticationProviders) {
  713. if (provider.getAccountType().equals(team.accountType)) {
  714. return provider;
  715. }
  716. }
  717. return AuthenticationProvider.NULL_PROVIDER;
  718. }
  719. }