Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor to comply with JDK 17 code standards #39

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions src/main/java/com/alibou/security/SecurityApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import com.alibou.security.auth.AuthenticationService;
import com.alibou.security.auth.RegisterRequest;
import com.alibou.security.user.Role;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
Expand All @@ -11,6 +11,7 @@
import static com.alibou.security.user.Role.ADMIN;
import static com.alibou.security.user.Role.MANAGER;

@Slf4j
@SpringBootApplication
public class SecurityApplication {

Expand All @@ -30,7 +31,7 @@ public CommandLineRunner commandLineRunner(
.password("password")
.role(ADMIN)
.build();
System.out.println("Admin token: " + service.register(admin).getAccessToken());
log.debug("Admin token: " + service.register(admin).getAccessToken());

var manager = RegisterRequest.builder()
.firstname("Admin")
Expand All @@ -39,7 +40,7 @@ public CommandLineRunner commandLineRunner(
.password("password")
.role(MANAGER)
.build();
System.out.println("Manager token: " + service.register(manager).getAccessToken());
log.debug("Manager token: " + service.register(manager).getAccessToken());

};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import com.alibou.security.token.Token;
import com.alibou.security.token.TokenRepository;
import com.alibou.security.token.TokenType;
import com.alibou.security.user.Role;
import com.alibou.security.user.User;
import com.alibou.security.user.UserRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
Expand All @@ -14,13 +13,11 @@
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Objects;

@Service
@RequiredArgsConstructor
Expand Down Expand Up @@ -71,7 +68,7 @@ public AuthenticationResponse authenticate(AuthenticationRequest request) {
private void saveUserToken(User user, String jwtToken) {
var token = Token.builder()
.user(user)
.token(jwtToken)
.tokenCode(jwtToken)
.tokenType(TokenType.BEARER)
.expired(false)
.revoked(false)
Expand All @@ -97,12 +94,12 @@ public void refreshToken(
final String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
final String refreshToken;
final String userEmail;
if (authHeader == null ||!authHeader.startsWith("Bearer ")) {
if (Objects.isNull(authHeader) ||!authHeader.startsWith("Bearer ")) {
return;
}
refreshToken = authHeader.substring(7);
userEmail = jwtService.extractUsername(refreshToken);
if (userEmail != null) {
if (Objects.nonNull(userEmail)) {
var user = this.repository.findByEmail(userEmail)
.orElseThrow();
if (jwtService.isTokenValid(refreshToken, user)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,9 @@
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.beans.Transient;
import java.io.IOException;
import java.security.Security;
import java.util.Objects;

import jakarta.transaction.TransactionScoped;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
Expand Down Expand Up @@ -43,18 +40,18 @@ protected void doFilterInternal(
final String authHeader = request.getHeader("Authorization");
final String jwt;
final String userEmail;
if (authHeader == null ||!authHeader.startsWith("Bearer ")) {
if (Objects.isNull(authHeader) || !authHeader.startsWith("Bearer ")) {
filterChain.doFilter(request, response);
return;
}
jwt = authHeader.substring(7);
userEmail = jwtService.extractUsername(jwt);
if (userEmail != null && SecurityContextHolder.getContext().getAuthentication() == null) {
if (Objects.nonNull(userEmail) && Objects.isNull(SecurityContextHolder.getContext().getAuthentication())) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(userEmail);
var isTokenValid = tokenRepository.findByToken(jwt)
var isTokenValid = tokenRepository.findByTokenCode(jwt)
.map(t -> !t.isExpired() && !t.isRevoked())
.orElse(false);
if (jwtService.isTokenValid(jwt, userDetails) && isTokenValid) {
if (jwtService.isTokenValid(jwt, userDetails) && Boolean.TRUE.equals(isTokenValid)) {
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
userDetails,
null,
Expand Down
8 changes: 5 additions & 3 deletions src/main/java/com/alibou/security/config/LogoutService.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
@RequiredArgsConstructor
public class LogoutService implements LogoutHandler {
Expand All @@ -23,13 +25,13 @@ public void logout(
) {
final String authHeader = request.getHeader("Authorization");
final String jwt;
if (authHeader == null ||!authHeader.startsWith("Bearer ")) {
if (Objects.isNull(authHeader) || !authHeader.startsWith("Bearer ")) {
return;
}
jwt = authHeader.substring(7);
var storedToken = tokenRepository.findByToken(jwt)
var storedToken = tokenRepository.findByTokenCode(jwt)
.orElse(null);
if (storedToken != null) {
if (Objects.nonNull(storedToken)) {
storedToken.setExpired(true);
storedToken.setRevoked(true);
tokenRepository.save(storedToken);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
package com.alibou.security.config;

import jakarta.servlet.Filter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
Expand All @@ -16,20 +13,10 @@
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import static com.alibou.security.user.Permission.ADMIN_CREATE;
import static com.alibou.security.user.Permission.ADMIN_DELETE;
import static com.alibou.security.user.Permission.ADMIN_READ;
import static com.alibou.security.user.Permission.ADMIN_UPDATE;
import static com.alibou.security.user.Permission.MANAGER_CREATE;
import static com.alibou.security.user.Permission.MANAGER_DELETE;
import static com.alibou.security.user.Permission.MANAGER_READ;
import static com.alibou.security.user.Permission.MANAGER_UPDATE;
import static com.alibou.security.user.Permission.*;
import static com.alibou.security.user.Role.ADMIN;
import static com.alibou.security.user.Role.MANAGER;
import static org.springframework.http.HttpMethod.DELETE;
import static org.springframework.http.HttpMethod.GET;
import static org.springframework.http.HttpMethod.POST;
import static org.springframework.http.HttpMethod.PUT;
import static org.springframework.http.HttpMethod.*;

@Configuration
@EnableWebSecurity
Expand Down
65 changes: 43 additions & 22 deletions src/main/java/com/alibou/security/token/Token.java
Original file line number Diff line number Diff line change
@@ -1,42 +1,63 @@
package com.alibou.security.token;

import com.alibou.security.user.User;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@NoArgsConstructor
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.proxy.HibernateProxy;

import java.util.Objects;

@Getter
@Setter
@ToString
@RequiredArgsConstructor
@AllArgsConstructor
@Builder
@Entity
@Table(name = "token")
public class Token {

@Id
@GeneratedValue
public Integer id;
private Integer id;

@Column(unique = true)
public String token;
private String tokenCode;

@Enumerated(EnumType.STRING)
public TokenType tokenType = TokenType.BEARER;
private TokenType tokenType = TokenType.BEARER;

public boolean revoked;
private boolean revoked;

public boolean expired;
private boolean expired;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
@ToString.Exclude
public User user;

@Override
public final boolean equals(Object o) {
if (Objects.isNull(o)) {
return false;
}
if (this == o) {
return true;
}
Class<?> oEffectiveClass = o instanceof HibernateProxy hibernateProxy ?
hibernateProxy.getHibernateLazyInitializer().getPersistentClass() : o.getClass();
Class<?> thisEffectiveClass = this instanceof HibernateProxy hibernateProxy ?
hibernateProxy.getHibernateLazyInitializer().getPersistentClass() : this.getClass();
if (thisEffectiveClass != oEffectiveClass) {
return false;
}
Token token = (Token) o;
return Objects.nonNull(getId()) && Objects.equals(getId(), token.getId());
}

@Override
public final int hashCode() {
return this instanceof HibernateProxy hibernateProxy ?
hibernateProxy.getHibernateLazyInitializer().getPersistentClass().hashCode() : getClass().hashCode();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,5 @@ public interface TokenRepository extends JpaRepository<Token, Integer> {
""")
List<Token> findAllValidTokenByUser(Integer id);

Optional<Token> findByToken(String token);
Optional<Token> findByTokenCode(String token);
}
2 changes: 1 addition & 1 deletion src/main/java/com/alibou/security/user/Permission.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@ public enum Permission {
;

@Getter
private final String permission;
private final String permissionStr;
}
2 changes: 1 addition & 1 deletion src/main/java/com/alibou/security/user/Role.java
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public enum Role {
public List<SimpleGrantedAuthority> getAuthorities() {
var authorities = getPermissions()
.stream()
.map(permission -> new SimpleGrantedAuthority(permission.getPermission()))
.map(permission -> new SimpleGrantedAuthority(permission.getPermissionStr()))
.collect(Collectors.toList());
authorities.add(new SimpleGrantedAuthority("ROLE_" + this.name()));
return authorities;
Expand Down
57 changes: 39 additions & 18 deletions src/main/java/com/alibou/security/user/User.java
Original file line number Diff line number Diff line change
@@ -1,27 +1,22 @@
package com.alibou.security.user;

import com.alibou.security.token.Token;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
import java.util.Collection;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.proxy.HibernateProxy;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

@Data
@Builder
@NoArgsConstructor
import java.util.Collection;
import java.util.List;
import java.util.Objects;

@Getter
@Setter
@ToString
@RequiredArgsConstructor
@AllArgsConstructor
@Builder
@Entity
@Table(name = "_user")
public class User implements UserDetails {
Expand All @@ -38,7 +33,8 @@ public class User implements UserDetails {
private Role role;

@OneToMany(mappedBy = "user")
private List<Token> tokens;
@ToString.Exclude
private transient List<Token> tokens;

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Expand Down Expand Up @@ -74,4 +70,29 @@ public boolean isCredentialsNonExpired() {
public boolean isEnabled() {
return true;
}

@Override
public final boolean equals(Object o) {
if (Objects.isNull(o)) {
return false;
}
if (this == o) {
return true;
}
Class<?> oEffectiveClass = o instanceof HibernateProxy hibernateProxy ?
hibernateProxy.getHibernateLazyInitializer().getPersistentClass() : o.getClass();
Class<?> thisEffectiveClass = this instanceof HibernateProxy hibernateProxy ?
hibernateProxy.getHibernateLazyInitializer().getPersistentClass() : this.getClass();
if (thisEffectiveClass != oEffectiveClass) {
return false;
}
User user = (User) o;
return Objects.nonNull(getId()) && Objects.equals(getId(), user.getId());
}

@Override
public final int hashCode() {
return this instanceof HibernateProxy hibernateProxy ?
hibernateProxy.getHibernateLazyInitializer().getPersistentClass().hashCode() : getClass().hashCode();
}
}