Search in sources :

Example 6 with UnauthorizedException

use of com.google.api.server.spi.response.UnauthorizedException in project endpoints-java by cloudendpoints.

the class ServletRequestParamReaderTest method testAppEngineUserInjectionThrowsExceptionIfRequired.

@Test
public void testAppEngineUserInjectionThrowsExceptionIfRequired() throws Exception {
    @SuppressWarnings("unused")
    class TestUser {

        @SuppressWarnings("unused")
        public void getUser(com.google.appengine.api.users.User user) {
        }
    }
    ApiMethodConfig methodConfig = Mockito.mock(ApiMethodConfig.class);
    when(methodConfig.getAuthLevel()).thenReturn(AuthLevel.REQUIRED);
    methodConfig.setAuthLevel(AuthLevel.REQUIRED);
    try {
        Method method = TestUser.class.getDeclaredMethod("getUser", com.google.appengine.api.users.User.class);
        readParameters("{}", EndpointMethod.create(method.getDeclaringClass(), method), methodConfig, null, null);
        fail("expected unauthorized method exception");
    } catch (UnauthorizedException ex) {
    // expected
    }
}
Also used : ApiMethodConfig(com.google.api.server.spi.config.model.ApiMethodConfig) User(com.google.api.server.spi.auth.common.User) UnauthorizedException(com.google.api.server.spi.response.UnauthorizedException) Method(java.lang.reflect.Method) EndpointMethod(com.google.api.server.spi.EndpointMethod) Test(org.junit.Test)

Example 7 with UnauthorizedException

use of com.google.api.server.spi.response.UnauthorizedException in project endpoints-java by cloudendpoints.

the class ServletRequestParamReader method deserializeParams.

protected Object[] deserializeParams(JsonNode node) throws IOException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, ServiceException {
    EndpointMethod method = getMethod();
    Class<?>[] paramClasses = method.getParameterClasses();
    TypeToken<?>[] paramTypes = method.getParameterTypes();
    Object[] params = new Object[paramClasses.length];
    List<String> parameterNames = getParameterNames(method);
    for (int i = 0; i < paramClasses.length; i++) {
        TypeToken<?> type = paramTypes[i];
        Class<?> clazz = paramClasses[i];
        if (User.class.isAssignableFrom(clazz)) {
            // User type parameter requires no Named annotation (ignored if present)
            User user = getUser();
            if (user == null && methodConfig != null && methodConfig.getAuthLevel() == AuthLevel.REQUIRED) {
                throw new UnauthorizedException("Valid user credentials are required.");
            }
            if (user == null || clazz.isAssignableFrom(user.getClass())) {
                params[i] = user;
                logger.atFine().log("deserialize: User injected into param[%d]", i);
            } else {
                logger.atWarning().log("deserialize: User object of type %s is not assignable to %s. User will be null.", user.getClass().getName(), clazz.getName());
            }
        } else if (APPENGINE_USER_CLASS_NAME.equals(clazz.getName())) {
            // User type parameter requires no Named annotation (ignored if present)
            com.google.appengine.api.users.User appEngineUser = getAppEngineUser();
            if (appEngineUser == null && methodConfig != null && methodConfig.getAuthLevel() == AuthLevel.REQUIRED) {
                throw new UnauthorizedException("Valid user credentials are required.");
            }
            params[i] = appEngineUser;
            logger.atFine().log("deserialize: App Engine User injected into param[%d]", i);
        } else if (clazz == HttpServletRequest.class) {
            // HttpServletRequest type parameter requires no Named annotation (ignored if present)
            params[i] = endpointsContext.getRequest();
            logger.atFine().log("deserialize: HttpServletRequest injected into param[%d]", i);
        } else if (clazz == ServletContext.class) {
            // ServletContext type parameter requires no Named annotation (ignored if present)
            params[i] = servletContext;
            logger.atFine().log("deserialize: ServletContext %s injected into param[%d]", params[i], i);
        } else {
            String name = parameterNames.get(i);
            if (Strings.isNullOrEmpty(name)) {
                params[i] = (node == null) ? null : objectReader.forType(clazz).readValue(node);
                logger.atFine().log("deserialize: %s %s injected into unnamed param[%d]", clazz, params[i], i);
            } else if (StandardParameters.isStandardParamName(name)) {
                params[i] = getStandardParamValue(node, name);
            } else {
                JsonNode nodeValue = node.get(name);
                if (nodeValue == null) {
                    params[i] = null;
                } else {
                    // Check for collection type
                    if (Collection.class.isAssignableFrom(clazz) && type.getType() instanceof ParameterizedType) {
                        params[i] = deserializeCollection(clazz, (ParameterizedType) type.getType(), nodeValue);
                    } else {
                        params[i] = objectReader.forType(clazz).readValue(nodeValue);
                    }
                }
                if (params[i] == null && isRequiredParameter(method, i)) {
                    throw new BadRequestException("null value for parameter '" + name + "' not allowed");
                }
                logger.atFine().log("deserialize: %s %s injected into param[%d] named {%s}", clazz, params[i], i, name);
            }
        }
    }
    return params;
}
Also used : User(com.google.api.server.spi.auth.common.User) JsonNode(com.fasterxml.jackson.databind.JsonNode) ParameterizedType(java.lang.reflect.ParameterizedType) TypeToken(com.google.common.reflect.TypeToken) UnauthorizedException(com.google.api.server.spi.response.UnauthorizedException) EndpointMethod(com.google.api.server.spi.EndpointMethod) ServletContext(javax.servlet.ServletContext) Collection(java.util.Collection) BadRequestException(com.google.api.server.spi.response.BadRequestException)

