Search in sources :

Example 11 with User

use of com.auth0.flickr2.domain.User in project gravitee-api-management by gravitee-io.

the class UserServiceImpl method update.

@Override
public UserEntity update(String id, UpdateUserEntity updateUserEntity, String newsletterEmail) {
    try {
        LOGGER.debug("Updating {}", updateUserEntity);
        Optional<User> checkUser = userRepository.findById(id);
        if (!checkUser.isPresent()) {
            throw new UserNotFoundException(id);
        }
        User user = checkUser.get();
        User previousUser = new User(user);
        // Set date fields
        user.setUpdatedAt(new Date());
        // Set variant fields
        if (updateUserEntity.getPicture() != null) {
            user.setPicture(updateUserEntity.getPicture());
        }
        if (updateUserEntity.getFirstname() != null) {
            user.setFirstname(updateUserEntity.getFirstname());
        }
        if (updateUserEntity.getLastname() != null) {
            user.setLastname(updateUserEntity.getLastname());
        }
        if (updateUserEntity.getEmail() != null && !updateUserEntity.getEmail().equals(user.getEmail())) {
            if (isInternalUser(user)) {
                // sourceId can be updated only for user registered into the Gravitee Repository
                // in that case, check if the email is available before update sourceId
                final Optional<User> optionalUser = userRepository.findBySource(user.getSource(), updateUserEntity.getEmail(), user.getOrganizationId());
                if (optionalUser.isPresent()) {
                    throw new UserAlreadyExistsException(user.getSource(), updateUserEntity.getEmail(), user.getOrganizationId());
                }
                user.setSourceId(updateUserEntity.getEmail());
            }
            user.setEmail(updateUserEntity.getEmail());
        }
        if (updateUserEntity.getStatus() != null) {
            user.setStatus(UserStatus.valueOf(updateUserEntity.getStatus()));
        }
        if (updateUserEntity.isNewsletter() != null) {
            user.setNewsletterSubscribed(updateUserEntity.isNewsletter());
            if (updateUserEntity.isNewsletter() && newsletterEmail != null) {
                newsletterService.subscribe(newsletterEmail);
            }
        }
        User updatedUser = userRepository.update(user);
        auditService.createOrganizationAuditLog(GraviteeContext.getCurrentOrganization(), Collections.singletonMap(USER, user.getId()), User.AuditEvent.USER_UPDATED, user.getUpdatedAt(), previousUser, user);
        List<UserMetadataEntity> updatedMetadata = new ArrayList<>();
        if (updateUserEntity.getCustomFields() != null && !updateUserEntity.getCustomFields().isEmpty()) {
            List<UserMetadataEntity> metadata = userMetadataService.findAllByUserId(user.getId());
            for (Map.Entry<String, Object> entry : updateUserEntity.getCustomFields().entrySet()) {
                Optional<UserMetadataEntity> existingMeta = metadata.stream().filter(meta -> meta.getKey().equals(entry.getKey())).findFirst();
                if (existingMeta.isPresent()) {
                    UserMetadataEntity meta = existingMeta.get();
                    UpdateUserMetadataEntity metadataEntity = new UpdateUserMetadataEntity();
                    metadataEntity.setName(meta.getName());
                    metadataEntity.setKey(meta.getKey());
                    metadataEntity.setValue(String.valueOf(entry.getValue()));
                    metadataEntity.setUserId(meta.getUserId());
                    metadataEntity.setFormat(meta.getFormat());
                    updatedMetadata.add(userMetadataService.update(metadataEntity));
                } else {
                    // some additional fields may have been added after the user registration
                    NewUserMetadataEntity metadataEntity = new NewUserMetadataEntity();
                    metadataEntity.setName(entry.getKey());
                    metadataEntity.setValue(String.valueOf(entry.getValue()));
                    metadataEntity.setUserId(user.getId());
                    metadataEntity.setFormat(MetadataFormat.STRING);
                    updatedMetadata.add(userMetadataService.create(metadataEntity));
                }
            }
        }
        return convert(updatedUser, true, updatedMetadata);
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to update {}", updateUserEntity, ex);
        throw new TechnicalManagementException("An error occurs while trying update " + updateUserEntity, ex);
    }
}
Also used : BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder) Page(io.gravitee.common.data.domain.Page) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) LoggerFactory(org.slf4j.LoggerFactory) MembershipRepository(io.gravitee.repository.management.api.MembershipRepository) Autowired(org.springframework.beans.factory.annotation.Autowired) SocialIdentityProviderEntity(io.gravitee.rest.api.model.configuration.identity.SocialIdentityProviderEntity) RoleScope(io.gravitee.rest.api.model.permissions.RoleScope) StringUtils(org.apache.commons.lang3.StringUtils) UPDATE(io.gravitee.rest.api.model.permissions.RolePermissionAction.UPDATE) IdentityProviderService(io.gravitee.rest.api.service.configuration.identity.IdentityProviderService) TemplateEngine(io.gravitee.el.TemplateEngine) Algorithm(com.auth0.jwt.algorithms.Algorithm) AuditQuery(io.gravitee.rest.api.model.audit.AuditQuery) PageableBuilder(io.gravitee.repository.management.api.search.builder.PageableBuilder) RoleMappingEntity(io.gravitee.rest.api.model.configuration.identity.RoleMappingEntity) Duration(java.time.Duration) PortalHook(io.gravitee.rest.api.service.notification.PortalHook) GroupMappingEntity(io.gravitee.rest.api.model.configuration.identity.GroupMappingEntity) Collectors.toSet(java.util.stream.Collectors.toSet) ApplicationSettings(io.gravitee.rest.api.model.application.ApplicationSettings) RolePermissionAction(io.gravitee.rest.api.model.permissions.RolePermissionAction) JsonPathFunction(io.gravitee.el.spel.function.json.JsonPathFunction) Instant(java.time.Instant) SimpleApplicationSettings(io.gravitee.rest.api.model.application.SimpleApplicationSettings) Collectors(java.util.stream.Collectors) Key(io.gravitee.rest.api.model.parameters.Key) NotificationParamsBuilder(io.gravitee.rest.api.service.notification.NotificationParamsBuilder) EmailNotificationBuilder(io.gravitee.rest.api.service.builder.EmailNotificationBuilder) UrlSanitizerUtils(io.gravitee.rest.api.service.sanitizer.UrlSanitizerUtils) DatatypeConverter(javax.xml.bind.DatatypeConverter) AuditEntity(io.gravitee.rest.api.model.audit.AuditEntity) RolePermission(io.gravitee.rest.api.model.permissions.RolePermission) SearchEngineService(io.gravitee.rest.api.service.search.SearchEngineService) JWT(com.auth0.jwt.JWT) io.gravitee.rest.api.service(io.gravitee.rest.api.service) java.util(java.util) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Pageable(io.gravitee.rest.api.model.common.Pageable) GraviteeContext(io.gravitee.rest.api.service.common.GraviteeContext) DEFAULT_JWT_EMAIL_REGISTRATION_EXPIRE_AFTER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_EMAIL_REGISTRATION_EXPIRE_AFTER) InitializingBean(org.springframework.beans.factory.InitializingBean) Value(org.springframework.beans.factory.annotation.Value) JWTVerifier(com.auth0.jwt.JWTVerifier) ReadContext(com.jayway.jsonpath.ReadContext) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) UserRepository(io.gravitee.repository.management.api.UserRepository) Claims(io.gravitee.rest.api.service.common.JWTHelper.Claims) UserStatus(io.gravitee.repository.management.model.UserStatus) io.gravitee.rest.api.model(io.gravitee.rest.api.model) Membership(io.gravitee.repository.management.model.Membership) Query(io.gravitee.rest.api.service.search.query.Query) UuidString(io.gravitee.rest.api.service.common.UuidString) Logger(org.slf4j.Logger) ParameterReferenceType(io.gravitee.rest.api.model.parameters.ParameterReferenceType) JsonPath(com.jayway.jsonpath.JsonPath) Maps(io.gravitee.common.util.Maps) DEFAULT_JWT_ISSUER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER) MetadataPage(io.gravitee.common.data.domain.MetadataPage) Collectors.toList(java.util.stream.Collectors.toList) Component(org.springframework.stereotype.Component) USER(io.gravitee.repository.management.model.Audit.AuditProperties.USER) ChronoUnit(java.time.temporal.ChronoUnit) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) io.gravitee.rest.api.service.exceptions(io.gravitee.rest.api.service.exceptions) UserCriteria(io.gravitee.repository.management.api.search.UserCriteria) User(io.gravitee.repository.management.model.User) ACTION(io.gravitee.rest.api.service.common.JWTHelper.ACTION) QueryBuilder(io.gravitee.rest.api.service.search.query.QueryBuilder) SearchResult(io.gravitee.rest.api.service.impl.search.SearchResult) User(io.gravitee.repository.management.model.User) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) UuidString(io.gravitee.rest.api.service.common.UuidString)

