Search in sources :

Example 1 with io.kamax.matrix._MatrixID

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

the class GoogleFirebaseAuthenticator method authenticate.

@Override
public BackendAuthResult authenticate(_MatrixID mxid, String password) {
    if (!isEnabled()) {
        throw new IllegalStateException();
    }
    log.info("Trying to authenticate {}", mxid);
    final BackendAuthResult result = BackendAuthResult.failure();
    String localpart = mxid.getLocalPart();
    CountDownLatch l = new CountDownLatch(1);
    getFirebase().verifyIdToken(password).addOnSuccessListener(token -> {
        try {
            if (!StringUtils.equals(localpart, token.getUid())) {
                log.info("Failure to authenticate {}: Matrix ID localpart '{}' does not match Firebase UID '{}'", mxid, localpart, token.getUid());
                result.fail();
                return;
            }
            result.succeed(mxid.getId(), UserIdType.MatrixID.getId(), token.getName());
            log.info("{} was successfully authenticated", mxid);
            log.info("Fetching profile for {}", mxid);
            CountDownLatch userRecordLatch = new CountDownLatch(1);
            getFirebase().getUser(token.getUid()).addOnSuccessListener(user -> {
                try {
                    toEmail(result, user.getEmail());
                    toMsisdn(result, user.getPhoneNumber());
                    for (UserInfo info : user.getProviderData()) {
                        toEmail(result, info.getEmail());
                        toMsisdn(result, info.getPhoneNumber());
                    }
                    log.info("Got {} 3PIDs in profile", result.getProfile().getThreePids().size());
                } finally {
                    userRecordLatch.countDown();
                }
            }).addOnFailureListener(e -> {
                try {
                    log.warn("Unable to fetch Firebase user profile for {}", mxid);
                    result.fail();
                } finally {
                    userRecordLatch.countDown();
                }
            });
            waitOnLatch(result, userRecordLatch, "Firebase user profile");
        } finally {
            l.countDown();
        }
    }).addOnFailureListener(e -> {
        try {
            if (e instanceof IllegalArgumentException) {
                log.info("Failure to authenticate {}: invalid firebase token", mxid);
            } else {
                log.info("Failure to authenticate {}: {}", mxid, e.getMessage(), e);
                log.info("Exception", e);
            }
            result.fail();
        } finally {
            l.countDown();
        }
    });
    waitOnLatch(result, l, "Firebase auth check");
    return result;
}
Also used : BackendAuthResult(io.kamax.mxisd.auth.provider.BackendAuthResult) ThreePidMedium(io.kamax.matrix.ThreePidMedium) StringUtils(org.apache.commons.lang.StringUtils) Logger(org.slf4j.Logger) UserInfo(com.google.firebase.auth.UserInfo) AuthenticatorProvider(io.kamax.mxisd.auth.provider.AuthenticatorProvider) LoggerFactory(org.slf4j.LoggerFactory) io.kamax.matrix._MatrixID(io.kamax.matrix._MatrixID) BackendAuthResult(io.kamax.mxisd.auth.provider.BackendAuthResult) ThreePid(io.kamax.matrix.ThreePid) TimeUnit(java.util.concurrent.TimeUnit) PhoneNumberUtil(com.google.i18n.phonenumbers.PhoneNumberUtil) CountDownLatch(java.util.concurrent.CountDownLatch) NumberParseException(com.google.i18n.phonenumbers.NumberParseException) UserIdType(io.kamax.mxisd.UserIdType) UserInfo(com.google.firebase.auth.UserInfo) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 2 with io.kamax.matrix._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 io.kamax.matrix._MatrixID

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

the class AuthManager method authenticate.

