Search in sources :

Example 1 with ThreePid

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

the class GoogleFirebaseAuthenticator method toMsisdn.

private void toMsisdn(BackendAuthResult result, String phoneNumber) {
    if (StringUtils.isBlank(phoneNumber)) {
        return;
    }
    try {
        String number = phoneUtil.format(phoneUtil.parse(phoneNumber, // No default region
        null), PhoneNumberUtil.PhoneNumberFormat.E164).substring(// We want without the leading +
        1);
        result.withThreePid(new ThreePid(ThreePidMedium.PhoneNumber.getId(), number));
    } catch (NumberParseException e) {
        log.warn("Invalid phone number: {}", phoneNumber);
    }
}
Also used : NumberParseException(com.google.i18n.phonenumbers.NumberParseException) ThreePid(io.kamax.matrix.ThreePid)

Example 2 with ThreePid

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

the class LdapAuthProvider method authenticate.

@Override
public BackendAuthResult authenticate(_MatrixID mxid, String password) {
    log.info("Performing auth for {}", mxid);
    try (LdapConnection conn = getConn()) {
        bind(conn);
        String uidType = getAt().getUid().getType();
        String userFilterValue = StringUtils.equals(LdapBackend.UID, uidType) ? mxid.getLocalPart() : mxid.getId();
        if (StringUtils.isBlank(userFilterValue)) {
            log.warn("Username is empty, failing auth");
            return BackendAuthResult.failure();
        }
        String userFilter = "(" + getUidAtt() + "=" + userFilterValue + ")";
        userFilter = buildWithFilter(userFilter, getCfg().getAuth().getFilter());
        Set<String> attributes = new HashSet<>();
        attributes.add(getUidAtt());
        attributes.add(getAt().getName());
        getAt().getThreepid().forEach((k, v) -> attributes.addAll(v));
        String[] attArray = new String[attributes.size()];
        attributes.toArray(attArray);
        log.debug("Base DN: {}", getBaseDn());
        log.debug("Query: {}", userFilter);
        log.debug("Attributes: {}", GsonUtil.build().toJson(attArray));
        try (EntryCursor cursor = conn.search(getBaseDn(), userFilter, SearchScope.SUBTREE, attArray)) {
            while (cursor.next()) {
                Entry entry = cursor.get();
                String dn = entry.getDn().getName();
                log.info("Checking possible match, DN: {}", dn);
                if (!getAttribute(entry, getUidAtt()).isPresent()) {
                    continue;
                }
                log.info("Attempting authentication on LDAP for {}", dn);
                try {
                    conn.bind(entry.getDn(), password);
                } catch (LdapException e) {
                    log.info("Unable to bind using {} because {}", entry.getDn().getName(), e.getMessage());
                    return BackendAuthResult.failure();
                }
                Attribute nameAttribute = entry.get(getAt().getName());
                String name = nameAttribute != null ? nameAttribute.get().toString() : null;
                log.info("Authentication successful for {}", entry.getDn().getName());
                log.info("DN {} is a valid match", dn);
                // TODO should we canonicalize the MXID?
                BackendAuthResult result = BackendAuthResult.success(mxid.getId(), UserIdType.MatrixID, name);
                log.info("Processing 3PIDs for profile");
                getAt().getThreepid().forEach((k, v) -> {
                    log.info("Processing 3PID type {}", k);
                    v.forEach(attId -> {
                        List<String> values = getAttributes(entry, attId);
                        log.info("\tAttribute {} has {} value(s)", attId, values.size());
                        getAttributes(entry, attId).forEach(tpidValue -> {
                            if (ThreePidMedium.PhoneNumber.is(k)) {
                                tpidValue = getMsisdn(tpidValue).orElse(tpidValue);
                            }
                            result.withThreePid(new ThreePid(k, tpidValue));
                        });
                    });
                });
                log.info("Found {} 3PIDs", result.getProfile().getThreePids().size());
                return result;
            }
        } catch (CursorLdapReferralException e) {
            log.warn("Entity for {} is only available via referral, skipping", mxid);
        }
        log.info("No match were found for {}", mxid);
        return BackendAuthResult.failure();
    } catch (LdapException | IOException | CursorException e) {
        throw new RuntimeException(e);
    }
}
Also used : EntryCursor(org.apache.directory.api.ldap.model.cursor.EntryCursor) Attribute(org.apache.directory.api.ldap.model.entry.Attribute) IOException(java.io.IOException) BackendAuthResult(io.kamax.mxisd.auth.provider.BackendAuthResult) Entry(org.apache.directory.api.ldap.model.entry.Entry) CursorException(org.apache.directory.api.ldap.model.cursor.CursorException) CursorLdapReferralException(org.apache.directory.api.ldap.model.cursor.CursorLdapReferralException) ThreePid(io.kamax.matrix.ThreePid) LdapException(org.apache.directory.api.ldap.model.exception.LdapException) LdapConnection(org.apache.directory.ldap.client.api.LdapConnection) HashSet(java.util.HashSet)

