Compare commits

..

No commits in common. "fa6f0774a1794c6b1117b65b4d1aa92bfd8b2bfa" and "e119911fefd0f28fd1d28277c40f6776630912c6" have entirely different histories.

24 changed files with 127 additions and 237 deletions

View file

@ -1,7 +1,5 @@
package be.jeffcheasey88.peeratcode;
import static be.jeffcheasey88.peeratcode.framework.RequestType.OPTIONS;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
@ -10,6 +8,9 @@ import java.util.regex.Matcher;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import org.jose4j.jwk.RsaJsonWebKey;
import org.jose4j.jwk.RsaJwkGenerator;
import be.jeffcheasey88.peeratcode.framework.Client;
import be.jeffcheasey88.peeratcode.framework.HttpReader;
import be.jeffcheasey88.peeratcode.framework.HttpUtil;
@ -30,9 +31,7 @@ import be.jeffcheasey88.peeratcode.routes.PuzzleResponse;
import be.jeffcheasey88.peeratcode.routes.Register;
import be.jeffcheasey88.peeratcode.routes.Result;
import be.jeffcheasey88.peeratcode.routes.groups.CreateGroup;
import be.jeffcheasey88.peeratcode.routes.groups.GroupJoin;
import be.jeffcheasey88.peeratcode.routes.groups.GroupList;
import be.jeffcheasey88.peeratcode.routes.groups.GroupQuit;
public class Main {
public static void main(String[] args) throws Exception {
@ -55,7 +54,7 @@ public class Main {
});
router.register(new Response() {
@Route(path = "^(.*)$", type = OPTIONS)
@Route(path = "^(.*)$", type = "OPTIONS")
@Override
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
HttpUtil.responseHeaders(writer, 200, "Access-Control-Allow-Origin: *",
@ -82,8 +81,6 @@ public class Main {
router.register(new GroupList(router.getDataBase()));
router.register(new CreateGroup(router.getDataBase()));
router.register(new GroupJoin(router.getDataBase()));
router.register(new GroupQuit(router.getDataBase()));
}
private static void startWebServer(Configuration config, Router router) throws IOException {
@ -98,7 +95,7 @@ public class Main {
while (!server.isClosed()) {
Socket socket = server.accept();
Client client = new Client(socket, router);
Client client = new Client(socket, router, RsaJwkGenerator.generateJwk(2048));
client.start();
}
} catch (Exception e) {
@ -112,7 +109,8 @@ public class Main {
try (ServerSocket server = new ServerSocket(config.getTcpPort())) {
while (!server.isClosed()) {
Socket socket = server.accept();
Client client = new Client(socket, router);
RsaJsonWebKey rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);
Client client = new Client(socket, router, rsaJsonWebKey);
client.start();
}
} catch (Exception e) {

View file

@ -15,11 +15,13 @@ public class Client extends Thread{
private HttpReader reader;
private HttpWriter writer;
private Router router;
private RsaJsonWebKey key; // Really needed ?
public Client(Socket socket, Router router) throws Exception{
public Client(Socket socket, Router router, RsaJsonWebKey key) throws Exception {
this.reader = new HttpReader(socket);
this.writer = new HttpWriter(socket);
this.router = router;
this.key = key;
}
@Override
@ -28,7 +30,7 @@ public class Client extends Thread{
String[] headers = reader.readLine().split("\\s");
System.out.println(Arrays.toString(headers));
router.exec(RequestType.valueOf(headers[0]), headers[1], isLogin(reader), reader, writer);
router.exec(headers[0], headers[1], isLogin(reader), reader, writer);
writer.flush();
writer.close();
} catch (Exception e) {
@ -38,12 +40,11 @@ public class Client extends Thread{
private User isLogin(HttpReader reader) throws Exception {
String auth = HttpUtil.readAuthorization(reader);
if(auth == null) return null;
if (auth == null)
return null;
try {
JwtConsumer jwtConsumer = new JwtConsumerBuilder()
.setRequireExpirationTime()
.setAllowedClockSkewInSeconds(30)
.setExpectedIssuer(this.router.getTokenIssuer())
JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireExpirationTime()
.setAllowedClockSkewInSeconds(30).setExpectedIssuer(this.router.getTokenIssuer())
.setVerificationKey(this.router.getWebKey().getKey())
.setJwsAlgorithmConstraints(ConstraintType.PERMIT, AlgorithmIdentifiers.RSA_USING_SHA256).build();

View file

@ -10,18 +10,21 @@ import org.json.simple.parser.JSONParser;
public class HttpUtil {
private HttpUtil(){}
private HttpUtil() {
}
public static void responseHeaders(HttpWriter writer, int code, String... headers) throws Exception {
writer.write("HTTP/1.1 " + code + " " + codeMessage(code) + "\n");
for(String header : headers) writer.write(header + "\n");
for (String header : headers)
writer.write(header + "\n");
writer.write("\n");
writer.flush();
}
public static void skipHeaders(HttpReader reader) throws Exception {
String line;
while(((line = reader.readLine()) != null) && (line.length() > 0));
while (((line = reader.readLine()) != null) && (line.length() > 0))
;
}
public static List<String> readMultiPartData(HttpReader reader) throws Exception {
@ -46,7 +49,8 @@ public class HttpUtil{
public static void switchToWebSocket(HttpReader reader, HttpWriter writer) throws Exception {
String key = readWebSocketKey(reader);
if (key == null) throw new IllegalArgumentException();
if (key == null)
throw new IllegalArgumentException();
writer.write("HTTP/1.1 101 Switching Protocols\n");
writer.write("Connection: Upgrade\n");
@ -63,9 +67,12 @@ public class HttpUtil{
String line;
String key = null;
while (((line = reader.readLine()) != null) && (line.length() > 0)) {
if(key != null) continue;
if (key != null) {
continue;
}
Matcher matcher = WEBSOCKET_KEY.matcher(line);
if(matcher.matches()) key = matcher.group(1);
if (matcher.matches())
key = matcher.group(1);
}
return key;
}
@ -97,7 +104,8 @@ public class HttpUtil{
parse = new JSONParser().parse(line);
if (parse != null)
return parse;
}catch(Exception e){}
} catch (Exception e) {
}
}
}
return null;

View file

@ -1,7 +0,0 @@
package be.jeffcheasey88.peeratcode.framework;
public enum RequestType {
GET, POST, OPTIONS;
}

View file

@ -11,7 +11,7 @@ public @interface Route{
String path() default "^.*$";
RequestType type() default RequestType.GET;
String type() default "GET";
boolean needLogin() default false;

View file

@ -56,19 +56,20 @@ public class Router{
this.noFileFound = response;
}
public void exec(RequestType type, String path, User user, HttpReader reader, HttpWriter writer) throws Exception{
if(type == null) return;
public void exec(String type, String path, User user, HttpReader reader, HttpWriter writer) throws Exception {
for (Entry<Response, Route> routes : this.responses.entrySet()) {
if (routes.getValue().type().equals(type)) {
Matcher matcher = this.patterns.get(routes.getKey()).matcher(path);
if (matcher.matches()) {
if(user == null && routes.getValue().needLogin()) return;
if (user == null && routes.getValue().needLogin())
return;
routes.getKey().exec(matcher, user, reader, writer);
return;
}
}
}
if(noFileFound != null) noFileFound.exec(null, user, reader, writer);
if (noFileFound != null)
noFileFound.exec(null, user, reader, writer);
}
public RsaJsonWebKey getWebKey() {

View file

@ -16,11 +16,7 @@ public enum DatabaseQuery {
ALL_CHAPTERS_QUERY("SELECT * FROM chapters WHERE id_chapter > 0"),
// GROUPS
ALL_GROUPS("SELECT * FROM groups"),
GET_GROUP_ID_BY_DATA("SELECT id_group FROM groups WHERE name = ? AND fk_chapter = ? AND fk_puzzle = ?"),
INSERT_GROUP("INSERT INTO groups (name, fk_chapter, fk_puzzle) VALUES (?,?,?)"),
INSERT_PLAYER_IN_GROUP("INSERT INTO containsGroups (fk_player, fk_group) VALUES (?,?)"),
LEAVE_GROUP("DELETE FROM containsGroups WHERE fk_player = ? AND fk_group = ?"),
ALL_GROUPS("SELCT * FROM groups"), INSERT_GROUP("INSERT INTO groups (name, fk_chapter, fk_puzzle) VALUES (?,?,?)"),
// LEADERBOARD
ALL_PLAYERS_FOR_LEADERBOARD(

View file

@ -16,7 +16,6 @@ import com.password4j.Hash;
import com.password4j.Password;
import be.jeffcheasey88.peeratcode.Configuration;
import be.jeffcheasey88.peeratcode.framework.User;
import be.jeffcheasey88.peeratcode.model.Badge;
import be.jeffcheasey88.peeratcode.model.Chapter;
import be.jeffcheasey88.peeratcode.model.Completion;
@ -488,53 +487,16 @@ public class DatabaseRepository {
statement.executeUpdate();
}
public boolean insertGroup(Group group, User creator){
public boolean insertGroup(Group group) {
try {
ensureConnection();
PreparedStatement statement = DatabaseQuery.INSERT_GROUP.prepare(this.con);
statement.setString(1, group.getName());
statement.setInt(2, group.getLinkToChapter());
statement.setInt(3, group.getLinkToPuzzle());
if(statement.executeUpdate() >= 0) return insertUserInGroup(group, creator);
} catch (Exception e){}
return false;
return statement.executeUpdate() >= 0;
} catch (Exception e) {
}
private int getGroupId(Group group) throws Exception{
ensureConnection();
PreparedStatement stmt = DatabaseQuery.GET_GROUP_ID_BY_DATA.prepare(this.con);
stmt.setString(1, group.getName());
stmt.setInt(2, group.getLinkToChapter());
stmt.setInt(3, group.getLinkToPuzzle());
ResultSet result = stmt.executeQuery();
if(result.next()) return result.getInt("id_group");
throw new NullPointerException();
}
public boolean insertUserInGroup(Group group, User user){
try {
int id = getGroupId(group);
PreparedStatement stmt = DatabaseQuery.INSERT_PLAYER_IN_GROUP.prepare(this.con);
stmt.setInt(1, user.getId());
stmt.setInt(2, id);
return stmt.executeUpdate() >= 0;
}catch(Exception e){}
return false;
}
public boolean leaveGroup(Group group, User user){
try {
int id = getGroupId(group);
PreparedStatement stmt = DatabaseQuery.LEAVE_GROUP.prepare(this.con);
stmt.setInt(1, user.getId());
stmt.setInt(2, id);
return stmt.executeUpdate() >= 0;
}catch(Exception e){}
return false;
}

View file

@ -23,6 +23,7 @@ public class BadgeDetails implements Response {
}
@Route(path = "^\\/badge\\/([0-9]+)$", needLogin = true)
@Override
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
if (matcher.groupCount() > 0) {
int badgeId = Integer.parseInt(matcher.group(1));

View file

@ -24,6 +24,7 @@ public class ChapterElement implements Response {
}
@Route(path = "^\\/chapter\\/([0-9]+)$", needLogin = true)
@Override
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
Chapter chapter = databaseRepo.getChapter(extractId(matcher));
if (chapter != null) {

View file

@ -24,6 +24,7 @@ public class ChapterList implements Response {
}
@Route(path = "^\\/chapters$", needLogin = true)
@Override
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
List<Chapter> allChapters = databaseRepo.getAllChapters();
if (allChapters != null) {

View file

@ -28,6 +28,7 @@ public class Leaderboard implements Response {
}
@Route(path = "^\\/leaderboard\\/?(\\d+)?$")
@Override
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
HttpUtil.responseHeaders(writer, 200, "Access-Control-Allow-Origin: *");
if (matcher.group(1) != null) {

View file

@ -1,7 +1,5 @@
package be.jeffcheasey88.peeratcode.routes;
import static be.jeffcheasey88.peeratcode.framework.RequestType.POST;
import java.util.regex.Matcher;
import org.json.simple.JSONObject;
@ -25,7 +23,8 @@ public class Login implements Response {
this.router = router;
}
@Route(path = "^\\/login$", type = POST)
@Route(path = "^\\/login$", type = "POST")
@Override
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
if (user != null) {
HttpUtil.responseHeaders(writer, 403, "Access-Control-Allow-Origin: *");

View file

@ -23,6 +23,7 @@ public class PlayerDetails implements Response {
}
@Route(path = "^\\/player\\/?(.+)?$", needLogin = true)
@Override
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
Player player;
if (matcher.group(1) != null) {

View file

@ -22,6 +22,7 @@ public class PuzzleElement implements Response {
}
@Route(path = "^\\/puzzle\\/([0-9]+)$", needLogin = true)
@Override
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
Puzzle puzzle = databaseRepo.getPuzzle(extractId(matcher));
if (puzzle != null) {

View file

@ -1,7 +1,5 @@
package be.jeffcheasey88.peeratcode.routes;
import static be.jeffcheasey88.peeratcode.framework.RequestType.POST;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
@ -32,7 +30,8 @@ public class PuzzleResponse implements Response {
usersFilesPath = initUsersFilesPath;
}
@Route(path = "^\\/puzzleResponse\\/([0-9]+)$", type = POST, needLogin = true)
@Route(path = "^\\/puzzleResponse\\/([0-9]+)$", type = "POST")
@Override
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
if (user == null) {
HttpUtil.responseHeaders(writer, 401, "Access-Control-Allow-Origin: *");

View file

@ -1,7 +1,5 @@
package be.jeffcheasey88.peeratcode.routes;
import static be.jeffcheasey88.peeratcode.framework.RequestType.POST;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
@ -30,7 +28,8 @@ public class Register implements Response {
usersFilesPath = initUsersFilesPath;
}
@Route(path = "^\\/register$", type = POST)
@Route(path = "^\\/register$", type = "POST")
@Override
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
if (user != null) {
HttpUtil.responseHeaders(writer, 403, "Access-Control-Allow-Origin: *");

View file

@ -19,6 +19,7 @@ public class Result implements Response {
}
@Route(path = "^\\/result\\/(\\d+)$", needLogin = true)
@Override
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
int puzzle = Integer.parseInt(matcher.group(1));

View file

@ -1,7 +1,5 @@
package be.jeffcheasey88.peeratcode.routes.groups;
import static be.jeffcheasey88.peeratcode.framework.RequestType.POST;
import java.util.regex.Matcher;
import org.json.simple.JSONObject;
@ -23,11 +21,12 @@ public class CreateGroup implements Response {
this.repo = repo;
}
@Route(path = "^\\/groupCreate$", type = POST, needLogin = true)
@Route(path = "^\\/groupCreate$", type = "POST", needLogin = true)
@Override
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
HttpUtil.skipHeaders(reader);
if (this.repo.insertGroup(new Group((JSONObject) HttpUtil.readJson(reader)), user)) {
if (this.repo.insertGroup(new Group((JSONObject) HttpUtil.readJson(reader)))) {
HttpUtil.responseHeaders(writer, 200, "Access-Control-Allow-Origin: *");
} else {
HttpUtil.responseHeaders(writer, 403, "Access-Control-Allow-Origin: *");

View file

@ -1,37 +0,0 @@
package be.jeffcheasey88.peeratcode.routes.groups;
import static be.jeffcheasey88.peeratcode.framework.RequestType.POST;
import java.util.regex.Matcher;
import org.json.simple.JSONObject;
import be.jeffcheasey88.peeratcode.framework.HttpReader;
import be.jeffcheasey88.peeratcode.framework.HttpUtil;
import be.jeffcheasey88.peeratcode.framework.HttpWriter;
import be.jeffcheasey88.peeratcode.framework.Response;
import be.jeffcheasey88.peeratcode.framework.Route;
import be.jeffcheasey88.peeratcode.framework.User;
import be.jeffcheasey88.peeratcode.model.Group;
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;
public class GroupJoin implements Response{
private DatabaseRepository repo;
public GroupJoin(DatabaseRepository repo){
this.repo = repo;
}
@Route(path = "^\\/groupJoin$", type = POST, needLogin = true)
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
HttpUtil.responseHeaders(writer, 200, "Access-Control-Allow-Origin: *");
if (this.repo.insertUserInGroup(new Group((JSONObject) HttpUtil.readJson(reader)), user)) {
HttpUtil.responseHeaders(writer, 200, "Access-Control-Allow-Origin: *");
} else {
HttpUtil.responseHeaders(writer, 403, "Access-Control-Allow-Origin: *");
}
}
}

View file

@ -22,10 +22,12 @@ public class GroupList implements Response {
}
@Route(path = "^\\/groups$", needLogin = true)
@Override
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
HttpUtil.responseHeaders(writer, 200, "Access-Control-Allow-Origin: *");
JSONArray result = new JSONArray();
for(Group group : this.repo.getAllGroups()) result.add(group.toJson());
for (Group group : this.repo.getAllGroups())
result.add(group.toJson());
writer.write(result.toJSONString());
}

View file

@ -1,37 +0,0 @@
package be.jeffcheasey88.peeratcode.routes.groups;
import static be.jeffcheasey88.peeratcode.framework.RequestType.POST;
import java.util.regex.Matcher;
import org.json.simple.JSONObject;
import be.jeffcheasey88.peeratcode.framework.HttpReader;
import be.jeffcheasey88.peeratcode.framework.HttpUtil;
import be.jeffcheasey88.peeratcode.framework.HttpWriter;
import be.jeffcheasey88.peeratcode.framework.Response;
import be.jeffcheasey88.peeratcode.framework.Route;
import be.jeffcheasey88.peeratcode.framework.User;
import be.jeffcheasey88.peeratcode.model.Group;
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;
public class GroupQuit implements Response{
private DatabaseRepository repo;
public GroupQuit(DatabaseRepository repo){
this.repo = repo;
}
@Route(path = "^\\/groupQuit$", type = POST, needLogin = true)
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
HttpUtil.responseHeaders(writer, 200, "Access-Control-Allow-Origin: *");
if (this.repo.leaveGroup(new Group((JSONObject) HttpUtil.readJson(reader)), user)) {
HttpUtil.responseHeaders(writer, 200, "Access-Control-Allow-Origin: *");
} else {
HttpUtil.responseHeaders(writer, 403, "Access-Control-Allow-Origin: *");
}
}
}