package io.conducive.client.ui.views;
import com.ekuefler.supereventbus.EventBus;
import io.conducive.client.crypt.Hash;
import io.conducive.client.ui.events.ClickLoginEvent;
import io.conducive.client.ui.events.ClickRegisterEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.*;
import io.conducive.client.ui.widgets.gwt.PasswordTextInput;
import io.conducive.client.ui.widgets.gwt.TextInput;
import javax.inject.Inject;
import static io.conducive.client.crypt.Hash.*;
import static io.conducive.client.ui.widgets.HTML.*;
import static io.conducive.client.ui.widgets.Foundation.*;
/**
* Username/password, with login/register buttons. Basic but functional.
*
* Posts a ClickLoginEvent with the contents of username / password textfields.
*
* TODO inline validation / error messaging
*
* @author Reuben Firmin
*/
public class LoginView extends Composite {
private int EXP = 12;
@Inject
public LoginView(final EventBus eventBus) {
final TextInput username = new TextInput("username").placeholder("Username").focus();
final PasswordTextInput password = new PasswordTextInput("password").placeholder("Password");
Runnable submit = new Runnable() {
@Override
public void run() {
login(username, password, eventBus);
}
};
username.enter(submit);
password.enter(submit);
initWidget(div().id("login-content").wrap(
box("login-form", noclass).radius().wrap(
h2().text("Please Sign In"),
username,
password,
button("login-button", noclass, "Login",
new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
login(username, password, eventBus);
}
}
),
button("register-button", noclass, "Register",
new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
register(username, password, eventBus);
}
}
)
)
)
);
}
private void register(TextInput username, PasswordTextInput password, EventBus eventBus) {
String user = username.getValue();
String salt = salt(user);
eventBus.post(new ClickRegisterEvent(user, salt, Hash.stretch(password.getValue(), salt, EXP)));
password.setValue("");
}
private void login(TextInput username, PasswordTextInput password, EventBus eventBus) {
String user = username.getValue();
String salt = salt(user);
eventBus.post(new ClickLoginEvent(user, salt, Hash.stretch(password.getValue(), salt, EXP)));
password.setValue("");
}
private String salt(String username) {
// need a consistent salt per username. it's public, so it makes no difference whether it's derivable or findable
return Hash.toString(hash256(username));
}
}