Search in sources :

Example 6 with ScaleError

use of com.tremolosecurity.scalejs.data.ScaleError in project OpenUnison by TremoloSecurity.

the class ScaleMain method loadApproval.

private void loadApproval(HttpFilterRequest request, HttpFilterResponse response, Gson gson) throws ProvisioningException, IOException, LDAPException {
    int approvalID = Integer.parseInt(request.getRequestURI().substring(request.getRequestURI().lastIndexOf('/') + 1));
    AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
    String uid = userData.getAttribs().get(this.scaleConfig.getUidAttributeName()).getValues().get(0);
    boolean ok = false;
    ApprovalSummaries summaries = ServiceActions.listOpenApprovals(uid, this.scaleConfig.getDisplayNameAttribute(), GlobalEntries.getGlobalEntries().getConfigManager());
    for (ApprovalSummary as : summaries.getApprovals()) {
        if (as.getApproval() == approvalID) {
            ok = true;
        }
    }
    if (!ok) {
        response.setStatus(401);
        response.setContentType("application/json");
        ScaleError error = new ScaleError();
        error.getErrors().add("Unauthorized");
        ScaleJSUtils.addCacheHeaders(response);
        response.getWriter().print(gson.toJson(error).trim());
        response.getWriter().flush();
    } else {
        response.setContentType("application/json");
        ApprovalDetails details = ServiceActions.loadApprovalDetails(uid, approvalID);
        String filter = equal(this.scaleConfig.getUidAttributeName(), details.getUserObj().getUserID()).toString();
        ArrayList<String> attrs = new ArrayList<String>();
        /*for (String attrName : this.scaleConfig.getApprovalAttributes().keySet()) {
				attrs.add(attrName);
			}
			
			if (this.scaleConfig.getRoleAttribute() != null && ! this.scaleConfig.getRoleAttribute().isEmpty()) {
				attrs.add(this.scaleConfig.getRoleAttribute());
			}*/
        LDAPSearchResults res = GlobalEntries.getGlobalEntries().getConfigManager().getMyVD().search(GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getLdapRoot(), 2, filter, attrs);
        if (res.hasMore()) {
            LDAPEntry entry = res.next();
            details.getUserObj().getAttribs().clear();
            for (String attrName : this.scaleConfig.getApprovalAttributes().keySet()) {
                LDAPAttribute attr = entry.getAttribute(attrName);
                if (attr != null) {
                    details.getUserObj().getAttribs().put(scaleConfig.getApprovalAttributes().get(attrName).getDisplayName(), new Attribute(scaleConfig.getApprovalAttributes().get(attrName).getDisplayName(), attr.getStringValue()));
                }
            }
            if (this.scaleConfig.getRoleAttribute() != null && !this.scaleConfig.getRoleAttribute().isEmpty()) {
                LDAPAttribute attr = entry.getAttribute(this.scaleConfig.getRoleAttribute());
                if (attr != null) {
                    details.getUserObj().getGroups().clear();
                    for (String val : attr.getStringValueArray()) {
                        details.getUserObj().getGroups().add(val);
                    }
                }
            } else {
                details.getUserObj().getGroups().clear();
                ArrayList<String> attrNames = new ArrayList<String>();
                attrNames.add("cn");
                LDAPSearchResults res2 = GlobalEntries.getGlobalEntries().getConfigManager().getMyVD().search(GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getLdapRoot(), 2, equal(GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getGroupMemberAttribute(), entry.getDN()).toString(), attrNames);
                while (res2.hasMore()) {
                    LDAPEntry entry2 = res2.next();
                    LDAPAttribute la = entry2.getAttribute("cn");
                    if (la != null) {
                        details.getUserObj().getGroups().add(la.getStringValue());
                    }
                }
            }
        }
        while (res.hasMore()) res.next();
        ScaleJSUtils.addCacheHeaders(response);
        response.getWriter().println(gson.toJson(details).trim());
        response.getWriter().flush();
    }
}
Also used : LDAPAttribute(com.novell.ldap.LDAPAttribute) AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) Attribute(com.tremolosecurity.saml.Attribute) LDAPAttribute(com.novell.ldap.LDAPAttribute) ScaleAttribute(com.tremolosecurity.scalejs.cfg.ScaleAttribute) ArrayList(java.util.ArrayList) ScaleError(com.tremolosecurity.scalejs.data.ScaleError) XSSFRichTextString(org.apache.poi.xssf.usermodel.XSSFRichTextString) RichTextString(org.apache.poi.ss.usermodel.RichTextString) AuthController(com.tremolosecurity.proxy.auth.AuthController) ApprovalDetails(com.tremolosecurity.provisioning.service.util.ApprovalDetails) LDAPEntry(com.novell.ldap.LDAPEntry) LDAPSearchResults(com.novell.ldap.LDAPSearchResults) ApprovalSummaries(com.tremolosecurity.provisioning.service.util.ApprovalSummaries) ApprovalSummary(com.tremolosecurity.provisioning.service.util.ApprovalSummary)

