From 6bbe5de62c234cffe62a0639bd8b7353c85ca4c8 Mon Sep 17 00:00:00 2001 From: Benjamin Elsdon Date: Mon, 2 May 2022 18:32:55 +0800 Subject: [PATCH] New Authentication Handler Support --- src/main/java/me/exzork/gcauth/Config.java | 1 - src/main/java/me/exzork/gcauth/GCAuth.java | 237 +----------------- .../gcauth/handler/AuthStatusHandler.java | 20 -- .../gcauth/handler/ChangePasswordHandler.java | 60 ++--- .../gcauth/handler/ClientLoginHandler.java | 100 -------- .../handler/GCAuthAuthenticationHandler.java | 75 ++++++ .../exzork/gcauth/handler/LoginHandler.java | 52 ++-- .../gcauth/handler/RegisterHandler.java | 57 ++--- 8 files changed, 162 insertions(+), 440 deletions(-) delete mode 100644 src/main/java/me/exzork/gcauth/handler/AuthStatusHandler.java delete mode 100644 src/main/java/me/exzork/gcauth/handler/ClientLoginHandler.java create mode 100644 src/main/java/me/exzork/gcauth/handler/GCAuthAuthenticationHandler.java diff --git a/src/main/java/me/exzork/gcauth/Config.java b/src/main/java/me/exzork/gcauth/Config.java index f4cca43..28ea88e 100644 --- a/src/main/java/me/exzork/gcauth/Config.java +++ b/src/main/java/me/exzork/gcauth/Config.java @@ -2,5 +2,4 @@ package me.exzork.gcauth; public final class Config { public String Hash = "BCRYPT"; - public boolean Enable = true; } diff --git a/src/main/java/me/exzork/gcauth/GCAuth.java b/src/main/java/me/exzork/gcauth/GCAuth.java index da845d3..20b1e7c 100644 --- a/src/main/java/me/exzork/gcauth/GCAuth.java +++ b/src/main/java/me/exzork/gcauth/GCAuth.java @@ -46,239 +46,22 @@ public class GCAuth extends Plugin { @Override public void onEnable() { + if(Grasscutter.getDispatchServer().registerAuthHandler(new GCAuthAuthenticationHandler())) { + Grasscutter.getLogger().info("GCAuth Enabled!"); - Express httpServer = new Express(config -> { - config.server(() -> { - Server server = new Server(); - ServerConnector serverConnector; - - if(Grasscutter.getConfig().getDispatchOptions().UseSSL) { - SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); - File keystoreFile = new File(Grasscutter.getConfig().getDispatchOptions().KeystorePath); - - if(keystoreFile.exists()) { - try { - sslContextFactory.setKeyStorePath(keystoreFile.getPath()); - sslContextFactory.setKeyStorePassword(Grasscutter.getConfig().getDispatchOptions().KeystorePassword); - } catch (Exception e) { - e.printStackTrace(); - Grasscutter.getLogger().warn("[Dispatch] Unable to load keystore. Trying default keystore password..."); - - try { - sslContextFactory.setKeyStorePath(keystoreFile.getPath()); - sslContextFactory.setKeyStorePassword("123456"); - Grasscutter.getLogger().warn("[Dispatch] The default keystore password was loaded successfully. Please consider setting the password to 123456 in config.json."); - } catch (Exception e2) { - Grasscutter.getLogger().warn("[Dispatch] Error while loading keystore!"); - e2.printStackTrace(); - } - } - - serverConnector = new ServerConnector(server, sslContextFactory); - } else { - Grasscutter.getLogger().warn("[Dispatch] No SSL cert found! Falling back to HTTP server."); - Grasscutter.getConfig().getDispatchOptions().UseSSL = false; - - serverConnector = new ServerConnector(server); - } - } else { - serverConnector = new ServerConnector(server); - } - - serverConnector.setPort(Grasscutter.getConfig().getDispatchOptions().Port); - server.setConnectors(new Connector[]{serverConnector}); - return server; - }); - - config.enforceSsl = Grasscutter.getConfig().getDispatchOptions().UseSSL; - if(Grasscutter.getConfig().DebugMode.equalsIgnoreCase("ALL")) { - config.enableDevLogging(); + if(Grasscutter.getConfig().getDispatchOptions().AutomaticallyCreateAccounts) { + Grasscutter.getLogger().warn("GCAuth does not support automatic account creation. Please disable in the server's config.json or just ignore this warning."); } - }); - - httpServer.get("/grasscutter/auth_status",new AuthStatusHandler()); - httpServer.post("/grasscutter/login", new LoginHandler()); - httpServer.post("/grasscutter/register", new RegisterHandler()); - httpServer.post("/grasscutter/change_password", new ChangePasswordHandler()); - httpServer.post("/hk4e_global/mdk/shield/api/login", new ClientLoginHandler()); - - httpServer.get("/", (req, res) -> res.send("Welcome to Grasscutter")); - - httpServer.raw().error(404, ctx -> { - if(Grasscutter.getConfig().DebugMode.equalsIgnoreCase("MISSING")) { - Grasscutter.getLogger().info(String.format("[Dispatch] Potential unhandled %s request: %s", ctx.method(), ctx.url())); - } - ctx.contentType("text/html"); - ctx.result(""); // I'm like 70% sure this won't break anything. - }); - - // Dispatch - httpServer.get("/query_region_list", (req, res) -> { - // Log - Grasscutter.getLogger().info(String.format("[Dispatch] Client %s request: query_region_list", req.ip())); - - // Invoke event. - QueryAllRegionsEvent event = new QueryAllRegionsEvent(Grasscutter.getDispatchServer().regionListBase64); event.call(); - // Respond with event result. - res.send(event.getRegionList()); - }); - - httpServer.get("/query_cur_region/:id", (req, res) -> { - String regionName = req.params("id"); - // Log - Grasscutter.getLogger().info( - String.format("Client %s request: query_cur_region/%s", req.ip(), regionName)); - // Create a response form the request query parameters - String response = "CAESGE5vdCBGb3VuZCB2ZXJzaW9uIGNvbmZpZw=="; - if (req.query().values().size() > 0) { - response = Grasscutter.getDispatchServer().regions.get(regionName).getBase64(); - } - - // Invoke event. - QueryCurrentRegionEvent event = new QueryCurrentRegionEvent(response); event.call(); - // Respond with event result. - res.send(event.getRegionInfo()); - }); - - - // Login via token - httpServer.post("/hk4e_global/mdk/shield/api/verify", (req, res) -> { - // Get post data - LoginTokenRequestJson requestData = null; - try { - String body = req.ctx().body(); - requestData = Grasscutter.getGsonFactory().fromJson(body, LoginTokenRequestJson.class); - } catch (Exception ignored) { - } - - // Create response json - if (requestData == null) { - return; - } - LoginResultJson responseData = new LoginResultJson(); - Grasscutter.getLogger().info(String.format("[Dispatch] Client %s is trying to log in via token", req.ip())); - - // Login - Account account = DatabaseHelper.getAccountById(requestData.uid); - - // Test - if (account == null || !account.getSessionKey().equals(requestData.token)) { - responseData.retcode = -111; - responseData.message = "Game account cache information error"; - - Grasscutter.getLogger() - .info(String.format("[Dispatch] Client %s failed to log in via token", req.ip())); - } else { - responseData.message = "OK"; - responseData.data.account.uid = requestData.uid; - responseData.data.account.token = requestData.token; - responseData.data.account.email = account.getEmail(); - - Grasscutter.getLogger().info(String.format("[Dispatch] Client %s logged in via token as %s", - req.ip(), responseData.data.account.uid)); - } - - res.send(responseData); - }); - - // Exchange for combo token - httpServer.post("/hk4e_global/combo/granter/login/v2/login", (req, res) -> { - // Get post data - ComboTokenReqJson requestData = null; - try { - String body = req.ctx().body(); - requestData = Grasscutter.getGsonFactory().fromJson(body, ComboTokenReqJson.class); - } catch (Exception ignored) { - } - - // Create response json - if (requestData == null || requestData.data == null) { - return; - } - ComboTokenReqJson.LoginTokenData loginData = Grasscutter.getGsonFactory().fromJson(requestData.data, ComboTokenReqJson.LoginTokenData.class); // Get login - // data - ComboTokenResJson responseData = new ComboTokenResJson(); - - // Login - Account account = DatabaseHelper.getAccountById(loginData.uid); - - // Test - if (account == null || !account.getSessionKey().equals(loginData.token)) { - responseData.retcode = -201; - responseData.message = "Wrong session key."; - - Grasscutter.getLogger().info( - String.format("[Dispatch] Client %s failed to exchange combo token", req.ip())); - } else { - responseData.message = "OK"; - responseData.data.open_id = loginData.uid; - responseData.data.combo_id = "157795300"; - responseData.data.combo_token = account.generateLoginToken(); - - Grasscutter.getLogger().info( - String.format("[Dispatch] Client %s succeed to exchange combo token", req.ip())); - } - - res.send(responseData); - }); - - // TODO: There are some missing route request types here (You can tell if they are missing if they are .all and not anything else) - // When http requests for theses routes are found please remove it from the list in DispatchHttpJsonHandler and update the route request types here - - // Agreement and Protocol - // hk4e-sdk-os.hoyoverse.com - httpServer.get("/hk4e_global/mdk/agreement/api/getAgreementInfos", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"marketing_agreements\":[]}}")); - // hk4e-sdk-os.hoyoverse.com - httpServer.post("/hk4e_global/combo/granter/api/compareProtocolVersion", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"modified\":true,\"protocol\":{\"id\":0,\"app_id\":4,\"language\":\"en\",\"user_proto\":\"\",\"priv_proto\":\"\",\"major\":7,\"minimum\":0,\"create_time\":\"0\",\"teenager_proto\":\"\",\"third_proto\":\"\"}}}")); - - // Game data - // hk4e-api-os.hoyoverse.com - httpServer.all("/common/hk4e_global/announcement/api/getAlertPic", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"total\":0,\"list\":[]}}")); - // hk4e-api-os.hoyoverse.com - httpServer.all("/common/hk4e_global/announcement/api/getAlertAnn", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"alert\":false,\"alert_id\":0,\"remind\":true}}")); - // hk4e-api-os.hoyoverse.com - httpServer.all("/common/hk4e_global/announcement/api/getAnnList", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"list\":[],\"total\":0,\"type_list\":[],\"alert\":false,\"alert_id\":0,\"timezone\":0,\"t\":\"" + System.currentTimeMillis() + "\"}}")); - // hk4e-api-os-static.hoyoverse.com - httpServer.all("/common/hk4e_global/announcement/api/getAnnContent", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"list\":[],\"total\":0}}")); - // hk4e-sdk-os.hoyoverse.com - httpServer.all("/hk4e_global/mdk/shopwindow/shopwindow/listPriceTier", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"suggest_currency\":\"USD\",\"tiers\":[]}}")); - - // Captcha - // api-account-os.hoyoverse.com - httpServer.post("/account/risky/api/check", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"id\":\"none\",\"action\":\"ACTION_NONE\",\"geetest\":null}}")); - - // Config - // sdk-os-static.hoyoverse.com - httpServer.get("/combo/box/api/config/sdk/combo", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"vals\":{\"disable_email_bind_skip\":\"false\",\"email_bind_remind_interval\":\"7\",\"email_bind_remind\":\"true\"}}}")); - // hk4e-sdk-os-static.hoyoverse.com - httpServer.get("/hk4e_global/combo/granter/api/getConfig", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"protocol\":true,\"qr_enabled\":false,\"log_level\":\"INFO\",\"announce_url\":\"https://webstatic-sea.hoyoverse.com/hk4e/announcement/index.html?sdk_presentation_style=fullscreen\\u0026sdk_screen_transparent=true\\u0026game_biz=hk4e_global\\u0026auth_appid=announcement\\u0026game=hk4e#/\",\"push_alias_type\":2,\"disable_ysdk_guard\":false,\"enable_announce_pic_popup\":true}}")); - // hk4e-sdk-os-static.hoyoverse.com - httpServer.get("/hk4e_global/mdk/shield/api/loadConfig", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"id\":6,\"game_key\":\"hk4e_global\",\"client\":\"PC\",\"identity\":\"I_IDENTITY\",\"guest\":false,\"ignore_versions\":\"\",\"scene\":\"S_NORMAL\",\"name\":\"原神海外\",\"disable_regist\":false,\"enable_email_captcha\":false,\"thirdparty\":[\"fb\",\"tw\"],\"disable_mmt\":false,\"server_guest\":false,\"thirdparty_ignore\":{\"tw\":\"\",\"fb\":\"\"},\"enable_ps_bind_account\":false,\"thirdparty_login_configs\":{\"tw\":{\"token_type\":\"TK_GAME_TOKEN\",\"game_token_expires_in\":604800},\"fb\":{\"token_type\":\"TK_GAME_TOKEN\",\"game_token_expires_in\":604800}}}}")); - // Test api? - // abtest-api-data-sg.hoyoverse.com - httpServer.post("/data_abtest_api/config/experiment/list", new DispatchHttpJsonHandler("{\"retcode\":0,\"success\":true,\"message\":\"\",\"data\":[{\"code\":1000,\"type\":2,\"config_id\":\"14\",\"period_id\":\"6036_99\",\"version\":\"1\",\"configs\":{\"cardType\":\"old\"}}]}")); - - // log-upload-os.mihoyo.com - httpServer.all("/log/sdk/upload", new DispatchHttpJsonHandler("{\"code\":0}")); - httpServer.all("/sdk/upload", new DispatchHttpJsonHandler("{\"code\":0}")); - httpServer.post("/sdk/dataUpload", new DispatchHttpJsonHandler("{\"code\":0}")); - // /perf/config/verify?device_id=xxx&platform=x&name=xxx - httpServer.all("/perf/config/verify", new DispatchHttpJsonHandler("{\"code\":0}")); - - // Logging servers - // overseauspider.yuanshen.com - httpServer.all("/log", new DispatchHttpJsonHandler("{\"code\":0}")); - // log-upload-os.mihoyo.com - httpServer.all("/crash/dataUpload", new DispatchHttpJsonHandler("{\"code\":0}")); - - httpServer.get("/gacha", (req, res) -> res.send("Gacha")); - - Grasscutter.getDispatchServer().setHttpServer(httpServer); + } else { + Grasscutter.getLogger().error("GCAuth could not be enabled"); + } } @Override public void onDisable() { - super.onDisable(); + if(Grasscutter.getDispatchServer().getAuthHandler().getClass().equals(GCAuthAuthenticationHandler.class)) { + Grasscutter.getDispatchServer().resetAuthHandler(); + } } public static void loadConfig() { diff --git a/src/main/java/me/exzork/gcauth/handler/AuthStatusHandler.java b/src/main/java/me/exzork/gcauth/handler/AuthStatusHandler.java deleted file mode 100644 index f7c83c9..0000000 --- a/src/main/java/me/exzork/gcauth/handler/AuthStatusHandler.java +++ /dev/null @@ -1,20 +0,0 @@ -package me.exzork.gcauth.handler; - -import express.http.HttpContextHandler; -import express.http.Request; -import express.http.Response; -import me.exzork.gcauth.GCAuth; -import me.exzork.gcauth.json.AuthResponseJson; - -import java.io.IOException; - -public class AuthStatusHandler implements HttpContextHandler { - @Override - public void handle(Request request, Response response) throws IOException { - AuthResponseJson authResponse = new AuthResponseJson(); - authResponse.success = true; - authResponse.message = GCAuth.getConfig().Enable ? "AUTH_ENABLED" : "AUTH_DISABLED"; - authResponse.jwt = ""; - response.send(authResponse); - } -} diff --git a/src/main/java/me/exzork/gcauth/handler/ChangePasswordHandler.java b/src/main/java/me/exzork/gcauth/handler/ChangePasswordHandler.java index b5d2983..5b61004 100644 --- a/src/main/java/me/exzork/gcauth/handler/ChangePasswordHandler.java +++ b/src/main/java/me/exzork/gcauth/handler/ChangePasswordHandler.java @@ -18,47 +18,41 @@ public class ChangePasswordHandler implements HttpContextHandler { public void handle(Request request, Response response) throws IOException { AuthResponseJson authResponse = new AuthResponseJson(); - if (GCAuth.getConfig().Enable) { - try { - String requestBody = request.ctx().body(); - if (requestBody.isEmpty()) { - authResponse.success = false; - authResponse.message = "EMPTY_BODY"; // ENG = "No data was sent with the request" - authResponse.jwt = ""; - } else { - ChangePasswordAccount changePasswordAccount = new Gson().fromJson(requestBody, ChangePasswordAccount.class); - if (changePasswordAccount.new_password.equals(changePasswordAccount.new_password_confirmation)) { - Account account = Authentication.getAccountByUsernameAndPassword(changePasswordAccount.username, changePasswordAccount.old_password); - if (account == null) { - authResponse.success = false; - authResponse.message = "INVALID_ACCOUNT"; // ENG = "Invalid username or password" - authResponse.jwt = ""; - } - String newPassword = Authentication.generateHash(changePasswordAccount.new_password); - account.setPassword(newPassword); - account.save(); - authResponse.success = true; - authResponse.message = ""; - authResponse.jwt = ""; - } else { + try { + String requestBody = request.ctx().body(); + if (requestBody.isEmpty()) { + authResponse.success = false; + authResponse.message = "EMPTY_BODY"; // ENG = "No data was sent with the request" + authResponse.jwt = ""; + } else { + ChangePasswordAccount changePasswordAccount = new Gson().fromJson(requestBody, ChangePasswordAccount.class); + if (changePasswordAccount.new_password.equals(changePasswordAccount.new_password_confirmation)) { + Account account = Authentication.getAccountByUsernameAndPassword(changePasswordAccount.username, changePasswordAccount.old_password); + if (account == null) { authResponse.success = false; - authResponse.message = "PASSWORD_MISMATCH"; // ENG = "Passwords do not match." + authResponse.message = "INVALID_ACCOUNT"; // ENG = "Invalid username or password" authResponse.jwt = ""; } + String newPassword = Authentication.generateHash(changePasswordAccount.new_password); + account.setPassword(newPassword); + account.save(); + authResponse.success = true; + authResponse.message = ""; + authResponse.jwt = ""; + } else { + authResponse.success = false; + authResponse.message = "PASSWORD_MISMATCH"; // ENG = "Passwords do not match." + authResponse.jwt = ""; } - } catch (Exception e) { - authResponse.success = false; - authResponse.message = "UNKNOWN"; // ENG = "An unknown error has occurred..." - authResponse.jwt = ""; - Grasscutter.getLogger().error("[Dispatch] Error while changing user password."); - e.printStackTrace(); - response.send(authResponse); } - } else { + } catch (Exception e) { authResponse.success = false; - authResponse.message = "AUTH_DISABLED"; // ENG = "Authentication is not required for this server..." + authResponse.message = "UNKNOWN"; // ENG = "An unknown error has occurred..." authResponse.jwt = ""; + Grasscutter.getLogger().error("[Dispatch] Error while changing user password."); + e.printStackTrace(); } + response.send(authResponse); } } diff --git a/src/main/java/me/exzork/gcauth/handler/ClientLoginHandler.java b/src/main/java/me/exzork/gcauth/handler/ClientLoginHandler.java deleted file mode 100644 index 20aa7b6..0000000 --- a/src/main/java/me/exzork/gcauth/handler/ClientLoginHandler.java +++ /dev/null @@ -1,100 +0,0 @@ -package me.exzork.gcauth.handler; - -import emu.grasscutter.Grasscutter; -import emu.grasscutter.database.DatabaseHelper; -import emu.grasscutter.game.Account; -import emu.grasscutter.server.dispatch.json.LoginAccountRequestJson; -import emu.grasscutter.server.dispatch.json.LoginResultJson; -import express.http.HttpContextHandler; -import express.http.Request; -import express.http.Response; -import me.exzork.gcauth.GCAuth; -import me.exzork.gcauth.utils.Authentication; - -import java.io.IOException; - -public class ClientLoginHandler implements HttpContextHandler { - - @Override - public void handle(Request request, Response response) throws IOException { - LoginAccountRequestJson requestData = null; - try { - String body = request.ctx().body(); - Grasscutter.getLogger().info("Received login request: " + body); - requestData = Grasscutter.getGsonFactory().fromJson(body, LoginAccountRequestJson.class); - } catch (Exception ignored) { - } - - // Create response json - if (requestData == null) { - return; - } - LoginResultJson responseData = new LoginResultJson(); - - Grasscutter.getLogger() - .info(String.format("[Dispatch] Client %s is trying to log in", request.ip())); - - // Login - Account account = null; - if(GCAuth.getConfig().Enable){ - account = Authentication.getAccountByOneTimeToken(requestData.account); - if(account == null) { - Grasscutter.getLogger().info("[Dispatch] Client " + request.ip() + " failed to log in"); - responseData.retcode = -201; - responseData.message = "Token is invalid"; - response.send(responseData); - } - }else{ - account = DatabaseHelper.getAccountByName(requestData.account); - } - - // Check if account exists, else create a new one. - if (account == null) { - // Account doesnt exist, so we can either auto create it if the config value is - // set - if (Grasscutter.getConfig().getDispatchOptions().AutomaticallyCreateAccounts) { - // This account has been created AUTOMATICALLY. There will be no permissions - // added. - account = DatabaseHelper.createAccountWithId(requestData.account, 0); - - for (String permission : Grasscutter.getConfig().getDispatchOptions().defaultPermissions) { - account.addPermission(permission); - } - - if (account != null) { - responseData.message = "OK"; - responseData.data.account.uid = account.getId(); - responseData.data.account.token = account.generateSessionKey(); - responseData.data.account.email = account.getEmail(); - - Grasscutter.getLogger() - .info(String.format("[Dispatch] Client %s failed to log in: Account %s created", - request.ip(), responseData.data.account.uid)); - } else { - responseData.retcode = -201; - responseData.message = "Username not found, create failed."; - - Grasscutter.getLogger().info(String.format( - "[Dispatch] Client %s failed to log in: Account create failed", request.ip())); - } - } else { - responseData.retcode = -201; - responseData.message = "Username not found."; - - Grasscutter.getLogger().info(String - .format("[Dispatch] Client %s failed to log in: Account no found", request.ip())); - } - } else { - // Account was found, log the player in - responseData.message = "OK"; - responseData.data.account.uid = account.getId(); - responseData.data.account.token = account.generateSessionKey(); - responseData.data.account.email = account.getEmail(); - - Grasscutter.getLogger().info(String.format("[Dispatch] Client %s logged in as %s", request.ip(), - responseData.data.account.uid)); - } - - response.send(responseData); - } -} diff --git a/src/main/java/me/exzork/gcauth/handler/GCAuthAuthenticationHandler.java b/src/main/java/me/exzork/gcauth/handler/GCAuthAuthenticationHandler.java new file mode 100644 index 0000000..fe5a65d --- /dev/null +++ b/src/main/java/me/exzork/gcauth/handler/GCAuthAuthenticationHandler.java @@ -0,0 +1,75 @@ +package me.exzork.gcauth.handler; + + +import emu.grasscutter.Grasscutter; +import emu.grasscutter.database.DatabaseHelper; +import emu.grasscutter.game.Account; +import emu.grasscutter.server.dispatch.authentication.AuthenticationHandler; +import emu.grasscutter.server.dispatch.json.LoginAccountRequestJson; +import emu.grasscutter.server.dispatch.json.LoginResultJson; +import express.http.Request; +import express.http.Response; +import me.exzork.gcauth.GCAuth; +import me.exzork.gcauth.utils.Authentication; + +import java.io.IOException; + +public class GCAuthAuthenticationHandler implements AuthenticationHandler { + + @Override + public void handleLogin(Request req, Response res) { + try { + new LoginHandler().handle(req, res); + } catch (IOException e) { + Grasscutter.getLogger().warn("[GCAuth] Unable to handle login request"); + e.printStackTrace(); + } + } + + @Override + public void handleRegister(Request req, Response res) { + try { + new RegisterHandler().handle(req, res); + } catch (IOException e) { + Grasscutter.getLogger().warn("[GCAuth] Unable to handle register request"); + e.printStackTrace(); + } + } + + @Override + public void handleChangePassword(Request req, Response res) { + try { + new ChangePasswordHandler().handle(req, res); + } catch (IOException e) { + Grasscutter.getLogger().warn("[GCAuth] Unable to handle change password request"); + e.printStackTrace(); + } + } + + @Override + public LoginResultJson handleGameLogin(Request request, LoginAccountRequestJson requestData) { + LoginResultJson responseData = new LoginResultJson(); + + Grasscutter.getLogger() + .info(String.format("[Dispatch] Client %s is trying to log in", request.ip())); + + // Login + Account account = Authentication.getAccountByOneTimeToken(requestData.account); + if(account == null) { + Grasscutter.getLogger().info("[Dispatch] Client " + request.ip() + " failed to log in"); + responseData.retcode = -201; + responseData.message = "Token is invalid"; + return responseData; + } + + // Account was found, log the player in + responseData.message = "OK"; + responseData.data.account.uid = account.getId(); + responseData.data.account.token = account.generateSessionKey(); + responseData.data.account.email = account.getEmail(); + + Grasscutter.getLogger().info(String.format("[Dispatch] Client %s logged in as %s", request.ip(), responseData.data.account.uid)); + + return responseData; + } +} diff --git a/src/main/java/me/exzork/gcauth/handler/LoginHandler.java b/src/main/java/me/exzork/gcauth/handler/LoginHandler.java index 6593cf9..fedee7e 100644 --- a/src/main/java/me/exzork/gcauth/handler/LoginHandler.java +++ b/src/main/java/me/exzork/gcauth/handler/LoginHandler.java @@ -18,44 +18,40 @@ public class LoginHandler implements HttpContextHandler { public void handle(Request request, Response response) throws IOException { AuthResponseJson authResponse = new AuthResponseJson(); - if (GCAuth.getConfig().Enable) { - try { - String requestBody = request.ctx().body(); - if (requestBody.isEmpty()) { + + try { + String requestBody = request.ctx().body(); + if (requestBody.isEmpty()) { + authResponse.success = false; + authResponse.message = "EMPTY_BODY"; // ENG = "No data was sent with the request" + authResponse.jwt = ""; + } else { + LoginGenerateToken loginGenerateToken = new Gson().fromJson(requestBody, LoginGenerateToken.class); + Account account = Authentication.getAccountByUsernameAndPassword(loginGenerateToken.username, loginGenerateToken.password); + if (account == null) { authResponse.success = false; - authResponse.message = "EMPTY_BODY"; // ENG = "No data was sent with the request" + authResponse.message = "INVALID_ACCOUNT"; // ENG = "Invalid username or password" authResponse.jwt = ""; } else { - LoginGenerateToken loginGenerateToken = new Gson().fromJson(requestBody, LoginGenerateToken.class); - Account account = Authentication.getAccountByUsernameAndPassword(loginGenerateToken.username, loginGenerateToken.password); - if (account == null) { - authResponse.success = false; - authResponse.message = "INVALID_ACCOUNT"; // ENG = "Invalid username or password" - authResponse.jwt = ""; + if (account.getPassword() != null && !account.getPassword().isEmpty()) { + authResponse.success = true; + authResponse.message = ""; + authResponse.jwt = Authentication.generateJwt(account); } else { - if (account.getPassword() != null && !account.getPassword().isEmpty()) { - authResponse.success = true; - authResponse.message = ""; - authResponse.jwt = Authentication.generateJwt(account); - } else { - authResponse.success = false; - authResponse.message = "NO_PASSWORD"; // ENG = "There is no account password set. Please create a password by resetting it." - authResponse.jwt = ""; - } + authResponse.success = false; + authResponse.message = "NO_PASSWORD"; // ENG = "There is no account password set. Please create a password by resetting it." + authResponse.jwt = ""; } } - } catch (Exception e) { - authResponse.success = false; - authResponse.message = "UNKNOWN"; // ENG = "An unknown error has occurred..." - authResponse.jwt = ""; - Grasscutter.getLogger().error("[Dispatch] An error occurred while a user was logging in."); - e.printStackTrace(); } - } else { + } catch (Exception e) { authResponse.success = false; - authResponse.message = "AUTH_DISABLED"; // ENG = "Authentication is not required for this server..." + authResponse.message = "UNKNOWN"; // ENG = "An unknown error has occurred..." authResponse.jwt = ""; + Grasscutter.getLogger().error("[Dispatch] An error occurred while a user was logging in."); + e.printStackTrace(); } + response.send(authResponse); } } diff --git a/src/main/java/me/exzork/gcauth/handler/RegisterHandler.java b/src/main/java/me/exzork/gcauth/handler/RegisterHandler.java index fa89f34..e0534bf 100644 --- a/src/main/java/me/exzork/gcauth/handler/RegisterHandler.java +++ b/src/main/java/me/exzork/gcauth/handler/RegisterHandler.java @@ -19,45 +19,40 @@ public class RegisterHandler implements HttpContextHandler { public void handle(Request request, Response response) throws IOException { AuthResponseJson authResponse = new AuthResponseJson(); - if (GCAuth.getConfig().Enable) { - try { - String requestBody = request.ctx().body(); - if (requestBody.isEmpty()) { - authResponse.success = false; - authResponse.message = "EMPTY_BODY"; // ENG = "No data was sent with the request" - authResponse.jwt = ""; - } else { - RegisterAccount registerAccount = new Gson().fromJson(requestBody, RegisterAccount.class); - if (registerAccount.password.equals(registerAccount.password_confirmation)) { - String password = Authentication.generateHash(registerAccount.password); - Account account = DatabaseHelper.createAccountWithPassword(registerAccount.username, password); - if (account == null) { - authResponse.success = false; - authResponse.message = "USERNAME_TAKEN"; // ENG = "Username has already been taken by another user." - authResponse.jwt = ""; - } else { - authResponse.success = true; - authResponse.message = ""; - authResponse.jwt = ""; - } - } else { + try { + String requestBody = request.ctx().body(); + if (requestBody.isEmpty()) { + authResponse.success = false; + authResponse.message = "EMPTY_BODY"; // ENG = "No data was sent with the request" + authResponse.jwt = ""; + } else { + RegisterAccount registerAccount = new Gson().fromJson(requestBody, RegisterAccount.class); + if (registerAccount.password.equals(registerAccount.password_confirmation)) { + String password = Authentication.generateHash(registerAccount.password); + Account account = DatabaseHelper.createAccountWithPassword(registerAccount.username, password); + if (account == null) { authResponse.success = false; - authResponse.message = "PASSWORD_MISMATCH"; // ENG = "Passwords do not match." + authResponse.message = "USERNAME_TAKEN"; // ENG = "Username has already been taken by another user." + authResponse.jwt = ""; + } else { + authResponse.success = true; + authResponse.message = ""; authResponse.jwt = ""; } + } else { + authResponse.success = false; + authResponse.message = "PASSWORD_MISMATCH"; // ENG = "Passwords do not match." + authResponse.jwt = ""; } - } catch (Exception e) { - authResponse.success = false; - authResponse.message = "UNKNOWN"; // ENG = "An unknown error has occurred..." - authResponse.jwt = ""; - Grasscutter.getLogger().error("[Dispatch] An error occurred while creating an account."); - e.printStackTrace(); } - } else { + } catch (Exception e) { authResponse.success = false; - authResponse.message = "AUTH_DISABLED"; // ENG = "Authentication is not required for this server..." + authResponse.message = "UNKNOWN"; // ENG = "An unknown error has occurred..." authResponse.jwt = ""; + Grasscutter.getLogger().error("[Dispatch] An error occurred while creating an account."); + e.printStackTrace(); } + response.send(authResponse); } }