Skip to content

Commit

Permalink
User is now AppUser because of Postgres reservation
Browse files Browse the repository at this point in the history
  • Loading branch information
SanoranX authored and murraco committed Oct 6, 2021
1 parent 41d25fa commit ef4f753
Show file tree
Hide file tree
Showing 10 changed files with 39 additions and 43 deletions.
13 changes: 6 additions & 7 deletions src/main/java/murraco/JwtAuthServiceApp.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,14 @@
import java.util.Arrays;

import lombok.RequiredArgsConstructor;
import murraco.model.AppUser;
import murraco.model.AppUserRole;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import murraco.model.Role;
import murraco.model.User;
import murraco.service.UserService;

@SpringBootApplication
Expand All @@ -32,19 +31,19 @@ public ModelMapper modelMapper() {

@Override
public void run(String... params) throws Exception {
User admin = new User();
AppUser admin = new AppUser();
admin.setUsername("admin");
admin.setPassword("admin");
admin.setEmail("[email protected]");
admin.setRoles(new ArrayList<Role>(Arrays.asList(Role.ROLE_ADMIN)));
admin.setAppUserRoles(new ArrayList<AppUserRole>(Arrays.asList(AppUserRole.ROLE_ADMIN)));

userService.signup(admin);

User client = new User();
AppUser client = new AppUser();
client.setUsername("client");
client.setPassword("client");
client.setEmail("[email protected]");
client.setRoles(new ArrayList<Role>(Arrays.asList(Role.ROLE_CLIENT)));
client.setAppUserRoles(new ArrayList<AppUserRole>(Arrays.asList(AppUserRole.ROLE_CLIENT)));

userService.signup(client);
}
Expand Down
5 changes: 2 additions & 3 deletions src/main/java/murraco/controller/UserController.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
import javax.servlet.http.HttpServletRequest;

import lombok.RequiredArgsConstructor;
import murraco.model.AppUser;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
Expand All @@ -23,7 +23,6 @@
import io.swagger.annotations.Authorization;
import murraco.dto.UserDataDTO;
import murraco.dto.UserResponseDTO;
import murraco.model.User;
import murraco.service.UserService;

@RestController
Expand Down Expand Up @@ -53,7 +52,7 @@ public String login(//
@ApiResponse(code = 403, message = "Access denied"), //
@ApiResponse(code = 422, message = "Username is already in use")})
public String signup(@ApiParam("Signup User") @RequestBody UserDataDTO user) {
return userService.signup(modelMapper.map(user, User.class));
return userService.signup(modelMapper.map(user, AppUser.class));
}

@DeleteMapping(value = "/{username}")
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/murraco/dto/UserDataDTO.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
import murraco.model.Role;
import murraco.model.AppUserRole;

@Data
@NoArgsConstructor
Expand All @@ -18,6 +18,6 @@ public class UserDataDTO {
@ApiModelProperty(position = 2)
private String password;
@ApiModelProperty(position = 3)
List<Role> roles;
List<AppUserRole> appUserRoles;

}
4 changes: 2 additions & 2 deletions src/main/java/murraco/dto/UserResponseDTO.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import murraco.model.Role;
import murraco.model.AppUserRole;

