Search in sources :

Example 11 with InternalServerError

use of io.kamax.mxisd.exception.InternalServerError in project mxisd by kamax-io.

the class ExecAuthStore method authenticate.

@Override
public ExecAuthResult authenticate(_MatrixID uId, String password) {
    Objects.requireNonNull(uId);
    Objects.requireNonNull(password);
    log.info("Performing authentication for {}", uId.getId());
    ExecAuthResult result = new ExecAuthResult();
    result.setId(new UserID(UserIdType.Localpart, uId.getLocalPart()));
    Processor<ExecAuthResult> p = new Processor<>(cfg);
    p.addTokenMapper(cfg.getToken().getLocalpart(), uId::getLocalPart);
    p.addTokenMapper(cfg.getToken().getDomain(), uId::getDomain);
    p.addTokenMapper(cfg.getToken().getMxid(), uId::getId);
    p.addTokenMapper(cfg.getToken().getPassword(), () -> password);
    p.addJsonInputTemplate(tokens -> {
        RestAuthRequestJson json = new RestAuthRequestJson();
        json.setLocalpart(tokens.getLocalpart());
        json.setDomain(tokens.getDomain());
        json.setMxid(tokens.getMxid());
        json.setPassword(tokens.getPassword());
        return json;
    });
    p.addInputTemplate(PlainType, tokens -> tokens.getLocalpart() + System.lineSeparator() + tokens.getDomain() + System.lineSeparator() + tokens.getMxid() + System.lineSeparator() + tokens.getPassword() + System.lineSeparator());
    p.withExitHandler(pr -> result.setExitStatus(pr.getExitValue()));
    p.withSuccessHandler(pr -> result.setSuccess(true));
    p.withSuccessDefault(o -> result);
    p.addSuccessMapper(JsonType, output -> {
        JsonObject data = GsonUtil.getObj(GsonUtil.parseObj(output), "auth");
        GsonUtil.findPrimitive(data, "success").map(JsonPrimitive::getAsBoolean).ifPresent(result::setSuccess);
        GsonUtil.findObj(data, "profile").flatMap(profile -> GsonUtil.findString(profile, "display_name")).ifPresent(v -> result.getProfile().setDisplayName(v));
        return result;
    });
    p.addSuccessMapper(PlainType, output -> {
        String[] lines = output.split("\\R");
        if (lines.length > 2) {
            throw new InternalServerError("Exec auth command returned more than 2 lines (" + lines.length + ")");
        }
        result.setSuccess(Optional.ofNullable(StringUtils.isEmpty(lines[0]) ? null : lines[0]).map(v -> StringUtils.equalsAnyIgnoreCase(v, "true", "1")).orElse(result.isSuccess()));
        if (lines.length == 2) {
            Optional.ofNullable(StringUtils.isEmpty(lines[1]) ? null : lines[1]).ifPresent(v -> result.getProfile().setDisplayName(v));
        }
        return result;
    });
    p.withFailureHandler(pr -> result.setSuccess(false));
    p.withFailureDefault(o -> result);
    return p.execute();
}
Also used : JsonObject(com.google.gson.JsonObject) GsonUtil(io.kamax.matrix.json.GsonUtil) Logger(org.slf4j.Logger) AuthenticatorProvider(io.kamax.mxisd.auth.provider.AuthenticatorProvider) RestAuthRequestJson(io.kamax.mxisd.backend.rest.RestAuthRequestJson) LoggerFactory(org.slf4j.LoggerFactory) io.kamax.matrix._MatrixID(io.kamax.matrix._MatrixID) StringUtils(org.apache.commons.lang3.StringUtils) Objects(java.util.Objects) InternalServerError(io.kamax.mxisd.exception.InternalServerError) ExecConfig(io.kamax.mxisd.config.ExecConfig) UserID(io.kamax.mxisd.UserID) Optional(java.util.Optional) UserIdType(io.kamax.mxisd.UserIdType) JsonPrimitive(com.google.gson.JsonPrimitive) RestAuthRequestJson(io.kamax.mxisd.backend.rest.RestAuthRequestJson) UserID(io.kamax.mxisd.UserID) JsonObject(com.google.gson.JsonObject) InternalServerError(io.kamax.mxisd.exception.InternalServerError)