Example 12 with User

use of com.auth0.flickr2.domain.User in project gravitee-api-management by gravitee-io.

the class UserServiceImpl method finalizeResetPassword.

@Override
public UserEntity finalizeResetPassword(ResetPasswordUserEntity registerUserEntity) {
    try {
        DecodedJWT jwt = getDecodedJWT(registerUserEntity.getToken());
        final String action = jwt.getClaim(Claims.ACTION).asString();
        if (!RESET_PASSWORD.name().equals(action)) {
            throw new UserStateConflictException("Invalid action on reset password resource");
        }
        final Object subject = jwt.getSubject();
        User user;
        if (subject == null) {
            throw new UserNotFoundException("Subject missing from JWT token");
        } else {
            final String username = subject.toString();
            LOGGER.debug("Find user {} to update password", username);
            Optional<User> checkUser = userRepository.findById(username);
            user = checkUser.orElseThrow(() -> new UserNotFoundException(username));
        }
        // Set date fields
        user.setUpdatedAt(new Date());
        // Encrypt password if internal user
        encryptPassword(user, registerUserEntity.getPassword());
        user = userRepository.update(user);
        auditService.createOrganizationAuditLog(GraviteeContext.getCurrentOrganization(), Collections.singletonMap(USER, user.getId()), User.AuditEvent.PASSWORD_CHANGED, user.getUpdatedAt(), null, null);
        // Do not send back the password
        user.setPassword(null);
        return convert(user, true);
    } catch (AbstractManagementException ex) {
        throw ex;
    } catch (Exception ex) {
        LOGGER.error("An error occurs while trying to change password of an internal user with the token {}", registerUserEntity.getToken(), ex);
        throw new TechnicalManagementException(ex.getMessage(), ex);
    }
}
Also used : User(io.gravitee.repository.management.model.User) UuidString(io.gravitee.rest.api.service.common.UuidString) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) TechnicalException(io.gravitee.repository.exceptions.TechnicalException)

