Compare commits

..

1 Commits

Author SHA1 Message Date
43949e2b35
🔨 migrate env to config prop 2022-06-10 13:15:32 +02:00
16 changed files with 12 additions and 356 deletions

View File

@ -1,16 +1,16 @@
package net.Broken.Api.Controllers; package net.Broken.Api.Controllers;
import net.Broken.Api.Data.Guild.Guild; import net.Broken.Api.Data.Guild;
import net.Broken.Api.Data.Guild.Role;
import net.Broken.Api.Data.InviteLink; import net.Broken.Api.Data.InviteLink;
import net.Broken.Api.Data.Guild.Channel;
import net.Broken.Api.Security.Data.JwtPrincipal; import net.Broken.Api.Security.Data.JwtPrincipal;
import net.Broken.Api.Services.GuildService; import net.Broken.Api.Services.GuildService;
import net.Broken.MainBot; import net.Broken.MainBot;
import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.Permission;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List; import java.util.List;
@ -36,23 +36,4 @@ public class GuildController {
String link = MainBot.jda.getInviteUrl(Permission.ADMINISTRATOR); String link = MainBot.jda.getInviteUrl(Permission.ADMINISTRATOR);
return new InviteLink(link); return new InviteLink(link);
} }
@GetMapping("/{guildId}/voiceChannels")
@PreAuthorize("isInGuild(#guildId)")
public List<Channel> getVoiceChannels(@PathVariable String guildId){
return guildService.getVoiceChannel(guildId);
}
@GetMapping("/{guildId}/textChannels")
@PreAuthorize("isInGuild(#guildId)")
public List<Channel> getTextChannels(@PathVariable String guildId){
return guildService.getTextChannel(guildId);
}
@GetMapping("/{guildId}/roles")
@PreAuthorize("isInGuild(#guildId)")
public List<Role> getRoles(@PathVariable String guildId){
return guildService.getRole(guildId);
}
} }

View File

@ -5,7 +5,6 @@ import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.security.SecurityRequirements; import io.swagger.v3.oas.annotations.security.SecurityRequirements;
import net.Broken.Api.Security.Data.JwtPrincipal; import net.Broken.Api.Security.Data.JwtPrincipal;
import net.Broken.DB.Entity.UserEntity; import net.Broken.DB.Entity.UserEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;

View File

@ -1,26 +0,0 @@
package net.Broken.Api.Controllers;
import net.Broken.Api.Data.Settings.SettingGroup;
import net.Broken.Api.Services.SettingService;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/api/v2/setting")
@CrossOrigin(origins = "*", maxAge = 3600)
public class SettingController {
public final SettingService settingService;
public SettingController(SettingService settingService) {
this.settingService = settingService;
}
@GetMapping("description")
public List<SettingGroup> getSettingDescription(){
return settingService.getSettingDescription();
}
}

View File

@ -1,4 +1,4 @@
package net.Broken.Api.Data.Guild; package net.Broken.Api.Data;
public record Guild(String id, String name, String iconUrl) { public record Guild(String id, String name, String iconUrl) {
} }

View File

@ -1,4 +0,0 @@
package net.Broken.Api.Data.Guild;
public record Channel(String id, String name) {
}

View File

@ -1,4 +0,0 @@
package net.Broken.Api.Data.Guild;
public record Role(String id, String name) {
}

View File

@ -1,16 +0,0 @@
package net.Broken.Api.Data.Settings;
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
public record SettingDescriber(
String id,
String name,
String description,
TYPE type
) {
public enum TYPE {
BOOL, LIST, STRING, ROLE, TEXT_CHANNEL, VOICE_CHANNEL
}
}

View File

@ -1,13 +0,0 @@
package net.Broken.Api.Data.Settings;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.util.List;
@JsonInclude(JsonInclude.Include.NON_NULL)
public record SettingGroup(
String name,
SettingDescriber mainField,
List<SettingDescriber> fields
) {
}

View File

