Search in sources :

Example 16 with ConcordApplicationException

use of com.walmartlabs.concord.server.sdk.ConcordApplicationException in project concord by walmartlabs.

the class LdapRealm method queryForAuthenticationInfo.

@Override
@WithTimer
protected AuthenticationInfo queryForAuthenticationInfo(AuthenticationToken token, LdapContextFactory ldapContextFactory) throws NamingException {
    if (this.url == null) {
        return null;
    }
    UsernamePasswordToken t = (UsernamePasswordToken) token;
    LdapPrincipal ldapPrincipal;
    try {
        ldapPrincipal = getPrincipal(t);
    } catch (Exception e) {
        throw new AuthenticationException("LDAP error while attempting to retrieve the user's principal: " + t.getUsername(), e);
    }
    if (ldapPrincipal == null) {
        throw new AuthenticationException("LDAP data not found: " + t.getUsername());
    }
    // TODO merge getOrCreate+update operations into a single one (only for this use case)
    UserEntry u = userManager.getOrCreate(ldapPrincipal.getUsername(), ldapPrincipal.getDomain(), UserType.LDAP).orElseThrow(() -> new ConcordApplicationException("User not found: " + ldapPrincipal.getUsername()));
    if (u.isDisabled()) {
        throw new AuthenticationException("User account '" + u.getName() + "' is disabled");
    }
    UUID userId = u.getId();
    u = userManager.update(userId, ldapPrincipal.getDisplayName(), ldapPrincipal.getEmail(), UserType.LDAP, false, null).orElseThrow(() -> new RuntimeException("User record not found: " + userId));
    ldapGroupManager.cacheLdapGroupsIfNeeded(userId, ldapPrincipal.getGroups());
    UserPrincipal userPrincipal = new UserPrincipal(REALM_NAME, u);
    auditLog.add(AuditObject.SYSTEM, AuditAction.ACCESS).userId(userId).field("username", u.getName()).field("domain", u.getDomain()).field("realm", REALM_NAME).log();
    return new SimpleAccount(Arrays.asList(userPrincipal, t, ldapPrincipal), t, getName());
}
Also used : ConcordApplicationException(com.walmartlabs.concord.server.sdk.ConcordApplicationException) UserEntry(com.walmartlabs.concord.server.user.UserEntry) UUID(java.util.UUID) NamingException(javax.naming.NamingException) ConcordApplicationException(com.walmartlabs.concord.server.sdk.ConcordApplicationException) UserPrincipal(com.walmartlabs.concord.server.security.UserPrincipal) WithTimer(com.walmartlabs.concord.server.sdk.metrics.WithTimer)

Example 17 with ConcordApplicationException

use of com.walmartlabs.concord.server.sdk.ConcordApplicationException in project concord by walmartlabs.

the class UserLdapGroup method sync.

/**
 * Sync Ldap groups for a ldap user
 *
 * @param req user's data
 * @return GenericOperationResult result
 */
@POST
@ApiOperation("Sync ldap groups for a user")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/sync")
@Validate
public GenericOperationResult sync(@ApiParam @Valid SyncUserLdapGroupRequest req) {
    assertAdmin();
    UUID id = userManager.getId(req.getUsername(), req.getUserDomain(), UserType.LDAP).orElse(null);
    if (id == null) {
        throw new ConcordApplicationException("User not found: " + req.getUsername(), Response.Status.BAD_REQUEST);
    }
    UserInfoProvider.UserInfo info = ldapUserInfoProvider.getInfo(id, req.getUsername(), req.getUserDomain());
    if (info == null) {
        throw new ConcordApplicationException("User '" + req.getUsername() + "' with domain '" + req.getUserDomain() + "' not found in LDAP", Response.Status.BAD_REQUEST);
    }
    try {
        Set<String> groups = ldapManager.getGroups(req.getUsername(), req.getUserDomain());
        if (groups == null) {
            ldapGroupsDao.update(id, Collections.emptySet());
        } else {
            ldapGroupsDao.update(id, groups);
        }
    } catch (Exception e) {
        throw new ConcordApplicationException("Failed to update groups for user '" + req.getUsername() + "' error -> '" + e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR);
    }
    return new GenericOperationResult(OperationResult.UPDATED);
}
Also used : GenericOperationResult(com.walmartlabs.concord.server.GenericOperationResult) ConcordApplicationException(com.walmartlabs.concord.server.sdk.ConcordApplicationException) UserInfoProvider(com.walmartlabs.concord.server.user.UserInfoProvider) UUID(java.util.UUID) UnauthorizedException(org.apache.shiro.authz.UnauthorizedException) ConcordApplicationException(com.walmartlabs.concord.server.sdk.ConcordApplicationException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) Validate(org.sonatype.siesta.Validate) ApiOperation(io.swagger.annotations.ApiOperation)

