From 6d7c2fccff43f090cb3323ad1be424ee1c45f857 Mon Sep 17 00:00:00 2001 From: Alexander Date: Tue, 7 Oct 2025 00:17:54 +0200 Subject: [PATCH] Migrated authentication to OAuth2 and removed legacy user management functionality. --- pom.xml | 20 ++++ resources/config.yml | 31 ++++++ resources/web/css/style.css | 28 +++++ resources/web/index.html | 56 ++-------- resources/web/js/client.account.js | 22 ---- resources/web/js/client.js | 31 +++--- resources/web/js/client.settings.js | 105 ------------------ .../github/dead_i/bungeeweb/APICommand.java | 6 +- src/io/github/dead_i/bungeeweb/BungeeWeb.java | 57 +--------- .../github/dead_i/bungeeweb/WebHandler.java | 64 ++++++++--- .../dead_i/bungeeweb/api/ChangePassword.java | 39 ------- .../dead_i/bungeeweb/api/CreateUser.java | 51 --------- .../dead_i/bungeeweb/api/DeleteUser.java | 35 ------ .../github/dead_i/bungeeweb/api/EditUser.java | 81 -------------- .../dead_i/bungeeweb/api/GetSession.java | 11 +- .../github/dead_i/bungeeweb/api/GetUsers.java | 41 ------- 16 files changed, 175 insertions(+), 503 deletions(-) delete mode 100644 resources/web/js/client.account.js delete mode 100644 resources/web/js/client.settings.js delete mode 100644 src/io/github/dead_i/bungeeweb/api/ChangePassword.java delete mode 100644 src/io/github/dead_i/bungeeweb/api/CreateUser.java delete mode 100644 src/io/github/dead_i/bungeeweb/api/DeleteUser.java delete mode 100644 src/io/github/dead_i/bungeeweb/api/EditUser.java delete mode 100644 src/io/github/dead_i/bungeeweb/api/GetUsers.java diff --git a/pom.xml b/pom.xml index 2b8e167..4afe31c 100644 --- a/pom.xml +++ b/pom.xml @@ -137,5 +137,25 @@ 1.15 compile + + + com.nimbusds + oauth2-oidc-sdk + 9.43.3 + compile + + + com.nimbusds + nimbus-jose-jwt + 9.37.3 + compile + + + + org.apache.httpcomponents + httpclient + 4.5.14 + compile + diff --git a/resources/config.yml b/resources/config.yml index 43f74f5..c63ab02 100644 --- a/resources/config.yml +++ b/resources/config.yml @@ -56,6 +56,37 @@ log: punishment: true info: true +# OAuth2 Configuration +oauth2: + # OAuth2 provider settings + client_id: "your_client_id" + client_secret: "your_client_secret" + + # OAuth2 endpoints + authorization_url: "https://your-provider.com/oauth2/authorize" + token_url: "https://your-provider.com/oauth2/token" + user_info_url: "https://your-provider.com/oauth2/userinfo" + + # OAuth2 scopes to request + scopes: "openid profile groups" + + # Redirect URI (should match your web server URL + /oauth2/callback) + redirect_uri: "http://localhost:8080/oauth2/callback" + + # Group mapping from OAuth2 claims to local groups + # Maps OAuth2 group names to local group numbers + group_mapping: + "moderators": 1 + "admins": 2 + "superadmins": 3 + "default": 1 # Default group for users not in any mapped group + + # JWT claim field that contains user groups (e.g., "groups", "roles", "teams") + groups_claim: "groups" + + # JWT claim field that contains username (e.g., "preferred_username", "sub", "email") + username_claim: "preferred_username" + # Permissions for each group permissions: group1: # moderator diff --git a/resources/web/css/style.css b/resources/web/css/style.css index a883019..5d53321 100644 --- a/resources/web/css/style.css +++ b/resources/web/css/style.css @@ -682,3 +682,31 @@ input[type="submit"]:hover, .btn:hover { font-size:16px; } } + +/* OAuth2 Login Button Styles */ +.oauth2-btn { + display: inline-block; + padding: 12px 24px; + background-color: #4CAF50; + color: white; + text-decoration: none; + border-radius: 4px; + font-size: 16px; + font-weight: bold; + transition: background-color 0.3s; +} + +.oauth2-btn:hover { + background-color: #45a049; + text-decoration: none; + color: white; +} + +.oauth2-login { + text-align: center; +} + +.oauth2-login p { + margin: 20px 0; + color: #666; +} \ No newline at end of file diff --git a/resources/web/index.html b/resources/web/index.html index d01bd6c..bbe4c24 100644 --- a/resources/web/index.html +++ b/resources/web/index.html @@ -57,11 +57,9 @@