@Data
public class UserResponseDTO {
Expand All @@ -16,6 +16,6 @@ public class UserResponseDTO {
@ApiModelProperty(position = 2)
private String email;
@ApiModelProperty(position = 3)
List<Role> roles;
List<AppUserRole> appUserRoles;

}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
@Entity
@Data // Create getters and setters
@NoArgsConstructor
public class User {
public class AppUser {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Expand All @@ -34,6 +34,6 @@ public class User {
private String password;

@ElementCollection(fetch = FetchType.EAGER)
List<Role> roles;
List<AppUserRole> appUserRoles;

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import org.springframework.security.core.GrantedAuthority;

public enum Role implements GrantedAuthority {
public enum AppUserRole implements GrantedAuthority {
ROLE_ADMIN, ROLE_CLIENT;

public String getAuthority() {
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/murraco/repository/UserRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@

import org.springframework.data.jpa.repository.JpaRepository;

import murraco.model.User;
import murraco.model.AppUser;

public interface UserRepository extends JpaRepository<User, Integer> {
public interface UserRepository extends JpaRepository<AppUser, Integer> {

boolean existsByUsername(String username);

User findByUsername(String username);
AppUser findByUsername(String username);

@Transactional
void deleteByUsername(String username);
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/murraco/security/JwtTokenProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import murraco.model.AppUserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
Expand All @@ -23,7 +24,6 @@
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import murraco.exception.CustomException;
import murraco.model.Role;

@Component
public class JwtTokenProvider {
Expand All @@ -46,10 +46,10 @@ protected void init() {
secretKey = Base64.getEncoder().encodeToString(secretKey.getBytes());
}

public String createToken(String username, List<Role> roles) {
public String createToken(String username, List<AppUserRole> appUserRoles) {

Claims claims = Jwts.claims().setSubject(username);
claims.put("auth", roles.stream().map(s -> new SimpleGrantedAuthority(s.getAuthority())).filter(Objects::nonNull).collect(Collectors.toList()));
claims.put("auth", appUserRoles.stream().map(s -> new SimpleGrantedAuthority(s.getAuthority())).filter(Objects::nonNull).collect(Collectors.toList()));

Date now = new Date();
Date validity = new Date(now.getTime() + validityInMilliseconds);
Expand Down
11 changes: 5 additions & 6 deletions src/main/java/murraco/security/MyUserDetails.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
package murraco.security;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import murraco.model.AppUser;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import murraco.model.User;
import murraco.repository.UserRepository;

@Service
Expand All @@ -18,16 +17,16 @@ public class MyUserDetails implements UserDetailsService {

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
final User user = userRepository.findByUsername(username);
final AppUser appUser = userRepository.findByUsername(username);

if (user == null) {
if (appUser == null) {
throw new UsernameNotFoundException("User '" + username + "' not found");
}

return org.springframework.security.core.userdetails.User//
.withUsername(username)//
.password(user.getPassword())//
.authorities(user.getRoles())//
.password(appUser.getPassword())//
.authorities(appUser.getAppUserRoles())//
.accountExpired(false)//
.accountLocked(false)//
.credentialsExpired(false)//
Expand Down
27 changes: 13 additions & 14 deletions src/main/java/murraco/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import javax.servlet.http.HttpServletRequest;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
Expand All @@ -12,7 +11,7 @@
import org.springframework.stereotype.Service;

import murraco.exception.CustomException;
import murraco.model.User;
import murraco.model.AppUser;
import murraco.repository.UserRepository;
import murraco.security.JwtTokenProvider;

Expand All @@ -28,17 +27,17 @@ public class UserService {
public String signin(String username, String password) {
try {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
return jwtTokenProvider.createToken(username, userRepository.findByUsername(username).getRoles());
return jwtTokenProvider.createToken(username, userRepository.findByUsername(username).getAppUserRoles());
} catch (AuthenticationException e) {
throw new CustomException("Invalid username/password supplied", HttpStatus.UNPROCESSABLE_ENTITY);
}
}

public String signup(User user) {
if (!userRepository.existsByUsername(user.getUsername())) {
user.setPassword(passwordEncoder.encode(user.getPassword()));
userRepository.save(user);
return jwtTokenProvider.createToken(user.getUsername(), user.getRoles());
public String signup(AppUser appUser) {
if (!userRepository.existsByUsername(appUser.getUsername())) {
appUser.setPassword(passwordEncoder.encode(appUser.getPassword()));
userRepository.save(appUser);
return jwtTokenProvider.createToken(appUser.getUsername(), appUser.getAppUserRoles());
} else {
throw new CustomException("Username is already in use", HttpStatus.UNPROCESSABLE_ENTITY);
}
Expand All @@ -48,20 +47,20 @@ public void delete(String username) {
userRepository.deleteByUsername(username);
}

public User search(String username) {
User user = userRepository.findByUsername(username);
if (user == null) {
public AppUser search(String username) {
AppUser appUser = userRepository.findByUsername(username);
if (appUser == null) {
throw new CustomException("The user doesn't exist", HttpStatus.NOT_FOUND);
}
return user;
return appUser;
}

public User whoami(HttpServletRequest req) {
public AppUser whoami(HttpServletRequest req) {
return userRepository.findByUsername(jwtTokenProvider.getUsername(jwtTokenProvider.resolveToken(req)));
}

public String refresh(String username) {
return jwtTokenProvider.createToken(username, userRepository.findByUsername(username).getRoles());
return jwtTokenProvider.createToken(username, userRepository.findByUsername(username).getAppUserRoles());
}

}

0 comments on commit ef4f753

Please sign in to comment.