Example 7 with ScaleError

use of com.tremolosecurity.scalejs.data.ScaleError in project OpenUnison by TremoloSecurity.

the class ScaleMain method saveUser.

private void saveUser(HttpFilterRequest request, HttpFilterResponse response, Gson gson) throws IOException {
    ScaleError errors = new ScaleError();
    String json = new String((byte[]) request.getAttribute(ProxySys.MSG_BODY));
    AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
    Set<String> allowedAttrs = null;
    if (this.scaleConfig.getUiDecisions() != null) {
        allowedAttrs = this.scaleConfig.getUiDecisions().availableAttributes(userData, request.getServletRequest());
    }
    JsonElement root = new JsonParser().parse(json);
    JsonObject jo = root.getAsJsonObject();
    HashMap<String, String> values = new HashMap<String, String>();
    boolean ok = true;
    for (Entry<String, JsonElement> entry : jo.entrySet()) {
        String attributeName = entry.getKey();
        if (allowedAttrs == null || allowedAttrs.contains(attributeName)) {
            String value = entry.getValue().getAsJsonObject().get("value").getAsString();
            if (this.scaleConfig.getAttributes().get(attributeName) == null) {
                errors.getErrors().add("Invalid attribute : '" + attributeName + "'");
                ok = false;
            } else if (this.scaleConfig.getAttributes().get(attributeName).isReadOnly()) {
                errors.getErrors().add("Attribute is read only : '" + this.scaleConfig.getAttributes().get(attributeName).getDisplayName() + "'");
                ok = false;
            } else if (this.scaleConfig.getAttributes().get(attributeName).isRequired() && value.length() == 0) {
                errors.getErrors().add("Attribute is required : '" + this.scaleConfig.getAttributes().get(attributeName).getDisplayName() + "'");
                ok = false;
            } else if (this.scaleConfig.getAttributes().get(attributeName).getMinChars() > 0 && this.scaleConfig.getAttributes().get(attributeName).getMinChars() > value.length()) {
                errors.getErrors().add(this.scaleConfig.getAttributes().get(attributeName).getDisplayName() + " must have at least " + this.scaleConfig.getAttributes().get(attributeName).getMinChars() + " characters");
                ok = false;
            } else if (this.scaleConfig.getAttributes().get(attributeName).getMaxChars() > 0 && this.scaleConfig.getAttributes().get(attributeName).getMaxChars() < value.length()) {
                errors.getErrors().add(this.scaleConfig.getAttributes().get(attributeName).getDisplayName() + " must have at most " + this.scaleConfig.getAttributes().get(attributeName).getMaxChars() + " characters");
                ok = false;
            } else if (this.scaleConfig.getAttributes().get(attributeName).getPattern() != null) {
                try {
                    Matcher m = this.scaleConfig.getAttributes().get(attributeName).getPattern().matcher(value);
                    if (m == null || !m.matches()) {
                        ok = false;
                    }
                } catch (Exception e) {
                    ok = false;
                }
                if (!ok) {
                    errors.getErrors().add("Attribute value not valid : '" + this.scaleConfig.getAttributes().get(attributeName).getDisplayName() + "' - " + this.scaleConfig.getAttributes().get(attributeName).getRegExFailedMsg());
                }
            }
            values.put(attributeName, value);
        }
    }
    for (String attrName : this.scaleConfig.getAttributes().keySet()) {
        if (this.scaleConfig.getAttributes().get(attrName).isRequired() && !values.containsKey(attrName) && (allowedAttrs == null || allowedAttrs.contains(attrName))) {
            errors.getErrors().add("Attribute is required : '" + this.scaleConfig.getAttributes().get(attrName).getDisplayName() + "'");
            ok = false;
        }
    }
    if (ok) {
        ConfigManager cfgMgr = GlobalEntries.getGlobalEntries().getConfigManager();
        WFCall wfCall = new WFCall();
        wfCall.setName(this.scaleConfig.getWorkflowName());
        wfCall.setReason("User update");
        wfCall.setUidAttributeName(this.scaleConfig.getUidAttributeName());
        TremoloUser tu = new TremoloUser();
        tu.setUid(userData.getAttribs().get(this.scaleConfig.getUidAttributeName()).getValues().get(0));
        for (String name : values.keySet()) {
            tu.getAttributes().add(new Attribute(name, values.get(name)));
        }
        tu.getAttributes().add(new Attribute(this.scaleConfig.getUidAttributeName(), userData.getAttribs().get(this.scaleConfig.getUidAttributeName()).getValues().get(0)));
        wfCall.setUser(tu);
        try {
            com.tremolosecurity.provisioning.workflow.ExecuteWorkflow exec = new com.tremolosecurity.provisioning.workflow.ExecuteWorkflow();
            exec.execute(wfCall, GlobalEntries.getGlobalEntries().getConfigManager());
            lookupUser(request, response, gson);
        } catch (Exception e) {
            logger.error("Could not update user", e);
            response.setStatus(500);
            ScaleError error = new ScaleError();
            error.getErrors().add("Please contact your system administrator");
            ScaleJSUtils.addCacheHeaders(response);
            response.getWriter().print(gson.toJson(error).trim());
            response.getWriter().flush();
        }
    } else {
        response.setStatus(500);
        ScaleJSUtils.addCacheHeaders(response);
        response.getWriter().print(gson.toJson(errors).trim());
        response.getWriter().flush();
    }
}
Also used : AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) WFCall(com.tremolosecurity.provisioning.service.util.WFCall) HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) Attribute(com.tremolosecurity.saml.Attribute) LDAPAttribute(com.novell.ldap.LDAPAttribute) ScaleAttribute(com.tremolosecurity.scalejs.cfg.ScaleAttribute) JsonObject(com.google.gson.JsonObject) ScaleError(com.tremolosecurity.scalejs.data.ScaleError) XSSFRichTextString(org.apache.poi.xssf.usermodel.XSSFRichTextString) RichTextString(org.apache.poi.ss.usermodel.RichTextString) AuthController(com.tremolosecurity.proxy.auth.AuthController) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) LDAPException(com.novell.ldap.LDAPException) SQLException(java.sql.SQLException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) MalformedURLException(java.net.MalformedURLException) ConfigManager(com.tremolosecurity.config.util.ConfigManager) TremoloUser(com.tremolosecurity.provisioning.service.util.TremoloUser) JsonElement(com.google.gson.JsonElement) JsonParser(com.google.gson.JsonParser)

