package org.ros.chatto.security;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ros.chatto.model.UserToken;
import org.ros.chatto.service.UserTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.token.Token;
import org.springframework.security.core.token.TokenService;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.stereotype.Component;

@Component
public class CustomBasicAuthenticationFilter extends BasicAuthenticationFilter {

	@Autowired
	private TokenService tokenService;
	@Autowired
	private UserTokenService userTokenService;

	@Autowired
	public CustomBasicAuthenticationFilter(
			final AuthenticationManager authenticationManager) {
		super(authenticationManager);
	}

	@Override
	protected void onSuccessfulAuthentication(final HttpServletRequest request,
			final HttpServletResponse response,
			final Authentication authResult) {
		// Generate Token
		// Save the token for the logged in user
		// send token in the response
		UserToken userToken = userTokenService
				.getTokenByUserName(authResult.getName());
		if (userToken == null) {
			final Token token = tokenService.allocateToken("");
			userToken = new UserToken();
			userToken.setTokenContent(token.getKey());
			userToken.setUserName(authResult.getName());
			userToken.setRole(authResult.getAuthorities().iterator().next()
					.getAuthority());
			userTokenService.saveToken(userToken);
			response.setHeader("X-AUTH-TOKEN", token.getKey());
		} else {
			response.setHeader("X-AUTH-TOKEN", userToken.getTokenContent());
		}

	}

}