how to connect proxies in the ccxt library? - proxy

I try to call a function (sell/buy, whatever) through a proxy, but it gives an error. What am I doing wrong?
account_binance = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True,
'options': {
'defaultType': 'spot'
},
'proxy': f'http://{login}:{password}#{ip}:3000'
})

Try this
account_binance = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True,
'options': {
'defaultType': 'spot'
},
'proxies': {
'http': 'http://myproxy.com:1080',
'https': 'http://myproxy.com:1080',
})

Related

How to call Redux-toolkit-query Manually on button click

i am using Redux-toolkit-query to fetch data from server. Now i want to call my query on button click,not automatically.I tried this but it's not working.
const { data, refetch } = useGetBuisnessAreasQuery({
enable: false,
refetchOnWindowFocus: false,
manual: true,
refetchOnReconnect: false,
});
You have to use the lazy query hook:
const [ trigger, { data } ] = api.endpoints.getBuisnessAreas.useLazyQuery()
const onClick = () => {
trigger()
}
This is how I did it, it's only cleaner:
in feature/service.ts:
export const authenticationApi = createApi({
reducerPath: 'myApi',
baseQuery: fetchBaseQuery({ baseUrl: baseUrl }),
endpoints: builder => ({
attemptLogin: builder.query({
query: (credentials) => ({
url: '/',
body: JSON.stringify(body)
})
})
})
})
export const { useLazyAttemptLoginQuery } = authenticationApi
and using it:
const [getAuthenticated, { data, isLoading, error }] = useLazyAttemptLoginQuery()

NextAuth credentials provider and Strapi - User only has email

I'm trying to use NextAuth and Strapi in my app, but NextAuth session only shows email for the user.
When I call the Strapi login API directly:
axios
.post(`${process.env.STRAPI_URL}/api/auth/local`, {
identifier: "email#provider.com",
password: "test123",
})
.then((response) => {
console.log("User profile", response.data.user);
})
I get this object (response.data.user) in console:
{
"id": 4,
"username": "theusername",
"email": "email#provider.com",
"provider": "local",
"confirmed": true,
"blocked": false,
"createdAt": "2022-09-18T17:02:43.581Z",
"updatedAt": "2022-09-27T16:39:22.993Z"
}
But when I try to sign in with NextAuth:
import axios from "axios";
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
export default NextAuth({
// Configure one or more authentication providers
providers: [
CredentialsProvider({
name: "Sign in with Email",
credentials: {
email: { label: "Email", type: "text" },
password: { label: "Password", type: "password" },
},
async authorize(credentials, req) {
// return (
if (credentials == null) return null;
try {
/* I tried `...rest` but no luck. also console log doesn't work here and I can't see the actual response from the API call */
const { user, jwt } =
(await axios
.post(
`${process.env.STRAPI_URL}/api/auth/local`,
{
identifier: credentials.email,
password: credentials.password,
}
)
.then((response) => {
return response.data;
})
.catch((error) => {
console.log(error.response);
throw new Error(error.response.data.message);
})) || null;
return { jwt, ...user };
} catch (error) {
console.warn(error);
// Sign In Fail
// return null;
}
// );
},
}),
],
callbacks: {
session: async ({ session, token }) => {
session.id = token.id;
session.jwt = token.jwt;
return Promise.resolve(session);
},
jwt: async ({ token, user }) => {
if (user) {
token.id = user.id;
token.jwt = user.jwt;
}
return Promise.resolve(token);
},
},
});
I only get email for the user:
{
"user": {
"email": "email#provider.com"
},
"expires": "2022-10-27T20:03:20.177Z",
"id": 4,
"jwt": "somejwtcodethatichangedhereforsecurity"
}
How can I have other properties, like username, in the user returned from NextAuth?
It's possible, by modifying callbacks:
callbacks: {
session: async ({ session, token }) => {
session.id = token.id;
session.jwt = token.jwt;
session.user.username = token.username /* added */
return Promise.resolve(session);
},
jwt: async ({ token, user }) => {
if (user) {
token.id = user.id;
token.jwt = user.jwt;
token.username = user.username /* added */
}
return Promise.resolve(token);
},
},