Example 18 with ConcordApplicationException

use of com.walmartlabs.concord.server.sdk.ConcordApplicationException in project concord by walmartlabs.

the class UserResource method createOrUpdate.

/**
 * Creates a new user or updated an existing one.
 *
 * @param req user's data
 * @return
 */
@POST
@ApiOperation("Create a new user or update an existing one")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Validate
public CreateUserResponse createOrUpdate(@ApiParam @Valid CreateUserRequest req) {
    assertAdmin();
    String username = req.getUsername();
    UserType type = assertUserType(req.getType());
    UUID id = userManager.getId(username, req.getUserDomain(), type).orElse(null);
    if (id == null) {
        UserEntry e = userManager.create(username, req.getUserDomain(), req.getDisplayName(), req.getEmail(), req.getType(), req.getRoles());
        return new CreateUserResponse(e.getId(), e.getName(), OperationResult.CREATED);
    } else {
        UserEntry e = userManager.update(id, req.getDisplayName(), req.getEmail(), req.getType(), req.isDisabled(), req.getRoles()).orElse(null);
        if (e == null) {
            throw new ConcordApplicationException("User not found: " + id, Status.BAD_REQUEST);
        }
        return new CreateUserResponse(id, e.getName(), OperationResult.UPDATED);
    }
}
Also used : ConcordApplicationException(com.walmartlabs.concord.server.sdk.ConcordApplicationException) UUID(java.util.UUID) Validate(org.sonatype.siesta.Validate) ApiOperation(io.swagger.annotations.ApiOperation)

Example 19 with ConcordApplicationException

use of com.walmartlabs.concord.server.sdk.ConcordApplicationException in project concord by walmartlabs.

the class CustomFormServiceV2 method continueSession.

