package com.uip.tatar.auth;
import com.uip.tatar.APITatarException;
import com.uip.tatar.api.APITatarDefaultClient;
import com.uip.tatar.api.APITatarRequest;
import com.uip.tatar.config.Configuration;
import com.uip.tatar.model.APITatarSession;
import com.uip.tatar.model.Session;
import com.uip.tatar.network.JsonHttpEntity;
/**
* Author: Khamidullin Kamil
* Date: 28.05.14
* Time: 10:15
*/
public class DefaultAuthorization implements Authorization, AuthSupport {
private Session session;
private APITatarDefaultClient client;
private String username;
private String password;
public DefaultAuthorization(Configuration configuration) {
this.client = new APITatarDefaultClient(configuration);
}
@Override
public boolean isAuthenticated() {
return session != null;
}
@Override
public boolean isEnabled() {
return isAuthenticated();
}
@Override
public void setCredentials(String username, String password) {
if(username == null) {
throw new IllegalArgumentException("username may not be null");
}
if(password == null) {
throw new IllegalArgumentException("password may not be null");
}
this.username = username;
this.password = password;
}
@Override
public Session auth(String username, String password) throws APITatarException {
setCredentials(username, password);
updateSession();
return this.session;
}
private boolean isValidCredentials() {
return !(this.username == null || this.password == null);
}
@Override
public void updateSession() throws APITatarException {
if(!isValidCredentials()) {
throw new IllegalStateException("Wrong credentials");
}
setSession(loadSession());
}
private Session loadSession() throws APITatarException {
if(!isValidCredentials()) {
throw new IllegalStateException("Wrong credentials");
}
return client.post(
createAuthRequest(this.username, this.password),
new APITatarDefaultClient.DefaultResultHandler<APITatarSession>(APITatarSession.class, true)
);
}
@Override
public Session getSession() {
if(!isEnabled()) {
throw new IllegalStateException("No session available");
}
return session;
}
@Override
public void setSession(Session session) {
this.session = session;
}
private APITatarRequest createAuthRequest(String username, String password) {
JsonHttpEntity userAuthParams = new JsonHttpEntity();
userAuthParams.put("username", username);
userAuthParams.put("password", password);
return new APITatarRequest("sessions", userAuthParams);
}
}