Search in sources :

Example 1 with User

use of com.auth0.json.mgmt.users.User in project CollectiveOneWebapp by CollectiveOne.

the class AppUserService method updateUserDataInLocalDB.

@Transactional
public Boolean updateUserDataInLocalDB(UUID c1Id) {
    AppUser appUser = appUserRepository.findByC1Id(c1Id);
    try {
        User auth0User = mgmt.users().get(appUser.getAuth0Ids().get(0), null).execute();
        appUser.getProfile().setPictureUrl(auth0User.getPicture());
        appUserRepository.save(appUser);
        return true;
    } catch (APIException exception) {
        System.out.println(exception.getMessage());
    } catch (Auth0Exception exception) {
        System.out.println(exception.getMessage());
    }
    return false;
}
Also used : User(com.auth0.json.mgmt.users.User) APIException(com.auth0.exception.APIException) Auth0Exception(com.auth0.exception.Auth0Exception) Transactional(javax.transaction.Transactional)

Example 2 with User

use of com.auth0.json.mgmt.users.User in project CollectiveOneWebapp by CollectiveOne.

the class AppUserService method addUserToLocalDB.

@Transactional
private AppUser addUserToLocalDB(String auth0Id) {
    /* retrieve from Auth0 */
    AppUser appUser = null;
    User auth0User = null;
    if (auth0Id.equals("anonymousUser")) {
        return null;
    }
    try {
        auth0User = mgmt.users().get(auth0Id, null).execute();
        /* check if this email is already registered. */
        appUser = appUserRepository.findByEmail(auth0User.getEmail());
        if (appUser == null) {
            // if (auth0User.isEmailVerified()) {
            if (true) {
                /* create a new user if not */
                appUser = new AppUser();
                appUser.getAuth0Ids().add((auth0User.getId()));
                appUser.setEmail(auth0User.getEmail());
                appUser.setEmailNotificationsEnabled(true);
                AppUserProfile profile = new AppUserProfile();
                if (auth0User.getIdentities().get(0).getProvider().equals("auth0")) {
                    profile.setNickname(auth0User.getNickname());
                } else {
                    profile.setNickname(auth0User.getName());
                }
                profile.setUser(appUser);
                profile.setPictureUrl(auth0User.getPicture());
                profile = appUserProfileRepository.save(profile);
                appUser.setProfile(profile);
            }
        } else {
            /* just add the auth0id to the existing user */
            appUser.getAuth0Ids().add(auth0Id);
        }
        appUser = appUserRepository.save(appUser);
    } catch (APIException exception) {
        System.out.println(exception.getMessage());
    } catch (Auth0Exception exception) {
        System.out.println(exception.getMessage());
    }
    return appUser;
}
Also used : User(com.auth0.json.mgmt.users.User) APIException(com.auth0.exception.APIException) Auth0Exception(com.auth0.exception.Auth0Exception) Transactional(javax.transaction.Transactional)

Example 3 with User

use of com.auth0.json.mgmt.users.User in project gravitee-management-rest-api by gravitee-io.

the class UserServiceImpl method findAll.

