Archived
Save the actual version of the embryon api.
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
package org.codiki.account;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import javax.naming.AuthenticationException;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.codiki.core.entities.dto.PasswordWrapperDTO;
|
||||
import org.codiki.core.entities.dto.UserDTO;
|
||||
import org.codiki.core.entities.persistence.User;
|
||||
import org.codiki.core.repositories.UserRepository;
|
||||
import org.codiki.core.security.TokenService;
|
||||
import org.codiki.core.utils.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class AccountService {
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
private TokenService tokenService;
|
||||
|
||||
/**
|
||||
* Check the user credentials and generate him a token if they are correct.
|
||||
*
|
||||
* @param pUser
|
||||
* The user sent from client.
|
||||
* @return The user populated with the generated token.
|
||||
* @throws AuthenticationException
|
||||
* If the credentials are wrong.
|
||||
*/
|
||||
public UserDTO checkCredentials(HttpServletResponse pResponse, UserDTO pUser) {
|
||||
UserDTO result = null;
|
||||
|
||||
Optional<User> user = userRepository.findByEmail(pUser.getEmail());
|
||||
|
||||
if(user.isPresent() && StringUtils.compareHash(pUser.getPassword(), user.get().getPassword())) {
|
||||
tokenService.addUser(user.get());
|
||||
result = new UserDTO(user.get(), true);
|
||||
} else {
|
||||
pResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public boolean changePassword(final User pUser, final PasswordWrapperDTO pPasswordWrapper,
|
||||
final HttpServletResponse pResponse) {
|
||||
boolean result = false;
|
||||
|
||||
if(pPasswordWrapper.getNewPassword().equals(pPasswordWrapper.getConfirmPassword())) {
|
||||
// We fetch the connected user from database to get his hashed password
|
||||
final Optional<User> userFromDb = userRepository.findById(pUser.getId());
|
||||
if(userFromDb.isPresent() && StringUtils.compareHash(pPasswordWrapper.getOldPassword(),
|
||||
userFromDb.get().getPassword())) {
|
||||
result = true;
|
||||
userFromDb.get().setPassword(StringUtils.hashPassword(pPasswordWrapper.getNewPassword()));
|
||||
userRepository.save(userFromDb.get());
|
||||
} else {
|
||||
pResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user