/*******************************************************************************
 * Copyright 2Fi Business Solutions Ltd.
 *
 * This code is copyrighted. Under no circumstances should any party, people,
 * or organization should redistribute any portions of this code in any form,
 * either verbatim or through electronic media, to any third parties, unless
 * under explicit written permission by 2Fi Business Solutions Ltd.
 ******************************************************************************/
package com.ffii.core.security.authentication;

import com.ffii.core.User;
import com.ffii.core.security.service.TokenUserDetailsService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * Token Authentication Provider
 *
 * @author Patrick
 */
@Component
public class TokenAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private TokenUserDetailsService tokenUserDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        final AuthToken authToken = (AuthToken) authentication;
        final String token = authToken.getToken();

        User user = tokenUserDetailsService.findUserByToken(token);

        if (user == null)
            throw new BadCredentialsException("No user found for token - " + token);

        return new AuthToken(token, user);
    }

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