@Override
public Set<UserEntity> findAll(boolean loadRoles) {
    try {
        LOGGER.debug("Find all users");
        Set<User> users = userRepository.findAll();
        return users.stream().map(u -> convert(u, loadRoles)).collect(Collectors.toSet());
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to find all users", ex);
        throw new TechnicalManagementException("An error occurs while trying to find all users", ex);
    }
}
Also used : RoleScope(io.gravitee.repository.management.model.RoleScope) java.util(java.util) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder) NotificationParamsBuilder(io.gravitee.management.service.notification.NotificationParamsBuilder) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) MembershipDefaultReferenceId(io.gravitee.repository.management.model.MembershipDefaultReferenceId) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) EmailNotificationBuilder(io.gravitee.management.service.builder.EmailNotificationBuilder) StringUtils(org.apache.commons.lang3.StringUtils) Value(org.springframework.beans.factory.annotation.Value) DEFAULT_JWT_EMAIL_REGISTRATION_EXPIRE_AFTER(io.gravitee.management.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_EMAIL_REGISTRATION_EXPIRE_AFTER) JWTVerifier(com.auth0.jwt.JWTVerifier) UUID(io.gravitee.common.utils.UUID) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) io.gravitee.management.model(io.gravitee.management.model) UserRepository(io.gravitee.repository.management.api.UserRepository) JWTSigner(com.auth0.jwt.JWTSigner) DEFAULT_JWT_ISSUER(io.gravitee.management.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER) UserNotFoundException(io.gravitee.management.service.exceptions.UserNotFoundException) Claims(io.gravitee.management.service.common.JWTHelper.Claims) MembershipReferenceType(io.gravitee.repository.management.model.MembershipReferenceType) UsernameAlreadyExistsException(io.gravitee.management.service.exceptions.UsernameAlreadyExistsException) Logger(org.slf4j.Logger) DefaultRoleNotFoundException(io.gravitee.management.service.exceptions.DefaultRoleNotFoundException) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) PortalHook(io.gravitee.management.service.notification.PortalHook) Collectors(java.util.stream.Collectors) IOUtils(org.apache.commons.io.IOUtils) Component(org.springframework.stereotype.Component) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) USER(io.gravitee.repository.management.model.Audit.AuditProperties.USER) io.gravitee.management.service(io.gravitee.management.service) User(io.gravitee.repository.management.model.User) io.gravitee.common.utils(io.gravitee.common.utils) DatatypeConverter(javax.xml.bind.DatatypeConverter) User(io.gravitee.repository.management.model.User) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException)

Example 4 with User

use of com.auth0.json.mgmt.users.User in project gravitee-management-rest-api by gravitee-io.

the class UserServiceImpl method register.

/**
 * Allows to pre-create a user and send an email notification to finalize its creation.
 */
@Override
public UserEntity register(final NewExternalUserEntity newExternalUserEntity) {
    checkUserRegistrationEnabled();
    newExternalUserEntity.setUsername(newExternalUserEntity.getEmail());
    newExternalUserEntity.setSource("gravitee");
    newExternalUserEntity.setSourceId(newExternalUserEntity.getUsername());
    final UserEntity userEntity = create(newExternalUserEntity, true);
    // generate a JWT to store user's information and for security purpose
    final Map<String, Object> claims = new HashMap<>();
    claims.put(Claims.ISSUER, environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER));
    claims.put(Claims.SUBJECT, userEntity.getUsername());
    claims.put(Claims.EMAIL, userEntity.getEmail());
    claims.put(Claims.FIRSTNAME, userEntity.getFirstname());
    claims.put(Claims.LASTNAME, userEntity.getLastname());
    final JWTSigner.Options options = new JWTSigner.Options();
    options.setExpirySeconds(environment.getProperty("user.creation.token.expire-after", Integer.class, DEFAULT_JWT_EMAIL_REGISTRATION_EXPIRE_AFTER));
    options.setIssuedAt(true);
    options.setJwtId(true);
    // send a confirm email with the token
    final String jwtSecret = environment.getProperty("jwt.secret");
    if (jwtSecret == null || jwtSecret.isEmpty()) {
        throw new IllegalStateException("JWT secret is mandatory");
    }
    final String token = new JWTSigner(jwtSecret).sign(claims, options);
    String portalUrl = environment.getProperty("portalURL");
    if (portalUrl.endsWith("/")) {
        portalUrl = portalUrl.substring(0, portalUrl.length() - 1);
    }
    String registrationUrl = portalUrl + "/#!/registration/confirm/" + token;
    final Map<String, Object> params = new NotificationParamsBuilder().user(userEntity).token(token).registrationUrl(registrationUrl).build();
    notifierService.trigger(PortalHook.USER_REGISTERED, params);
    emailService.sendAsyncEmailNotification(new EmailNotificationBuilder().to(userEntity.getEmail()).subject("User registration - " + userEntity.getUsername()).template(EmailNotificationBuilder.EmailTemplate.USER_REGISTRATION).params(params).build());
    return userEntity;
}
Also used : JWTSigner(com.auth0.jwt.JWTSigner) EmailNotificationBuilder(io.gravitee.management.service.builder.EmailNotificationBuilder) NotificationParamsBuilder(io.gravitee.management.service.notification.NotificationParamsBuilder)

Example 5 with User