Example 12 with InternalServerError

use of io.kamax.mxisd.exception.InternalServerError in project mxisd by kamax-io.

the class PhoneSmsTwilioConnector method send.

@Override
public void send(String recipient, String content) {
    if (StringUtils.isBlank(cfg.getAccountSid()) || StringUtils.isBlank(cfg.getAuthToken()) || StringUtils.isBlank(cfg.getNumber())) {
        log.error("Twilio connector in not fully configured and is missing mandatory configuration values.");
        throw new NotImplementedException("Phone numbers cannot be validated at this time. Contact your administrator.");
    }
    recipient = "+" + recipient;
    log.info("Sending SMS notification from {} to {} with {} characters", cfg.getNumber(), recipient, content.length());
    try {
        Message.creator(new PhoneNumber("+" + recipient), new PhoneNumber(cfg.getNumber()), content).create();
    } catch (ApiException e) {
        throw new InternalServerError(e);
    }
}
Also used : NotImplementedException(io.kamax.mxisd.exception.NotImplementedException) PhoneNumber(com.twilio.type.PhoneNumber) InternalServerError(io.kamax.mxisd.exception.InternalServerError) ApiException(com.twilio.exception.ApiException)

Example 13 with InternalServerError

use of io.kamax.mxisd.exception.InternalServerError in project mxisd by kamax-io.

the class EmailSmtpConnector method send.

@Override
public void send(String senderAddress, String senderName, String recipient, String content) {
    if (StringUtils.isBlank(senderAddress)) {
        throw new FeatureNotAvailable("3PID Email identity: sender address is empty - " + "You must set a value for notifications to work");
    }
    if (StringUtils.isBlank(content)) {
        throw new InternalServerError("Notification content is empty");
    }
    try {
        InternetAddress sender = new InternetAddress(senderAddress, senderName);
        MimeMessage msg = new MimeMessage(session, IOUtils.toInputStream(content, StandardCharsets.UTF_8));
        // We must encode our headers ourselves as we have no guarantee that they were in the provided data.
        // This is required to support UTF-8 characters from user display names or room names in the subject header per example
        Enumeration<Header> headers = msg.getAllHeaders();
        while (headers.hasMoreElements()) {
            Header header = headers.nextElement();
            msg.setHeader(header.getName(), MimeUtility.encodeText(header.getValue()));
        }
        msg.setHeader("X-Mailer", MimeUtility.encodeText(Mxisd.Agent));
        msg.setSentDate(new Date());
        msg.setFrom(sender);
        msg.setRecipients(Message.RecipientType.TO, recipient);
        msg.saveChanges();
        log.info("Sending invite to {} via SMTP using {}:{}", recipient, cfg.getHost(), cfg.getPort());
        SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");
        if (cfg.getTls() < 3) {
            transport.setStartTLS(cfg.getTls() > 0);
            transport.setRequireStartTLS(cfg.getTls() > 1);
        }
        log.info("Connecting to {}:{}", cfg.getHost(), cfg.getPort());
        if (StringUtils.isAllEmpty(cfg.getLogin(), cfg.getPassword())) {
            log.info("Not using SMTP authentication");
            transport.connect();
        } else {
            log.info("Using SMTP authentication");
            transport.connect(cfg.getLogin(), cfg.getPassword());
        }
        try {
            transport.sendMessage(msg, InternetAddress.parse(recipient));
            log.info("Invite to {} was sent", recipient);
        } finally {
            transport.close();
        }
    } catch (UnsupportedEncodingException | MessagingException e) {
        throw new RuntimeException("Unable to send e-mail invite to " + recipient, e);
    }
}
Also used : FeatureNotAvailable(io.kamax.mxisd.exception.FeatureNotAvailable) InternetAddress(javax.mail.internet.InternetAddress) Header(javax.mail.Header) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InternalServerError(io.kamax.mxisd.exception.InternalServerError) Date(java.util.Date) SMTPTransport(com.sun.mail.smtp.SMTPTransport)

