Search in sources :

Example 1 with AppUser

use of b3.spl.splb.model.AppUser in project Automated-Parking-Lot by ParkingLotDevOps.

the class RoleToUserForm method refreshToken.

@GetMapping("/token/refresh")
public void refreshToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String authorizationHeader = request.getHeader("Authorization");
    if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
        try {
            String refresh_token = authorizationHeader.substring("Bearer ".length());
            // TODO : de mutat in fisier de configurare
            Algorithm algorithm = Algorithm.HMAC256("secret".getBytes());
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT decodedJWT = verifier.verify(refresh_token);
            String username = decodedJWT.getSubject();
            AppUser user = appUserService.getUser(username);
            String access_token = JWT.create().withSubject(user.getEmail()).withExpiresAt(new Date(System.currentTimeMillis() + 30 * 60 * 1000)).withIssuer(request.getRequestURL().toString()).withClaim("roles", user.getRoles().stream().map(Role::getName).collect(Collectors.toList())).sign(algorithm);
            Map<String, String> tokens = new HashMap<>();
            tokens.put("access_token", access_token);
            tokens.put("refresh_token", refresh_token);
            response.setContentType("application/json");
            new ObjectMapper().writeValue(response.getOutputStream(), tokens);
        } catch (Exception exception) {
            response.setHeader("error", exception.getMessage());
            response.setStatus(403);
            Map<String, String> error = new HashMap<>();
            error.put("error", exception.getMessage());
            response.setContentType("application/json");
            new ObjectMapper().writeValue(response.getOutputStream(), error);
        }
    }
}
Also used : AppUser(b3.spl.splb.model.AppUser) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException)

Example 2 with AppUser

use of b3.spl.splb.model.AppUser in project Automated-Parking-Lot by ParkingLotDevOps.

the class AppUserServiceImpl method loadUserByUsername.

// am rescris ca sa caute dupa email in baza de date
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
    email = email.trim().toLowerCase();
    AppUser appUser = appUserRepo.findByEmail(email);
    if (appUser == null) {
        log.error("User not found in database");
        throw new UsernameNotFoundException("User not found in the database");
    } else {
        log.info("User found in database : {}", email);
    }
    Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
    appUser.getRoles().forEach(role -> {
        authorities.add(new SimpleGrantedAuthority(role.getName()));
    });
    return new org.springframework.security.core.userdetails.User(appUser.getUsername(), appUser.getPassword(), authorities);
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) AppUser(b3.spl.splb.model.AppUser) ArrayList(java.util.ArrayList) AppUser(b3.spl.splb.model.AppUser)

Example 3 with AppUser

use of b3.spl.splb.model.AppUser in project Automated-Parking-Lot by ParkingLotDevOps.

the class AppUserServiceImpl method addRoleToAppUser.

@Override
public boolean addRoleToAppUser(String email, String rolName) {
    log.info("Adding role {} to user {}", rolName, email);
    AppUser appUser = appUserRepo.findByEmail(email);
    Role role = roleRepo.findByName(rolName);
    if (appUser == null || role == null)
        return false;
    appUser.getRoles().add(role);
    return true;
}
Also used : Role(b3.spl.splb.model.Role) AppUser(b3.spl.splb.model.AppUser)

Example 4 with AppUser

use of b3.spl.splb.model.AppUser in project Automated-Parking-Lot by ParkingLotDevOps.

the class RoleToUserForm method saveUser.

@PostMapping("/user/save")
public ResponseEntity saveUser(@RequestBody AppUser user) {
    if (user == null || user.getUsername() == null || user.getPassword() == null || user.getName() == null || user.getEmail() == null) {
        return ResponseEntity.badRequest().body("Invalid input.");
    }
    user.setEmail(user.getEmail().trim().toLowerCase());
    if (!user.getEmail().matches("[a-zA-Z0-9_\\.-]+@[a-zA-Z0-9]+(\\.[a-zA-Z0-9_-]{2,4})+")) {
        return ResponseEntity.badRequest().body("Invalid email.");
    }
    if (user.getPassword().length() < 8 || !user.getPassword().matches(".*[A-Z].*") || !user.getPassword().matches(".*[a-z].*") || !user.getPassword().matches(".*[0-9].*")) {
        return ResponseEntity.badRequest().body("Invalid password.");
    }
    URI uri = URI.create(ServletUriComponentsBuilder.fromCurrentContextPath().path("/api/user/save").toString());
    AppUser resp = appUserService.saveUser(user);
    if (resp == null) {
        return ResponseEntity.badRequest().body("This email address is already being used.");
    }
    return ResponseEntity.created(uri).body(resp);
}
Also used : AppUser(b3.spl.splb.model.AppUser) URI(java.net.URI)

Aggregations

AppUser (b3.spl.splb.model.AppUser)4 Role (b3.spl.splb.model.Role)1 JWTVerifier (com.auth0.jwt.JWTVerifier)1 Algorithm (com.auth0.jwt.algorithms.Algorithm)1 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 IOException (java.io.IOException)1 URI (java.net.URI)1 ArrayList (java.util.ArrayList)1 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)1 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)1