Search in sources :

Example 1 with MatrixID

use of io.kamax.matrix.MatrixID in project mxisd by kamax-io.

the class GenericSqlDirectoryProvider method search.

public UserDirectorySearchResult search(String searchTerm, GenericSqlProviderConfig.Query query) {
    try (Connection conn = pool.get()) {
        log.info("Will execute query: {}", query.getValue());
        try (PreparedStatement stmt = conn.prepareStatement(query.getValue())) {
            setParameters(stmt, searchTerm);
            try (ResultSet rSet = stmt.executeQuery()) {
                UserDirectorySearchResult result = new UserDirectorySearchResult();
                result.setLimited(false);
                while (rSet.next()) {
                    processRow(rSet).ifPresent(e -> {
                        if (StringUtils.equalsIgnoreCase("localpart", query.getType())) {
                            e.setUserId(new MatrixID(e.getUserId(), mxCfg.getDomain()).getId());
                        }
                        result.addResult(e);
                    });
                }
                return result;
            }
        }
    } catch (SQLException e) {
        throw new InternalServerError(e);
    }
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) MatrixID(io.kamax.matrix.MatrixID) UserDirectorySearchResult(io.kamax.mxisd.controller.directory.v1.io.UserDirectorySearchResult) InternalServerError(io.kamax.mxisd.exception.InternalServerError)

Example 2 with MatrixID

use of io.kamax.matrix.MatrixID in project mxisd by kamax-io.

the class SessionMananger method bind.

public void bind(String sid, String secret, String mxidRaw) {
    _MatrixID mxid = new MatrixID(mxidRaw);
    ThreePidSession session = getSessionIfValidated(sid, secret);
    if (!session.isRemote()) {
        log.info("Session {} for {}: MXID {} was bound locally", sid, session.getThreePid(), mxid);
        return;
    }
    log.info("Session {} for {}: MXID {} bind is remote", sid, session.getThreePid(), mxid);
    if (!session.isRemoteValidated()) {
        log.error("Session {} for {}: Not validated remotely", sid, session.getThreePid());
        throw new SessionNotValidatedException();
    }
    log.info("Session {} for {}: Performing remote bind", sid, session.getThreePid());
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(Arrays.asList(new BasicNameValuePair("sid", session.getRemoteId()), new BasicNameValuePair("client_secret", session.getRemoteSecret()), new BasicNameValuePair("mxid", mxid.getId())), StandardCharsets.UTF_8);
    HttpPost bindReq = new HttpPost(session.getRemoteServer() + "/_matrix/identity/api/v1/3pid/bind");
    bindReq.setEntity(entity);
    try (CloseableHttpResponse response = client.execute(bindReq)) {
        int status = response.getStatusLine().getStatusCode();
        if (status < 200 || status >= 300) {
            String body = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
            log.error("Session {} for {}: Remote IS {} failed when trying to bind {} for remote session {}\n{}", sid, session.getThreePid(), session.getRemoteServer(), mxid, session.getRemoteId(), body);
            throw new RemoteIdentityServerException(body);
        }
        log.error("Session {} for {}: MXID {} was bound remotely", sid, session.getThreePid(), mxid);
    } catch (IOException e) {
        log.error("Session {} for {}: I/O Error when trying to bind mxid {}", sid, session.getThreePid(), mxid);
        throw new RemoteIdentityServerException(e.getMessage());
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) ThreePidSession(io.kamax.mxisd.threepid.session.ThreePidSession) IThreePidSession(io.kamax.mxisd.threepid.session.IThreePidSession) io.kamax.matrix._MatrixID(io.kamax.matrix._MatrixID) MatrixID(io.kamax.matrix.MatrixID) io.kamax.matrix._MatrixID(io.kamax.matrix._MatrixID)

Example 3 with MatrixID

use of io.kamax.matrix.MatrixID in project mxisd by kamax-io.

the class InvitationManager method postConstruct.

@PostConstruct
private void postConstruct() {
    gson = new Gson();
    log.info("Loading saved invites");
    Collection<ThreePidInviteIO> ioList = storage.getInvites();
    ioList.forEach(io -> {
        log.info("Processing invite {}", gson.toJson(io));
        ThreePidInvite invite = new ThreePidInvite(new MatrixID(io.getSender()), io.getMedium(), io.getAddress(), io.getRoomId(), io.getProperties());
        ThreePidInviteReply reply = new ThreePidInviteReply(getId(invite), invite, io.getToken(), "");
        invitations.put(reply.getId(), reply);
    });
    // FIXME export such madness into matrix-java-sdk with a nice wrapper to talk to a homeserver
    try {
        SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial(new TrustSelfSignedStrategy()).build();
        HostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
        client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();
    } catch (Exception e) {
        // FIXME do better...
        throw new RuntimeException(e);
    }
    log.info("Setting up invitation mapping refresh timer");
    refreshTimer = new Timer();
    refreshTimer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            try {
                lookupMappingsForInvites();
            } catch (Throwable t) {
                log.error("Error when running background mapping refresh", t);
            }
        }
    }, 5000L, TimeUnit.MILLISECONDS.convert(cfg.getResolution().getTimer(), TimeUnit.MINUTES));
}
Also used : NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) ThreePidInviteIO(io.kamax.mxisd.storage.ormlite.ThreePidInviteIO) Gson(com.google.gson.Gson) SSLContext(javax.net.ssl.SSLContext) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) MappingAlreadyExistsException(io.kamax.mxisd.exception.MappingAlreadyExistsException) BadRequestException(io.kamax.mxisd.exception.BadRequestException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) HostnameVerifier(javax.net.ssl.HostnameVerifier) MatrixID(io.kamax.matrix.MatrixID) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy) PostConstruct(javax.annotation.PostConstruct)

