🔨 Update user info in db on login

This commit is contained in:
SebClem 2022-05-23 14:53:10 +02:00
parent 88e4b07312
commit 62db3f0f6d
Signed by: sebclem
GPG Key ID: 5A4308F6A359EA50
11 changed files with 278 additions and 27 deletions

View File

@ -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();
}
}

View File

@ -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<UserEntity> 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 ?");

View File

@ -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>(T response, boolean created) {
}
public LoginOrRegisterResponse<UserEntity> loginOrRegisterDiscordUser(DiscordOauthUserInfo discordOauthUserInfo) {
Optional<UserEntity> 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<String, String> 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());
}
}

View File

@ -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)

View File

@ -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;
}
}

View File

@ -11,7 +11,7 @@ import java.util.Optional;
*/
public interface UserRepository extends CrudRepository<UserEntity, Integer> {
List<UserEntity> findByName(String name);
List<UserEntity> findByUsername(String username);
Optional<UserEntity> findByDiscordId(String discordId);
}

View File

@ -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);
}
}

View File

@ -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();
}

View File

@ -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;

View File

@ -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<UserStats> stats;
if (userEntity.getUserStats() == null || userEntity.getUserStats().size() == 0) {
@ -118,7 +118,7 @@ public class UserStatsUtils {
List<UserStats> 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<UserStats> 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;
}

View File

@ -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