BungeeWeb

@@ -109,37 +107,6 @@

-
-

-
- -
    -
    - -
    -
    - -
    -
    -
    -
    - - - -
    -
    -
    -
    - -
    -

    -
    -
    -
    -
    - -
    -
    @@ -147,16 +114,13 @@

    BungeeWeb

    -
    +
    @@ -168,7 +132,5 @@

    BungeeWeb

    - - diff --git a/resources/web/js/client.account.js b/resources/web/js/client.account.js deleted file mode 100644 index c697868..0000000 --- a/resources/web/js/client.account.js +++ /dev/null @@ -1,22 +0,0 @@ -// Account settings page -pages.account = (function() { - // Password change submission handler - $('.password').submit(function(e) { - e.preventDefault(); - if ($(this).find('#newpass').val() != $(this).find('#confirmpass').val()) { - error(lang.error.passwordmismatch); - return; - } - - $.post('api/changepassword', $(this).serialize()).done(function(data) { - data = parse(data); - if (data.status == 1) { - error(lang.error.passwordsuccess); - }else{ - error(lang.error.passwordincorrect); - } - }); - }); - - return {} -})(); \ No newline at end of file diff --git a/resources/web/js/client.js b/resources/web/js/client.js index c80ab11..a00a48c 100644 --- a/resources/web/js/client.js +++ b/resources/web/js/client.js @@ -17,20 +17,25 @@ $(document).ready(function () { }); }); -// Login handler -$('.login form').submit(function (e) { - e.preventDefault(); - hide($('.login .error')); - $.post('login', $(this).serialize()).done(function (data) { - var data = parse(data); - if (data.status == 1) { - updateSession(function () { - hide($('.login'), loadClient); - }); - } else { - $('.login .error').slideDown(200); +// OAuth2 error handler +$(document).ready(function() { + var urlParams = new URLSearchParams(window.location.search); + var error = urlParams.get('error'); + if (error) { + var errorMessage = 'Authentication failed'; + switch(error) { + case 'oauth_failed': + errorMessage = 'OAuth2 authentication failed'; + break; + case 'oauth_exchange_failed': + errorMessage = 'Failed to exchange OAuth2 code'; + break; + case 'missing_code': + errorMessage = 'Missing authorization code'; + break; } - }); + $('.login .error').text(errorMessage).show(); + } }); // Session updater diff --git a/resources/web/js/client.settings.js b/resources/web/js/client.settings.js deleted file mode 100644 index 8798d58..0000000 --- a/resources/web/js/client.settings.js +++ /dev/null @@ -1,105 +0,0 @@ -// Server settings page -pages.settings = (function() { - // When the page is navigated to - function navigate() { - $('#settings > div').removeClass('active').hide(); - $('#settings .userlist').addClass('active').show(); - updateUsers(); - } - - // Settings page switcher - function switchSettings(el) { - hide($('#settings .active').removeClass('active'), function() { - show($('#settings').find(el).addClass('active')); - }); - } - - // Settings group updater - function updateGroups() { - var sel = $('#settings select#group').html(''); - for (id in groups) { - if (id > 0 && (id < session.group || session.group >= 3)) { - sel.append(''); - } - } - } - - // Settings list updater - function updateUsers() { - $('#settings .log').html(''); - query('api/getusers', function(data) { - for (item in data) { - $('#settings .log').append('
  • ' + strip(data[item].user) + ' (' + groups[data[item].group] + ')
  • '); - if (session.group >= 3 || (session.group > data[item].group && item != session.id)) $('#settings .log li .right').last().append('Edit'); - } - }); - } - - // Settings ajax handler - function settingsHandler(data) { - var data = parse(data); - if (data.status == 1) { - updateUsers(); - switchSettings('.userlist'); - error(lang.error.modifysuccess); - }else{ - error(lang.error.modifyerror); - } - } - - // User create button handler - $('#settings #createbtn').click(function() { - updateGroups(); - $('.useredit #id').val('0'); - $('.useredit input[type="text"], .useredit input[type="password"]').val(''); - $('.useredit .delete').hide(); - switchSettings('.useredit'); - }); - - // User edit button handler - $('#settings .log').on('click', '.edit', function() { - updateGroups(); - var li = $(this).closest('li'); - $('.useredit .delete').show(); - $('.useredit #id').val(li.attr('data-user-id')); - $('.useredit #user').val(li.find('.user').text()); - $('.useredit #pass').val('password'); - $('.useredit #group option[value="' + li.attr('data-group-id') + '"]').prop('selected', true); - switchSettings('.useredit'); - }); - - // User delete button handler - $('#settings .delete').click(function() { - if (window.confirm('Are you sure you wish to permanently delete this user? This action cannot be undone.')) { - query('api/deleteuser?id=' + $('.useredit #id').val(), function(data) { - if (data.status == 1) { - updateUsers(); - switchSettings('.userlist'); - error(lang.error.deletesuccess); - }else{ - error(lang.error.deleteerror); - } - }); - } - }); - - // User cancel button handler - $('#settings .cancel').click(function() { - switchSettings('.userlist'); - }); - - // User edit form handler - $('#settings .useredit form').submit(function(e) { - e.preventDefault(); - if ($(this).find('#id').val() > 0) { - if ($(this).find('#pass').val() == 'password') $(this).find('#pass').val(''); - $.post('api/edituser', $(this).serialize(), settingsHandler); - }else{ - $.post('api/createuser', $(this).serialize(), settingsHandler); - } - }); - - return { - navigate: navigate - } -})(); \ No newline at end of file diff --git a/src/io/github/dead_i/bungeeweb/APICommand.java b/src/io/github/dead_i/bungeeweb/APICommand.java index 3ec2185..2891b7e 100644 --- a/src/io/github/dead_i/bungeeweb/APICommand.java +++ b/src/io/github/dead_i/bungeeweb/APICommand.java @@ -32,8 +32,12 @@ public boolean hasPermission(HttpServletRequest req, String i) { if (group == null) { group = 0; } + + // Check if user is authenticated via OAuth2 + String oauth2User = (String) req.getSession().getAttribute("oauth2_user"); + boolean isAuthenticated = oauth2User != null; - return group > 0 && (i == null || i.isEmpty() || BungeeWeb.getGroupPermissions(group).contains(permission)); + return isAuthenticated && group > 0 && (i == null || i.isEmpty() || BungeeWeb.getGroupPermissions(group).contains(permission)); } public abstract void execute(Plugin plugin, HttpServletRequest req, HttpServletResponse res, String[] args) throws IOException, SQLException; diff --git a/src/io/github/dead_i/bungeeweb/BungeeWeb.java b/src/io/github/dead_i/bungeeweb/BungeeWeb.java index a64f410..43f4989 100644 --- a/src/io/github/dead_i/bungeeweb/BungeeWeb.java +++ b/src/io/github/dead_i/bungeeweb/BungeeWeb.java @@ -82,26 +82,14 @@ public void onEnable() { try (PreparedStatement preparedStatement = connection.prepareStatement("CREATE TABLE IF NOT EXISTS `" + getConfig().getString("database.prefix") + "log` (`id` int(16) NOT NULL AUTO_INCREMENT, `time` int(10) NOT NULL, `type` int(2) NOT NULL, `uuid` varchar(32) NOT NULL, `username` varchar(16) NOT NULL, `content` varchar(100) NOT NULL DEFAULT '', PRIMARY KEY (`id`)) CHARACTER SET utf8")) { preparedStatement.executeUpdate(); } - try (PreparedStatement preparedStatement = connection.prepareStatement("CREATE TABLE IF NOT EXISTS `" + getConfig().getString("database.prefix") + "users` (`id` int(4) NOT NULL AUTO_INCREMENT, `user` varchar(16) NOT NULL, `pass` varchar(32) NOT NULL, `salt` varchar(16) NOT NULL, `group` int(1) NOT NULL DEFAULT '1', PRIMARY KEY (`id`)) CHARACTER SET utf8")) { - preparedStatement.executeUpdate(); - } try (PreparedStatement preparedStatement = connection.prepareStatement("CREATE TABLE IF NOT EXISTS `" + getConfig().getString("database.prefix") + "stats` (`id` int(16) NOT NULL AUTO_INCREMENT, `time` int(10) NOT NULL, `playercount` int(6) NOT NULL DEFAULT -1, `maxplayers` int(6) NOT NULL DEFAULT -1, `activity` int(12) NOT NULL DEFAULT -1, PRIMARY KEY (`id`)) CHARACTER SET utf8")) { preparedStatement.executeUpdate(); } - try (PreparedStatement preparedStatement = connection.prepareStatement("SELECT COUNT(*) FROM `" + getConfig().getString("database.prefix") + "users`")) { - ResultSet resultSet = preparedStatement.executeQuery(); - while (resultSet.next()) { - if (resultSet.getInt(1) == 0) { - String salt = salt(); - try (PreparedStatement preparedStatement1 = connection.prepareStatement("INSERT INTO `" + getConfig().getString("database.prefix") + "users` (`user`, `pass`, `salt`, `group`) VALUES('admin', '" + encrypt("admin", salt) + "', '" + salt + "', 3)")) { - preparedStatement1.executeUpdate(); - } - getLogger().warning("A new admin account has been created."); - getLogger().warning("Both the username and password is 'admin'. Please change the password after first logging in."); - } - } - } + // Note: OAuth2 authentication is now used instead of database users + getLogger().info("OAuth2 authentication is configured. Please ensure your OAuth2 settings are correct in config.yml"); + getLogger().info("Users will authenticate via OAuth2 provider instead of local username/password"); + getLogger().info("Group mapping is configured via the oauth2.group_mapping section in config.yml"); } catch (SQLException e) { getLogger().severe("Unable to connect to the database. Disabling..."); e.printStackTrace(); @@ -236,28 +224,7 @@ public static String getUUID(ProxiedPlayer p) { return p.getUniqueId().toString().replace("-", ""); } - public static LoginEntity getLogin(String user, String pass) { - if (user == null || pass == null) return null; - try (Connection connection = hikariDataSource.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `" + BungeeWeb.getConfig().getString("database.prefix") + "users` WHERE `user`=?")) { - preparedStatement.setString(1, user); - ResultSet rs = preparedStatement.executeQuery(); - while (rs.next()) { - if (rs.getString("pass").equals(BungeeWeb.encrypt(pass + rs.getString("salt")))) { - return LoginEntity.builder() - .id(rs.getInt("id")) - .user(rs.getString("user")) - .pass(rs.getString("pass")) - .group(rs.getInt("group")) - .salt(rs.getString("salt")) - .build(); - } - } - } catch (SQLException e) { - e.printStackTrace(); - } - return null; - } + // Legacy method removed - OAuth2 authentication is now used public static List getGroupPermissions(int group) { List permissions = new ArrayList<>(); @@ -276,19 +243,7 @@ public static int getGroupPower(HttpServletRequest req) { return group; } - public static String encrypt(String pass) { - return Password.MD5.digest(pass).split(":")[1]; - } - - public static String encrypt(String pass, String salt) { - return encrypt(pass + salt); - } - - public static String salt() { - byte[] salt = new byte[16]; - new SecureRandom().nextBytes(salt); - return DatatypeConverter.printBase64Binary(salt).substring(0, 16); - } + // Legacy password encryption methods removed - OAuth2 authentication is now used public static boolean isNumber(String number) { int o; diff --git a/src/io/github/dead_i/bungeeweb/WebHandler.java b/src/io/github/dead_i/bungeeweb/WebHandler.java index f4a10e7..3543f56 100644 --- a/src/io/github/dead_i/bungeeweb/WebHandler.java +++ b/src/io/github/dead_i/bungeeweb/WebHandler.java @@ -3,6 +3,8 @@ import com.google.common.io.ByteStreams; import io.github.dead_i.bungeeweb.api.*; import io.github.dead_i.bungeeweb.classes.LoginEntity; +import io.github.dead_i.bungeeweb.classes.OAuth2UserEntity; +import io.github.dead_i.bungeeweb.oauth2.OAuth2Service; import net.md_5.bungee.api.plugin.Plugin; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; @@ -20,22 +22,20 @@ public class WebHandler extends AbstractHandler { private final HashMap commands = new HashMap<>(); private final Plugin plugin; + private final OAuth2Service oauth2Service; public WebHandler(Plugin plugin) { this.plugin = plugin; - registerCommand(new ChangePassword()); - registerCommand(new CreateUser()); - registerCommand(new DeleteUser()); - registerCommand(new EditUser()); + this.oauth2Service = new OAuth2Service(); registerCommand(new GetLang()); registerCommand(new GetLogs()); registerCommand(new GetServers()); registerCommand(new GetSession()); registerCommand(new GetStats()); registerCommand(new GetTypes()); - registerCommand(new GetUsers()); registerCommand(new GetUUID()); registerCommand(new ListServers()); + // Note: Removed user management commands as they're no longer needed with OAuth2 } @Override @@ -65,14 +65,52 @@ public void handle(String target, Request baseReq, HttpServletRequest req, HttpS baseReq.setHandled(true); } } else if (path.length > 1 && path[1].equalsIgnoreCase("login")) { - LoginEntity login = BungeeWeb.getLogin(req.getParameter("user"), req.getParameter("pass")); - if (req.getMethod().equals("POST") && login != null) { - req.getSession().setAttribute("id", login.getId()); - req.getSession().setAttribute("user", login.getUser()); - req.getSession().setAttribute("group", login.getGroup()); - res.getWriter().print("{ \"status\": 1 }"); - } else { - res.getWriter().print("{ \"status\": 0 }"); + // Redirect to OAuth2 authorization URL + try { + String authUrl = oauth2Service.getAuthorizationUrl(); + res.sendRedirect(authUrl); + } catch (Exception e) { + plugin.getLogger().severe("Failed to generate OAuth2 authorization URL: " + e.getMessage()); + res.getWriter().print("{ \"error\": \"OAuth2 configuration error\" }"); + } + baseReq.setHandled(true); + } else if (path.length > 2 && path[1].equalsIgnoreCase("oauth2") && path[2].equalsIgnoreCase("callback")) { + // Handle OAuth2 callback + String code = req.getParameter("code"); + String state = req.getParameter("state"); + String error = req.getParameter("error"); + + if (error != null) { + plugin.getLogger().warning("OAuth2 error: " + error); + res.sendRedirect("/?error=oauth_failed"); + baseReq.setHandled(true); + return; + } + + if (code == null) { + res.sendRedirect("/?error=missing_code"); + baseReq.setHandled(true); + return; + } + + try { + OAuth2UserEntity user = oauth2Service.exchangeCodeForUser(code, state); + + // Store user info in session + req.getSession().setAttribute("oauth2_user", user.getUsername()); + req.getSession().setAttribute("oauth2_email", user.getEmail()); + req.getSession().setAttribute("group", user.getGroup()); + req.getSession().setAttribute("oauth2_groups", user.getOauth2Groups()); + req.getSession().setAttribute("oauth2_access_token", user.getAccessToken()); + req.getSession().setAttribute("oauth2_refresh_token", user.getRefreshToken()); + req.getSession().setAttribute("oauth2_expires_at", user.getExpiresAt()); + + // Redirect to main page + res.sendRedirect("/"); + } catch (Exception e) { + plugin.getLogger().severe("Failed to exchange OAuth2 code: " + e.getMessage()); + e.printStackTrace(); + res.sendRedirect("/?error=oauth_exchange_failed"); } baseReq.setHandled(true); } else if (path.length > 1 && path[1].equalsIgnoreCase("logout")) { diff --git a/src/io/github/dead_i/bungeeweb/api/ChangePassword.java b/src/io/github/dead_i/bungeeweb/api/ChangePassword.java deleted file mode 100644 index 867cac2..0000000 --- a/src/io/github/dead_i/bungeeweb/api/ChangePassword.java +++ /dev/null @@ -1,39 +0,0 @@ -package io.github.dead_i.bungeeweb.api; - -import io.github.dead_i.bungeeweb.APICommand; -import io.github.dead_i.bungeeweb.BungeeWeb; -import net.md_5.bungee.api.plugin.Plugin; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; - -public class ChangePassword extends APICommand { - public ChangePassword() { - super("changepassword", "settings.password"); - } - - @Override - public void execute(Plugin plugin, HttpServletRequest req, HttpServletResponse res, String[] args) throws IOException, SQLException { - String current = req.getParameter("currentpass"); - String pass = req.getParameter("newpass"); - String confirm = req.getParameter("confirmpass"); - if (current != null && pass != null && pass.equals(confirm) && BungeeWeb.getLogin((String) req.getSession().getAttribute("user"), current) != null) { - try (Connection connection = BungeeWeb.getHikariDataSource().getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `" + BungeeWeb.getConfig().getString("database.prefix") + "users` SET `pass`=?, `salt`=? WHERE `id`=?")) { - - String salt = BungeeWeb.salt(); - preparedStatement.setString(1, BungeeWeb.encrypt(req.getParameter("newpass"), salt)); - preparedStatement.setString(2, salt); - preparedStatement.setInt(3, (Integer) req.getSession().getAttribute("id")); - preparedStatement.executeUpdate(); - } - res.getWriter().print("{ \"status\": 1 }"); - } else { - res.getWriter().print("{ \"status\": 0 }"); - } - } -} diff --git a/src/io/github/dead_i/bungeeweb/api/CreateUser.java b/src/io/github/dead_i/bungeeweb/api/CreateUser.java deleted file mode 100644 index bbb6419..0000000 --- a/src/io/github/dead_i/bungeeweb/api/CreateUser.java +++ /dev/null @@ -1,51 +0,0 @@ -package io.github.dead_i.bungeeweb.api; - -import io.github.dead_i.bungeeweb.APICommand; -import io.github.dead_i.bungeeweb.BungeeWeb; -import net.md_5.bungee.api.plugin.Plugin; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; - -public class CreateUser extends APICommand { - public CreateUser() { - super("createuser", "settings.users.create"); - } - - @Override - public void execute(Plugin plugin, HttpServletRequest req, HttpServletResponse res, String[] args) throws IOException, SQLException { - String user = req.getParameter("user"); - String pass = req.getParameter("pass"); - String group = req.getParameter("group"); - String salt = BungeeWeb.salt(); - - if (user != null && !user.isEmpty() && pass != null && !pass.isEmpty() && group != null && BungeeWeb.isNumber(group)) { - if (user.length() <= 16) { - int groupid = Integer.parseInt(group); - if (groupid < BungeeWeb.getGroupPower(req)) { - try (Connection connection = BungeeWeb.getHikariDataSource().getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `" + BungeeWeb.getConfig().getString("database.prefix") + "users` (`user`, `pass`, `salt`, `group`) VALUES(?, ?, ?, ?)")) { - - preparedStatement.setString(1, user); - preparedStatement.setString(2, BungeeWeb.encrypt(pass, salt)); - preparedStatement.setString(3, salt); - preparedStatement.setInt(4, groupid); - preparedStatement.executeUpdate(); - } - - res.getWriter().print("{ \"status\": 1 }"); - } else { - res.getWriter().print("{ \"status\": 0, \"error\": \"You do not have permission to create a user of this group.\" }"); - } - } else { - res.getWriter().print("{ \"status\": 0, \"error\": \"The username provided is too long.\" }"); - } - } else { - res.getWriter().print("{ \"status\": 0, \"error\": \"Incorrect usage.\" }"); - } - } -} diff --git a/src/io/github/dead_i/bungeeweb/api/DeleteUser.java b/src/io/github/dead_i/bungeeweb/api/DeleteUser.java deleted file mode 100644 index c652e9c..0000000 --- a/src/io/github/dead_i/bungeeweb/api/DeleteUser.java +++ /dev/null @@ -1,35 +0,0 @@ -package io.github.dead_i.bungeeweb.api; - -import io.github.dead_i.bungeeweb.APICommand; -import io.github.dead_i.bungeeweb.BungeeWeb; -import net.md_5.bungee.api.plugin.Plugin; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; - -public class DeleteUser extends APICommand { - public DeleteUser() { - super("deleteuser", "settings.users.delete"); - } - - @Override - public void execute(Plugin plugin, HttpServletRequest req, HttpServletResponse res, String[] args) throws IOException, SQLException { - String id = req.getParameter("id"); - if (id != null && !id.isEmpty() && BungeeWeb.isNumber(id)) { - try (Connection connection = BungeeWeb.getHikariDataSource().getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `" + BungeeWeb.getConfig().getString("database.prefix") + "users` WHERE `id`=? AND `group` conditions = new ArrayList<>(); - List params = new ArrayList<>(); - - String user = req.getParameter("user"); - if (user != null && !user.isEmpty() && user.length() <= 16) { - conditions.add("user"); - params.add(user); - } - - String pass = req.getParameter("pass"); - if (pass != null && !pass.isEmpty()) { - String salt = BungeeWeb.salt(); - conditions.add("pass"); - params.add(BungeeWeb.encrypt(pass, salt)); - conditions.add("salt"); - params.add(salt); - } - - String group = req.getParameter("group"); - int groupid = Integer.parseInt(group); - if (!group.isEmpty() && BungeeWeb.isNumber(group)) { - conditions.add("group"); - params.add(groupid); - } - - String id = req.getParameter("id"); - if (id != null && !id.isEmpty() && BungeeWeb.isNumber(id) && !conditions.isEmpty()) { - int power = BungeeWeb.getGroupPower(req); - if (!conditions.contains("group") || groupid < power) { - StringBuilder cond = new StringBuilder(); - for (String s : conditions) { - cond.append("`").append(s).append("`=?, "); - } - cond = new StringBuilder(cond.substring(0, cond.length() - 2)); - - try (Connection connection = BungeeWeb.getHikariDataSource().getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `" + BungeeWeb.getConfig().getString("database.prefix") + "users` SET " + cond + " WHERE `id`=? AND `group` out = new HashMap<>(); Integer group = (Integer) req.getSession().getAttribute("group"); - if (group == null) { + String oauth2User = (String) req.getSession().getAttribute("oauth2_user"); + + if (group == null || oauth2User == null) { out.put("group", 0); - }else{ - out.put("id", req.getSession().getAttribute("id")); - out.put("user", req.getSession().getAttribute("user")); + } else { + out.put("user", oauth2User); + out.put("email", req.getSession().getAttribute("oauth2_email")); out.put("group", group); + out.put("oauth2_groups", req.getSession().getAttribute("oauth2_groups")); out.put("updatetime", BungeeWeb.getConfig().getInt("server.updatetime", 10)); out.put("permissions", BungeeWeb.getGroupPermissions(group)); } diff --git a/src/io/github/dead_i/bungeeweb/api/GetUsers.java b/src/io/github/dead_i/bungeeweb/api/GetUsers.java deleted file mode 100644 index 3938838..0000000 --- a/src/io/github/dead_i/bungeeweb/api/GetUsers.java +++ /dev/null @@ -1,41 +0,0 @@ -package io.github.dead_i.bungeeweb.api; - -import com.google.gson.Gson; -import io.github.dead_i.bungeeweb.APICommand; -import io.github.dead_i.bungeeweb.BungeeWeb; -import net.md_5.bungee.api.plugin.Plugin; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.HashMap; -import java.util.Map; - -public class GetUsers extends APICommand { - private final Gson gson = new Gson(); - - public GetUsers() { - super("getusers", "settings.users.list"); - } - - @Override - public void execute(Plugin plugin, HttpServletRequest req, HttpServletResponse res, String[] args) throws IOException, SQLException { - Map out = new HashMap<>(); - try (Connection connection = BungeeWeb.getHikariDataSource().getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `" + BungeeWeb.getConfig().getString("database.prefix") + "users`")) { - ResultSet resultSet = preparedStatement.executeQuery(); - - while (resultSet.next()) { - HashMap record = new HashMap<>(); - record.put("user", resultSet.getString("user")); - record.put("group", resultSet.getInt("group")); - out.put(resultSet.getInt("id"), record); - } - res.getWriter().print(gson.toJson(out)); - } - } -}