Example 3 with ThreePid

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

the class SessionRestController method init.

@RequestMapping(value = "/validate/{medium}/requestToken")
String init(HttpServletRequest request, HttpServletResponse response, @PathVariable String medium) throws IOException {
    log.info("Request {}: {}", request.getMethod(), request.getRequestURL(), request.getQueryString());
    if (ThreePidMedium.Email.is(medium)) {
        SessionEmailTokenRequestJson req = parser.parse(request, SessionEmailTokenRequestJson.class);
        return gson.toJson(new Sid(mgr.create(request.getRemoteHost(), new ThreePid(req.getMedium(), req.getValue()), req.getSecret(), req.getAttempt(), req.getNextLink())));
    }
    if (ThreePidMedium.PhoneNumber.is(medium)) {
        SessionPhoneTokenRequestJson req = parser.parse(request, SessionPhoneTokenRequestJson.class);
        ThreePid threepid = new ThreePid(req.getMedium(), req.getValue());
        String sessionId = mgr.create(request.getRemoteHost(), threepid, req.getSecret(), req.getAttempt(), req.getNextLink());
        JsonObject res = new JsonObject();
        res.addProperty("sid", sessionId);
        res.addProperty(threepid.getMedium(), threepid.getAddress());
        return gson.toJson(res);
    }
    JsonObject obj = new JsonObject();
    obj.addProperty("errcode", "M_INVALID_3PID_TYPE");
    obj.addProperty("error", medium + " is not supported as a 3PID type");
    response.setStatus(HttpStatus.SC_BAD_REQUEST);
    return gson.toJson(obj);
}
Also used : JsonObject(com.google.gson.JsonObject) ThreePid(io.kamax.matrix.ThreePid) SessionPhoneTokenRequestJson(io.kamax.mxisd.controller.identity.v1.io.SessionPhoneTokenRequestJson) SessionEmailTokenRequestJson(io.kamax.mxisd.controller.identity.v1.io.SessionEmailTokenRequestJson)

Example 4 with ThreePid

use of io.kamax.matrix.ThreePid 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 5 with ThreePid

use of io.kamax.matrix.ThreePid 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)

Aggregations

ThreePid (io.kamax.matrix.ThreePid)9 io.kamax.matrix._ThreePid (io.kamax.matrix._ThreePid)3 BackendAuthResult (io.kamax.mxisd.auth.provider.BackendAuthResult)3 JsonObject (com.google.gson.JsonObject)2 io.kamax.matrix._MatrixID (io.kamax.matrix._MatrixID)2 IOException (java.io.IOException)2 NumberParseException (com.google.i18n.phonenumbers.NumberParseException)1 MatrixID (io.kamax.matrix.MatrixID)1 AuthenticatorProvider (io.kamax.mxisd.auth.provider.AuthenticatorProvider)1 MemoryIdentityConfig (io.kamax.mxisd.config.memory.MemoryIdentityConfig)1 MemoryThreePid (io.kamax.mxisd.config.memory.MemoryThreePid)1 SessionEmailTokenRequestJson (io.kamax.mxisd.controller.identity.v1.io.SessionEmailTokenRequestJson)1 SessionPhoneTokenRequestJson (io.kamax.mxisd.controller.identity.v1.io.SessionPhoneTokenRequestJson)1 SingleLookupReply (io.kamax.mxisd.lookup.SingleLookupReply)1 ThreePidMapping (io.kamax.mxisd.lookup.ThreePidMapping)1 IThreePidSession (io.kamax.mxisd.threepid.session.IThreePidSession)1 ThreePidSession (io.kamax.mxisd.threepid.session.ThreePidSession)1 GsonParser (io.kamax.mxisd.util.GsonParser)1 Connection (java.sql.Connection)1 PreparedStatement (java.sql.PreparedStatement)1