Example 8 with UnauthorizedException

use of com.google.api.server.spi.response.UnauthorizedException in project cryptonomica by Cryptonomica.

the class UserTools method ensureNotaryOrCryptonomicaOfficer.

// end of ensureCryptonomicaOfficer method
/* --- Check if user is a notary or IACC officer: */
public static CryptonomicaUser ensureNotaryOrCryptonomicaOfficer(final User googleUser) throws UnauthorizedException {
    // 
    CryptonomicaUser cryptonomicaUser = ensureCryptonomicaRegisteredUser(googleUser);
    // 
    LOG.warning("cryptonomicaUser: ");
    LOG.warning(new Gson().toJson(cryptonomicaUser));
    // if (cryptonomicaOfficer == null && notary == null) {
    LOG.warning("cryptonomicaUser.getCryptonomicaOfficer(): " + cryptonomicaUser.getCryptonomicaOfficer());
    LOG.warning("cryptonomicaUser.getNotary(): " + cryptonomicaUser.getNotary());
    // if isCryptonomicaOfficer and isNotary are both false or null:
    if ((cryptonomicaUser.getCryptonomicaOfficer() == null || !cryptonomicaUser.getCryptonomicaOfficer()) && (cryptonomicaUser.getNotary() == null || !cryptonomicaUser.getNotary())) {
        throw new UnauthorizedException("You are not a Notary or Cryptonomica officer");
    }
    return cryptonomicaUser;
}
Also used : UnauthorizedException(com.google.api.server.spi.response.UnauthorizedException) Gson(com.google.gson.Gson) CryptonomicaUser(net.cryptonomica.entities.CryptonomicaUser)

Example 9 with UnauthorizedException

use of com.google.api.server.spi.response.UnauthorizedException in project cryptonomica by Cryptonomica.

the class UserTools method ensureCryptonomicaRegisteredUser.

/* --- Check if user is registered user: */
public static CryptonomicaUser ensureCryptonomicaRegisteredUser(final User googleUser) throws UnauthorizedException {
    ensureGoogleAuth(googleUser);
    CryptonomicaUser cryptonomicaUser = null;
    try {
        cryptonomicaUser = ofy().load().key(Key.create(CryptonomicaUser.class, googleUser.getUserId())).now();
    } catch (Exception e) {
        LOG.warning(e.getMessage());
    }
    if (cryptonomicaUser == null) {
        throw new UnauthorizedException("You are not registered on Cryptonomica server");
    }
    return cryptonomicaUser;
}
Also used : UnauthorizedException(com.google.api.server.spi.response.UnauthorizedException) CryptonomicaUser(net.cryptonomica.entities.CryptonomicaUser) JSONException(org.json.JSONException) UnauthorizedException(com.google.api.server.spi.response.UnauthorizedException)