Django-Rest/Djoser JWT Verify returning 500 error

I'm having issues verifying if an access token is still valid. I'm using Django-Rest-Framework and Djoser.
I am sending to jwt/verify but it is returning a 500 error. jwt/create and jwt/refresh work without any issues. I've tested through Postman and through my app. Both come back with the 500 code. I followed this tutorial way back when but it appears to work in the tutorial and not on my end. I have changed some things since but haven't touched the djoser stuff.
Request
export const checkAuthenticated = () => async (dispatch) => {
const token = await AsyncStorage.getItem("access")
if (token) {
const config = {
headers: {
"Content-Type": "application/json",
},
};
const body = JSON.stringify({ token: token });
try {
const res = await axios.post(
`${REACT_APP_API_URL}/auth/jwt/verify/`,
body,
config
);
if (res.data.code !== "token_not_valid") {
dispatch({
type: AUTHENTICATED_SUCCESS,
});
} else {
dispatch({
type: AUTHENTICATED_FAIL,
});
}
} catch (err) {
dispatch({
type: AUTHENTICATED_FAIL,
});
}
} else {
dispatch({
type: AUTHENTICATED_FAIL,
});
}
};
Rest Framework and Djoser Settings - Settings.py
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated'
],
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}
AUTHENTICATION_BACKENDS = (
'social_core.backends.google.GoogleOAuth2',
'social_core.backends.facebook.FacebookOAuth2',
'django.contrib.auth.backends.ModelBackend'
)
SIMPLE_JWT = {
'AUTH_HEADER_TYPES': ('JWT',),
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'AUTH_TOKEN_CLASSES': (
'rest_framework_simplejwt.tokens.AccessToken',
)
}
DJOSER = {
'LOGIN_FIELD': 'email',
'USER_CREATE_PASSWORD_RETYPE': True,
'USERNAME_CHANGED_EMAIL_CONFIRMATION': True,
'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True,
'SEND_CONFIRMATION_EMAIL': True,
'SET_USERNAME_RETYPE': True,
'SET_PASSWORD_RETYPE': True,
'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}',
'USERNAME_RESET_CONFIRM_URL': 'email/reset/confirm/{uid}/{token}',
'ACTIVATION_URL': 'activate/{uid}/{token}',
# 'SEND_ACTIVATION_EMAIL': True,
'SOCIAL_AUTH_TOKEN_STRATEGY': 'djoser.social.token.jwt.TokenStrategy',
'SOCIAL_AUTH_ALLOWED_REDIRECT_URIS': ['http://localhost:3000/google', 'http://localhost:3000/facebook'],
'SERIALIZERS': {
'user_create': 'accounts.serializers.UserCreateSerializer',
'user': 'accounts.serializers.UserCreateSerializer',
'current_user': 'accounts.serializers.UserCreateSerializer',
'user_delete': 'djoser.serializers.UserDeleteSerializer',
}
}
urls.py
from django.contrib import admin
from django.urls import path, include, re_path
from django.views.generic import TemplateView
urlpatterns = [
path('admin/', admin.site.urls),
path('auth/', include('djoser.urls')),
path('auth/', include('djoser.urls.jwt')),
path('auth/', include('djoser.social.urls')),
path('', include('clients.urls')),
path('', include('assessments.urls'))
]

how can I find all of the indexes associated with an Elastic search alias?