Example 8 with ScaleError

use of com.tremolosecurity.scalejs.data.ScaleError in project OpenUnison by TremoloSecurity.

the class ScaleMain method exportToExcel.

private void exportToExcel(HttpFilterRequest request, HttpFilterResponse response, Gson gson) throws IOException {
    int lastslash = request.getRequestURI().lastIndexOf('/');
    int secondlastslash = request.getRequestURI().lastIndexOf('/', lastslash - 1);
    String id = request.getRequestURI().substring(secondlastslash + 1, lastslash);
    ReportResults res = (ReportResults) request.getSession().getAttribute(id);
    if (res == null) {
        response.setStatus(404);
        ScaleError error = new ScaleError();
        error.getErrors().add("Report no longer available");
        ScaleJSUtils.addCacheHeaders(response);
        response.getWriter().print(gson.toJson(error).trim());
        response.getWriter().flush();
    } else {
        response.setHeader("Cache-Control", "private, no-store, no-cache, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        Workbook wb = new XSSFWorkbook();
        Font font = wb.createFont();
        font.setBold(true);
        Font titleFont = wb.createFont();
        titleFont.setBold(true);
        titleFont.setFontHeightInPoints((short) 16);
        Sheet sheet = wb.createSheet(WorkbookUtil.createSafeSheetName(res.getName()));
        // Create a header
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(0);
        RichTextString title = new XSSFRichTextString(res.getName());
        title.applyFont(titleFont);
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3));
        cell.setCellValue(title);
        row = sheet.createRow(1);
        cell = row.createCell(0);
        cell.setCellValue(res.getDescription());
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 3));
        row = sheet.createRow(2);
        cell = row.createCell(0);
        // cell.setCellValue(new DateTime().toString("MMMM Do, YYYY h:mm:ss a"));
        sheet.addMergedRegion(new CellRangeAddress(2, 2, 0, 3));
        row = sheet.createRow(3);
        int rowNum = 4;
        if (res.getGrouping().isEmpty()) {
            row = sheet.createRow(rowNum);
            cell = row.createCell(0);
            cell.setCellValue("There is no data for this report");
        } else {
            for (ReportGrouping group : res.getGrouping()) {
                for (String colHeader : res.getHeaderFields()) {
                    row = sheet.createRow(rowNum);
                    cell = row.createCell(0);
                    RichTextString rcolHeader = new XSSFRichTextString(colHeader);
                    rcolHeader.applyFont(font);
                    cell.setCellValue(rcolHeader);
                    cell = row.createCell(1);
                    cell.setCellValue(group.getHeader().get(colHeader));
                    rowNum++;
                }
                row = sheet.createRow(rowNum);
                int cellNum = 0;
                for (String colHeader : res.getDataFields()) {
                    cell = row.createCell(cellNum);
                    RichTextString rcolHeader = new XSSFRichTextString(colHeader);
                    rcolHeader.applyFont(font);
                    cell.setCellValue(rcolHeader);
                    cellNum++;
                }
                rowNum++;
                for (Map<String, String> dataRow : group.getData()) {
                    cellNum = 0;
                    row = sheet.createRow(rowNum);
                    for (String colHeader : res.getDataFields()) {
                        cell = row.createCell(cellNum);
                        cell.setCellValue(dataRow.get(colHeader));
                        cellNum++;
                    }
                    rowNum++;
                }
                row = sheet.createRow(rowNum);
                rowNum++;
            }
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        wb.write(response.getOutputStream());
    }
}
Also used : ScaleError(com.tremolosecurity.scalejs.data.ScaleError) ReportGrouping(com.tremolosecurity.provisioning.service.util.ReportGrouping) XSSFRichTextString(org.apache.poi.xssf.usermodel.XSSFRichTextString) RichTextString(org.apache.poi.ss.usermodel.RichTextString) XSSFRichTextString(org.apache.poi.xssf.usermodel.XSSFRichTextString) RichTextString(org.apache.poi.ss.usermodel.RichTextString) XSSFWorkbook(org.apache.poi.xssf.usermodel.XSSFWorkbook) Workbook(org.apache.poi.ss.usermodel.Workbook) Font(org.apache.poi.ss.usermodel.Font) XSSFRichTextString(org.apache.poi.xssf.usermodel.XSSFRichTextString) ReportResults(com.tremolosecurity.provisioning.service.util.ReportResults) XSSFWorkbook(org.apache.poi.xssf.usermodel.XSSFWorkbook) Row(org.apache.poi.ss.usermodel.Row) CellRangeAddress(org.apache.poi.ss.util.CellRangeAddress) Sheet(org.apache.poi.ss.usermodel.Sheet) Cell(org.apache.poi.ss.usermodel.Cell)