Example 10 with UnauthorizedException

use of com.google.api.server.spi.response.UnauthorizedException in project cryptonomica by Cryptonomica.

the class EthNodeAPI method verifyEthAddress.

@ApiMethod(name = "verifyEthAddress", path = "verifyEthAddress", httpMethod = ApiMethod.HttpMethod.POST)
@SuppressWarnings("unused")
public BooleanWrapperObject verifyEthAddress(// final HttpServletRequest httpServletRequest,
final User googleUser, @Named("ethereumAcc") final String ethereumAcc) throws IllegalArgumentException, UnauthorizedException, Exception {
    BooleanWrapperObject result = new BooleanWrapperObject();
    // ensure registered user ( - may be later only for verified):
    CryptonomicaUser cryptonomicaUser = UserTools.ensureCryptonomicaRegisteredUser(googleUser);
    // check form:
    LOG.warning("ethereumAcc" + ethereumAcc);
    if (ethereumAcc == null || ethereumAcc.equals("")) {
        throw new IllegalArgumentException("Provided text is to short or empty");
    }
    String tomcatWeb3jAPIkey = ofy().load().key(Key.create(AppSettings.class, "tomcatweb3jAPIkey")).now().getValue();
    String urlHost = "https://tomcatweb3j.cryptonomica.net";
    String urlPath = "/GetVerificationRequestDataServlet";
    String urlAddress = urlHost + urlPath;
    // HashMap<String, String> queryMap = new HashMap<>();
    // queryMap.put("address", ethereumAcc);
    String postRequestBody = "address=" + ethereumAcc;
    HTTPResponse httpResponse = HttpService.postRequestWithAPIkey(urlAddress, postRequestBody, tomcatWeb3jAPIkey);
    byte[] httpResponseContentBytes = httpResponse.getContent();
    String httpResponseContentString = new String(httpResponseContentBytes, StandardCharsets.UTF_8);
    // Test:
    // Object resObj = new Gson().fromJson(httpResponseContentString, Object.class); // --- exception
    // LOG.warning("resObj: " + new Gson().toJson(resObj));
    LOG.warning("httpResponseContentString: " + httpResponseContentString);
    VerificationRequestDataFromSC verificationRequestDataFromSC = GSON.fromJson(httpResponseContentString, VerificationRequestDataFromSC.class);
    // GET Key from DataBase by fingerprint:
    String unverifiedFingerprint = verificationRequestDataFromSC.getUnverifiedFingerprint();
    String signedString = verificationRequestDataFromSC.getSignedString();
    PGPPublicKeyData pgpPublicKeyData = PGPTools.getPGPPublicKeyDataFromDataBaseByFingerprint(unverifiedFingerprint);
    Boolean keyVerifiedOffline = pgpPublicKeyData.getVerified();
    Boolean keyVerifiedOnline = pgpPublicKeyData.getOnlineVerificationFinished();
    if (!keyVerifiedOffline && !keyVerifiedOnline) {
        throw new Exception("Owner of the OpenPGP key " + pgpPublicKeyData.getFingerprint() + " not verified. Can not process with ETH address verification for " + ethereumAcc);
    }
    PGPPublicKey publicKey = PGPTools.readPublicKeyFromString(pgpPublicKeyData.getAsciiArmored().getValue());
    result.setResult(PGPTools.verifyText(signedString, publicKey));
    if (result.getResult()) {
        Map<String, String> parameterMap = new HashMap<>();
        parameterMap.put("acc", ethereumAcc);
        parameterMap.put("fingerprint", unverifiedFingerprint);
        // https://stackoverflow.com/questions/7784421/getting-unix-timestamp-from-date
        Long keyCertificateValidUntilUnixTimeLong = pgpPublicKeyData.getExp().getTime() / 1000;
        Integer keyCertificateValidUntilUnixTime = keyCertificateValidUntilUnixTimeLong.intValue();
        parameterMap.put("keyCertificateValidUntil", keyCertificateValidUntilUnixTime.toString());
        parameterMap.put("firstName", pgpPublicKeyData.getFirstName());
        parameterMap.put("lastName", pgpPublicKeyData.getLastName());
        if (pgpPublicKeyData.getUserBirthday() != null) {
            // for testing with old keys only
            Long birthDateUnixTimeLong = pgpPublicKeyData.getUserBirthday().getTime() / 1000;
            Integer birthDateUnixTime = birthDateUnixTimeLong.intValue();
            parameterMap.put("birthDate", birthDateUnixTime.toString());
        } else {
            parameterMap.put("birthDate", "null");
        }
        if (pgpPublicKeyData.getNationality() != null) {
            // for testing with old keys only
            parameterMap.put("nationality", pgpPublicKeyData.getNationality());
        } else {
            parameterMap.put("nationality", "null");
        }
        LOG.warning("parameterMap: ");
        LOG.warning(GSON.toJson(parameterMap));
        HTTPResponse httpResponseFromAddVerificationDataServlet = HttpService.makePostRequestWithParametersMapAndApiKey("https://tomcatweb3j.cryptonomica.net/addVerificationData", tomcatWeb3jAPIkey, parameterMap);
        byte[] httpResponseContentBytesFromAddVerificationDataServlet = httpResponseFromAddVerificationDataServlet.getContent();
        String httpResponseContentStringAddVerificationDataServlet = new String(httpResponseContentBytesFromAddVerificationDataServlet, StandardCharsets.UTF_8);
        LOG.warning(httpResponseContentStringAddVerificationDataServlet);
        result.setMessage(// tx receipt
        httpResponseContentStringAddVerificationDataServlet);
    }
    LOG.warning("result:");
    LOG.warning(GSON.toJson(result));
    return result;
}
Also used : PGPPublicKeyData(net.cryptonomica.entities.PGPPublicKeyData) AppSettings(net.cryptonomica.entities.AppSettings) HashMap(java.util.HashMap) HTTPResponse(com.google.appengine.api.urlfetch.HTTPResponse) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey) BooleanWrapperObject(net.cryptonomica.returns.BooleanWrapperObject) CryptonomicaUser(net.cryptonomica.entities.CryptonomicaUser) VerificationRequestDataFromSC(net.cryptonomica.entities.VerificationRequestDataFromSC) UnauthorizedException(com.google.api.server.spi.response.UnauthorizedException) ApiMethod(com.google.api.server.spi.config.ApiMethod)

