diff --git a/pom.xml b/pom.xml index e08bead..802138e 100644 --- a/pom.xml +++ b/pom.xml @@ -64,10 +64,46 @@ spring-boot-starter-test test + + io.jsonwebtoken + jjwt-impl + 0.11.5 + + + io.jsonwebtoken + jjwt-jackson + 0.11.5 + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + org.springframework.security + spring-security-test + test + + + org.springframework.boot + spring-boot-starter-security + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M5 + + + Sample.java + + + + org.springframework.boot spring-boot-maven-plugin diff --git a/src/main/java/dk/kea/onav2ndproject_rest/JwtAuthenticationEntryPoint.java b/src/main/java/dk/kea/onav2ndproject_rest/JwtAuthenticationEntryPoint.java new file mode 100644 index 0000000..d62a87d --- /dev/null +++ b/src/main/java/dk/kea/onav2ndproject_rest/JwtAuthenticationEntryPoint.java @@ -0,0 +1,21 @@ +package dk.kea.onav2ndproject_rest; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.io.Serializable; + +@Component +public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, + Serializable { + @Override + public void commence(HttpServletRequest request, HttpServletResponse response, + AuthenticationException authException) throws IOException { + System.out.println("JwtAuthenticationEntryPoint commence"); + response.sendError(HttpServletResponse.SC_UNAUTHORIZED,"Unauthorized"); + } +} diff --git a/src/main/java/dk/kea/onav2ndproject_rest/JwtFilter.java b/src/main/java/dk/kea/onav2ndproject_rest/JwtFilter.java new file mode 100644 index 0000000..e2c34cd --- /dev/null +++ b/src/main/java/dk/kea/onav2ndproject_rest/JwtFilter.java @@ -0,0 +1,59 @@ +package dk.kea.onav2ndproject_rest; + +import dk.kea.onav2ndproject_rest.service.JwtUserDetailsService; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +import lombok.AllArgsConstructor; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +@AllArgsConstructor +@Component +public class JwtFilter extends OncePerRequestFilter { + private JwtUserDetailsService userDetailsService; + private JwtTokenManager jwtTokenManager; + @Override + protected void doFilterInternal(HttpServletRequest request, + HttpServletResponse response, FilterChain filterChain) + throws ServletException, IOException { + String tokenHeader = request.getHeader("Authorization"); + System.out.println("JwtFilter doFilterInternal call 3 request header" + tokenHeader ); // + JwtController.printHeader(request) + String username = null; + String token = null; + if (tokenHeader != null && tokenHeader.startsWith("Bearer ")) { + token = tokenHeader.substring(7); + try { + username = jwtTokenManager.getUsernameFromToken(token); + } catch (Exception e) { + System.out.println("Unable to get JWT Token"); + } + } else { + System.out.println("String does not start with Bearer or tokenheader == NULL"); + } + validateToken(request, username, token); + filterChain.doFilter(request, response); //possible: response.setHeader( "key",value); its up to you. + } + + private void validateToken(HttpServletRequest request, String username, String token) { + if (null != username && SecurityContextHolder.getContext().getAuthentication() == null) { + UserDetails userDetails = userDetailsService.loadUserByUsername(username); + if (jwtTokenManager.validateJwtToken(token, userDetails)) { + UsernamePasswordAuthenticationToken + authenticationToken = new UsernamePasswordAuthenticationToken( + userDetails, null, + userDetails.getAuthorities()); + authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); + SecurityContextHolder.getContext().setAuthentication(authenticationToken); + } + } + } +} \ No newline at end of file diff --git a/src/main/java/dk/kea/onav2ndproject_rest/JwtTokenManager.java b/src/main/java/dk/kea/onav2ndproject_rest/JwtTokenManager.java new file mode 100644 index 0000000..00ed4f8 --- /dev/null +++ b/src/main/java/dk/kea/onav2ndproject_rest/JwtTokenManager.java @@ -0,0 +1,71 @@ +package dk.kea.onav2ndproject_rest; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.security.Keys; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Component; + +import java.security.Key; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +@Component +public class JwtTokenManager { + public static final long TOKEN_VALIDITY = 10 * 60 * 60 * 1000; // 10 timer + // aha: Below is the server's private key. Which is used to generate new tokens. Length: Minimum 512 bits. + // Which corresponds to minimum 86 characters in cleartext. + @Value("${secret}") + private String jwtSecret; + public String generateJwtToken(UserDetails userDetails) { + System.out.println("TokenManager generateJwtToken(UserDetails) call: 7"); + Map claims = new HashMap<>(); + return Jwts.builder().setClaims(claims).setSubject(userDetails.getUsername()) + .setIssuedAt(new Date(System.currentTimeMillis())) + .setExpiration(new Date(System.currentTimeMillis() + TOKEN_VALIDITY )) + .signWith(getSignInKey(),SignatureAlgorithm.HS512 ) + .compact(); + //.signWith(SignatureAlgorithm.HS512, jwtSecret).compact(); // before Spring 3 + } + + private Key getSignInKey() { + byte[] keyBytes = Decoders.BASE64.decode(jwtSecret); + return Keys.hmacShaKeyFor(keyBytes); + } + public Boolean validateJwtToken(String token, UserDetails userDetails) { + System.out.println("TokenManager validateJwtToken(String token, UserDetails) With token: Call: B"); + String username = getUsernameFromToken(token); + Claims claims = getClaims(token); + Boolean isTokenExpired = claims.getExpiration().before(new Date()); + return (username.equals(userDetails.getUsername()) && !isTokenExpired); + } + public String getUsernameFromToken(String token) { + System.out.println("TokenManager getUsernameFromToken(String token) With token: Call: A"); + //Claims claims = Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody(); // before Spring 3 + Claims claims = getClaims(token); + if(claims != null){ + return claims.getSubject(); + }else { + return "no user found"; + } + } + + private Claims getClaims(String token){ + try{ + Claims claims = Jwts + .parserBuilder() + .setSigningKey(getSignInKey()) + .build() + .parseClaimsJws(token) + .getBody(); + return claims; + }catch (Exception e){ + System.out.println("could not parse JWT token for claims"); + } + return null; + } +} diff --git a/src/main/java/dk/kea/onav2ndproject_rest/api/EventController.java b/src/main/java/dk/kea/onav2ndproject_rest/api/EventController.java index 54ed450..8b23583 100644 --- a/src/main/java/dk/kea/onav2ndproject_rest/api/EventController.java +++ b/src/main/java/dk/kea/onav2ndproject_rest/api/EventController.java @@ -12,7 +12,6 @@ import org.springframework.web.bind.annotation.*; @RestController -@CrossOrigin(origins = "*") @RequestMapping("/api/event") public class EventController { diff --git a/src/main/java/dk/kea/onav2ndproject_rest/api/UserController.java b/src/main/java/dk/kea/onav2ndproject_rest/api/UserController.java new file mode 100644 index 0000000..6fe8a0b --- /dev/null +++ b/src/main/java/dk/kea/onav2ndproject_rest/api/UserController.java @@ -0,0 +1,95 @@ +package dk.kea.onav2ndproject_rest.api; + +import dk.kea.onav2ndproject_rest.JwtTokenManager; +import dk.kea.onav2ndproject_rest.entity.JwtRequestModel; +import dk.kea.onav2ndproject_rest.entity.JwtResponseModel; +import dk.kea.onav2ndproject_rest.entity.User; +import dk.kea.onav2ndproject_rest.service.IUserService; +import dk.kea.onav2ndproject_rest.service.JwtUserDetailsService; +import dk.kea.onav2ndproject_rest.service.UserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.DisabledException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/api/user") +public class UserController { + @Autowired + private JwtUserDetailsService userDetailsService; + @Autowired + private AuthenticationManager authenticationManager; + @Autowired + private JwtTokenManager jwtTokenManager; + @Autowired + private IUserService userService; + + @PostMapping("/signup") + public ResponseEntity signup(@RequestBody JwtRequestModel request){ + System.out.println("signup: username:" + request.getUsername() + " password: " + request.getPassword() ); + User user = new User(request.getUsername(),request.getPassword()); + if(userService.findByName(user.getUsername()).size()==0) { + if (userService.save(user) != null) { + return ResponseEntity.ok(new JwtResponseModel("created user: " + user.getUsername() + " pw: " + user.getPassword())); + } else { + return ResponseEntity.ok(new JwtResponseModel("error creating user: " + user.getUsername())); + } + }else { + return ResponseEntity.ok(new JwtResponseModel("error: user exists: " + user.getUsername())); + } + } + + @PostMapping("/login") + public ResponseEntity createToken(@RequestBody JwtRequestModel request) throws Exception { + // HttpServletRequest servletRequest is available from Spring, if needed. + System.out.println(" JwtController createToken Call: 4" + request.getUsername()); + try { + authenticationManager.authenticate( + new UsernamePasswordAuthenticationToken(request.getUsername(), + request.getPassword()) + ); + } catch (DisabledException e) { + throw new Exception("USER_DISABLED", e); + } catch (BadCredentialsException e) { + return ResponseEntity.ok(new JwtResponseModel("bad credentials")); + } + final UserDetails userDetails = userDetailsService.loadUserByUsername(request.getUsername()); + final String jwtToken = jwtTokenManager.generateJwtToken(userDetails); + return ResponseEntity.ok(new JwtResponseModel(jwtToken)); + } + + + @PostMapping("/getSecret") + public ResponseEntity getSecret() { + System.out.println("getSecret is called"); + Map map = new HashMap<>(); + map.put("message","this is secret from server"); + return ResponseEntity.ok(map); + } + + @DeleteMapping("/deleteUser") + public ResponseEntity deleteUser(@RequestBody User user) { + System.out.println("deleteUser is called with user: " + user.getUsername()); + List users = userService.findByName(user.getUsername()); + User userToDelete = users.get(0); + userService.delete(userToDelete); + Map map = new HashMap<>(); + map.put("message","user deleted, if found " + user.getUsername()); + return ResponseEntity.ok(map); + } + + @GetMapping() + public ResponseEntity getUserByToken(@RequestParam String token){ + System.out.println("getUserByToken is called with token: " + token); + User user = userService.findByToken(token); + return ResponseEntity.ok(user); + } +} diff --git a/src/main/java/dk/kea/onav2ndproject_rest/config/InitData.java b/src/main/java/dk/kea/onav2ndproject_rest/config/InitData.java new file mode 100644 index 0000000..bc4d49d --- /dev/null +++ b/src/main/java/dk/kea/onav2ndproject_rest/config/InitData.java @@ -0,0 +1,69 @@ +package dk.kea.onav2ndproject_rest.config; + +import dk.kea.onav2ndproject_rest.entity.Role; +import dk.kea.onav2ndproject_rest.entity.User; +import dk.kea.onav2ndproject_rest.repository.UserRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Component; + +import java.util.Random; + +@Component +public class InitData implements CommandLineRunner { + + @Autowired + UserRepository userRepository; + + @Autowired + private PasswordEncoder passwordEncoder; + + @Override + public void run(String... args) throws Exception { + User user1 = new User(); + user1.setName("Anders"); + user1.setId(31); + user1.setEmail("anders@mail.dk"); + user1.setRole(Role.EMPLOYEE); + user1.setPassword(passwordEncoder.encode("1234")); + user1.setUsername("anders"); + userRepository.save(user1); + + User user2 = new User(); + user2.setName("Benny"); + user2.setId(32); + user2.setEmail("benny@mail.dk"); + user2.setRole(Role.MANAGER); + user2.setPassword(passwordEncoder.encode("5678")); + user2.setUsername("benny"); + userRepository.save(user2); + + User user3 = new User(); + user3.setName("Carla"); + user3.setId(33); + user3.setEmail("carla@mail.dk"); + user3.setRole(Role.EMPLOYEE); + user3.setPassword(passwordEncoder.encode("9012")); + user3.setUsername("carla"); + userRepository.save(user3); + + User user4 = new User(); + user4.setName("Dennis"); + user4.setId(34); + user4.setEmail("dennis@mail.dk"); + user4.setRole(Role.HEADCHEF); + user4.setPassword(passwordEncoder.encode("3456")); + user4.setUsername("dennis"); + userRepository.save(user4); + + User user5 = new User(); + user5.setName("Eva"); + user5.setId(35); + user5.setEmail("eva@mail.dk"); + user5.setRole(Role.EMPLOYEE); + user5.setPassword(passwordEncoder.encode("7890")); + user5.setUsername("eva"); + userRepository.save(user5); + } +} diff --git a/src/main/java/dk/kea/onav2ndproject_rest/config/SecurityConfiguration.java b/src/main/java/dk/kea/onav2ndproject_rest/config/SecurityConfiguration.java new file mode 100644 index 0000000..dee2759 --- /dev/null +++ b/src/main/java/dk/kea/onav2ndproject_rest/config/SecurityConfiguration.java @@ -0,0 +1,70 @@ +package dk.kea.onav2ndproject_rest.config; + +import dk.kea.onav2ndproject_rest.JwtAuthenticationEntryPoint; +import dk.kea.onav2ndproject_rest.JwtFilter; +import lombok.AllArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.security.web.util.matcher.AntPathRequestMatcher; +import org.springframework.security.web.util.matcher.OrRequestMatcher; +import org.springframework.security.web.util.matcher.RequestMatcher; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +@AllArgsConstructor +public class SecurityConfiguration implements WebMvcConfigurer { + private JwtAuthenticationEntryPoint authenticationEntryPoint; + private JwtFilter filter; + private static PasswordEncoder passwordEncoder; + @Bean + public static PasswordEncoder passwordEncoder() { + if(passwordEncoder==null){ + passwordEncoder = new BCryptPasswordEncoder(); + } + return passwordEncoder; + } + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + RequestMatcher loginMatcher = new AntPathRequestMatcher("/api/user/login"); + RequestMatcher signupMatcher = new AntPathRequestMatcher("/api/user/signup"); + RequestMatcher eventMatcher = new AntPathRequestMatcher("/api/event", HttpMethod.GET.name()); + RequestMatcher orMatcher = new OrRequestMatcher(loginMatcher, signupMatcher, eventMatcher); + + http.cors().and().csrf().disable() + .authorizeHttpRequests().requestMatchers(orMatcher).permitAll() + .anyRequest().authenticated() + .and() + .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint) + .and() + .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); + http.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class); + return http.build(); + } + + @Bean + public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) + throws Exception { + return authenticationConfiguration.getAuthenticationManager(); + } + + @Override + public void addCorsMappings(CorsRegistry registry) { + System.out.println("addCorsMappings called"); + registry.addMapping("/**") // /** means match any string recursively + .allowedOriginPatterns("http://localhost:*", "http://127.0.0.1:*/") //Multiple strings allowed. Wildcard * matches all port numbers. + .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS") // decide which methods to allow + .allowCredentials(true); + } + +} diff --git a/src/main/java/dk/kea/onav2ndproject_rest/entity/JwtRequestModel.java b/src/main/java/dk/kea/onav2ndproject_rest/entity/JwtRequestModel.java new file mode 100644 index 0000000..892c35b --- /dev/null +++ b/src/main/java/dk/kea/onav2ndproject_rest/entity/JwtRequestModel.java @@ -0,0 +1,11 @@ +package dk.kea.onav2ndproject_rest.entity; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class JwtRequestModel { + private String username; + private String password; +} diff --git a/src/main/java/dk/kea/onav2ndproject_rest/entity/JwtResponseModel.java b/src/main/java/dk/kea/onav2ndproject_rest/entity/JwtResponseModel.java new file mode 100644 index 0000000..0afae4b --- /dev/null +++ b/src/main/java/dk/kea/onav2ndproject_rest/entity/JwtResponseModel.java @@ -0,0 +1,12 @@ +package dk.kea.onav2ndproject_rest.entity; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@AllArgsConstructor +public class JwtResponseModel { + private final String token; +} \ No newline at end of file diff --git a/src/main/java/dk/kea/onav2ndproject_rest/entity/User.java b/src/main/java/dk/kea/onav2ndproject_rest/entity/User.java index c792538..4c998b2 100644 --- a/src/main/java/dk/kea/onav2ndproject_rest/entity/User.java +++ b/src/main/java/dk/kea/onav2ndproject_rest/entity/User.java @@ -15,7 +15,7 @@ public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; + private int id; private String name; private String username; private String password; @@ -28,4 +28,8 @@ public class User { @OneToMany(mappedBy = "user") private Set userEventDetails; + public User(String username, String password) { + this.username = username; + this.password = password; + } } diff --git a/src/main/java/dk/kea/onav2ndproject_rest/repository/UserRepository.java b/src/main/java/dk/kea/onav2ndproject_rest/repository/UserRepository.java new file mode 100644 index 0000000..81b1683 --- /dev/null +++ b/src/main/java/dk/kea/onav2ndproject_rest/repository/UserRepository.java @@ -0,0 +1,12 @@ +package dk.kea.onav2ndproject_rest.repository; + +import dk.kea.onav2ndproject_rest.entity.User; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; + +public interface UserRepository extends JpaRepository { + List findByUsername(String name); + //List findUserByPasswordContains(String passwordPart); + +} diff --git a/src/main/java/dk/kea/onav2ndproject_rest/service/ICrudService.java b/src/main/java/dk/kea/onav2ndproject_rest/service/ICrudService.java new file mode 100644 index 0000000..0161691 --- /dev/null +++ b/src/main/java/dk/kea/onav2ndproject_rest/service/ICrudService.java @@ -0,0 +1,12 @@ +package dk.kea.onav2ndproject_rest.service; + +import java.util.Optional; +import java.util.Set; + +public interface ICrudService { + Set findAll(); + T save(T object); + void delete(T object); + void deleteById(ID id); + Optional findById(ID id); +} diff --git a/src/main/java/dk/kea/onav2ndproject_rest/service/IUserService.java b/src/main/java/dk/kea/onav2ndproject_rest/service/IUserService.java new file mode 100644 index 0000000..f196f44 --- /dev/null +++ b/src/main/java/dk/kea/onav2ndproject_rest/service/IUserService.java @@ -0,0 +1,11 @@ +package dk.kea.onav2ndproject_rest.service; + +import dk.kea.onav2ndproject_rest.entity.User; + +import java.util.List; + +public interface IUserService extends ICrudService{ + List findByName(String name); + + User findByToken(String token); +} diff --git a/src/main/java/dk/kea/onav2ndproject_rest/service/JwtUserDetailsService.java b/src/main/java/dk/kea/onav2ndproject_rest/service/JwtUserDetailsService.java new file mode 100644 index 0000000..66500d6 --- /dev/null +++ b/src/main/java/dk/kea/onav2ndproject_rest/service/JwtUserDetailsService.java @@ -0,0 +1,40 @@ +package dk.kea.onav2ndproject_rest.service; + +import lombok.AllArgsConstructor; +import org.springframework.security.core.userdetails.User; +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 java.util.ArrayList; +import java.util.List; + +@Service +@AllArgsConstructor +public class JwtUserDetailsService implements UserDetailsService { + private IUserService userService; + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + System.out.println(" JwtUserDetailsService loadUserByUsername Call: 5,6"); + // point mht. bruger database: + // Brugere bliver oprettet ved /login. Der gemmes brugernavn og bcrypt encoded password + // Når bruger efterfølgende logger på, hentes brugerens usr/pw fra databasen. + // Herefter opretter man et nyt userdetails.User objekt med usr/pw fra databasen. + // Spring Security vil herefter bruge bcrypt.compare() til at sammenligne clear-text pw fra + // login-formular med datbasens bcrypt af pw. Hvis svaret er true, er brugeren godkendt. + List users = userService.findByName(username); + System.out.println("users from database: length: " + users.size()); + if(users.size()==1) { + System.out.println("found the user in Database: " + users.get(0).getUsername()); + return new User(username, + users.get(0).getPassword(), // "password" encoded here + // Point: Bcrypt can hash the same clear-text string many times: each time will lead to a different hashed string. + // You can check https://bcrypt-generator.com/ to verify if a cleartext string matches any bcrypt hash. + new ArrayList<>()); + // bcrypt example: $2a$10$WG/h8E/8U6j48JOn7BnWTe7g9OenBlzapETPHeqZgrBxjcKmsWTmm + }else{ + throw new UsernameNotFoundException("User not found with username: " + username); + } + } +} diff --git a/src/main/java/dk/kea/onav2ndproject_rest/service/UserService.java b/src/main/java/dk/kea/onav2ndproject_rest/service/UserService.java new file mode 100644 index 0000000..969ab1e --- /dev/null +++ b/src/main/java/dk/kea/onav2ndproject_rest/service/UserService.java @@ -0,0 +1,65 @@ +package dk.kea.onav2ndproject_rest.service; + + +import dk.kea.onav2ndproject_rest.JwtTokenManager; +import dk.kea.onav2ndproject_rest.config.SecurityConfiguration; +import dk.kea.onav2ndproject_rest.entity.User; +import dk.kea.onav2ndproject_rest.repository.UserRepository; +import lombok.AllArgsConstructor; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; + +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +@AllArgsConstructor +@Service +public class UserService implements IUserService{ + + private UserRepository userRepository; + private JwtTokenManager jwtTokenManager; + @Override + public Set findAll() { + Set set = new HashSet<>(); + userRepository.findAll().forEach(set::add); + return set; + } + + @Override + public User save(User user) { +// if(user.getPassword() == null) { + PasswordEncoder pw = SecurityConfiguration.passwordEncoder(); + user.setPassword(pw.encode(user.getPassword())); +// } + return userRepository.save(user); + } + + @Override + public void delete(User object) { + userRepository.delete(object); + } + + @Override + public void deleteById(Long aLong) { + + } + + @Override + public Optional findById(Long aLong) { + return userRepository.findById(aLong); + } + + @Override + public List findByName(String name) { + System.out.println("Userservice called findByName with argument: " + name); + return userRepository.findByUsername(name); + } + + @Override + public User findByToken(String token) { + String username = jwtTokenManager.getUsernameFromToken(token); + return userRepository.findByUsername(username).get(0); + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 9308dfa..27f2870 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -4,4 +4,5 @@ spring.datasource.url=${DATABASE_URL} spring.datasource.username=${DATABASE_USERNAME} spring.datasource.password=${DATABASE_PASSWORD} spring.jpa.show-sql=true -spring.jpa.hibernate.ddl-auto=update \ No newline at end of file +spring.jpa.hibernate.ddl-auto=update +secret=${SECRET} \ No newline at end of file