Example 9 with ScaleError

use of com.tremolosecurity.scalejs.data.ScaleError in project OpenUnison by TremoloSecurity.

the class ScaleRegister method doFilter.

@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain) throws Exception {
    Gson gson = new Gson();
    request.getServletRequest().setAttribute("com.tremolosecurity.unison.proxy.noRedirectOnError", "com.tremolosecurity.unison.proxy.noRedirectOnError");
    if (request.getRequestURI().endsWith("/register/config")) {
        response.setContentType("application/json");
        ScaleJSUtils.addCacheHeaders(response);
        ScaleJSRegisterConfig localCfg = gson.fromJson(gson.toJson(this.scaleConfig), ScaleJSRegisterConfig.class);
        for (String attrName : scaleConfig.getAttributes().keySet()) {
            ScaleAttribute fromMainCfg = scaleConfig.getAttributes().get(attrName);
            if (fromMainCfg.getDynamicSource() != null) {
                ScaleAttribute fromLocalCfg = localCfg.getAttributes().get(attrName);
                fromLocalCfg.setValues(fromMainCfg.getDynamicSource().getSourceList(request));
            }
        }
        response.getWriter().println(gson.toJson(localCfg).trim());
    } else if (request.getRequestURI().endsWith("/register/values")) {
        String attributeName = request.getParameter("name").getValues().get(0);
        List<NVP> values = this.scaleConfig.getAttributes().get(attributeName).getDynamicSource().getSourceList(request);
        response.setContentType("application/json");
        ScaleJSUtils.addCacheHeaders(response);
        response.getWriter().println(gson.toJson(values).trim());
    } else if (request.getRequestURI().endsWith("/register/submit")) {
        ScaleError errors = new ScaleError();
        String json = new String((byte[]) request.getAttribute(ProxySys.MSG_BODY));
        NewUserRequest newUser = gson.fromJson(json, NewUserRequest.class);
        if (scaleConfig.isRequireReCaptcha()) {
            if (newUser.getReCaptchaCode() == null || newUser.getReCaptchaCode().isEmpty()) {
                errors.getErrors().add("Please verify you are not a robot");
            } else {
                BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(GlobalEntries.getGlobalEntries().getConfigManager().getHttpClientSocketRegistry());
                RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
                CloseableHttpClient http = HttpClients.custom().setConnectionManager(bhcm).setDefaultRequestConfig(rc).build();
                HttpPost httppost = new HttpPost("https://www.google.com/recaptcha/api/siteverify");
                List<NameValuePair> formparams = new ArrayList<NameValuePair>();
                formparams.add(new BasicNameValuePair("secret", scaleConfig.getRcSecretKey()));
                formparams.add(new BasicNameValuePair("response", newUser.getReCaptchaCode()));
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
                httppost.setEntity(entity);
                CloseableHttpResponse resp = http.execute(httppost);
                ReCaptchaResponse res = gson.fromJson(EntityUtils.toString(resp.getEntity()), ReCaptchaResponse.class);
                if (!res.isSuccess()) {
                    errors.getErrors().add("Human validation failed");
                }
                http.close();
                bhcm.close();
            }
        }
        if (scaleConfig.isRequireTermsAndConditions() && !newUser.isCheckedTermsAndConditions()) {
            errors.getErrors().add("You must accept the terms and conditions to register");
        }
        if (this.scaleConfig.isRequireReason() && (newUser.getReason() == null || newUser.getReason().isEmpty())) {
            errors.getErrors().add("Reason is required");
        }
        if (this.scaleConfig.isPreSetPassword()) {
            if (newUser.getPassword() == null || newUser.getPassword().isEmpty()) {
                errors.getErrors().add("Password is required");
            } else if (!newUser.getPassword().equals(newUser.getPassword2())) {
                errors.getErrors().add("Passwords must match");
            }
        }
        for (String attributeName : this.scaleConfig.getAttributes().keySet()) {
            String value = newUser.getAttributes().get(attributeName);
            if (this.scaleConfig.getAttributes().get(attributeName) == null) {
                errors.getErrors().add("Invalid attribute : '" + attributeName + "'");
            }
            if (this.scaleConfig.getAttributes().get(attributeName).isReadOnly()) {
                errors.getErrors().add("Attribute is read only : '" + this.scaleConfig.getAttributes().get(attributeName).getDisplayName() + "'");
            }
            if (this.scaleConfig.getAttributes().get(attributeName).isRequired() && (value == null || value.length() == 0)) {
                errors.getErrors().add("Attribute is required : '" + this.scaleConfig.getAttributes().get(attributeName).getDisplayName() + "'");
            }
            if (this.scaleConfig.getAttributes().get(attributeName).getMinChars() > 0 && this.scaleConfig.getAttributes().get(attributeName).getMinChars() > value.length()) {
                errors.getErrors().add(this.scaleConfig.getAttributes().get(attributeName).getDisplayName() + " must have at least " + this.scaleConfig.getAttributes().get(attributeName).getMinChars() + " characters");
            }
            if (this.scaleConfig.getAttributes().get(attributeName).getMaxChars() > 0 && this.scaleConfig.getAttributes().get(attributeName).getMaxChars() < value.length()) {
                errors.getErrors().add(this.scaleConfig.getAttributes().get(attributeName).getDisplayName() + " must have at most " + this.scaleConfig.getAttributes().get(attributeName).getMaxChars() + " characters");
            }
            if (this.scaleConfig.getAttributes().get(attributeName).getType().equalsIgnoreCase("list")) {
                if (this.scaleConfig.getAttributes().get(attributeName).getDynamicSource() == null) {
                    boolean found = false;
                    for (NVP nvp : this.scaleConfig.getAttributes().get(attributeName).getValues()) {
                        if (nvp.getValue().equalsIgnoreCase(value)) {
                            found = true;
                        }
                    }
                    if (!found) {
                        errors.getErrors().add(this.scaleConfig.getAttributes().get(attributeName).getDisplayName() + " has an invalid value");
                    }
                }
            }
            if (this.scaleConfig.getAttributes().get(attributeName).getPattern() != null) {
                boolean ok = true;
                try {
                    Matcher m = this.scaleConfig.getAttributes().get(attributeName).getPattern().matcher(value);
                    if (m == null || !m.matches()) {
                        ok = false;
                    }
                } catch (Exception e) {
                    ok = false;
                }
                if (!ok) {
                    errors.getErrors().add("Attribute value not valid : '" + this.scaleConfig.getAttributes().get(attributeName).getDisplayName() + "' - " + this.scaleConfig.getAttributes().get(attributeName).getRegExFailedMsg());
                }
            }
            if (this.scaleConfig.getAttributes().get(attributeName).isUnique()) {
                String filter = equal(attributeName, value).toString();
                LDAPSearchResults res = GlobalEntries.getGlobalEntries().getConfigManager().getMyVD().search(GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getLdapRoot(), 2, filter, new ArrayList<String>());
                if (res.hasMore()) {
                    errors.getErrors().add(this.scaleConfig.getAttributes().get(attributeName).getDisplayName() + " is not available");
                }
                while (res.hasMore()) res.next();
            }
            if (this.scaleConfig.getAttributes().get(attributeName).getDynamicSource() != null) {
                String error = this.scaleConfig.getAttributes().get(attributeName).getDynamicSource().validate(value, request);
                if (error != null) {
                    errors.getErrors().add(this.scaleConfig.getAttributes().get(attributeName).getDisplayName() + " - " + error);
                }
            }
        }
        WFCall wfcall = null;
        String wfName = this.scaleConfig.getWorkflowName();
        if (errors.getErrors().isEmpty()) {
            if (scaleConfig.isUseCustomSubmission()) {
                AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
                wfName = cru.createTremoloUser(newUser, errors.getErrors(), userData);
            }
        }
        if (errors.getErrors().isEmpty()) {
            TremoloUser user = new TremoloUser();
            AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
            if (this.scaleConfig.isSubmitLoggedInUser()) {
                user.setUid(userData.getAttribs().get(this.scaleConfig.getUidAttributeName()).getValues().get(0));
                user.getAttributes().add(new Attribute(this.scaleConfig.getUidAttributeName(), userData.getAttribs().get(this.scaleConfig.getUidAttributeName()).getValues().get(0)));
            } else {
                user.setUid(newUser.getAttributes().get(this.scaleConfig.getUidAttributeName()));
            }
            for (String attrName : newUser.getAttributes().keySet()) {
                user.getAttributes().add(new Attribute(attrName, newUser.getAttributes().get(attrName)));
            }
            if (this.scaleConfig.isPreSetPassword()) {
                user.setUserPassword(newUser.getPassword());
            }
            wfcall = new WFCall();
            wfcall.setUidAttributeName(this.scaleConfig.getUidAttributeName());
            wfcall.setReason(newUser.getReason());
            wfcall.setName(wfName);
            wfcall.setUser(user);
            HashMap<String, Object> params = new HashMap<String, Object>();
            wfcall.setRequestParams(params);
            if (userData.getAuthLevel() != 0 && !this.scaleConfig.isSubmitLoggedInUser()) {
                wfcall.setRequestor(userData.getAttribs().get(GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getProvisioning().getApprovalDB().getUserIdAttribute()).getValues().get(0));
                wfcall.getRequestParams().put(Approval.SEND_NOTIFICATION, "false");
                wfcall.getRequestParams().put(Approval.REASON, newUser.getReason());
                wfcall.getRequestParams().put(Approval.IMMEDIATE_ACTION, "true");
            }
            if (scaleConfig.isUseCustomSubmission()) {
                cru.setWorkflowParameters(params, newUser, userData);
            }
            ExecuteWorkflow exec = new ExecuteWorkflow();
            try {
                exec.execute(wfcall, GlobalEntries.getGlobalEntries().getConfigManager());
            } catch (Exception e) {
                throw new ProvisioningException("Could not complete registration", e);
            }
            SubmitResponse res = new SubmitResponse();
            res.setAddNewUsers(userData.getAuthLevel() != 0);
            ScaleJSUtils.addCacheHeaders(response);
            response.getWriter().print(gson.toJson(res));
            response.getWriter().flush();
        } else {
            response.setStatus(500);
            ScaleJSUtils.addCacheHeaders(response);
            response.getWriter().print(gson.toJson(errors).trim());
            response.getWriter().flush();
        }
    } else {
        response.setStatus(500);
        ScaleJSUtils.addCacheHeaders(response);
        ScaleError error = new ScaleError();
        error.getErrors().add("Operation not supported");
        response.getWriter().print(gson.toJson(error).trim());
        response.getWriter().flush();
    }
}
Also used : ScaleAttribute(com.tremolosecurity.scalejs.cfg.ScaleAttribute) HttpPost(org.apache.http.client.methods.HttpPost) Matcher(java.util.regex.Matcher) Attribute(com.tremolosecurity.saml.Attribute) ScaleAttribute(com.tremolosecurity.scalejs.cfg.ScaleAttribute) HashMap(java.util.HashMap) ScaleJSRegisterConfig(com.tremolosecurity.scalejs.register.cfg.ScaleJSRegisterConfig) SubmitResponse(com.tremolosecurity.scalejs.register.data.SubmitResponse) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) NVP(com.tremolosecurity.util.NVP) ReCaptchaResponse(com.tremolosecurity.scalejs.register.data.ReCaptchaResponse) TremoloUser(com.tremolosecurity.provisioning.service.util.TremoloUser) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ArrayList(java.util.ArrayList) SourceList(com.tremolosecurity.scalejs.sdk.SourceList) List(java.util.List) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) WFCall(com.tremolosecurity.provisioning.service.util.WFCall) AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) ScaleError(com.tremolosecurity.scalejs.data.ScaleError) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) AuthController(com.tremolosecurity.proxy.auth.AuthController) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) LDAPSearchResults(com.novell.ldap.LDAPSearchResults) ExecuteWorkflow(com.tremolosecurity.provisioning.workflow.ExecuteWorkflow) NewUserRequest(com.tremolosecurity.scalejs.register.data.NewUserRequest)