Example 13 with User

use of com.auth0.flickr2.domain.User in project chemvantage by chuckwight.

the class LTILaunch method basicLtiLaunchRequest.

void basicLtiLaunchRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // check for required LTI launch parameters:
    try {
        String lti_message_type = request.getParameter("lti_message_type");
        if (lti_message_type == null || !"basic-lti-launch-request".contentEquals(lti_message_type)) {
            doError(request, response, "Invalid lti_message_type parameter.", null, null);
            return;
        }
        String lti_version = request.getParameter("lti_version");
        if (lti_version == null) {
            doError(request, response, "Missing lti_version parameter.", null, null);
            return;
        } else if (!lti_version.equals("LTI-1p0")) {
            doError(request, response, "Invalid lti_version parameter.", null, null);
            return;
        }
        String oauth_consumer_key = request.getParameter("oauth_consumer_key");
        if (oauth_consumer_key == null) {
            doError(request, response, "Missing oauth_consumer_key.", null, null);
            return;
        }
        String resource_link_id = request.getParameter("resource_link_id");
        if (resource_link_id == null) {
            doError(request, response, "Missing resource_link_id.", null, null);
            return;
        }
        Date now = new Date();
        BLTIConsumer tc;
        try {
            tc = ofy().load().type(BLTIConsumer.class).id(oauth_consumer_key).safe();
            if ("suspended".equals(tc.status)) {
                response.getWriter().println(Subject.header("ChemVantage Account Management") + suspendedAccount(tc) + Subject.footer);
                return;
            } else if (tc.expires != null && tc.expires.before(now)) {
                response.getWriter().println(Subject.header("ChemVantage Account Management") + expiredAccount(tc, request.getServerName()) + Subject.footer);
                return;
            }
            if (tc.secret == null)
                throw new Exception("Shared secret was not found in the ChemVantage database.");
            // 24 hrs ago
            Date yesterday = new Date(now.getTime() - 86400000L);
            if (tc.lastLogin == null || tc.lastLogin.before(yesterday)) {
                tc.lastLogin = now;
                tc.launchParameters = request.getParameterMap();
                try {
                    // this section synchronizes expiration dates from a single domain
                    String domain = new URL(tc.launchParameters.get("lis_outcome_service_url")[0]).getHost();
                    // domain may be null for instructors
                    if (domain != null)
                        tc.domain = domain;
                    if (tc.domain != null) {
                        // tc.domain may be null if grades are never returned to the LMS
                        List<BLTIConsumer> companions = ofy().load().type(BLTIConsumer.class).filter("domain", tc.domain).list();
                        companions.remove(tc);
                        for (BLTIConsumer tcc : companions) {
                            // assign the shortest expiration time found for this domain
                            if (tcc.expires != null && (tc.expires == null || tcc.expires.before(tc.expires)))
                                tc.expires = tcc.expires;
                        }
                    }
                } catch (Exception e) {
                }
                // update the lastLogin value and possibly the domain and expires fields
                ofy().save().entity(tc);
            }
        } catch (Exception e) {
            String use = request.getServerName().contains("dev-vantage") ? "dev" : "prod";
            throw new Exception("Invalid oauth_consumer_key. " + "Please verify that the oauth_consumer_key is entered into your LMS exactly as you are registered with ChemVantage. " + "If your account has been inactive for more than " + ("dev".equals(use) ? "30 days" : "six months") + ", it may have been " + "deleted in accordance with our <a href=https://www.chemvantage.org/About#privacy target=_blank>privacy policy</a>.<br/>" + "Please use the <a href=https://www.chemvantage.org/lti/registration target=_blank>ChemVantage Registration Page</a> " + "to reregister your LMS.");
        }
        OAuthMessage oam = OAuthServlet.getMessage(request, null);
        OAuthValidator oav = new SimpleOAuthValidator();
        OAuthConsumer cons = new OAuthConsumer("about:blank#OAuth+CallBack+NotUsed", oauth_consumer_key, tc.secret, null);
        OAuthAccessor acc = new OAuthAccessor(cons);
        OAuthSignatureMethod.getBaseString(oam);
        if (!Nonce.isUnique(request.getParameter("oauth_nonce"), request.getParameter("oauth_timestamp")))
            throw new Exception("Invalid nonce or timestamp.");
        try {
            oav.validateMessage(oam, acc);
        } catch (Exception e) {
            throw new Exception("OAuth validation failed, most likely due to an invalid shared_secret value in your LMS. Check carefully to eliminate leading or trailing blank spaces.");
        }
        // BLTI Launch message was validated successfully at this point
        // debug.append("Basic LTI launch message validated...");
        // Detect whether this is an anonymous LTI launch request per LTIv1p1p2. This is a security patch that
        // prevents a cross-site request forgery threat applicable to versions of LTI released prior to v1.3.
        // The launch procedure is for the TC to issue an anonymous BLTI launch request with no user information.
        // The TP wraps the TC-defined platform_state into an encrypted JSON Web Token (JWT) and redircects the browser
        // to the TC-specified relaunch_url with the original platform_state and the new tool_state parameters, where
        // tool_state is the encrypted JWT. The TC then relaunches to the TP with the user information and the
        // two state parameters, which must be verified by the TP to proceed with the launch. This security patch makes
        // ChemVantage compliant with LTIv1p1p2. If the parameters are not included, the TP may proceed with a
        // normal v1p0 BLTI launch; however this is subject to the following deprecation schedule:
        // LTIv1p0		last certification 12/31/2019 and last market availability 12/31/2020
        // LTIv1p1p2 	last certification 06/30/2021 and last market availability 06/30/2022
        String relaunch_url = request.getParameter("relaunch_url");
        String platform_state = request.getParameter("platform_state");
        String tool_state = request.getParameter("tool_state");
        Algorithm algorithm = Algorithm.HMAC256(Subject.getHMAC256Secret());
        if (tool_state != null && platform_state != null) {
            // This is a LTIv1.1.2 relaunch response. Validate the tool_state value
            try {
                JWT.require(algorithm).withIssuer("https://www.chemvantage.org").withClaim("platform_state", platform_state).build().verify(tool_state);
                if (tc.lti_version == null || !tc.lti_version.equals("LTI-1p1p2")) {
                    tc.lti_version = "LTI-1p1p2";
                    // should have to do this only once
                    ofy().save().entity(tc);
                }
            } catch (Exception e) {
                throw new Exception("Tool state could not be validated.");
            }
        } else if (relaunch_url != null && platform_state != null) {
            // Anonymous LRTIv1p1p2 launch request. Execute relaunch sequence:
            try {
                // 10 minutes from now
                Date expires = new Date(new Date().getTime() + 600000);
                tool_state = JWT.create().withIssuer("https://www.chemvantage.org").withClaim("platform_state", platform_state).withExpiresAt(expires).sign(algorithm);
                response.sendRedirect(relaunch_url + "?platform_state=" + platform_state + "&tool_state=" + tool_state);
                lti_version = "LTI-1p1p2_proposed";
            } catch (Exception e) {
                throw new Exception("Tool state JWT could not be created.");
            }
            // wait for relaunch from platform
            return;
        }
        // End of LTIv1p1p2 section. Continue with normal LTI launch sequence
        // Gather some information about the user
        String userId = request.getParameter("user_id");
        userId = oauth_consumer_key + ":" + (userId == null ? "" : userId);
        // Process user information, provision a new user account if necessary, and store the userId in the user's session
        User user = new User(userId);
        // check if user has Instructor or Administrator role
        String roles = request.getParameter("roles");
        if (roles != null) {
            roles = roles.toLowerCase();
            user.setIsInstructor(roles.contains("instructor"));
            user.setIsAdministrator(roles.contains("administrator"));
            user.setIsTeachingAssistant(roles.contains("teachingassistant"));
        }
        // user information OK;
        // debug.append("userId=" + userId + " and role=" + (user.isInstructor()?"Instructor":"Learner") + "...");
        // Gather information that may be needed to return a score to the LMS:
        String lis_result_sourcedid = request.getParameter("lis_result_sourcedid");
        // debug.append("lis_result_sourcedid=" + lis_result_sourcedid + "...");
        String lisOutcomeServiceUrl = request.getParameter("lis_outcome_service_url");
        // debug.append("lis_outcome_service_url=" + lisOutcomeServiceUrl + "...");
        // Use the resourceLinkId to find the assignment or create a new one:
        Assignment myAssignment = null;
        boolean saveAssignment = false;
        try {
            // load the requested Assignment entity if it exists
            myAssignment = ofy().load().type(Assignment.class).filter("domain", oauth_consumer_key).filter("resourceLinkId", resource_link_id).first().safe();
            if (lisOutcomeServiceUrl != null && !lisOutcomeServiceUrl.equals(myAssignment.lis_outcome_service_url)) {
                myAssignment.lis_outcome_service_url = lisOutcomeServiceUrl;
                saveAssignment = true;
            }
            if (saveAssignment)
                ofy().save().entity(myAssignment);
        } catch (Exception e) {
            // or create a new one with the available information (but no assignmentType or topicIds)
            myAssignment = new Assignment(oauth_consumer_key, resource_link_id, lisOutcomeServiceUrl, true);
            // we'll need the new id value immediately
            ofy().save().entity(myAssignment).now();
        }
        user.setAssignment(myAssignment.id, lis_result_sourcedid);
        if (myAssignment.isValid()) {
            // used for hashing userIds by Task queue
            Queue queue = QueueFactory.getDefaultQueue();
            queue.add(withUrl("/HashUserIds").param("sig", user.getTokenSignature()));
            response.sendRedirect("/" + myAssignment.assignmentType + "?sig=" + user.getTokenSignature());
        } else
            response.getWriter().println(Subject.header("Select A ChemVantage Assignment") + pickResourceForm(user, myAssignment, -1) + Subject.footer);
        return;
    } catch (Exception e) {
        doError(request, response, "LTI Launch failed. " + e.getMessage(), null, e);
    }
}
Also used : SimpleOAuthValidator(net.oauth.SimpleOAuthValidator) OAuthMessage(net.oauth.OAuthMessage) OAuthConsumer(net.oauth.OAuthConsumer) Algorithm(com.auth0.jwt.algorithms.Algorithm) Date(java.util.Date) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) URL(java.net.URL) OAuthAccessor(net.oauth.OAuthAccessor) SimpleOAuthValidator(net.oauth.SimpleOAuthValidator) OAuthValidator(net.oauth.OAuthValidator) Queue(com.google.appengine.api.taskqueue.Queue)