Example 14 with InternalServerError

use of io.kamax.mxisd.exception.InternalServerError in project mxisd by kamax-io.

the class ProfileManager method enhance.

public Response enhance(_MatrixID userId, HttpRequestBase request) {
    try {
        request.setURI(dns.transform(request.getURI()).build());
        Response res = new Response();
        try (CloseableHttpResponse hsResponse = client.execute(request)) {
            res.setStatus(hsResponse.getStatusLine().getStatusCode());
            JsonElement el = GsonUtil.parse(EntityUtils.toString(hsResponse.getEntity()));
            if (el.isJsonObject()) {
                JsonObject obj = el.getAsJsonObject();
                List<_ThreePid> list = getThreepids(userId);
                obj.add("threepids", GsonUtil.get().toJsonTree(list));
            }
            res.setBody(GsonUtil.get().toJson(el));
            return res;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } catch (URISyntaxException e) {
        log.error("Unable to build target URL for profile proxy enhancement", e);
        throw new InternalServerError(e);
    }
}
Also used : Response(io.kamax.mxisd.proxy.Response) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) JsonElement(com.google.gson.JsonElement) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) JsonObject(com.google.gson.JsonObject) io.kamax.matrix._ThreePid(io.kamax.matrix._ThreePid) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) InternalServerError(io.kamax.mxisd.exception.InternalServerError)

Example 15 with InternalServerError

use of io.kamax.mxisd.exception.InternalServerError in project mxisd by kamax-io.

the class MappingController method bulkLookup.

@RequestMapping(value = "/bulk_lookup", method = POST)
String bulkLookup(HttpServletRequest request) {
    BulkLookupRequest lookupRequest = new BulkLookupRequest();
    setRequesterInfo(lookupRequest, request);
    log.info("Got bulk lookup request from {} with client {} - Is recursive? {}", lookupRequest.getRequester(), lookupRequest.getUserAgent(), lookupRequest.isRecursive());
    try {
        ClientBulkLookupRequest input = parser.parse(request, ClientBulkLookupRequest.class);
        List<ThreePidMapping> mappings = new ArrayList<>();
        for (List<String> mappingRaw : input.getThreepids()) {
            ThreePidMapping mapping = new ThreePidMapping();
            mapping.setMedium(mappingRaw.get(0));
            mapping.setValue(mappingRaw.get(1));
            mappings.add(mapping);
        }
        lookupRequest.setMappings(mappings);
        ClientBulkLookupAnswer answer = new ClientBulkLookupAnswer();
        answer.addAll(strategy.find(lookupRequest));
        return gson.toJson(answer);
    } catch (IOException e) {
        throw new InternalServerError(e);
    }
}
Also used : ArrayList(java.util.ArrayList) IOException(java.io.IOException) InternalServerError(io.kamax.mxisd.exception.InternalServerError) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

InternalServerError (io.kamax.mxisd.exception.InternalServerError)24 IOException (java.io.IOException)13 LdapException (org.apache.directory.api.ldap.model.exception.LdapException)6 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)6 io.kamax.matrix._MatrixID (io.kamax.matrix._MatrixID)5 CursorException (org.apache.directory.api.ldap.model.cursor.CursorException)5 CursorLdapReferralException (org.apache.directory.api.ldap.model.cursor.CursorLdapReferralException)5 EntryCursor (org.apache.directory.api.ldap.model.cursor.EntryCursor)5 Entry (org.apache.directory.api.ldap.model.entry.Entry)5 JsonObject (com.google.gson.JsonObject)4 ThreePid (io.kamax.matrix.ThreePid)4 UserDirectorySearchResult (io.kamax.mxisd.http.io.UserDirectorySearchResult)4 Connection (java.sql.Connection)4 PreparedStatement (java.sql.PreparedStatement)4 ResultSet (java.sql.ResultSet)4 SQLException (java.sql.SQLException)4 ArrayList (java.util.ArrayList)4 LdapConnection (org.apache.directory.ldap.client.api.LdapConnection)4 MatrixID (io.kamax.matrix.MatrixID)3 GsonUtil (io.kamax.matrix.json.GsonUtil)3