public UserAuthResult authenticate(String id, String password) {
    _MatrixID mxid = MatrixID.asAcceptable(id);
    for (AuthenticatorProvider provider : providers) {
        if (!provider.isEnabled()) {
            continue;
        }
        BackendAuthResult result = provider.authenticate(mxid, password);
        if (result.isSuccess()) {
            String mxId;
            if (UserIdType.Localpart.is(result.getId().getType())) {
                mxId = MatrixID.from(result.getId().getValue(), mxCfg.getDomain()).acceptable().getId();
            } else if (UserIdType.MatrixID.is(result.getId().getType())) {
                mxId = MatrixID.asAcceptable(result.getId().getValue()).getId();
            } else {
                log.warn("Unsupported User ID type {} for backend {}", result.getId().getType(), provider.getClass().getSimpleName());
                continue;
            }
            UserAuthResult authResult = new UserAuthResult().success(result.getProfile().getDisplayName());
            for (_ThreePid pid : result.getProfile().getThreePids()) {
                authResult.withThreePid(pid.getMedium(), pid.getAddress());
            }
            log.info("{} was authenticated by {}, publishing 3PID mappings, if any", id, provider.getClass().getSimpleName());
            for (ThreePid pid : authResult.getThreePids()) {
                log.info("Processing {} for {}", pid, id);
                invMgr.publishMappingIfInvited(new ThreePidMapping(pid, mxId));
            }
            invMgr.lookupMappingsForInvites();
            return authResult;
        }
    }
    return new UserAuthResult().failure();
}
Also used : BackendAuthResult(io.kamax.mxisd.auth.provider.BackendAuthResult) ThreePidMapping(io.kamax.mxisd.lookup.ThreePidMapping) AuthenticatorProvider(io.kamax.mxisd.auth.provider.AuthenticatorProvider) io.kamax.matrix._ThreePid(io.kamax.matrix._ThreePid) ThreePid(io.kamax.matrix.ThreePid) io.kamax.matrix._ThreePid(io.kamax.matrix._ThreePid) io.kamax.matrix._MatrixID(io.kamax.matrix._MatrixID)

Example 4 with io.kamax.matrix._MatrixID

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

the class SqlThreePidProvider method getThreepids.

@Override
public List<_ThreePid> getThreepids(_MatrixID mxid) {
    List<_ThreePid> threepids = new ArrayList<>();
    String stmtSql = cfg.getProfile().getThreepid().getQuery();
    try (Connection conn = pool.get()) {
        PreparedStatement stmt = conn.prepareStatement(stmtSql);
        stmt.setString(1, mxid.getId());
        ResultSet rSet = stmt.executeQuery();
        while (rSet.next()) {
            String medium = rSet.getString("medium");
            String address = rSet.getString("address");
            threepids.add(new ThreePid(medium, address));
        }
        return threepids;
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}
Also used : SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) io.kamax.matrix._ThreePid(io.kamax.matrix._ThreePid) PreparedStatement(java.sql.PreparedStatement) ThreePid(io.kamax.matrix.ThreePid) io.kamax.matrix._ThreePid(io.kamax.matrix._ThreePid)

Example 5 with io.kamax.matrix._MatrixID

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

the class ProfileInternalController method getProfile.

@RequestMapping(method = GET, path = "/_matrix-internal/profile/v1/{userId:.+}")
public String getProfile(@PathVariable String userId) throws UnsupportedEncodingException {
    userId = URLDecoder.decode(userId, StandardCharsets.UTF_8.name());
    _MatrixID mxId = MatrixID.asAcceptable(userId);
    return GsonUtil.get().toJson(GsonUtil.makeObj("roles", GsonUtil.asArray(mgr.getRoles(mxId))));
}
Also used : io.kamax.matrix._MatrixID(io.kamax.matrix._MatrixID) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

io.kamax.matrix._MatrixID (io.kamax.matrix._MatrixID)4 ThreePid (io.kamax.matrix.ThreePid)3 io.kamax.matrix._ThreePid (io.kamax.matrix._ThreePid)2 AuthenticatorProvider (io.kamax.mxisd.auth.provider.AuthenticatorProvider)2 BackendAuthResult (io.kamax.mxisd.auth.provider.BackendAuthResult)2 UserInfo (com.google.firebase.auth.UserInfo)1 NumberParseException (com.google.i18n.phonenumbers.NumberParseException)1 PhoneNumberUtil (com.google.i18n.phonenumbers.PhoneNumberUtil)1 MatrixID (io.kamax.matrix.MatrixID)1 ThreePidMedium (io.kamax.matrix.ThreePidMedium)1 UserIdType (io.kamax.mxisd.UserIdType)1 ThreePidMapping (io.kamax.mxisd.lookup.ThreePidMapping)1 IThreePidSession (io.kamax.mxisd.threepid.session.IThreePidSession)1 ThreePidSession (io.kamax.mxisd.threepid.session.ThreePidSession)1 IOException (java.io.IOException)1 Connection (java.sql.Connection)1 PreparedStatement (java.sql.PreparedStatement)1 ResultSet (java.sql.ResultSet)1 SQLException (java.sql.SQLException)1 ArrayList (java.util.ArrayList)1