-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathApiSiteController.java
More file actions
289 lines (253 loc) · 15.6 KB
/
Copy pathApiSiteController.java
File metadata and controls
289 lines (253 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
/*
Insecure Web App (IWA)
Copyright 2020-2023 Open Text or one of its affiliates.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.microfocus.example.api.controllers;
import com.microfocus.example.entity.CustomUserDetails;
import com.microfocus.example.entity.RefreshToken;
import com.microfocus.example.entity.User;
import com.microfocus.example.exception.ApiBadCredentialsException;
import com.microfocus.example.exception.ApiRefreshTokenException;
import com.microfocus.example.payload.request.LoginRequest;
import com.microfocus.example.payload.request.RefreshTokenRequest;
import com.microfocus.example.payload.request.RegisterUserRequest;
import com.microfocus.example.payload.request.SubscribeUserRequest;
import com.microfocus.example.payload.response.*;
import com.microfocus.example.repository.RoleRepository;
import com.microfocus.example.repository.UserRepository;
import com.microfocus.example.service.RefreshTokenService;
import com.microfocus.example.service.UserService;
import com.microfocus.example.utils.JwtUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* A RESTFul controller for accessing site information.
*
* @author Kevin A. Lee
*/
@RestController
@RequestMapping(value = "/api/v3/site")
@Tag(name = "site", description = "Site operations")
public class ApiSiteController {
private static final org.slf4j.Logger log = LoggerFactory.getLogger(ApiSiteController.class);
@Autowired
private UserService userService;
@Autowired
AuthenticationManager authenticationManager;
@Autowired
RefreshTokenService refreshTokenService;
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Bean("ApiSiteControllerPasswordEncoder")
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Autowired
JwtUtils jwtUtils;
public class SiteStatus {
private String health;
private String motd;
SiteStatus() { }
SiteStatus(String health, String motd) {
this.health = health;
this.motd = motd;
}
public String getHealth() {
return health;
}
public void setHealth(String health) {
this.health = health;
}
public String getMotd() {
return motd;
}
public void setMotd(String motd) {
this.motd = motd;
}
}
@Operation(summary = "Get the site status", description = "Get the site message of the day", tags = {"users"})
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Success", content = @Content(array = @ArraySchema(schema = @Schema(implementation = SiteStatus.class)))),
@ApiResponse(responseCode = "500", description = "Internal Server Error", content = @Content(schema = @Schema(implementation = ApiStatusResponse.class))),
})
@GetMapping(value = {"/status"}, produces = {"application/json"})
public ResponseEntity<SiteStatus> getSiteStatus() {
log.debug("API::Retrieving Site Status");
SiteStatus siteStatus = new SiteStatus("GREEN", "The site is currently healthy");
return ResponseEntity.ok().body(siteStatus);
}
@Operation(summary = "Check if username is taken", description = "Check if a user with the specified username already exists in the site", tags = {"site"})
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Success", content = @Content(schema = @Schema(implementation = User.class))),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(schema = @Schema(implementation = ApiStatusResponse.class))),
@ApiResponse(responseCode = "500", description = "Internal Server Error", content = @Content(schema = @Schema(implementation = ApiStatusResponse.class))),
})
@GetMapping(value = {"/username-already-exists/{username}"}, produces = {"application/json"})
public ResponseEntity<Boolean> usernameIsTaken(
@Parameter(description = "Username to check. Cannot be empty.", example = "user1", required = true) @PathVariable("username") String username) {
log.debug("API::Checking for user with username: " + username);
Optional<User> user = userService.findUserByUsername(username);
if (user.isPresent()) {
return new ResponseEntity<Boolean>(Boolean.TRUE, HttpStatus.OK);
} else {
return new ResponseEntity<Boolean>(Boolean.FALSE, HttpStatus.OK);
}
}
@Operation(summary = "Check if email exists", description = "Check if a user with the specified email address already exists in the site", tags = {"site"})
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Success", content = @Content(schema = @Schema(implementation = User.class))),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(schema = @Schema(implementation = ApiStatusResponse.class))),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(implementation = ApiStatusResponse.class))),
@ApiResponse(responseCode = "500", description = "Internal Server Error", content = @Content(schema = @Schema(implementation = ApiStatusResponse.class))),
})
@GetMapping(value = {"/email-already-exists/{email}"}, produces = {"application/json"})
public ResponseEntity<Boolean> emailIsTaken(
@Parameter(description = "Email address to check. Cannot be empty.", example = "user1@localhost.com", required = true) @PathVariable("email") String email) {
log.debug("API::Checking for user with email: " + email);
Optional<User> user = userService.findUserByEmail(email);
if (user.isPresent()) {
return new ResponseEntity<Boolean>(Boolean.TRUE, HttpStatus.OK);
} else {
return new ResponseEntity<Boolean>(Boolean.FALSE, HttpStatus.OK);
}
}
@Operation(summary = "Register a new user", description = "Register a new user with the site", tags = {"site"})
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Success", content = @Content(schema = @Schema(implementation = RegisterUserResponse.class))),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(schema = @Schema(implementation = ApiStatusResponse.class))),
@ApiResponse(responseCode = "409", description = "User Already Exists", content = @Content(schema = @Schema(implementation = ApiStatusResponse.class))),
@ApiResponse(responseCode = "500", description = "Internal Server Error", content = @Content(schema = @Schema(implementation = ApiStatusResponse.class))),
})
@PostMapping(value = {"/register-user"}, produces = {"application/json"}, consumes = {"application/json"})
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<ApiStatusResponse> registerUser(
@io.swagger.v3.oas.annotations.parameters.RequestBody(description = "") @Valid @RequestBody RegisterUserRequest newUser) {
log.debug("API::Registering new user: " + newUser.toString());
RegisterUserResponse user = userService.registerUser(newUser);
ApiStatusResponse response = new ApiStatusResponse();
if (user.getEmail().equals(newUser.getEmail())) response.setSuccess(true);
return new ResponseEntity<>(response, HttpStatus.CREATED);
}
@Operation(summary = "Subscribe a new user", description = "Subscribe a new user to the newsletter", tags = {"site"})
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Success", content = @Content(schema = @Schema(implementation = SubscribeUserResponse.class))),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(schema = @Schema(implementation = ApiStatusResponse.class))),
@ApiResponse(responseCode = "409", description = "User Already Exists", content = @Content(schema = @Schema(implementation = ApiStatusResponse.class))),
@ApiResponse(responseCode = "500", description = "Internal Server Error", content = @Content(schema = @Schema(implementation = ApiStatusResponse.class))),
})
@PostMapping(value = {"/subscribe-user"}, produces = {"application/json"}, consumes = {"application/json"})
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<ApiStatusResponse> subscribeUser(
@io.swagger.v3.oas.annotations.parameters.RequestBody(description = "") @Valid @RequestBody SubscribeUserRequest newUser) {
log.debug("API::Subscribing a user to the newsletter: " + newUser.toString());
SubscribeUserResponse user = userService.subscribeUser(newUser);
ApiStatusResponse response = new ApiStatusResponse();
if ((user.getEmail().equals(newUser.getEmail()))) response.setSuccess(true);
return new ResponseEntity<>(response, HttpStatus.OK);
}
@Operation(summary = "Sign in", description = "Sign in to the system", tags = {"site"})
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Success", content = @Content(schema = @Schema(implementation = User.class))),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(schema = @Schema(implementation = ApiStatusResponse.class))),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(schema = @Schema(implementation = ApiStatusResponse.class))),
@ApiResponse(responseCode = "403", description = "Forbidden", content = @Content(schema = @Schema(implementation = ApiStatusResponse.class))),
@ApiResponse(responseCode = "500", description = "Internal Server Error", content = @Content(schema = @Schema(implementation = ApiStatusResponse.class))),
})
@PostMapping(value = {"/sign-in"}, produces = {"application/json"}, consumes = {"application/json"})
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<JwtResponse> signIn(@Valid @RequestBody LoginRequest loginRequest, HttpServletResponse response) {
Authentication authentication = null;
try {
authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
} catch (final BadCredentialsException ex) {
throw new ApiBadCredentialsException(loginRequest.getUsername());
}
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
CustomUserDetails iwaUser = (CustomUserDetails) authentication.getPrincipal();
User user = iwaUser.getUserDetails();
List<String> roles = authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.toList());
Cookie jwtTokenCookie = new Cookie("jwtToken", jwt);
jwtTokenCookie.setSecure(true);
jwtTokenCookie.setHttpOnly(true);
response.addCookie(jwtTokenCookie);
RefreshToken refreshToken = refreshTokenService.createRefreshToken(user.getId());
return ResponseEntity.ok(new JwtResponse(jwt,
refreshToken.getId().toString(),
jwtUtils.getExpirationFromJwtToken(jwt),
user.getId(),
user.getUsername(),
user.getEmail(),
roles));
}
@Operation(summary = "Refresh Token", description = "Refresh users JWT access token", tags = {"site"})
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Success", content = @Content(schema = @Schema(implementation = User.class))),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(schema = @Schema(implementation = ApiStatusResponse.class))),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(schema = @Schema(implementation = ApiStatusResponse.class))),
@ApiResponse(responseCode = "403", description = "Forbidden", content = @Content(schema = @Schema(implementation = ApiStatusResponse.class))),
@ApiResponse(responseCode = "500", description = "Internal Server Error", content = @Content(schema = @Schema(implementation = ApiStatusResponse.class))),
})
@PostMapping(value = {"/refresh-token"}, produces = {"application/json"}, consumes = {"application/json"})
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<RefreshTokenResponse> refreshToken(@Valid @RequestBody RefreshTokenRequest refreshTokenRequest) {
String requestRefreshToken = refreshTokenRequest.getRefreshToken();
try{
UUID uuid = UUID.fromString(requestRefreshToken);
log.debug("Refresh token request: " + uuid.toString());
} catch (IllegalArgumentException ex){
throw new ApiRefreshTokenException(requestRefreshToken, "Invalid refresh token format.");
}
return refreshTokenService.findByToken(requestRefreshToken)
.map(refreshTokenService::verifyExpiration)
.map(RefreshToken::getUser)
.map(user -> {
String token = jwtUtils.generateJwtTokenFromUsername(user.getUsername());
long tokenExpiration = jwtUtils.getExpirationFromJwtToken(token);
return ResponseEntity.ok(new RefreshTokenResponse(token, requestRefreshToken, tokenExpiration));
})
.orElseThrow(() -> new ApiRefreshTokenException(requestRefreshToken,
"Refresh token not found in database."));
}
}