I use external camunda-external-task-client-js to setup a service task for deployed camunda tomcat with ssh setup.
geting error : * polling failed with RequestError: unable to verify the first certificate
tanks.
import {
Client,
logger,
BasicAuthInterceptor,
Variables,
File,
} from "camunda-external-task-client-js";
const basicAuthentication = new BasicAuthInterceptor({
username: "username",
password: "password",
});
const client = new Client({
baseUrl: "https://xxx/engine-rest",
interceptors: basicAuthentication,
use:logger
});
client.subscribe("topic-name", async function ({ task, taskService }) {
}
but i get this error in console :
polling failed with RequestError: unable to verify the first certificate
tanks.
Related
I'm having some issues determining and connecting with the right MetaMask network.
In Ganache, my RPC server is 127.0.0.1.7545 and the network id is 5777. However, when I try to create a custom RPC in MetaMask with this info, I get the following error:
The endpoint returned a different chain ID: 1337
This is my truffle-config.js:
module.exports = {
networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*" // Match any network id
},
develop: {
port: 8545
}
}
};
I'm hoping this would match any network id as I've specified, but the console shows the following error:
Contract has not been deployed to a detected network (network/artifact mismatch)
I've already tried truffle migrate --reset, without success. I've also tried creating an explicit network for testrpc in truffle-config.js - that didn't work either.
Any help would be much appreciated!
You are seeing that error because your contract is deployed to Ganache but you are connected to a different network.
The code that you are writing to load the contract should be inside try/catch block.
inside loading contract logic:
export const loadContract = async (name, provider) => {
// Load the contract
// set the provider
let deployedContract = null;
try {
// Get the contract
deployedContract = await _contract.deployed();
} catch {
console.error("You are connected to the wrong network");
}
return deployedContract;
};
In the component that you are using loadContract, call it inside useEffect.
useEffect(() => {
// Detect Provider
if (provider) {
// contract should be loaded when provider exists
const contract = await loadContract("ContractName", provider);
rLoaded: true,
// Add More logic
} else {
console.error("Please, install Metamask.");
}
};
}, []);
Now you need to make sure if you are not connected to Ganache, disable the button, so your app won't crash. for this create a state variable
// You probably already have logic to get account and contract
const canConnectToContract = account && contract;
now write a proper ui:
{!canConnectToContract && (
<h2>Connect to Ganache</h2>
)}
<button
disabled={!canConnectToContract}
>
Donate 1 Ethreum
</button>
I am using AWS Cognito for Authentication using user pools and I have all my APIs configured on the API gateway. I directly hit cognito from the Angular client, store the tokens returned by Cognito in local storage and use them in subsequent calls.
The problem however is, if the token I send from Angular has expired the Cognito authentication fails and no Integration backend is hit in this case. As a result, I am getting a 401 error in Chrome.
The interesting thing however is that this 401 code is not available to me in the HTTP response object that is passed to Angular. A default 0 code is received by the Angular and this seems to be the case with all the error code received from server (either cognito or backend).
I tried to explore around and found that the issue might be because the gateway is not sending proper CORS headers in the error cases. I have read following related docs but unfortunately I couldn't find out a way to resolve the issue.
Can someone suggest a solution to this.
Edit: I also read somewhere that it is a known AWS issue. Is that the case ?
You can manage the Cognito session before making the call to the API Gateway.
In the example below, the getSession method has a callback that prints out any error messages to the console, and returns.
////// Cognito.js
import {
CognitoUserPool,
CookieStorage
} from 'amazon-cognito-identity-js'
import config from '../config'
const cookieSettings = {
domain: '.xxxxxxxxxxx.com',
secure: true
}
export default {
cookieSettings,
pool: new CognitoUserPool({
UserPoolId: config.UserPoolId,
ClientId: config.ClientId,
Storage: new CookieStorage(cookieSettings)
})
}
//////
////// actions.js
import Cognito from './Cognito'
export function fetchUser() {
// get cognito user cookies
const cognitoUser = Cognito.pool.getCurrentUser()
if (cognitoUser != null) {
// try to get session from cognito
cognitoUser.getSession(function(err, session) {
if (err) {
console.log(err)
return;
}
fetch('https://api-gateway-url', {
headers: {
Authorization: 'Bearer ' + session.getAccessToken().getJwtToken(),
}
})
.then(response => response.json())
.then(json => console.log(json))
})
}
}
I want to start a federated apollo server:
const gateway = new ApolloGateway({
serviceList: [
... list of services
],
});
const startServer = async () => {
const gatewayConfig = await gateway.load();
const server = new ApolloServer({
...gatewayConfig,
subscriptions: false,
});
server.listen().then(({ url }) => {
console.log("Server running!");
});
};
startServer();
When I start the server and one of the services in the serviceList is available, the server starts and logs which services have failed. I want the server to only start when all the services are available, ie when one service is unavailable an error is thrown and the server stops. Any ideas how to do this?
Apollo can't do this as of writing this answer. The only solution is to monitor the availability manually and leverage apollo accordingly. I used apollo-server-express for this.
Below is a demonstration of how I managed to leverage my apollo gateway based on the availability of my services.
Basically, you wrap the middleware of your apollo server. This allows you to exchange your apollo server instance as well as throwing an error when they are not available.
import express from 'express';
import { ApolloServer } from 'apollo-server-express';
import bodyParser from 'body-parser'; // use express body-parser for convinience
// your list of federated services
const serviceList = [
{ name: 'service1', url: 'http://service1/graphql' }
];
// a variable to store the server. We will need to replace him when a service goes offline or comes back online again
let server = null;
// setup express
const app = express();
app.use(bodyParser.json());
app.use(customRouterToLeverageApolloServer); // defined below
// middleware to leverage apollo server
function customRouterToLeverageApolloServer(req, res, next) {
// if services are down (no apollo instance) throw an error
if(!server) {
res.json({ error: 'services are currently not available' });
return;
}
// else pass the request to apollo
const router = server.getMiddleware(); // https://www.apollographql.com/docs/apollo-server/api/apollo-server/#apolloservergetmiddleware
return router(req, res, next);
}
function servicesAreAvailable() {
// go through your serviceList and check availability
}
// periodically check the availability of your services and create/destroy an ApolloServer instance accordingly. This will also be the indication whether or not your services are available at the time.
// you might want to also call this function at startup
setInterval(() => {
if(servicesAreAvailable()) {
server = new ApolloServer({ ... });
}
else {
server = null;
}
}, 1000 * 60 * 5) // check every 5 minutes
I am using react-native and the out of the box aws-amplify-react-native to sigin, signup users. Users are able to authenticate successfully but getting the following error in the signin form "no current user"
I pumped up the log level to debug in the application. I can see the user successfully authenticate and I get back the JWT token but I see the following in the logs:
[DEBUG] 22:47.149 AuthClass - Failed to get user from user pool
[ERROR] 22:47.154 AuthClass - Failed to get the signed in user No current user
[DEBUG] 22:47.161 AuthPiece - No current user
Below is a snippet of my code:
import { ConfirmSignIn, ConfirmSignUp, ForgotPassword, RequireNewPassword, SignIn, SignUp, VerifyContact, withAuthenticator } from 'aws-amplify-react-native';
const RootStack = createStackNavigator(
{
Login: LoginScreen,
Main: MainScreen,
Customer: CustomerScreen,
Reports: ReportsScreen,
Signup: SignupScreen
},
{
initialRouteName: 'Main',
}
);
const AppContainer = createAppContainer(RootStack);
export class App extends React.Component {
render() {
return (
<AppContainer />
);
}
}
export default withAuthenticator(App);
When I run my app. I see the default Sign In form for Amplify, I use it to enter username and password and then click on "SIGN IN" button which does successfully authenticate but I get the "No current user error" as shown above.
I had the similar problem. I removed the cookie storage block from the configure method and it worked.
Are you using the cookieStore? If true, do you use the secure flag? If so, change its value to false in the development environment.
The error is literally saying No current user - you need to sign in using the supported identity provider.
My solution to that:
import { Amplify } from "#aws-amplify/core";
import { Auth } from "#aws-amplify/auth";
import { CookieStorage } from 'amazon-cognito-identity-js';
import amplifyConfig from "../lib/Amplify";
Amplify.configure(amplifyConfig);
const cookieStorage = new CookieStorage(amplifyConfig.Auth.cookieStorage);
// cookie that is set before Cognito redirect to prevent infinite loop if authorization fails due to other reason than "No current user"
const redirectedFromAuthorize = cookieStorage.getItem("redirected-from-authorize");
...
Auth.currentAuthenticatedUser()
.then(user => {
setUser(user); // your custom function to do something with user attributes
// authorization was successfull, we can remove the redirect cookie
cookieStorage.removeItem("redirected-from-authorize");
})
.catch(err => {
console.error(err);
// if the cookie is set, it means the authorization failed again and you should not redirect back to Cognito
if (!redirectedFromAuthorize) {
// set redirect cookie, so that we know next time the error is reocurring
cookieStorage.setItem("redirected-from-authorize", 'true');
// redirect to Cognito hosted UI
return Auth.federatedSignIn();
}
});
I had this issue and I was able to sort it out by making the password of the user permanent with the command:
aws cognito-idp admin-set-user-password --user-pool-id us-east-1_XXX --username XXXXX --password XXXX --permanent
resolved
Togle "secure" to true in config:
Auth: {
region: "us-west-2",
userPoolId: "us-west-2_xxxxx",
userPoolWebClientId: "xxxxxx",
cookieStorage: {
domain: "localhost",
path: "/",
expires: 5,
secure: true, // <------------------------ true
},
It seems like I have my server set up according to the Apollo docs at http://dev.apollodata.com/tools/apollo-server/setup.html. In my server/main.js file:
//SET UP APOLLO INCLUDING APOLLO PUBSUB
const executableSchema = makeExecutableSchema({
typeDefs: Schema,
resolvers: Resolvers,
connectors: Connectors,
logger: console,
});
const GRAPHQL_PORT = 8080;
const graphQLServer = express();
// `context` must be an object and can't be undefined when using connectors
graphQLServer.use('/graphql', bodyParser.json(), apolloExpress({
schema: executableSchema,
context: {}, //at least(!) an empty object
}));
graphQLServer.use('/graphiql', graphiqlExpress({
endpointURL: '/graphql',
}));
graphQLServer.listen(GRAPHQL_PORT, () => console.log(
`GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}/graphql`
));
//SET UP APOLLO INCLUDING APOLLO PUBSUB
It prints out "GraphQL Server is now running on http://localhost:8080/graphql" to the terminal log indicating that the server was successfully initialized.
But at the top of my main_layout component, when I run this code:
import { Client } from 'subscriptions-transport-ws';
const wsClient = new Client('ws://localhost:8080');
...I get this console message:
WebSocket connection to 'ws://localhost:8080/' failed: Connection closed before receiving a handshake response
What am I missing?
You need to create a dedicated websocket server. It will run on a different port and the code to set it up is provided on the subscriptions-transport-ws package.
Take a look on the following code from GitHunt-API example:
https://github.com/apollostack/GitHunt-API/blob/master/api/index.js#L101-L134
Also you would see that this code is dependent on a class called SubscriptionManager. It is a class from a package called graphql-subscriptions also by the apollo team, and you can find an example of how to use it here:
https://github.com/apollostack/GitHunt-API/blob/master/api/subscriptions.js
TL;DR: You can use graphql-up to quickly get a GraphQL server with subscriptions support up and ready. Here's a more detailed tutorial on using this in combination with Apollo and the websocket client subscriptions-transport-ws.
Obtain a GraphQL Server with one click
Let's say you want to build a Twitter clone based on this GraphQL Schema in IDL syntax:
type Tweet {
id: ID!
title: String!
author: User! #relation(name: "Tweets")
}
type User {
id: ID!
name: String!
tweets: [Tweet!]! #relation(name: "Tweets")
}
Click this button to receive your own GraphQL API and then open the Playground, where you can add some tweets, query all tweets and also test out subscriptions.
Simple to use API
First, let's create a user that will be the author for all coming tweets. Run this mutation in the Playground:
mutation createUser {
createUser(name: "Tweety") {
id # copy this id for future mutations!
}
}
Here's how you query all tweets and their authors stored at your GraphQL server:
query allTweets {
allTweets {
id
title
createdAt
author {
id
name
}
}
}
Subscription support using websockets
Let's now subscribe to new tweets from "Tweety". This is the syntax:
subscription createdTweets {
Message(filter: {
mutation_in: [CREATED]
node: {
author: {
name: "Tweety"
}
}
}) {
node {
id
text
createdAt
sentBy {
id
name
}
}
}
}
Now create a new tab in the Playground and create a new Tweet:
mutation createTweet {
createTweet(
title: "#GraphQL Subscriptions are awesome!"
authorId: "<id-from-above>"
) {
id
}
}
You should see a new event popping up in your other tab where you subscribed before.
Here is a demo about using Apollo GraphQL, React & Hapi: https://github.com/evolastech/todo-react. It's less overwhelmed than GitHunt-React & GitHunt-API
Seems like you aren't actually making the websocket server. use SubscriptionServer. Keep in mind that it is absolutely NOT true that you have to have a dedicated websocket port (I thought this once too) as davidyaha says. I have both my normal queries and subs on the same port.
import { createServer } from 'http';
import { SubscriptionServer } from 'subscriptions-transport-ws';
import { execute, subscribe } from 'graphql';
import { schema } from './my-schema';
// All your graphQLServer.use() etc setup goes here, MINUS the graphQLServer.listen(),
// you'll do that with websocketServer:
// Create WebSocket listener server
const websocketServer = createServer(graphQLServer);
// Bind it to port and start listening
websocketServer.listen(3000, () => console.log(
`Server is now running on http://localhost:3000`
));
const subscriptionServer = SubscriptionServer.create(
{
schema,
execute,
subscribe,
},
{
server: websocketServer,
path: '/subscriptions',
},
);