Example 14 with User

use of com.auth0.flickr2.domain.User in project chemvantage by chuckwight.

the class LTIv1p3Launch method ltiv1p3LaunchRequest.

void ltiv1p3LaunchRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    // StringBuffer debug = new StringBuffer();
    // ensures proper OIDC authorization flow completed
    JsonObject state = validateStateToken(request);
    // returns the validated Deployment
    Deployment d = validateIdToken(request);
    // Decode the JWT id_token payload as a JsonObject:
    JsonObject claims = null;
    try {
        DecodedJWT id_token = JWT.decode(request.getParameter("id_token"));
        String json = new String(Base64.getUrlDecoder().decode(id_token.getPayload()));
        claims = JsonParser.parseString(json).getAsJsonObject();
    } catch (Exception e) {
        throw new Exception("id_token was not a valid JWT.");
    }
    // verify that the redirect_uri are consistent with the state token:
    if (!state.get("redirect_uri").getAsString().contains("https://" + request.getServerName() + "/lti/launch"))
        throw new Exception("Invalid redirect_uri.");
    // required
    verifyLtiMessageClaims(claims);
    User user = getUserClaims(claims);
    switch(claims.get("https://purl.imsglobal.org/spec/lti/claim/message_type").getAsString()) {
        case "LtiResourceLinkRequest":
            launchResourceLink(request, response, d, user, claims);
            break;
        case "LtiSubmissionReviewRequest":
            launchSubmissionReview(response, claims, d, user);
            break;
    }
}
Also used : JsonObject(com.google.gson.JsonObject) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) ServletException(javax.servlet.ServletException) IOException(java.io.IOException)

