-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathAuthenticateCustomerApi.java
executable file
·273 lines (209 loc) · 11.9 KB
/
AuthenticateCustomerApi.java
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
package com.salesmanager.shop.store.api.v1.customer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.apache.commons.lang3.Validate;
import org.apache.http.auth.AuthenticationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.salesmanager.core.model.customer.Customer;
import com.salesmanager.core.model.merchant.MerchantStore;
import com.salesmanager.core.model.reference.language.Language;
import com.salesmanager.shop.constants.Constants;
import com.salesmanager.shop.model.customer.PersistableCustomer;
import com.salesmanager.shop.store.api.exception.GenericRuntimeException;
import com.salesmanager.shop.store.api.exception.ResourceNotFoundException;
import com.salesmanager.shop.store.api.exception.UnauthorizedException;
import com.salesmanager.shop.store.controller.customer.facade.CustomerFacade;
import com.salesmanager.shop.store.controller.store.facade.StoreFacade;
import com.salesmanager.shop.store.controller.user.facade.UserFacade;
import com.salesmanager.shop.store.security.AuthenticationRequest;
import com.salesmanager.shop.store.security.AuthenticationResponse;
import com.salesmanager.shop.store.security.JWTTokenUtil;
import com.salesmanager.shop.store.security.PasswordRequest;
import com.salesmanager.shop.store.security.user.JWTUser;
import com.salesmanager.shop.utils.AuthorizationUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.SwaggerDefinition;
import io.swagger.annotations.Tag;
import springfox.documentation.annotations.ApiIgnore;
@RestController
@RequestMapping("/api/v1")
@Api(tags = {"Customer authentication resource (Customer Authentication Api)"})
@SwaggerDefinition(tags = {
@Tag(name = "Customer authentication resource", description = "Authenticates customer, register customer and reset customer password")
})
public class AuthenticateCustomerApi {
private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticateCustomerApi.class);
@Value("${authToken.header}")
private String tokenHeader;
@Inject
private AuthenticationManager jwtCustomerAuthenticationManager;
@Inject
private JWTTokenUtil jwtTokenUtil;
@Inject
private UserDetailsService jwtCustomerDetailsService;
@Inject
private CustomerFacade customerFacade;
@Inject
private StoreFacade storeFacade;
@Autowired
AuthorizationUtils authorizationUtils;
@Autowired
private UserFacade userFacade;
/**
* Create new customer for a given MerchantStore, then authenticate that customer
*/
@RequestMapping( value={"/customer/register"}, method=RequestMethod.POST, produces ={ "application/json" })
@ResponseStatus(HttpStatus.CREATED)
@ApiOperation(httpMethod = "POST", value = "Registers a customer to the application", notes = "Used as self-served operation",response = AuthenticationResponse.class)
@ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "string", defaultValue = "DEFAULT"),
@ApiImplicitParam(name = "lang", dataType = "string", defaultValue = "en") })
@ResponseBody
public ResponseEntity<?> register(
@Valid @RequestBody PersistableCustomer customer,
@ApiIgnore MerchantStore merchantStore,
@ApiIgnore Language language) throws Exception {
customer.setUserName(customer.getEmailAddress());
if(customerFacade.checkIfUserExists(customer.getUserName(), merchantStore)) {
//409 Conflict
throw new GenericRuntimeException("409", "Customer with email [" + customer.getEmailAddress() + "] is already registered");
}
Validate.notNull(customer.getUserName(),"Username cannot be null");
Validate.notNull(customer.getBilling(),"Requires customer Country code");
Validate.notNull(customer.getBilling().getCountry(),"Requires customer Country code");
customerFacade.registerCustomer(customer, merchantStore, language);
// Perform the security
Authentication authentication = null;
try {
authentication = jwtCustomerAuthenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
customer.getUserName(),
customer.getPassword()
)
);
} catch(Exception e) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
if(authentication == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
SecurityContextHolder.getContext().setAuthentication(authentication);
// Reload password post-security so we can generate token
final JWTUser userDetails = (JWTUser)jwtCustomerDetailsService.loadUserByUsername(customer.getUserName());
final String token = jwtTokenUtil.generateToken(userDetails);
// Return the token
return ResponseEntity.ok(new AuthenticationResponse(customer.getId(),token));
}
/**
* Authenticate a customer using username & password
* @param authenticationRequest
* @param device
* @return
* @throws AuthenticationException
*/
@RequestMapping(value = "/customer/login", method = RequestMethod.POST, produces ={ "application/json" })
@ApiOperation(httpMethod = "POST", value = "Authenticates a customer to the application", notes = "Customer can authenticate after registration, request is {\"username\":\"admin\",\"password\":\"password\"}",response = ResponseEntity.class)
@ResponseBody
public ResponseEntity<?> authenticate(@RequestBody @Valid AuthenticationRequest authenticationRequest) throws AuthenticationException {
//TODO SET STORE in flow
// Perform the security
Authentication authentication = null;
try {
//to be used when username and password are set
authentication = jwtCustomerAuthenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
authenticationRequest.getUsername(),
authenticationRequest.getPassword()
)
);
} catch(BadCredentialsException unn) {
return new ResponseEntity<>("{\"message\":\"Bad credentials\"}",HttpStatus.UNAUTHORIZED);
} catch(Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
if(authentication == null) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
SecurityContextHolder.getContext().setAuthentication(authentication);
// Reload password post-security so we can generate token
// todo create one for social
final JWTUser userDetails = (JWTUser)jwtCustomerDetailsService.loadUserByUsername(authenticationRequest.getUsername());
final String token = jwtTokenUtil.generateToken(userDetails);
// Return the token
return ResponseEntity.ok(new AuthenticationResponse(userDetails.getId(),token));
}
@RequestMapping(value = "/auth/customer/refresh", method = RequestMethod.GET, produces ={ "application/json" })
public ResponseEntity<?> refreshToken(HttpServletRequest request) {
String token = request.getHeader(tokenHeader);
String username = jwtTokenUtil.getUsernameFromToken(token);
JWTUser user = (JWTUser) jwtCustomerDetailsService.loadUserByUsername(username);
if (jwtTokenUtil.canTokenBeRefreshed(token, user.getLastPasswordResetDate())) {
String refreshedToken = jwtTokenUtil.refreshToken(token);
return ResponseEntity.ok(new AuthenticationResponse(user.getId(),refreshedToken));
} else {
return ResponseEntity.badRequest().body(null);
}
}
@RequestMapping(value = "/private/customer/password", method = RequestMethod.PUT, produces ={ "application/json" })
@ApiOperation(httpMethod = "PUT", value = "Change customer password", notes = "Change password request object is {\"username\":\"test@email.com\"}",response = ResponseEntity.class)
public ResponseEntity<?> setPassword(
@RequestBody @Valid AuthenticationRequest authenticationRequest,
@ApiIgnore MerchantStore merchantStore,
@ApiIgnore Language language) {
String authenticatedUser = userFacade.authenticatedUser();
if (authenticatedUser == null) {
throw new UnauthorizedException();
}
userFacade.authorizedGroup(authenticatedUser, Stream.of(Constants.GROUP_SUPERADMIN, Constants.GROUP_ADMIN, Constants.GROUP_ADMIN_RETAIL).collect(Collectors.toList()));
Customer customer = customerFacade.getCustomerByUserName(authenticationRequest.getUsername(), merchantStore);
if(customer == null){
return ResponseEntity.notFound().build();
}
customerFacade.changePassword(customer, authenticationRequest.getPassword());
return ResponseEntity.ok(Void.class);
}
@RequestMapping(value = "/auth/customer/password", method = RequestMethod.POST, produces ={ "application/json" })
@ApiOperation(httpMethod = "POST", value = "Sends a request to reset password", notes = "Password reset request is {\"username\":\"test@email.com\"}",response = ResponseEntity.class)
public ResponseEntity<?> changePassword(@RequestBody @Valid PasswordRequest passwordRequest, HttpServletRequest request) {
try {
MerchantStore merchantStore = storeFacade.getByCode(request);
Customer customer = customerFacade.getCustomerByUserName(passwordRequest.getUsername(), merchantStore);
if(customer == null){
return ResponseEntity.notFound().build();
}
//need to validate if password matches
if(!customerFacade.passwordMatch(passwordRequest.getCurrent(), customer)) {
throw new ResourceNotFoundException("Username or password does not match");
}
if(!passwordRequest.getPassword().equals(passwordRequest.getRepeatPassword())) {
throw new ResourceNotFoundException("Both passwords do not match");
}
customerFacade.changePassword(customer, passwordRequest.getPassword());
return ResponseEntity.ok(Void.class);
} catch(Exception e) {
return ResponseEntity.badRequest().body("Exception when reseting password "+e.getMessage());
}
}
}