Skip to content

Commit

Permalink
Fix authentication, code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
krabiworld committed Dec 6, 2024
1 parent 5d3b7c7 commit 11e512a
Show file tree
Hide file tree
Showing 5 changed files with 33 additions and 50 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
Expand All @@ -23,7 +24,6 @@
@EnableWebSecurity
public class SecurityConfig {
private final JwtService jwtService;

private final UserDetailsServiceImpl userDetailsService;

@Autowired
Expand All @@ -35,7 +35,7 @@ public SecurityConfig(JwtService jwtService, UserDetailsServiceImpl userDetailsS
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.cors(AbstractHttpConfigurer::disable)
.cors(Customizer.withDefaults())
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests((authorize) -> authorize
Expand All @@ -44,7 +44,7 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
.requestMatchers(HttpMethod.GET, "/docs").permitAll()
.anyRequest().authenticated())
.authenticationManager(authenticationManager())
.addFilterBefore(new AuthenticationFilter(jwtService), UsernamePasswordAuthenticationFilter.class).build();
.addFilterBefore(new AuthenticationFilter(jwtService, userDetailsService), UsernamePasswordAuthenticationFilter.class).build();
}

@Bean
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@
import jakarta.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import su.foxogram.constants.AttributesConstants;
Expand All @@ -17,26 +22,24 @@

@Component
public class AuthenticationFilter extends OncePerRequestFilter {
// private static final Set<String> MFA_REQUIRED_PATHS = Set.of(
// "/users/@me/delete/confirm"
// );

private static final Set<String> EMAIL_VERIFICATION_IGNORE_PATHS = Set.of(
"/auth/email/verify",
"/users/@me",
"/auth/email/resend"
);

final JwtService jwtService;
private final JwtService jwtService;

private final UserDetailsService userDetailsService;

public AuthenticationFilter(JwtService jwtService) {
public AuthenticationFilter(JwtService jwtService, UserDetailsService userDetailsService) {
this.jwtService = jwtService;
this.userDetailsService = userDetailsService;
}

@Override
protected void doFilterInternal(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException, IOException {
String requestURI = request.getRequestURI();
// boolean MFAValidationRequired = MFA_REQUIRED_PATHS.stream().anyMatch(requestURI::contains);
boolean ignoreEmailVerification = EMAIL_VERIFICATION_IGNORE_PATHS.stream().anyMatch(requestURI::contains);

String accessToken = request.getHeader(HttpHeaders.AUTHORIZATION);
Expand All @@ -55,27 +58,14 @@ protected void doFilterInternal(HttpServletRequest request, @NotNull HttpServlet
return;
}

// if (MFAValidationRequired && user.hasFlag(UserConstants.Flags.AWAITING_CONFIRMATION)) {
// validateMFA(user, request);
// }

request.setAttribute(AttributesConstants.USER, user);
request.setAttribute(AttributesConstants.ACCESS_TOKEN, accessToken);

UserDetails userDetails = userDetailsService.loadUserByUsername(user.getEmail());
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, null);
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authenticationToken);

filterChain.doFilter(request, response);
}

// private void validateMFA(User user, HttpServletRequest request) throws MFAIsInvalidException, CodeExpiredException, CodeIsInvalidException {
// String code = request.getHeader("Code");
//
// if (!user.hasFlag(UserConstants.Flags.MFA_ENABLED)) {
// boolean MFAVerified = authenticationService.validateCode(code) != null;
//
// request.setAttribute(AttributesConstants.MFA_VERIFIED, MFAVerified);
// } else {
// boolean MFAVerified = Totp.validate(user.getKey(), code);
//
// request.setAttribute(AttributesConstants.MFA_VERIFIED, MFAVerified);
// }
// }
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,8 @@ private User createUser(String username, String email, String password) {
String avatar = new Avatar("").getId();
long flags = UserConstants.Flags.AWAITING_CONFIRMATION.getBit();
int type = UserConstants.Type.USER.getType();
String key = null;

return new User(id, avatar, null, username, email, Encryptor.hashPassword(password), flags, type, deletion, key);
return new User(id, avatar, null, username, email, Encryptor.hashPassword(password), flags, type, deletion, null);
}

private void sendConfirmationEmail(User user) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,12 @@
@Slf4j
@Service
public class ChannelsService {

private final ChannelRepository channelRepository;

private final MemberRepository memberRepository;

@Autowired
public ChannelsService(ChannelRepository channelRepository, MemberRepository memberRepository, AuthenticationService authenticationService) {
public ChannelsService(ChannelRepository channelRepository, MemberRepository memberRepository) {
this.channelRepository = channelRepository;
this.memberRepository = memberRepository;
}
Expand Down
31 changes: 13 additions & 18 deletions foxogram-common/src/main/java/su/foxogram/services/JwtService.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,20 @@ public JwtService(UserRepository userRepository, JwtConfig jwtConfig) {
}

public User getUser(String header, boolean ignoreEmailVerification) throws UserUnauthorizedException, UserEmailNotVerifiedException {
return validateUser(header.substring(7), ignoreEmailVerification);
}
String userId;

try {
Jws<Claims> claimsJws = Jwts.parserBuilder()
.setSigningKey(getSigningKey())
.build()
.parseClaimsJws(header.substring(7));

userId = claimsJws.getBody().getId();
} catch (Exception e) {
throw new UserUnauthorizedException();
}

public User validateUser(String token, boolean ignoreEmailVerification) throws UserUnauthorizedException, UserEmailNotVerifiedException {
String userId = validate(token).getId();
User user = userRepository.findById(userId).get();
User user = userRepository.findById(userId).orElseThrow(UserUnauthorizedException::new);

if (!ignoreEmailVerification && user.hasFlag(UserConstants.Flags.EMAIL_VERIFIED))
throw new UserEmailNotVerifiedException();
Expand All @@ -54,19 +62,6 @@ public String generate(String id) {
.compact();
}

public Claims validate(String token) throws UserUnauthorizedException {
try {
Jws<Claims> claimsJws = Jwts.parserBuilder()
.setSigningKey(getSigningKey())
.build()
.parseClaimsJws(token);

return claimsJws.getBody();
} catch (Exception e) {
throw new UserUnauthorizedException();
}
}

private Key getSigningKey() {
byte[] keyBytes = Decoders.BASE64.decode(jwtConfig.getSecret());
return Keys.hmacShaKeyFor(keyBytes);
Expand Down

0 comments on commit 11e512a

Please sign in to comment.