Example 15 with User

use of com.auth0.flickr2.domain.User in project myinfo-connector-java by singpass.

the class MyInfoConnector method getMyInfoPersonData.

/**
 * <p>
 * Get MyInfo Person Data
 * </p>
 * <p>
 * This function takes in all the required variables, invoke the
 * getAccessToken API to generate the access token. The access token is then
 * use to invoke the person API to get the Person data.
 * </p>
 *
 * @param authCode
 *            the authorisation code
 * @param txnNo
 *            the transaction no required in person call
 * @param state
 *            the state required in token call
 * @param publicCert
 *            the public cert
 * @param privateKey
 *            the private key
 * @param clientAppId
 *            the client id
 * @param clientAppPwd
 *            the client password
 * @param redirectUri
 *            the redirect url
 * @param attributes
 *            the attributes
 * @param env
 *            the environment
 * @param tokenUrl
 *            the token url
 * @param personUrl
 *            the person url
 * @param proxyTokenURL
 *            user provided proxy url
 * @param proxyPersonURL
 *            user provided proxy url
 * @param useProxy
 *            indicate the use of proxy url
 * @return the person's data in json format.
 * @see <a href=
 *      "https://www.ndi-api.gov.sg/library/trusted-data/myinfo/implementation-myinfo-data"></a>
 * @since 1.0
 * @throws MyInfoException
 */
