Last active
August 30, 2018 07:14
-
-
Save vdelacou/5d21b1102f39068d6e40f7f175f63c31 to your computer and use it in GitHub Desktop.
Auth0ManagementApiService
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.seelix.api.service; | |
import java.util.Arrays; | |
import java.util.HashMap; | |
import java.util.List; | |
import java.util.Map; | |
import java.util.Optional; | |
import java.util.stream.Collectors; | |
import org.apache.commons.lang3.RandomStringUtils; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import org.springframework.data.domain.Page; | |
import org.springframework.data.domain.PageImpl; | |
import org.springframework.data.domain.Pageable; | |
import org.springframework.stereotype.Service; | |
import com.auth0.client.auth.AuthAPI; | |
import com.auth0.client.mgmt.ManagementAPI; | |
import com.auth0.client.mgmt.filter.UserFilter; | |
import com.auth0.exception.Auth0Exception; | |
import com.auth0.json.mgmt.users.User; | |
import com.auth0.json.mgmt.users.UsersPage; | |
import com.auth0.net.Request; | |
import com.seelix.api.config.ApplicationProperties; | |
import com.seelix.api.config.Constants; | |
import com.seelix.api.security.AuthoritiesConstants; | |
import com.seelix.api.security.SecurityUtils; | |
import com.seelix.api.service.dto.UserDTO; | |
import com.seelix.api.web.rest.errors.InternalServerErrorException; | |
@Service | |
public class Auth0ManagementApiService { | |
private final Logger log = LoggerFactory.getLogger(Auth0ManagementApiService.class); | |
private final AuthAPI authAPI; | |
private final ManagementAPI managementAPI; | |
private final ApplicationProperties applicationProperties; | |
public static final String ROLES = "roles"; | |
public static final String LANG = "lang"; | |
public static final String PIC = "picture"; | |
public static final String GIVEN_NAME = "givenName"; | |
public static final String FAMILY_NAME = "familyName"; | |
public Auth0ManagementApiService(AuthAPI authAPI, ManagementAPI managementAPI, | |
ApplicationProperties applicationProperties) { | |
this.authAPI = authAPI; | |
this.managementAPI = managementAPI; | |
this.applicationProperties = applicationProperties; | |
} | |
public Optional<UserDTO> getCurrentUser() { | |
return SecurityUtils.getCurrentUserLogin().map(userId -> { | |
UserFilter userFilter = new UserFilter(); | |
userFilter.withQuery("user_id: " + userId); | |
Request<UsersPage> requestUser = managementAPI.users().list(userFilter); | |
try { | |
UsersPage usersPage = requestUser.execute(); | |
if (usersPage.getItems() != null && usersPage.getItems().size() > 0) { | |
UserDTO userDTO = new UserDTO(usersPage.getItems().get(0)); | |
return userDTO; | |
} else { | |
return null; | |
} | |
} catch (Auth0Exception e) { | |
throw new InternalServerErrorException(e.getMessage()); | |
} | |
}); | |
} | |
public Optional<User> findOneByLogin(String login) throws Auth0Exception { | |
UserFilter userFilter = new UserFilter(); | |
userFilter.withQuery("username: " + login); | |
Request<UsersPage> requestUser = managementAPI.users().list(userFilter); | |
UsersPage usersPage = requestUser.execute(); | |
if (usersPage.getItems() != null && usersPage.getItems().size() > 0) { | |
return Optional.of(usersPage.getItems().get(0)); | |
} else { | |
return Optional.empty(); | |
} | |
} | |
public Optional<User> findOneByUserId(String userId) throws Auth0Exception { | |
UserFilter userFilter = new UserFilter(); | |
userFilter.withQuery("user_id: " + userId); | |
Request<UsersPage> requestUser = managementAPI.users().list(userFilter); | |
UsersPage usersPage = requestUser.execute(); | |
if (usersPage.getItems() != null && usersPage.getItems().size() > 0) { | |
return Optional.of(usersPage.getItems().get(0)); | |
} else { | |
return Optional.empty(); | |
} | |
} | |
public Optional<User> findOneByEmailIgnoreCase(String email) throws Auth0Exception { | |
UserFilter userFilter = new UserFilter(); | |
// auth0 save the email in lowercase | |
userFilter.withQuery("email: " + email.toLowerCase()); | |
Request<UsersPage> requestUser = managementAPI.users().list(userFilter); | |
UsersPage usersPage = requestUser.execute(); | |
if (usersPage.getItems() != null && usersPage.getItems().size() > 0) { | |
return Optional.of(usersPage.getItems().get(0)); | |
} else { | |
return Optional.empty(); | |
} | |
} | |
public User registerUser(UserDTO userDTO, String password) throws Auth0Exception { | |
User newUser = new User(); | |
Map<String, Object> userMetadata = new HashMap<String, Object>(); | |
Map<String, Object> appMetadata = new HashMap<String, Object>(); | |
newUser.setUsername(userDTO.getLogin()); | |
newUser.setPassword(password); | |
newUser.setGivenName(userDTO.getFirstName()); | |
userMetadata.put(GIVEN_NAME, userDTO.getFirstName()); | |
newUser.setFamilyName(userDTO.getLastName()); | |
userMetadata.put(FAMILY_NAME, userDTO.getLastName()); | |
newUser.setEmail(userDTO.getEmail()); | |
userMetadata.put(LANG, userDTO.getLangKey()); | |
userMetadata.put(PIC, userDTO.getImageUrl()); | |
newUser.setEmailVerified(false); | |
appMetadata.put(ROLES, Arrays.asList(AuthoritiesConstants.USER.toString())); | |
newUser.setAppMetadata(appMetadata); | |
newUser.setConnection( | |
applicationProperties.getSecurity().getAuthentication().getAuth0().getManagement().getConnection()); | |
Request<User> requestUser = managementAPI.users().create(newUser); | |
User user = requestUser.execute(); | |
log.debug("Created Information for User: {}", user); | |
return user; | |
} | |
public UserDTO createUser(UserDTO userDTO) throws Auth0Exception { | |
User newUser = new User(); | |
Map<String, Object> userMetadata = new HashMap<String, Object>(); | |
Map<String, Object> appMetadata = new HashMap<String, Object>(); | |
newUser.setUsername(userDTO.getLogin()); | |
// newUser.setPassword(password); | |
newUser.setGivenName(userDTO.getFirstName()); | |
userMetadata.put(GIVEN_NAME, userDTO.getFirstName()); | |
newUser.setFamilyName(userDTO.getLastName()); | |
userMetadata.put(FAMILY_NAME, userDTO.getLastName()); | |
newUser.setEmail(userDTO.getEmail()); | |
if (userDTO.getLangKey() == null) { | |
// default language | |
userMetadata.put(LANG, Constants.DEFAULT_LANGUAGE); | |
} else { | |
userMetadata.put(LANG, userDTO.getLangKey()); | |
} | |
userMetadata.put(PIC, userDTO.getImageUrl()); | |
newUser.setEmailVerified(true); | |
newUser.setPassword(RandomStringUtils.random(6)); | |
appMetadata.put(ROLES, userDTO.getAuthorities()); | |
newUser.setAppMetadata(appMetadata); | |
newUser.setConnection( | |
applicationProperties.getSecurity().getAuthentication().getAuth0().getManagement().getConnection()); | |
Request<User> requestUser = managementAPI.users().create(newUser); | |
User user = requestUser.execute(); | |
log.debug("Created Information for User: {}", user); | |
// send email to ask user to change password | |
Request<?> resetPassword = authAPI.resetPassword(user.getEmail(), | |
applicationProperties.getSecurity().getAuthentication().getAuth0().getManagement().getConnection()); | |
resetPassword.execute(); | |
return new UserDTO(user); | |
} | |
/** | |
* Update basic information (first name, last name, email, language) for the | |
* current user. | |
* | |
* @param firstName | |
* first name of user | |
* @param lastName | |
* last name of user | |
* @param email | |
* email id of user | |
* @param langKey | |
* language key | |
* @param imageUrl | |
* image URL of user | |
*/ | |
public void updateUser(String firstName, String lastName, String email, String langKey, String imageUrl) { | |
SecurityUtils.getCurrentUserLogin().ifPresent(userId -> { | |
User user = new User(); | |
Map<String, Object> userMetadata = new HashMap<String, Object>(); | |
user.setConnection( | |
applicationProperties.getSecurity().getAuthentication().getAuth0().getManagement().getConnection()); | |
user.setClientId( | |
applicationProperties.getSecurity().getAuthentication().getAuth0().getManagement().getClientId()); | |
user.setEmail(email); | |
userMetadata.put(GIVEN_NAME, firstName); | |
userMetadata.put(FAMILY_NAME, lastName); | |
userMetadata.put(LANG, langKey); | |
userMetadata.put(PIC, imageUrl); | |
user.setUserMetadata(userMetadata); | |
Request<User> requestUser = managementAPI.users().update(userId, user); | |
try { | |
user = requestUser.execute(); | |
log.debug("Changed Information for User: {}", user); | |
} catch (Auth0Exception e) { | |
throw new InternalServerErrorException(e.getMessage()); | |
} | |
}); | |
} | |
/** | |
* Update all information for a specific user, and return the modified user. | |
* | |
* @param userDTO | |
* user to update | |
* @return updated user | |
*/ | |
public Optional<UserDTO> updateUser(UserDTO userDTO) { | |
return SecurityUtils.getCurrentUserLogin().map(userId -> { | |
User user = new User(); | |
Map<String, Object> userMetadata = new HashMap<String, Object>(); | |
user.setConnection( | |
applicationProperties.getSecurity().getAuthentication().getAuth0().getManagement().getConnection()); | |
user.setClientId( | |
applicationProperties.getSecurity().getAuthentication().getAuth0().getManagement().getClientId()); | |
user.setUsername(userDTO.getLogin()); | |
user.setEmail(userDTO.getEmail()); | |
userMetadata.put(GIVEN_NAME, userDTO.getFirstName()); | |
userMetadata.put(FAMILY_NAME, userDTO.getLastName()); | |
userMetadata.put(LANG, userDTO.getLangKey()); | |
userMetadata.put(PIC, userDTO.getImageUrl()); | |
user.setUserMetadata(userMetadata); | |
Request<User> requestUser = managementAPI.users().update(userId, user); | |
try { | |
user = requestUser.execute(); | |
log.debug("Changed Information for User: {}", user); | |
return user; | |
} catch (Auth0Exception e) { | |
throw new InternalServerErrorException(e.getMessage()); | |
} | |
}).map(UserDTO::new); | |
} | |
public void deleteUser(String login) { | |
try { | |
this.findOneByLogin(login).ifPresent(user -> { | |
Request<?> request = managementAPI.users().delete(login); | |
try { | |
request.execute(); | |
log.debug("Deleted User: {}", user); | |
} catch (Auth0Exception e) { | |
throw new InternalServerErrorException(e.getMessage()); | |
} | |
}); | |
} catch (Auth0Exception e) { | |
throw new InternalServerErrorException(e.getMessage()); | |
} | |
} | |
public void changePassword(String password) { | |
SecurityUtils.getCurrentUserLogin().ifPresent(userId -> { | |
User user = new User(); | |
user.setConnection( | |
applicationProperties.getSecurity().getAuthentication().getAuth0().getManagement().getConnection()); | |
user.setPassword(password); | |
Request<User> requestUser = managementAPI.users().update(userId, user); | |
try { | |
user = requestUser.execute(); | |
log.debug("Changed Password for User: {}", user); | |
} catch (Auth0Exception e) { | |
throw new InternalServerErrorException(e.getMessage()); | |
} | |
}); | |
} | |
public Page<UserDTO> getAllManagedUsers(Pageable pageable) { | |
UserFilter userFilter = new UserFilter(); | |
userFilter.withPage(pageable.getPageNumber(), pageable.getPageSize()); | |
userFilter.withTotals(true); | |
Request<UsersPage> requestUser = managementAPI.users().list(userFilter); | |
try { | |
UsersPage usersPage = requestUser.execute(); | |
List<UserDTO> list = usersPage.getItems().stream().map(user -> { | |
return new UserDTO(user); | |
}).collect(Collectors.toList()); | |
Page<UserDTO> result = new PageImpl<UserDTO>(list, pageable, usersPage.getTotal()); | |
return result; | |
} catch (Auth0Exception e) { | |
throw new InternalServerErrorException(e.getMessage()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment