package com.mobius.components;
import com.mobius.model.LoggedUser;
import com.mobius.model.MyAuthenticationToken;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: Pawel
* Date: 17.12.13
* Time: 10:46
* To change this template use File | Settings | File Templates.
*/
@Component
public class LVAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String name = authentication.getName();
if(Base64.isBase64(name) && !name.startsWith("[direct]")) {
name = StringUtils.newStringUtf8(Base64.decodeBase64(name));
}
String password = authentication.getCredentials().toString();
if(Base64.isBase64(password) && !name.startsWith("[direct]")) {
password = StringUtils.newStringUtf8(Base64.decodeBase64(password));
}
if(name.startsWith("[direct]")) {
name = name.substring(8);
}
LoggedUser user = new LoggedUser(name,password);
if (user.authorize()) {
List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
Authentication auth = new MyAuthenticationToken(name, password, grantedAuths,user);
return auth;
} else {
return null;
}
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}