Example 10 with ScaleError

use of com.tremolosecurity.scalejs.data.ScaleError in project OpenUnison by TremoloSecurity.

the class ScaleSingleRequest method doFilter.

@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain) throws Exception {
    Gson gson = new Gson();
    request.getServletRequest().setAttribute("com.tremolosecurity.unison.proxy.noRedirectOnError", "com.tremolosecurity.unison.proxy.noRedirectOnError");
    if (request.getRequestURI().endsWith("/singlerequest/config")) {
        response.setContentType("application/json");
        ScaleSingleRequestUser ssru = new ScaleSingleRequestUser();
        ssru.setConfig(scaleConfig);
        AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
        Attribute displayNameAttribute = userData.getAttribs().get(this.scaleConfig.getDisplayNameAttribute());
        if (displayNameAttribute != null) {
            ssru.setDisplayName(displayNameAttribute.getValues().get(0));
        } else {
            ssru.setDisplayName("Unknown");
        }
        ScaleJSUtils.addCacheHeaders(response);
        response.getWriter().println(gson.toJson(ssru).trim());
    } else if (request.getMethod().equalsIgnoreCase("POST") && request.getRequestURI().endsWith("/singlerequest/submit")) {
        AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
        String json = new String((byte[]) request.getAttribute(ProxySys.MSG_BODY));
        SingleRequest sr = gson.fromJson(json, SingleRequest.class);
        ScaleError errors = new ScaleError();
        if (sr.getReason() == null || sr.getReason().isEmpty()) {
            errors.getErrors().add("Reason is required");
        } else {
            ConfigManager cfgMgr = GlobalEntries.getGlobalEntries().getConfigManager();
            WFCall wfCall = new WFCall();
            wfCall.setName(this.scaleConfig.getWorkflowName());
            wfCall.setReason(sr.getReason());
            wfCall.setUidAttributeName(this.scaleConfig.getUidAttribute());
            TremoloUser tu = new TremoloUser();
            tu.setUid(userData.getAttribs().get(this.scaleConfig.getUidAttribute()).getValues().get(0));
            tu.getAttributes().add(new Attribute(this.scaleConfig.getUidAttribute(), userData.getAttribs().get(this.scaleConfig.getUidAttribute()).getValues().get(0)));
            if (this.scaleConfig.isUseAttributesFromAuthentication()) {
                for (String key : userData.getAttribs().keySet()) {
                    Attribute fromUser = userData.getAttribs().get(key);
                    if (!key.equalsIgnoreCase(this.scaleConfig.getUidAttribute())) {
                        Attribute forwf = new Attribute(key);
                        forwf.getValues().addAll(fromUser.getValues());
                        tu.getAttributes().add(forwf);
                    }
                }
            }
            wfCall.setUser(tu);
            try {
                com.tremolosecurity.provisioning.workflow.ExecuteWorkflow exec = new com.tremolosecurity.provisioning.workflow.ExecuteWorkflow();
                exec.execute(wfCall, GlobalEntries.getGlobalEntries().getConfigManager());
            } catch (Exception e) {
                logger.error("Could not update user", e);
                errors.getErrors().add("Please contact your system administrator");
            }
        }
        if (errors.getErrors().size() > 0) {
            response.setStatus(500);
            response.getWriter().print(gson.toJson(errors).trim());
            response.getWriter().flush();
        }
    }
}
Also used : SingleRequest(com.tremolosecurity.scalejs.singlerequest.data.SingleRequest) AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) WFCall(com.tremolosecurity.provisioning.service.util.WFCall) Attribute(com.tremolosecurity.saml.Attribute) Gson(com.google.gson.Gson) ScaleSingleRequestUser(com.tremolosecurity.scalejs.singlerequest.data.ScaleSingleRequestUser) ScaleError(com.tremolosecurity.scalejs.data.ScaleError) AuthController(com.tremolosecurity.proxy.auth.AuthController) ConfigManager(com.tremolosecurity.config.util.ConfigManager) TremoloUser(com.tremolosecurity.provisioning.service.util.TremoloUser)

