Projekt

Obecné

Profil

Stáhnout (2.98 KB) Statistiky
| Větev: | Tag: | Revize:
1
package cz.zcu.kiv.backendapi.user;
2

    
3
import com.auth0.jwt.JWT;
4
import com.auth0.jwt.JWTVerifier;
5
import com.auth0.jwt.algorithms.Algorithm;
6
import com.auth0.jwt.interfaces.DecodedJWT;
7
import com.google.common.base.Strings;
8
import cz.zcu.kiv.backendapi.security.jwt.JwtUtils;
9
import cz.zcu.kiv.backendapi.exception.ApiRequestException;
10
import lombok.RequiredArgsConstructor;
11
import lombok.extern.slf4j.Slf4j;
12
import org.springframework.http.HttpHeaders;
13
import org.springframework.http.HttpStatus;
14
import org.springframework.security.core.GrantedAuthority;
15
import org.springframework.web.bind.annotation.GetMapping;
16
import org.springframework.web.bind.annotation.RestController;
17

    
18
import javax.servlet.http.HttpServletRequest;
19
import javax.servlet.http.HttpServletResponse;
20
import java.io.IOException;
21
import java.time.LocalDateTime;
22
import java.time.ZoneId;
23
import java.util.Date;
24
import java.util.stream.Collectors;
25

    
26
/**
27
 * Controller for users
28
 */
29
@RestController()
30
@RequiredArgsConstructor
31
@Slf4j
32
public class UserController {
33

    
34
    /**
35
     * User service
36
     */
37
    private final IUserService userService;
38

    
39
    /**
40
     * JWT utils
41
     */
42
    private final JwtUtils jwtUtils;
43

    
44

    
45
    /**
46
     * Refreshes access token if refresh token is valid
47
     *
48
     * @param request  request
49
     * @param response response
50
     * @throws IOException I/O Exception
51
     */
52
    @GetMapping("token/refresh")
53
    public void refreshToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
54
        String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
55
        if (Strings.isNullOrEmpty(authorizationHeader) || !authorizationHeader.startsWith(jwtUtils.getTokenPrefix())) {
56
            throw new ApiRequestException("Refresh token is missing", HttpStatus.FORBIDDEN);
57
        }
58
        try {
59
            String refresh_token = authorizationHeader.substring(jwtUtils.getTokenPrefix().length());
60
            Algorithm algorithm = jwtUtils.getAlgorithm(); //TODO secure
61
            JWTVerifier verifier = JWT.require(algorithm).build();
62
            DecodedJWT decodedJWT = verifier.verify(refresh_token);
63
            String username = decodedJWT.getSubject();
64
            UserEntity user = userService.getUserByName(username);
65
            String access_token = JWT.create()
66
                    .withSubject(user.getUsername())
67
                    .withExpiresAt(Date.from((LocalDateTime.now().plusMinutes(jwtUtils.getTokenExpirationAfterMinutes())).atZone(ZoneId.systemDefault()).toInstant()))
68
                    .withIssuer(request.getRequestURL().toString())
69
                    .withClaim(jwtUtils.getClaimAuthoritiesName(), user.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()))
70
                    .sign(algorithm);
71
            jwtUtils.writeTokensToResponse(response, access_token, refresh_token);
72
        } catch (Exception e) {
73
            log.error("Error refreshing token in: " + e.getMessage());
74
            jwtUtils.writeErrorToResponse(response, e);
75
        }
76
    }
77
}
(4-4/7)