From 62db3f0f6dcd0d8fa2b9a7ded62a70aa1dfa7874 Mon Sep 17 00:00:00 2001 From: SebClem Date: Mon, 23 May 2022 14:53:10 +0200 Subject: [PATCH] :hammer: Update user info in db on login --- .../Api/Controllers/HelloController.java | 2 +- .../DiscordAuthenticationProvider.java | 6 +- .../Services/DiscordOauthService.java | 40 +++- .../Api/Security/Services/JwtService.java | 2 +- .../java/net/Broken/DB/Entity/UserEntity.java | 44 ++++- .../Broken/DB/Repository/UserRepository.java | 2 +- .../Broken/RestApi/MusicWebAPIController.java | 6 +- .../Broken/RestApi/SettingAPIController.java | 2 +- .../java/net/Broken/Tools/CacheTools.java | 2 +- .../UserManager/Stats/UserStatsUtils.java | 12 +- .../db/changelog/db.changelog-master.yml | 187 ++++++++++++++++++ 11 files changed, 278 insertions(+), 27 deletions(-) diff --git a/src/main/java/net/Broken/Api/Controllers/HelloController.java b/src/main/java/net/Broken/Api/Controllers/HelloController.java index 6541c8d..0f6c689 100644 --- a/src/main/java/net/Broken/Api/Controllers/HelloController.java +++ b/src/main/java/net/Broken/Api/Controllers/HelloController.java @@ -16,6 +16,6 @@ public class HelloController { @GetMapping("world") public String helloWorld(Authentication authentication){ UserEntity principal = (UserEntity) authentication.getPrincipal(); - return "Hello " + principal.getName(); + return "Hello " + principal.getUsername(); } } diff --git a/src/main/java/net/Broken/Api/Security/Components/DiscordAuthenticationProvider.java b/src/main/java/net/Broken/Api/Security/Components/DiscordAuthenticationProvider.java index 789bfc6..40b7bad 100644 --- a/src/main/java/net/Broken/Api/Security/Components/DiscordAuthenticationProvider.java +++ b/src/main/java/net/Broken/Api/Security/Components/DiscordAuthenticationProvider.java @@ -29,7 +29,11 @@ public class DiscordAuthenticationProvider implements AuthenticationProvider { String token = discordOauthService.getAccessToken(code, redirectUri); DiscordOauthUserInfo discordOauthUserInfo = discordOauthService.getUserInfo(token); discordOauthService.revokeToken(token); - UserEntity userEntity = discordOauthService.loginOrRegisterDiscordUser(discordOauthUserInfo); + DiscordOauthService.LoginOrRegisterResponse loginOrRegisterResponse = discordOauthService.loginOrRegisterDiscordUser(discordOauthUserInfo); + UserEntity userEntity = loginOrRegisterResponse.response(); + if(!loginOrRegisterResponse.created()){ + userEntity = discordOauthService.updateUserInfo(discordOauthUserInfo, loginOrRegisterResponse.response()); + } return new UsernamePasswordAuthenticationToken(userEntity, null, new ArrayList<>()); } catch (OAuthLoginFail e) { throw new BadCredentialsException("Bad response form Discord Oauth server ! Code expired ?"); diff --git a/src/main/java/net/Broken/Api/Security/Services/DiscordOauthService.java b/src/main/java/net/Broken/Api/Security/Services/DiscordOauthService.java index 2d2bb2d..8ab6d1a 100644 --- a/src/main/java/net/Broken/Api/Security/Services/DiscordOauthService.java +++ b/src/main/java/net/Broken/Api/Security/Services/DiscordOauthService.java @@ -21,6 +21,7 @@ import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; +import java.util.Optional; @Service public class DiscordOauthService { @@ -107,12 +108,41 @@ public class DiscordOauthService { } - public UserEntity loginOrRegisterDiscordUser(DiscordOauthUserInfo discordOauthUserInfo) { - return userRepository - .findByDiscordId(discordOauthUserInfo.id()) - .orElseGet(() -> userRepository.save(new UserEntity(discordOauthUserInfo.username(), discordOauthUserInfo.id()))); + public record LoginOrRegisterResponse(T response, boolean created) { } + public LoginOrRegisterResponse loginOrRegisterDiscordUser(DiscordOauthUserInfo discordOauthUserInfo) { + Optional optionalUserEntity = userRepository.findByDiscordId(discordOauthUserInfo.id()); + return optionalUserEntity.map( + userEntity -> new LoginOrRegisterResponse<>(userEntity, false)) + .orElseGet(() -> { + UserEntity created = userRepository.save(new UserEntity(discordOauthUserInfo)); + return new LoginOrRegisterResponse<>(created, true); + }); + } + + public UserEntity updateUserInfo(DiscordOauthUserInfo discordOauthUserInfo, UserEntity userEntity){ + boolean updated = false; + if(!userEntity.getUsername().equals(discordOauthUserInfo.username())){ + userEntity.setUsername(discordOauthUserInfo.username()); + updated = true; + } + if(!userEntity.getDiscriminator().equals(discordOauthUserInfo.discriminator())){ + userEntity.setDiscriminator(discordOauthUserInfo.discriminator()); + updated = true; + } + if(!userEntity.getAvatar().equals(discordOauthUserInfo.avatar())){ + userEntity.setAvatar(discordOauthUserInfo.avatar()); + updated = true; + } + + if(updated){ + return userRepository.save(userEntity); + } + return userEntity; + } + + private String getFormString(HashMap params) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); boolean first = true; @@ -138,4 +168,6 @@ public class DiscordOauthService { HttpClient client = HttpClient.newHttpClient(); return client.send(request, HttpResponse.BodyHandlers.ofString()); } + + } diff --git a/src/main/java/net/Broken/Api/Security/Services/JwtService.java b/src/main/java/net/Broken/Api/Security/Services/JwtService.java index e27434e..d12bac3 100644 --- a/src/main/java/net/Broken/Api/Security/Services/JwtService.java +++ b/src/main/java/net/Broken/Api/Security/Services/JwtService.java @@ -38,7 +38,7 @@ public class JwtService { return Jwts.builder() - .setSubject(user.getName()) + .setSubject(user.getUsername()) .claim("discord_id", user.getDiscordId()) .setId(uuid.toString()) .setIssuedAt(iat) diff --git a/src/main/java/net/Broken/DB/Entity/UserEntity.java b/src/main/java/net/Broken/DB/Entity/UserEntity.java index 68b9b5d..a35cbad 100644 --- a/src/main/java/net/Broken/DB/Entity/UserEntity.java +++ b/src/main/java/net/Broken/DB/Entity/UserEntity.java @@ -1,6 +1,7 @@ package net.Broken.DB.Entity; import com.fasterxml.jackson.annotation.JsonIgnore; +import net.Broken.Api.Security.Data.DiscordOauthUserInfo; import net.dv8tion.jda.api.entities.User; import javax.persistence.*; @@ -17,11 +18,15 @@ public class UserEntity { @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; - private String name; + private String username; + + private String discriminator; @Column(unique=true) private String discordId; + private String avatar; + private boolean isBotAdmin = false; @JsonIgnore @@ -36,15 +41,22 @@ public class UserEntity { } public UserEntity(User user) { - this.name = user.getName(); + this.username = user.getName(); this.discordId = user.getId(); } - public UserEntity(String name, String id) { - this.name = name; + public UserEntity(String username, String id) { + this.username = username; this.discordId = id; } + public UserEntity(DiscordOauthUserInfo discordOauthUserInfo){ + this.username = discordOauthUserInfo.username(); + this.discriminator = discordOauthUserInfo.discriminator(); + this.discordId = discordOauthUserInfo.id(); + this.avatar = discordOauthUserInfo.avatar(); + } + public Integer getId() { return id; @@ -54,12 +66,12 @@ public class UserEntity { this.id = id; } - public String getName() { - return name; + public void setUsername(String username) { + this.username = username; } - public void setName(String name) { - this.name = name; + public String getUsername() { + return username; } public String getDiscordId() { @@ -100,4 +112,20 @@ public class UserEntity { public void setBotAdmin(boolean botAdmin) { isBotAdmin = botAdmin; } + + public String getAvatar() { + return avatar; + } + + public void setAvatar(String avatar) { + this.avatar = avatar; + } + + public String getDiscriminator() { + return discriminator; + } + + public void setDiscriminator(String discriminator) { + this.discriminator = discriminator; + } } diff --git a/src/main/java/net/Broken/DB/Repository/UserRepository.java b/src/main/java/net/Broken/DB/Repository/UserRepository.java index fe00417..52bcede 100644 --- a/src/main/java/net/Broken/DB/Repository/UserRepository.java +++ b/src/main/java/net/Broken/DB/Repository/UserRepository.java @@ -11,7 +11,7 @@ import java.util.Optional; */ public interface UserRepository extends CrudRepository { - List findByName(String name); + List findByUsername(String username); Optional findByDiscordId(String discordId); } diff --git a/src/main/java/net/Broken/RestApi/MusicWebAPIController.java b/src/main/java/net/Broken/RestApi/MusicWebAPIController.java index 84e3d28..59a595d 100644 --- a/src/main/java/net/Broken/RestApi/MusicWebAPIController.java +++ b/src/main/java/net/Broken/RestApi/MusicWebAPIController.java @@ -100,7 +100,7 @@ public class MusicWebAPIController { try { UserEntity user = userUtils.getUserWithApiToken(userRepository, token); - logger.trace("All info from USER: " + user.getName() + " GUILD: " + guild.getName()); + logger.trace("All info from USER: " + user.getUsername() + " GUILD: " + guild.getName()); PlaylistData list = new PlaylistData(AudioM.getInstance(guild).getGuildMusicManager().scheduler.getList()); CurrentMusicData musicData; @@ -146,7 +146,7 @@ public class MusicWebAPIController { try { UserEntity user = userUtils.getUserWithApiToken(userRepository, token); - logger.info("[" + guild.getName() + "] Receive command" + data.command + " from" + request.getRemoteAddr() + " USER:" + user.getName() + " GUILD:" + guild.getName()); + logger.info("[" + guild.getName() + "] Receive command" + data.command + " from" + request.getRemoteAddr() + " USER:" + user.getUsername() + " GUILD:" + guild.getName()); if (ApiCommandLoader.apiCommands.containsKey(data.command)) { @@ -186,7 +186,7 @@ public class MusicWebAPIController { if (member == null) { member = guild.retrieveMember(CacheTools.getJdaUser(user)).complete(); if (member == null) { - logger.warn("Can't find member " + user.getName() + " for guild " + guild.getName() + ", User not in guild ?"); + logger.warn("Can't find member " + user.getUsername() + " for guild " + guild.getName() + ", User not in guild ?"); return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } } diff --git a/src/main/java/net/Broken/RestApi/SettingAPIController.java b/src/main/java/net/Broken/RestApi/SettingAPIController.java index eb5bc6c..fda8209 100644 --- a/src/main/java/net/Broken/RestApi/SettingAPIController.java +++ b/src/main/java/net/Broken/RestApi/SettingAPIController.java @@ -50,7 +50,7 @@ public class SettingAPIController { Guild jdaGuild = MainBot.jda.getGuildById(guild); try { UserEntity user = UserUtils.getInstance().getUserWithApiToken(userRepository, token); - logger.info(user.getName() + " change config of " + jdaGuild.getName()); + logger.info(user.getUsername() + " change config of " + jdaGuild.getName()); } catch (UnknownTokenException e) { e.printStackTrace(); } diff --git a/src/main/java/net/Broken/Tools/CacheTools.java b/src/main/java/net/Broken/Tools/CacheTools.java index 98668a3..22b0673 100644 --- a/src/main/java/net/Broken/Tools/CacheTools.java +++ b/src/main/java/net/Broken/Tools/CacheTools.java @@ -22,7 +22,7 @@ public class CacheTools { public static User getJdaUser(UserEntity userEntity) { User user = MainBot.jda.getUserById(userEntity.getDiscordId()); if (user == null) { - logger.debug("User cache not found for " + userEntity.getName() + ", fetching user."); + logger.debug("User cache not found for " + userEntity.getUsername() + ", fetching user."); user = MainBot.jda.retrieveUserById(userEntity.getDiscordId()).complete(); } return user; diff --git a/src/main/java/net/Broken/Tools/UserManager/Stats/UserStatsUtils.java b/src/main/java/net/Broken/Tools/UserManager/Stats/UserStatsUtils.java index 63da44a..d05a5ac 100644 --- a/src/main/java/net/Broken/Tools/UserManager/Stats/UserStatsUtils.java +++ b/src/main/java/net/Broken/Tools/UserManager/Stats/UserStatsUtils.java @@ -65,7 +65,7 @@ public class UserStatsUtils { logger.debug(userEntity); logger.debug(userEntity.getUserStats()); if (userEntity.getUserStats() == null || userEntity.getUserStats().size() == 0 || userEntity.getUserStats().size() < jdaUser.getMutualGuilds().size()) { - logger.debug("Stats not found for " + userEntity.getName()); + logger.debug("Stats not found for " + userEntity.getUsername()); List stats; if (userEntity.getUserStats() == null || userEntity.getUserStats().size() == 0) { @@ -118,7 +118,7 @@ public class UserStatsUtils { List userStatsList = userStatsRepository.findByUserAndGuildId(userEntity, member.getGuild().getId()); if (userStatsList.size() == 0) { - logger.debug("User stats not found for user " + userEntity.getName() + " guild: " + member.getGuild().getId()); + logger.debug("User stats not found for user " + userEntity.getUsername() + " guild: " + member.getGuild().getId()); getUserStats(userEntity); userStatsList = userStatsRepository.findByUserAndGuildId(userEntity, member.getGuild().getId()); } @@ -129,7 +129,7 @@ public class UserStatsUtils { public UserStats getGuildUserStats(UserEntity userEntity, String guildId) { List userStatsList = userStatsRepository.findByUserAndGuildId(userEntity, guildId); if (userStatsRepository.findByUserAndGuildId(userEntity, guildId).size() == 0) { - logger.debug("User stats not found for user " + userEntity.getName() + " guild: " + guildId); + logger.debug("User stats not found for user " + userEntity.getUsername() + " guild: " + guildId); getUserStats(userEntity); userStatsList = userStatsRepository.findByUserAndGuildId(userEntity, guildId); } @@ -186,7 +186,7 @@ public class UserStatsUtils { continue; } String avatar = member.getUser().getAvatarUrl(); - GuildStats temp = new GuildStats(stats.getUser().getName(), 0, avatar, stats.getVocalTime(), stats.getMessageCount(), stats.getApiCommandCount()); + GuildStats temp = new GuildStats(stats.getUser().getUsername(), 0, avatar, stats.getVocalTime(), stats.getMessageCount(), stats.getApiCommandCount()); if (stats.getUser().getId().equals(userEntity.getId())) { selfGuildStats = temp; } @@ -198,11 +198,11 @@ public class UserStatsUtils { for (UserStats stats : needCache) { Member member = guild.getMemberById(stats.getUser().getDiscordId()); if (member == null) { - logger.warn("Can't find member '" + stats.getUser().getName() + "'after load, User leave the guild ?"); + logger.warn("Can't find member '" + stats.getUser().getUsername() + "'after load, User leave the guild ?"); continue; } String avatar = member.getUser().getAvatarUrl(); - GuildStats temp = new GuildStats(stats.getUser().getName(), 0, avatar, stats.getVocalTime(), stats.getMessageCount(), stats.getApiCommandCount()); + GuildStats temp = new GuildStats(stats.getUser().getUsername(), 0, avatar, stats.getVocalTime(), stats.getMessageCount(), stats.getApiCommandCount()); if (stats.getUser().getId().equals(userEntity.getId())) { selfGuildStats = temp; } diff --git a/src/main/resources/db/changelog/db.changelog-master.yml b/src/main/resources/db/changelog/db.changelog-master.yml index 3a2fa24..3142169 100644 --- a/src/main/resources/db/changelog/db.changelog-master.yml +++ b/src/main/resources/db/changelog/db.changelog-master.yml @@ -558,3 +558,190 @@ databaseChangeLog: columnDataType: varchar(255) +databaseChangeLog: +- changeSet: + id: 1653309183173-13 + author: seb65 (generated) + changes: + - addColumn: + columns: + - column: + name: avatar + type: varchar(255) + tableName: user_entity +- changeSet: + id: 1653309183173-14 + author: seb65 (generated) + changes: + - addColumn: + columns: + - column: + name: discriminator + type: varchar(255) + tableName: user_entity +- changeSet: + id: 1653309183173-15 + author: seb65 (generated) + changes: + - renameColumn: + oldColumnName: name + newColumnName: username + columnDataType: varchar(255) + tableName: user_entity +- changeSet: + id: 1653309183173-16 + author: seb65 (generated) + changes: + - addUniqueConstraint: + columnNames: discord_id + constraintName: UC_USER_ENTITYDISCORD_ID_COL + tableName: user_entity +- changeSet: + id: 1653309183173-17 + author: seb65 (generated) + changes: + - dropForeignKeyConstraint: + baseTableName: pending_pwd_reset_entity + constraintName: FKatrj670ooxj9qiq230iacbt68 +- changeSet: + id: 1653309183173-18 + author: seb65 (generated) + changes: + - dropForeignKeyConstraint: + baseTableName: guild_preference_entity_visible_voice_chanel + constraintName: FKlyf6ksd3969rqtwm3bqupbniu +- changeSet: + id: 1653309183173-19 + author: seb65 (generated) + changes: + - dropTable: + tableName: guild_preference_entity_visible_voice_chanel +- changeSet: + id: 1653309183173-20 + author: seb65 (generated) + changes: + - dropTable: + tableName: hibernate_sequence +- changeSet: + id: 1653309183173-21 + author: seb65 (generated) + changes: + - dropTable: + tableName: pending_pwd_reset_entity +- changeSet: + id: 1653309183173-22 + author: seb65 (generated) + changes: + - dropTable: + tableName: pending_user_entity +- changeSet: + id: 1653309183173-23 + author: seb65 (generated) + changes: + - dropColumn: + columnName: api_token + tableName: user_entity +- changeSet: + id: 1653309183173-25 + author: seb65 (generated) + changes: + - dropColumn: + columnName: password + tableName: user_entity +- changeSet: + id: 1653309183173-1 + author: seb65 (generated) + changes: + - dropDefaultValue: + columnDataType: varchar(255) + columnName: auto_voice_channel_title + tableName: guild_preference_entity +- changeSet: + id: 1653309183173-2 + author: seb65 (generated) + changes: + - dropDefaultValue: + columnDataType: varchar(255) + columnName: auto_voice_channelid + tableName: guild_preference_entity +- changeSet: + id: 1653309183173-3 + author: seb65 (generated) + changes: + - dropDefaultValue: + columnDataType: varchar(255) + columnName: default_role_id + tableName: guild_preference_entity +- changeSet: + id: 1653309183173-4 + author: seb65 (generated) + changes: + - dropDefaultValue: + columnDataType: varchar(255) + columnName: discord_id + tableName: user_entity +- changeSet: + id: 1653309183173-5 + author: seb65 (generated) + changes: + - dropDefaultValue: + columnDataType: varchar(255) + columnName: guild_id + tableName: guild_preference_entity +- changeSet: + id: 1653309183173-6 + author: seb65 (generated) + changes: + - dropDefaultValue: + columnDataType: varchar(255) + columnName: guild_id + tableName: user_stats +- changeSet: + id: 1653309183173-7 + author: seb65 (generated) + changes: + - dropDefaultValue: + columnDataType: varchar(255) + columnName: identifier + tableName: track_entity +- changeSet: + id: 1653309183173-8 + author: seb65 (generated) + changes: + - dropDefaultValue: + columnDataType: varchar(255) + columnName: name + tableName: playlist_entity +- changeSet: + id: 1653309183173-9 + author: seb65 (generated) + changes: + - dropDefaultValue: + columnDataType: varchar(255) + columnName: title + tableName: track_entity +- changeSet: + id: 1653309183173-10 + author: seb65 (generated) + changes: + - dropDefaultValue: + columnDataType: varchar(255) + columnName: url + tableName: track_entity +- changeSet: + id: 1653309183173-11 + author: seb65 (generated) + changes: + - dropDefaultValue: + columnDataType: varchar(255) + columnName: welcome_chanelid + tableName: guild_preference_entity +- changeSet: + id: 1653309183173-12 + author: seb65 (generated) + changes: + - dropDefaultValue: + columnDataType: varchar(255) + columnName: welcome_message + tableName: guild_preference_entity +