@ -1,26 +0,0 @@
package net.Broken.Api.Security.Expression;
import net.Broken.Api.Security.Expression.CustomMethodSecurityExpressionRoot;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler;
import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.core.Authentication;
public class CustomMethodSecurityExpressionHandler
extends DefaultMethodSecurityExpressionHandler {
private AuthenticationTrustResolver trustResolver =
new AuthenticationTrustResolverImpl();
@Override
protected MethodSecurityExpressionOperations createSecurityExpressionRoot(
Authentication authentication, MethodInvocation invocation) {
CustomMethodSecurityExpressionRoot root =
new CustomMethodSecurityExpressionRoot(authentication);
root.setPermissionEvaluator(getPermissionEvaluator());
root.setTrustResolver(this.trustResolver);
root.setRoleHierarchy(getRoleHierarchy());
return root;
}
}

View File

@ -1,56 +0,0 @@
package net.Broken.Api.Security.Expression;
import net.Broken.Api.Security.Data.JwtPrincipal;
import net.Broken.MainBot;
import net.Broken.Tools.CacheTools;
import net.dv8tion.jda.api.entities.Guild;
import okhttp3.Cache;
import org.springframework.security.access.expression.SecurityExpressionRoot;
import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations;
import org.springframework.security.core.Authentication;
public class CustomMethodSecurityExpressionRoot
extends SecurityExpressionRoot
implements MethodSecurityExpressionOperations {
private Object filterObject;
private Object returnObject;
/**
* Creates a new instance
*
* @param authentication the {@link Authentication} to use. Cannot be null.
*/
public CustomMethodSecurityExpressionRoot(Authentication authentication) {
super(authentication);
}
public boolean isInGuild(String guildId){
JwtPrincipal jwtPrincipal = (JwtPrincipal) authentication.getPrincipal();
Guild guild = MainBot.jda.getGuildById(guildId);
return CacheTools.getJdaUser(jwtPrincipal.user()).getMutualGuilds().contains(guild);
}
@Override
public void setFilterObject(Object filterObject) {
this.filterObject = filterObject;
}
@Override
public Object getFilterObject() {
return this.filterObject;
}
@Override
public void setReturnObject(Object returnObject) {
this.returnObject = returnObject;
}
@Override
public Object getReturnObject() {
return this.returnObject;
}
@Override
public Object getThis() {
return this;
}
}

View File

