Added login check (test it)

This commit is contained in:
Norbi Peti 2016-07-22 14:45:45 +02:00
parent 7f3aefb9b5
commit 7c2c4400df
3 changed files with 35 additions and 5 deletions

View file

@ -10,7 +10,6 @@ import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import org.apache.commons.io.IOUtils;
@ -93,4 +92,9 @@ public class IOHelper {
exchange.getResponseHeaders().add("Set-Cookie", "user_id=del; expires=" + expiretime);
exchange.getResponseHeaders().add("Set-Cookie", "session_id=del; expires=" + expiretime);
}
public static void Redirect(String url, HttpExchange exchange) throws IOException {
exchange.getResponseHeaders().add("Location", url);
IOHelper.SendResponse(303, "<a href=\"" + url + "\">If you can see this, click here to continue</a>", exchange);
}
}

View file

@ -1,16 +1,43 @@
package io.github.norbipeti.chat.server.page;
import java.io.IOException;
import java.util.HashMap;
import org.mindrot.jbcrypt.BCrypt;
import com.sun.net.httpserver.HttpExchange;
import io.github.norbipeti.chat.server.IOHelper;
import io.github.norbipeti.chat.server.db.DataProvider;
import io.github.norbipeti.chat.server.db.domain.User;
public class LoginPage extends Page {
@Override
public void handlePage(HttpExchange exchange) throws IOException {
IOHelper.SendPage(200, this, exchange);
HashMap<String, String> post = IOHelper.GetPOST(exchange);
if (post.size() == 0 || !post.containsKey("email") || !post.containsKey("pass")) {
IOHelper.SendPage(200, this, exchange);
return;
}
try (DataProvider provider = new DataProvider()) {
User loginuser = null;
for (User user : provider.getUsers()) {
if (user.getEmail().equals(post.get("email"))) {
loginuser = user;
break;
}
}
if (loginuser == null || !BCrypt.checkpw(post.get("pass"), loginuser.getPassword())) {
IOHelper.SendModifiedPage(200, this, "<errormsg />", "<p>The E-mail or password is incorrect</p>",
exchange);
return;
}
IOHelper.LoginUser(exchange, loginuser);
IOHelper.Redirect("/", exchange);
} catch (Exception e) {
throw e;
}
}
@Override

View file

@ -38,11 +38,10 @@ public class RegisterPage extends Page {
user.setName(post.get("name"));
user.setEmail(post.get("email"));
user.setSalt(BCrypt.gensalt()); // http://www.mindrot.org/projects/jBCrypt/
user.setPassword(BCrypt.hashpw(post.get("password"), user.getSalt()));
user.setPassword(BCrypt.hashpw(post.get("pass"), user.getSalt()));
provider.addUser(user);
IOHelper.LoginUser(exchange, user);
exchange.getResponseHeaders().add("Location", "/");
IOHelper.SendResponse(303, "<a href=\"/\">If you can see this, click here to continue</a>", exchange);
IOHelper.Redirect("/", exchange);
}
return; // TODO: Only show tag when needed
}