using elastic search SDK https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html how can find all of the indexes associated with an Elastic search alias
We do have sdk method cat. aliases where I can iterate and find the associated indexes. But is there any other elegant method available to achieve the same?
You can pass the alias name (or array of names) as a parameter. Docs
const { Client } = require("#elastic/elasticsearch");
var client;
client = new Client({
node: "http://localhost:9200",
maxRetries: 5,
requestTimeout: 60000,
sniffOnStart: true,
});
client.cat
.aliases({ format: "json", name: "alias_name" })
.then((result) => {
console.log(result.body);
})
.catch((error) => {
console.log(error);
});
Output
[
{
alias: 'alias_name',
index: 'index_name',
filter: '-',
'routing.index': '-',
'routing.search': '-',
is_write_index: '-'
}
]
And if you want the index names only
const { Client } = require("#elastic/elasticsearch");
var client;
client = new Client({
node: "http://localhost:9200",
maxRetries: 5,
requestTimeout: 60000,
sniffOnStart: true,
});
client.cat
.aliases({ format: "json", name: "alias_name" })
.then((result) => {
const clean_indices = result.body.map(r => r.index)
console.log(clean_indices);
})
.catch((error) => {
console.log(error);
});
This is what I have come up with now.
const { Client } = require('#elastic/elasticsearch');
const async = require('async');
var client;
client = new Client({
"node": "http://localhost:9200",
"maxRetries": 5,
"requestTimeout": 60000,
"sniffOnStart": true
});
client.cat.aliases({format:"json"}).then((result) => {
let indexes={};
result.body.forEach(element => {
if(!indexes[element.alias]){
indexes[element.alias] = [];
}
indexes[element.alias].push(element.index);
});
console.log(JSON.stringify(indexes,null,2));
}).catch((error) => {
console.log(error)
});

how to connect two apps with socket.io

So I have one electron-express-socket.io app that runs all fine.
I now need to connect an EXPO app to the socket.io with ("socket.io-client").
They are on different ports.
Eelectron-express-socket.io = http://localhost:3000/
EXPO app = http://localhost:19006/
I've tried this
https://socket.io/docs/v2/handling-cors/
ELECTRON:
const socketio = require('socket.io');
class WebSocket {
socket = null
allClients = [];
socketOptions = {
'path': '/ws',
'pingInterval': 10000,
"handlePreflightRequest": (req, res) => {
res.writeHead(200, {
"Access-Control-Allow-Origin": "http://localhost:3000",
"Access-Control-Allow-Methods": "GET,POST",
"Access-Control-Allow-Headers": "my-custom-header",
"Access-Control-Allow-Credentials": false
});
res.end();
}
}
constructor(httpServer) {
//-------------------------------------------------------
// this.socket = socketio(httpServer, this.socketOptions);
//-------------------------------------------------------
this.socket = socketio();
this.socket.attach(httpServer, this.socketOptions);
//-------------------------------------------------------
this.socket.on('connection', (client) => {
this.onConnection(client);
});
this.socket.on('error', this.onClientError);
}
}
EXPO APP:
import socketIOClient from "socket.io-client";
const ENDPOINT = "http://localhost:3000/";
export default function App() {
//-- SocketIO
const [response, setResponse] = useState("");
useEffect(() => {
const socket = socketIOClient(ENDPOINT, {
withCredentials: false,
});
socket.on("currentTime", data => {
setResponse(data);
});
}, []);
//-- SocketIO
return (
<View style={styles.container}>
<Text>{response}Open up App.js to start working on your app!</Text>
<StatusBar style="auto" />
</View>
);
}
I've also tired
socketOptions = {
'path': '/ws',
'pingInterval': 10000,
"handlePreflightRequest": (req, res) => {
res.writeHead(200, {
"Access-Control-Allow-Origin": "http://localhost:3000",
"Access-Control-Allow-Methods": "GET,POST",
"Access-Control-Allow-Headers": "my-custom-header",
"Access-Control-Allow-Credentials": true
});
res.end();
}
}
and
const socket = socketIOClient(ENDPOINT, {
withCredentials: true,
transportOptions: {
polling: {
extraHeaders: {
"my-custom-header": "abcd"
}
}
}
});
All I had to do was change EXPO to socket to this:
const socket = socketIOClient(ENDPOINT,{
path: '/ws',
});

Resources