@ -4,9 +4,7 @@ import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws; import io.jsonwebtoken.Jws;
import net.Broken.Api.Security.Data.JwtPrincipal; import net.Broken.Api.Security.Data.JwtPrincipal;
import net.Broken.Api.Security.Services.JwtService; import net.Broken.Api.Security.Services.JwtService;
import net.Broken.BotConfigLoader;
import net.Broken.DB.Entity.UserEntity; import net.Broken.DB.Entity.UserEntity;
import net.Broken.DB.Repository.UserRepository;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -25,10 +23,6 @@ import java.util.ArrayList;
public class JwtFilter extends OncePerRequestFilter { public class JwtFilter extends OncePerRequestFilter {
@Autowired @Autowired
private JwtService jwtService; private JwtService jwtService;
@Autowired
private BotConfigLoader config;
@Autowired
private UserRepository userRepository;
private final Logger logger = LogManager.getLogger(); private final Logger logger = LogManager.getLogger();
@Override @Override
@ -37,17 +31,9 @@ public class JwtFilter extends OncePerRequestFilter {
if (authHeader != null && authHeader.startsWith("Bearer ")) { if (authHeader != null && authHeader.startsWith("Bearer ")) {
String token = authHeader.replace("Bearer ", ""); String token = authHeader.replace("Bearer ", "");
try { try {
UserEntity user; Jws<Claims> jwt = jwtService.verifyAndParseJwt(token);
JwtPrincipal principal; UserEntity user = jwtService.getUserWithJwt(jwt);
if(config.mode().equals("DEV")){ JwtPrincipal principal = new JwtPrincipal(jwt.getBody().getId(), user);
user = userRepository.findByDiscordId(token).orElseThrow();
principal = new JwtPrincipal("DEV", user);
}
else {
Jws<Claims> jwt = jwtService.verifyAndParseJwt(token);
user = jwtService.getUserWithJwt(jwt);
principal = new JwtPrincipal(jwt.getBody().getId(), user);
}
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(principal, null, new ArrayList<>()); UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(principal, null, new ArrayList<>());
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authenticationToken); SecurityContextHolder.getContext().setAuthentication(authenticationToken);

View File

@ -1,16 +0,0 @@
package net.Broken.Api.Security;
import net.Broken.Api.Security.Expression.CustomMethodSecurityExpressionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
return new CustomMethodSecurityExpressionHandler();
}
}

View File

@ -1,10 +1,7 @@
package net.Broken.Api.Services; package net.Broken.Api.Services;
import net.Broken.Api.Data.Guild.Guild; import net.Broken.Api.Data.Guild;
import net.Broken.Api.Data.Guild.Channel;
import net.Broken.Api.Data.Guild.Role;
import net.Broken.DB.Entity.UserEntity; import net.Broken.DB.Entity.UserEntity;
import net.Broken.MainBot;
import net.Broken.Tools.CacheTools; import net.Broken.Tools.CacheTools;
import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.entities.User;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -25,32 +22,4 @@ public class GuildService {
return guildList; return guildList;
} }
public List<Channel> getVoiceChannel(String guildId){
net.dv8tion.jda.api.entities.Guild guild = MainBot.jda.getGuildById(guildId);
List<Channel> voiceChannels = new ArrayList<>();
for(net.dv8tion.jda.api.entities.VoiceChannel voiceChannel : guild.getVoiceChannels()){
voiceChannels.add(new Channel(voiceChannel.getId(), voiceChannel.getName()));
}
return voiceChannels;
}
public List<Channel> getTextChannel(String guildId){
net.dv8tion.jda.api.entities.Guild guild = MainBot.jda.getGuildById(guildId);
List<Channel> voiceChannels = new ArrayList<>();
for(net.dv8tion.jda.api.entities.TextChannel textChannel : guild.getTextChannels()){
voiceChannels.add(new Channel(textChannel.getId(), textChannel.getName()));
}
return voiceChannels;
}
public List<Role> getRole(String guildId){
net.dv8tion.jda.api.entities.Guild guild = MainBot.jda.getGuildById(guildId);
List<Role> roles = new ArrayList<>();
for(net.dv8tion.jda.api.entities.Role role : guild.getRoles()){
roles.add(new Role(role.getId(), role.getName()));
}
return roles;
}
} }

View File

@ -1,115 +0,0 @@
package net.Broken.Api.Services;
import net.Broken.Api.Data.Settings.SettingDescriber;
import net.Broken.Api.Data.Settings.SettingGroup;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class SettingService {
public List<SettingGroup> getSettingDescription() {
List<SettingGroup> toReturn = new ArrayList<>();
toReturn.add(getWelcomeGroup());
toReturn.add(getDefaultRoleGroup());
toReturn.add(getDailyGroup());
toReturn.add(getAutoVoiceChannelGroup());
return toReturn;
}
private SettingGroup getWelcomeGroup() {
SettingDescriber mainField = new SettingDescriber(
"welcome_enable",
"Enable Welcome Message",
null,
SettingDescriber.TYPE.BOOL
);
List<SettingDescriber> fields = new ArrayList<>();
fields.add(new SettingDescriber(
"welcome_chanel_id",
"Welcome Message chanel",
null,
SettingDescriber.TYPE.TEXT_CHANNEL
));
fields.add(new SettingDescriber(
"welcome_message",
"Welcome Message",
null,
SettingDescriber.TYPE.STRING
));
return new SettingGroup(
"Welcome Message",
mainField,
fields);
}
private SettingGroup getDefaultRoleGroup() {
SettingDescriber mainField = new SettingDescriber(
"default_role",
"Enable Default Role",
null,
SettingDescriber.TYPE.BOOL
);
List<SettingDescriber> fields = new ArrayList<>();
fields.add(new SettingDescriber(
"default_role_id",
"Default Role",
null,
SettingDescriber.TYPE.ROLE
));
return new SettingGroup(
"Default Role",
mainField,
fields);
}
private SettingGroup getDailyGroup() {
List<SettingDescriber> fields = new ArrayList<>();
fields.add(new SettingDescriber(
"daily_madame",
"[NSFW] Enable Daily Madame Message",
null,
SettingDescriber.TYPE.BOOL
));
return new SettingGroup(
"Daily",
null,
fields);
}
private SettingGroup getAutoVoiceChannelGroup() {
SettingDescriber mainField = new SettingDescriber(
"auto_voice",
"Enable Auto Create Voice Chanel",
"Auto create voice channel on join.",
SettingDescriber.TYPE.BOOL
);
List<SettingDescriber> fields = new ArrayList<>();
fields.add(new SettingDescriber(
"auto_voice_base_channel",
"Base Voice Channel For Auto Create",
"If someone joint this channel, a new voice channel will be created with the same settings.",
SettingDescriber.TYPE.VOICE_CHANNEL
));
fields.add(new SettingDescriber(
"auto_voice_channel_title",
"Auto Created Voice Channel title",
"Auto created voice channel will use this title, @count will be replaced by the channel count.",
SettingDescriber.TYPE.VOICE_CHANNEL
));
return new SettingGroup(
"Auto Voice Channel",
mainField,
fields);
}
}

View File

@ -1,9 +1,7 @@
package net.Broken.SlashCommands; package net.Broken.SlashCommands;
import net.Broken.BotConfigLoader;
import net.Broken.MainBot; import net.Broken.MainBot;
import net.Broken.SlashCommand; import net.Broken.SlashCommand;
import net.Broken.SpringContext;
import net.Broken.Tools.UserManager.Stats.UserStatsUtils; import net.Broken.Tools.UserManager.Stats.UserStatsUtils;
import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
@ -16,12 +14,11 @@ import java.util.List;
public class Rank implements SlashCommand { public class Rank implements SlashCommand {
@Override @Override
public void action(SlashCommandEvent event) { public void action(SlashCommandEvent event) {
String url = SpringContext.getAppContext().getBean(BotConfigLoader.class).url();
event.deferReply().queue(); event.deferReply().queue();
UserStatsUtils userStats = UserStatsUtils.getINSTANCE(); UserStatsUtils userStats = UserStatsUtils.getINSTANCE();
MessageEmbed messageEmbed = userStats.getRankMessage(event.getMember()); MessageEmbed messageEmbed = userStats.getRankMessage(event.getMember());
event.getHook().sendMessageEmbeds(messageEmbed).addActionRow( event.getHook().sendMessageEmbeds(messageEmbed).addActionRow(
Button.link("https://" + url + "/rank", "More stats") Button.link("https://" + MainBot.url + "/rank", "More stats")
).queue(); ).queue();
} }

View File

@ -2,7 +2,7 @@
<Appenders> <Appenders>
<Console name="Console" target="SYSTEM_OUT"> <Console name="Console" target="SYSTEM_OUT">
<!--<PatternLayout pattern="[%d{HH:mm:ss.SSS}][%-5level][%-30.30c{1.}]: %msg%n" />--> <!--<PatternLayout pattern="[%d{HH:mm:ss.SSS}][%-5level][%-30.30c{1.}]: %msg%n" />-->
<PatternLayout disableAnsi="false"> <PatternLayout>
<Pattern>[%d{HH:mm:ss.SSS}]%highlight{[%-5level]}{FATAL=red blink, ERROR=red, WARN=bright yellow , <Pattern>[%d{HH:mm:ss.SSS}]%highlight{[%-5level]}{FATAL=red blink, ERROR=red, WARN=bright yellow ,
INFO=blue, DEBUG=bright black, TRACE=cyan}[%-30.30c{1.}]: %highlight{%msg%n}{FATAL=red blink, INFO=blue, DEBUG=bright black, TRACE=cyan}[%-30.30c{1.}]: %highlight{%msg%n}{FATAL=red blink,
ERROR=red, WARN=bright yellow , INFO=blue, DEBUG=bright black, TRACE=cyan} ERROR=red, WARN=bright yellow , INFO=blue, DEBUG=bright black, TRACE=cyan}