private Response continueSession(UriInfo uriInfo, HttpHeaders headers, ProcessKey processKey, String formName, Map<String, Object> data) {
    // TODO locking
    Form form = assertForm(processKey, formName);
    boolean yield = form.options().yield();
    Path dst = cfg.getBaseDir().resolve(processKey.toString()).resolve(formName);
    Path formDir = dst.resolve(FORM_DIR_NAME);
    try {
        Map<String, Object> m = new HashMap<>();
        try {
            m = FormUtils.convert(new ExternalFileFormValidatorLocaleV2(processKey, formName, stateManager), form, data);
            FormSubmitResult r = formService.submit(processKey, formName, m);
            if (r.isValid()) {
                if (yield) {
                    // this was the last "interactive" form. The process will continue in "background"
                    // and users should get a success page.
                    writeData(formDir, success(form, m, processKey.getInstanceId()));
                } else {
                    while (true) {
                        ProcessStatus s = queueDao.getStatus(processKey);
                        if (s == ProcessStatus.SUSPENDED) {
                            String nextFormId = formService.nextFormId(processKey);
                            if (nextFormId == null) {
                                writeData(formDir, success(form, m, processKey.getInstanceId()));
                                break;
                            } else {
                                FormSessionResponse nextSession = startSession(processKey, nextFormId);
                                return redirectTo(nextSession.getUri());
                            }
                        } else if (s == ProcessStatus.FAILED || s == ProcessStatus.CANCELLED || s == ProcessStatus.TIMED_OUT) {
                            writeData(formDir, processFailed(form, m, processKey.getInstanceId()));
                            break;
                        } else if (s == ProcessStatus.FINISHED) {
                            writeData(formDir, success(form, m, processKey.getInstanceId()));
                            break;
                        }
                        try {
                            // TODO exp back off?
                            Thread.sleep(STATUS_REFRESH_DELAY);
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                    }
                }
            } else {
                writeData(formDir, prepareData(form, m, r.getErrors(), processKey.getInstanceId()));
            }
        } catch (FormUtils.ValidationException e) {
            ValidationError err = ValidationError.of(e.getField().name(), e.getMessage());
            FormData d = prepareData(form, m, Collections.singletonList(err), processKey.getInstanceId());
            writeData(formDir, d);
        }
    } catch (Exception e) {
        throw new ConcordApplicationException("Error while submitting a form", e);
    }
    return redirectToForm(uriInfo, headers, processKey, formName);
}
Also used : Path(java.nio.file.Path) FormData(com.walmartlabs.concord.server.console.CustomFormServiceV1.FormData) Form(com.walmartlabs.concord.forms.Form) ProcessStatus(com.walmartlabs.concord.server.sdk.ProcessStatus) FormSubmitResult(com.walmartlabs.concord.server.process.form.FormSubmitResult) FormUtils(com.walmartlabs.concord.forms.FormUtils) IOException(java.io.IOException) ConcordApplicationException(com.walmartlabs.concord.server.sdk.ConcordApplicationException) ConcordApplicationException(com.walmartlabs.concord.server.sdk.ConcordApplicationException) ValidationError(com.walmartlabs.concord.forms.ValidationError) ExternalFileFormValidatorLocaleV2(com.walmartlabs.concord.server.process.form.ExternalFileFormValidatorLocaleV2)

Example 20 with ConcordApplicationException

use of com.walmartlabs.concord.server.sdk.ConcordApplicationException in project concord by walmartlabs.

the class CustomFormServiceV2 method startSession.

private FormSessionResponse startSession(ProcessKey processKey, String formName) {
    // TODO locking
    Form form = assertForm(processKey, formName);
    Path dst = cfg.getBaseDir().resolve(processKey.toString()).resolve(formName);
    try {
        Path formDir = dst.resolve(FORM_DIR_NAME);
        if (!Files.exists(formDir)) {
            Files.createDirectories(formDir);
        }
        String resource = FormServiceV1.FORMS_RESOURCES_PATH + "/" + form.name();
        // copy original branding files into the target directory
        boolean branded = stateManager.exportDirectory(processKey, resource, copyTo(formDir));
        if (!branded) {
            // not branded, redirect to the default wizard
            String uri = String.format(NON_BRANDED_FORM_URL_TEMPLATE, processKey, formName);
            return new FormSessionResponse(uri);
        }
        // create JS file containing the form's data
        writeData(formDir, initialData(form, processKey.getInstanceId()));
        // copy shared resources (if present)
        copySharedResources(processKey, dst);
    } catch (IOException e) {
        log.warn("startSession ['{}', '{}'] -> error while preparing a custom form: {}", processKey, formName, e);
        throw new ConcordApplicationException("Error while preparing a custom form", e);
    }
    return new FormSessionResponse(formPath(processKey, formName));
}
Also used : Path(java.nio.file.Path) Form(com.walmartlabs.concord.forms.Form) ConcordApplicationException(com.walmartlabs.concord.server.sdk.ConcordApplicationException) IOException(java.io.IOException)

Aggregations

ConcordApplicationException (com.walmartlabs.concord.server.sdk.ConcordApplicationException)70 ApiOperation (io.swagger.annotations.ApiOperation)28 UUID (java.util.UUID)22 WithTimer (com.walmartlabs.concord.server.sdk.metrics.WithTimer)21 PartialProcessKey (com.walmartlabs.concord.server.sdk.PartialProcessKey)18 IOException (java.io.IOException)14 ValidationErrorsException (org.sonatype.siesta.ValidationErrorsException)12 GenericOperationResult (com.walmartlabs.concord.server.GenericOperationResult)11 ProcessKey (com.walmartlabs.concord.server.sdk.ProcessKey)11 Validate (org.sonatype.siesta.Validate)11 Path (java.nio.file.Path)10 UserPrincipal (com.walmartlabs.concord.server.security.UserPrincipal)9 OrganizationEntry (com.walmartlabs.concord.server.org.OrganizationEntry)8 EntryPoint (com.walmartlabs.concord.server.process.PayloadManager.EntryPoint)6 ProcessStatus (com.walmartlabs.concord.server.sdk.ProcessStatus)6 UnauthorizedException (org.apache.shiro.authz.UnauthorizedException)6 UserEntry (com.walmartlabs.concord.server.user.UserEntry)5 InputStream (java.io.InputStream)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 Form (com.walmartlabs.concord.forms.Form)3