Example 4 with MatrixID

use of io.kamax.matrix.MatrixID in project mxisd by kamax-io.

the class SingleLookupReply method fromRecursive.

public static SingleLookupReply fromRecursive(SingleLookupRequest request, String body) {
    SingleLookupReply reply = new SingleLookupReply();
    reply.isRecursive = true;
    reply.request = request;
    reply.body = body;
    try {
        SingeLookupReplyJson json = gson.fromJson(body, SingeLookupReplyJson.class);
        reply.mxid = new MatrixID(json.getMxid());
        reply.notAfter = Instant.ofEpochMilli(json.getNot_after());
        reply.notBefore = Instant.ofEpochMilli(json.getNot_before());
        reply.timestamp = Instant.ofEpochMilli(json.getTs());
        reply.isSigned = json.isSigned();
    } catch (JsonSyntaxException e) {
    // stub - we only want to try, nothing more
    }
    return reply;
}
Also used : JsonSyntaxException(com.google.gson.JsonSyntaxException) SingeLookupReplyJson(io.kamax.mxisd.controller.identity.v1.io.SingeLookupReplyJson) io.kamax.matrix._MatrixID(io.kamax.matrix._MatrixID) MatrixID(io.kamax.matrix.MatrixID)

Example 5 with MatrixID

use of io.kamax.matrix.MatrixID in project mxisd by kamax-io.

the class RestDirectoryProviderTest method byNameFound.

@Test
public void byNameFound() {
    stubFor(post(urlEqualTo(endpoint)).willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(byNameResponse)));
    UserDirectorySearchResult result = p.searchByDisplayName(byNameSearch);
    assertTrue(!result.isLimited());
    assertTrue(result.getResults().size() == 1);
    UserDirectorySearchResult.Result entry = result.getResults().get(0);
    assertNotNull(entry);
    assertTrue(StringUtils.equals(byNameAvatar, entry.getAvatarUrl()));
    assertTrue(StringUtils.equals(byNameDisplay, entry.getDisplayName()));
    assertTrue(StringUtils.equals(new MatrixID(byNameId, domain).getId(), entry.getUserId()));
    verify(postRequestedFor(urlMatching(endpoint)).withHeader("Content-Type", containing("application/json")).withRequestBody(equalTo(byNameRequest)));
}
Also used : MatrixID(io.kamax.matrix.MatrixID) UserDirectorySearchResult(io.kamax.mxisd.controller.directory.v1.io.UserDirectorySearchResult) Test(org.junit.Test)

Aggregations

MatrixID (io.kamax.matrix.MatrixID)10 io.kamax.matrix._MatrixID (io.kamax.matrix._MatrixID)4 UserDirectorySearchResult (io.kamax.mxisd.controller.directory.v1.io.UserDirectorySearchResult)4 IOException (java.io.IOException)3 InternalServerError (io.kamax.mxisd.exception.InternalServerError)2 SingleLookupReply (io.kamax.mxisd.lookup.SingleLookupReply)2 Connection (java.sql.Connection)2 PreparedStatement (java.sql.PreparedStatement)2 ResultSet (java.sql.ResultSet)2 SQLException (java.sql.SQLException)2 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)2 Test (org.junit.Test)2 Gson (com.google.gson.Gson)1 JsonSyntaxException (com.google.gson.JsonSyntaxException)1 ThreePid (io.kamax.matrix.ThreePid)1 io.kamax.matrix._ThreePid (io.kamax.matrix._ThreePid)1 MemoryIdentityConfig (io.kamax.mxisd.config.memory.MemoryIdentityConfig)1 MemoryThreePid (io.kamax.mxisd.config.memory.MemoryThreePid)1 UserDirectorySearchRequest (io.kamax.mxisd.controller.directory.v1.io.UserDirectorySearchRequest)1 SingeLookupReplyJson (io.kamax.mxisd.controller.identity.v1.io.SingeLookupReplyJson)1