package com.its.wthr.webapp.security;

import com.its.wthr.webapp.service.UserService;
import com.its.wthr.webapp.vo.UserVo;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

@Component
public class UserAuthenticationProvider implements AuthenticationProvider {
	private final UserService userService;

	public UserAuthenticationProvider(UserService userService) {
		this.userService = userService;
	}

	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		String id = authentication.getName();
		String password = (String) authentication.getCredentials();
		UserVo user = this.userService.loadUserByUsername(id);
		if (user == null) {
			throw new BadCredentialsException("Login Error !!");
		} else {
			UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(id, password,
					user.getAuthorities());
			result.setDetails(user);
			return result;
		}
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return authentication.equals(UsernamePasswordAuthenticationToken.class);
	}
}