Aggregations

UnauthorizedException (com.google.api.server.spi.response.UnauthorizedException)15 ApiMethod (com.google.api.server.spi.config.ApiMethod)7 BadRequestException (com.google.api.server.spi.response.BadRequestException)4 CryptonomicaUser (net.cryptonomica.entities.CryptonomicaUser)4 EndpointMethod (com.google.api.server.spi.EndpointMethod)3 User (com.google.api.server.spi.auth.common.User)3 Device (com.google.samples.apps.iosched.server.gcm.db.models.Device)3 Test (org.junit.Test)3 ApiMethodConfig (com.google.api.server.spi.config.model.ApiMethodConfig)2 MessageSender (com.google.samples.apps.iosched.server.gcm.device.MessageSender)2 Method (java.lang.reflect.Method)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ForbiddenException (com.google.api.server.spi.response.ForbiddenException)1 InternalServerErrorException (com.google.api.server.spi.response.InternalServerErrorException)1 NotFoundException (com.google.api.server.spi.response.NotFoundException)1 Queue (com.google.appengine.api.taskqueue.Queue)1 TaskOptions (com.google.appengine.api.taskqueue.TaskOptions)1 HTTPResponse (com.google.appengine.api.urlfetch.HTTPResponse)1 TypeToken (com.google.common.reflect.TypeToken)1 Gson (com.google.gson.Gson)1