Aggregations

ScaleError (com.tremolosecurity.scalejs.data.ScaleError)11 AuthInfo (com.tremolosecurity.proxy.auth.AuthInfo)10 AuthController (com.tremolosecurity.proxy.auth.AuthController)9 Attribute (com.tremolosecurity.saml.Attribute)7 RichTextString (org.apache.poi.ss.usermodel.RichTextString)7 XSSFRichTextString (org.apache.poi.xssf.usermodel.XSSFRichTextString)7 ConfigManager (com.tremolosecurity.config.util.ConfigManager)6 Gson (com.google.gson.Gson)5 TremoloUser (com.tremolosecurity.provisioning.service.util.TremoloUser)5 WFCall (com.tremolosecurity.provisioning.service.util.WFCall)5 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)5 LDAPAttribute (com.novell.ldap.LDAPAttribute)4 OrgType (com.tremolosecurity.config.xml.OrgType)4 AzSys (com.tremolosecurity.proxy.auth.AzSys)4 ScaleAttribute (com.tremolosecurity.scalejs.cfg.ScaleAttribute)4 IOException (java.io.IOException)4 HashSet (java.util.HashSet)4 LDAPException (com.novell.ldap.LDAPException)3 LDAPSearchResults (com.novell.ldap.LDAPSearchResults)3