protected static String getMyInfoPersonData(String authCode, String txnNo, String state, Certificate publicCert, Key privateKey, String clientAppId, String clientAppPwd, String redirectUri, String attributes, String env, String tokenURL, String personURL, String proxyTokenURL, String proxyPersonURL, String useProxy) throws MyInfoException {
    String result = null;
    String jsonResponse = null;
    RSAPublicKey pubKey = CertUtil.getPublicKey(publicCert);
    // Get access token
    String token = MyInfoConnector.getAccessToken(authCode, tokenURL, clientAppId, clientAppPwd, redirectUri, env, privateKey, state, proxyTokenURL, useProxy);
    HashMap<String, String> tokenList = new Gson().fromJson(token, new TypeToken<HashMap<String, String>>() {
    }.getType());
    DecodedJWT tokenJWT = MyInfoSecurityHelper.verifyToken(tokenList.get(ApplicationConstant.ACCESS_TOKEN), pubKey);
    // Get person
    result = MyInfoConnector.getPersonData(tokenJWT.getSubject(), tokenList.get(ApplicationConstant.ACCESS_TOKEN), txnNo, personURL, clientAppId, attributes, env, privateKey, proxyPersonURL, useProxy);
    if (!env.equalsIgnoreCase(ApplicationConstant.SANDBOX)) {
        try {
            String payload = MyInfoSecurityHelper.getPayload(result, privateKey);
            DecodedJWT personJWT = MyInfoSecurityHelper.verifyToken(payload, pubKey);
            // Convert byte[] to String
            byte[] base64Decode = Base64.getDecoder().decode(personJWT.getPayload());
            jsonResponse = new String(base64Decode);
        } catch (Exception e) {
            throw new MyInfoException();
        }
    } else {
        jsonResponse = result;
    }
    return jsonResponse;
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) TypeToken(com.google.gson.reflect.TypeToken) Gson(com.google.gson.Gson) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) IOException(java.io.IOException)

Aggregations

Algorithm (com.auth0.jwt.algorithms.Algorithm)64 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)60 IOException (java.io.IOException)51 Test (org.junit.Test)46 JWT (com.auth0.jwt.JWT)42 Instant (java.time.Instant)39 java.util (java.util)37 Duration (java.time.Duration)36 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)35 Maps (io.gravitee.common.util.Maps)34 DEFAULT_JWT_ISSUER (io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER)34 User (io.gravitee.repository.management.model.User)33 ConfigurableEnvironment (org.springframework.core.env.ConfigurableEnvironment)32 UserRepository (io.gravitee.repository.management.api.UserRepository)30 io.gravitee.rest.api.model (io.gravitee.rest.api.model)30 JWTVerifier (com.auth0.jwt.JWTVerifier)28 MetadataPage (io.gravitee.common.data.domain.MetadataPage)28 MembershipRepository (io.gravitee.repository.management.api.MembershipRepository)28 Membership (io.gravitee.repository.management.model.Membership)28 UserStatus (io.gravitee.repository.management.model.UserStatus)28