A self hosted chat application with end-to-end encrypted messaging.
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.

53 lines
1.8 KiB

  1. package org.ros.chatto.security;
  2. import javax.servlet.http.HttpServletRequest;
  3. import javax.servlet.http.HttpServletResponse;
  4. import org.ros.chatto.model.UserToken;
  5. import org.ros.chatto.service.UserTokenService;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.security.authentication.AuthenticationManager;
  8. import org.springframework.security.core.Authentication;
  9. import org.springframework.security.core.token.Token;
  10. import org.springframework.security.core.token.TokenService;
  11. import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
  12. import org.springframework.stereotype.Component;
  13. @Component
  14. public class CustomBasicAuthenticationFilter extends BasicAuthenticationFilter {
  15. @Autowired
  16. private TokenService tokenService;
  17. @Autowired
  18. private UserTokenService userTokenService;
  19. @Autowired
  20. public CustomBasicAuthenticationFilter(
  21. final AuthenticationManager authenticationManager) {
  22. super(authenticationManager);
  23. }
  24. @Override
  25. protected void onSuccessfulAuthentication(final HttpServletRequest request,
  26. final HttpServletResponse response,
  27. final Authentication authResult) {
  28. // Generate Token
  29. // Save the token for the logged in user
  30. // send token in the response
  31. UserToken userToken = userTokenService
  32. .getTokenByUserName(authResult.getName());
  33. if (userToken == null) {
  34. final Token token = tokenService.allocateToken("");
  35. userToken = new UserToken();
  36. userToken.setTokenContent(token.getKey());
  37. userToken.setUserName(authResult.getName());
  38. userToken.setRole(authResult.getAuthorities().iterator().next()
  39. .getAuthority());
  40. userTokenService.saveToken(userToken);
  41. response.setHeader("X-AUTH-TOKEN", token.getKey());
  42. } else {
  43. response.setHeader("X-AUTH-TOKEN", userToken.getTokenContent());
  44. }
  45. }
  46. }