use of com.auth0.json.mgmt.users.User in project gravitee-management-rest-api by gravitee-io.

the class UserServiceImpl method create.

/**
 * Allows to complete the creation of a user which is pre-created.
 * @param registerUserEntity a valid token and a password
 * @return the user
 */
@Override
public UserEntity create(final RegisterUserEntity registerUserEntity) {
    checkUserRegistrationEnabled();
    try {
        final String jwtSecret = environment.getProperty("jwt.secret");
        if (jwtSecret == null || jwtSecret.isEmpty()) {
            throw new IllegalStateException("JWT secret is mandatory");
        }
        final Map<String, Object> claims = new JWTVerifier(jwtSecret).verify(registerUserEntity.getToken());
        final NewUserEntity newUserEntity = new NewUserEntity();
        newUserEntity.setUsername(claims.get(Claims.SUBJECT).toString());
        newUserEntity.setEmail(claims.get(Claims.EMAIL).toString());
        newUserEntity.setFirstname(claims.get(Claims.FIRSTNAME).toString());
        newUserEntity.setLastname(claims.get(Claims.LASTNAME).toString());
        newUserEntity.setPassword(registerUserEntity.getPassword());
        LOGGER.debug("Create an internal user {}", newUserEntity);
        Optional<User> checkUser = userRepository.findByUsername(newUserEntity.getUsername());
        if (checkUser.isPresent() && StringUtils.isNotBlank(checkUser.get().getPassword())) {
            throw new UsernameAlreadyExistsException(newUserEntity.getUsername());
        }
        User user = convert(newUserEntity);
        user.setId(UUID.toString(UUID.random()));
        // Encrypt password if internal user
        if (user.getPassword() != null) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        // Set date fields
        user.setUpdatedAt(new Date());
        user = userRepository.update(user);
        auditService.createPortalAuditLog(Collections.singletonMap(USER, user.getUsername()), User.AuditEvent.USER_CREATED, user.getUpdatedAt(), null, user);
        return convert(user, true);
    } catch (Exception ex) {
        LOGGER.error("An error occurs while trying to create an internal user with the token {}", registerUserEntity.getToken(), ex);
        throw new TechnicalManagementException(ex.getMessage(), ex);
    }
}
Also used : UsernameAlreadyExistsException(io.gravitee.management.service.exceptions.UsernameAlreadyExistsException) User(io.gravitee.repository.management.model.User) JWTVerifier(com.auth0.jwt.JWTVerifier) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) UserNotFoundException(io.gravitee.management.service.exceptions.UserNotFoundException) UsernameAlreadyExistsException(io.gravitee.management.service.exceptions.UsernameAlreadyExistsException) DefaultRoleNotFoundException(io.gravitee.management.service.exceptions.DefaultRoleNotFoundException) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException) IOException(java.io.IOException) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException)

Aggregations

JWTSigner (com.auth0.jwt.JWTSigner)5 JWT (com.auth0.jwt.JWT)4 JWTVerifier (com.auth0.jwt.JWTVerifier)4 Algorithm (com.auth0.jwt.algorithms.Algorithm)4 Collectors (java.util.stream.Collectors)4 Test (org.junit.Test)4 JWTExpiredException (com.auth0.jwt.JWTExpiredException)3 JWTVerifyException (com.auth0.jwt.JWTVerifyException)3 EmailNotificationBuilder (io.gravitee.management.service.builder.EmailNotificationBuilder)3 DefaultRoleNotFoundException (io.gravitee.management.service.exceptions.DefaultRoleNotFoundException)3 TechnicalManagementException (io.gravitee.management.service.exceptions.TechnicalManagementException)3 UserNotFoundException (io.gravitee.management.service.exceptions.UserNotFoundException)3 URI (java.net.URI)3 APIException (com.auth0.exception.APIException)2 Auth0Exception (com.auth0.exception.Auth0Exception)2 User (com.auth0.json.mgmt.users.User)2 JWTCreator (com.auth0.jwt.JWTCreator)2 PublicClaims (com.auth0.jwt.impl.PublicClaims)2 Claim (com.auth0.jwt.interfaces.Claim)2 ImmutableList (com.google.common.collect.ImmutableList)2