How do i connect to csgo's community server? - server

So, I've been working on a bot and I've been stuck on this issue where my bot is not able to connect to the community server
Here is this code I've used:
const SteamUser = require('steam-user');
const steam = new SteamUser();
steam.logOn({
accountName: '',
password: ''
});
steam.on('loggedOn', () => {
console.log('We joinned steam');
steam.setPersona(SteamUser.EPersonaState.Online); // Makes steam online
steam.gamesPlayed(730); // Opens csgo
});
Is there any fixes?
I tried some fixing to the code using ChatGPT but I still get error
Here is the code provided by ChatGPT:
const { SteamClient } = require('steam-client');
const SteamUser = require('steam-user');
// Create a new Steam client and user objects
const client = new SteamClient();
const user = new SteamUser(client);
// Set your Steam username and password
const username = 'your_username';
const password = 'your_password';
// Authenticate with the Steam client
user.logOn({
accountName: username,
password: password
});
client.on('logOnResponse', () => {
console.log('Logged in to Steam!');
// Join a community server
client.joinCommunityServer('123.456.789.012', 27015);
console.log('Joined community server!');
// Disconnect from the server after 10 seconds
setTimeout(() => {
client.leaveCommunityServer();
console.log('Disconnected from community server.');
}, 10000);
});

Related

next-auth php hash legacy users

I am working on creating a next js application and have legacy user data I need to import from a word press site. The word press site had a signup with credential or a Facebook social login.
For the legacy data [credentials i.e email password] I wrote a script in [...nextauth.js] for logging in the user as follows.
CredentialsProvider({
name: 'Credentials',
credentials: {
email: { label: 'Email', type: 'email', placeholder: 'Email' },
password: {
label: 'Password',
type: 'password',
placeholder: 'Password',
},
},
async authorize(credentials, req) {
const len = 8;
const portable = true;
const phpversion = 9;
const hasher = new PasswordHash(portable, phpversion);
const encrypted_input = hasher.HashPassword(credentials.password);
await db.connect();
const user_raw = await LegacyUser.findOne({ email: credentials.email });
const user = JSON.parse(JSON.stringify(user_raw));
console.log(user.password);
await db.disconnect();
const valid = hasher.CheckPassword(credentials.password, user.password);
if (valid) {
console.log(user);
console.log('validPassword');
return user;
} else {
console.log('Passwords dont match');
return null;
}
},
})
Where db is the connection defined for all reads and writes to the mongo db and LegacyUser is the mongoose model defined. I test it out and so far so good.
Now I need to store the user session in the same db so I define database as the .env mongodb uri like bellow, including the mongodb adapter as in the documentation of next-auth:
adapter: MongoDBAdapter(clientPromise),
database: process.env.MONGODB_URI,
Now when I try to sign in again with the legacy password I don't get signed in and unfortunately I have no errors to show.
Only to point out that the console.log('validPassword'); of the CredentialsProvider does come through successfully.
I have been stuck on this issue for a few days, so any help is greatly appreciated.
Many thanks

Connect Metamask with a native mobile app built with Flutter

I want to connect the app to Metamask to get the user account and signature from the user to confirm the transaction. But the problem is that when I enter Metamask from the app, I am not asked any questions to confirm the connection and nothing happens inside Metamask, it is like only the Metamask app is opened and when I back up and return to the app, the null account is returned.
_walletConnect() async {
final connector = WalletConnect(
bridge: 'https://bridge.walletconnect.org',
clientMeta: const PeerMeta(
name: 'WalletConnect',
description: 'WalletConnect Developer App',
url: 'https://walletconnect.org',
icons: [
'https://gblobscdn.gitbook.com/spaces%2F-LJJeCjcLrr53DcT1Ml7%2Favatar.png?alt=media'
],
),
);
// Subscribe to events
connector.on('connect', (session) => print(session));
connector.on('session_update', (payload) => print(payload));
connector.on('disconnect', (session) => print(session));
// Create a new session
if (!connector.connected) {
session = await connector.createSession(
chainId: 97,
onDisplayUri: (uri) async => {print(uri), await launch(uri)});
}
setState(() {
account = session.accounts[0];
print(account);
});
if (account != null) {
final client = Web3Client(rpc, Client());
EthereumWalletConnectProvider provider =
EthereumWalletConnectProvider(connector);
credentials = WalletConnectEthereumCredentials(provider: provider);
yourContract = ethUtils.getDeployedContract(myAddress, client);
}
It sometimes happened to me as well.
I had just closed the MetaMask app and clicked on the button (Which triggered this function) and it worked fine.
I made a library for this, web3_connect, uses the same code and it gets the address back just fine for me

how to store user session into request object in expressjs

I am newbie in expressjs and read a very popular MERN project now.After an user(buyer) log into site and place an order which will be added into Mongodb tagged with the user(buyer),the backend code like below:
const addOrderItems = asyncHandler(async (req, res) => {
const {
orderItems,
shippingAddress,
paymentMethod,
itemsPrice,
taxPrice,
shippingPrice,
totalPrice,
} = req.body
if (orderItems && orderItems.length === 0) {
res.status(400)
throw new Error('No order items')
return
} else {
const order = new Order({
orderItems,
user: req.user._id,
shippingAddress,
paymentMethod,
itemsPrice,
taxPrice,
shippingPrice,
totalPrice,
})
const createdOrder = await order.save()
res.status(201).json(createdOrder)
}
})
Link:https://github.com/bradtraversy/proshop_mern/blob/master/backend/controllers/orderController.js
But where the req.user._id comes from?I check the whole project,some popular backend session or storage tools like express-session and cookie-sessiondid not installed and used.
It's comes from passport package. It will log user with JWT and populate the user property of the req object.

How can I register a Client through an express REST API in Hyperledger fabric

I want to register a user of the application through a REST API. I have already enrolled the admin and a user through the enrollAdmin.js and registerUser.js function but I want to call these functions through the node SDK and register users dynamically with there username (UUID) so that it's completly anonymous.
As the username I want to create a unique UUID and save that in the world state but also save that UUID on an off-chain database together with the personal information like password and name so that I can associate the personal information with the UUID.
Right know I'm confused by all the different steps I have to do to register a new user:
In what order do I have to enroll and register the user and should they all be defined in the express API or in chaincode?
This is my first approach of creating the REST Api and till now I have only defined the layout, the connection profile and wallet.
I would appreciate if somebody could help me implement the registration process in the express REST API so that an Identity for the UUID gets saved in the world state.
Thanks in advance.
server.js
'use strict';
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
// Setting for Hyperledger Fabric
const { Wallets, FileSystemWallet, Gateway } = require('fabric-network');
const path = require('path');
const fs = require('fs');
const channelName = 'mychannel';
const mspOrg1 = 'Org1MSP';
const walletPath = path.join(__dirname, '..', 'wallet');
const ccpPath = path.resolve(__dirname, '..', 'connection-org1.json');
//register
app.post('/api/register', async function (req, res) {
try{
// Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = new FileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);
} catch (error) {
}
});
//login
app.post('/api/login', async function (req, res) {
try{
// Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = new FileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);
} catch (error) {
}
});
app.listen(3000, ()=>{
console.log("***********************************");
console.log("API server listening at localhost:3000");
console.log("***********************************");
});
The process of how you want it to be is simple. In the middle, the off-chain database is used as a mapping table. I wrote only the core process logic.
/api/v1/register
validation check
Validate that the user's id is unique, that the required information value is missing, that the regular expression is correct, and that there is no wrong information.
generate random UUID
Create a random, unique uuid first. npm/uuid
const UUID = uuid.v4();
register/enroll user to fabric-ca
Perform the registration process as a user of the fabric. The information that goes into this process is UUID, and the user's information will not be stored in the blockchain.
fabricUser is a newly created class, and returns the result after fabric user registration and enroll process are performed by the Enroll method.
enrollment = await fabricUser.Enroll(UUID);
await wallet.put(enrollment);
insert to database
While saving the user information in the database, map it by storing the UUID created above.
The database was created as an example, assuming mongodb.
db.collection('User').insertOne({
'uuid': UUID,
'user_id': <input_user_id>,
...
});
/api/v1/login
The login process is as follows.
I don't know what authentication/authentication method you want to use, so I'll assume a token authentication method based on auth 2.0.
Verify the validity of the necessary information required for login and whether there is any incorrect information.
get UUID
generateAuthToken is a new function that generates JWT.
let res = await db.collection("User").findOne({'user_id': `<input_user_id>` });
return generateAuthToken(res.uuid);
/api/v1/invoke
Fabric resource request process is as follows.
Token validation and resource authorization check
get userName from token
getPayload is a function that gets the payload value located at the 1st index from the token.
const rawPayload = getPayload(token);
const jsonPayload = JSON.parse(rawPayload);
return jsonPayload
get wallet & invoke chaincode
The fabricChaincode is a function that wraps the invoke process of fabric-sdk. It is a function that executes invoke by inputting identity, chaincode information, and parameters, and returns a result.
const user = await db.collection("User").findOne({'user_id': jsonPayload.user_id });
const fabricIdentity = await wallet.get(user.uuid);
const res = fabricChaincode.invoke(fabricIdentity, `<your_chaincode_info>`, `<input_chaincode_params>`)
return res;
[EDIT]
Add it for your understanding.
fabricUser.js
/*
* Copyright IBM Corp. All Rights Reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
'use strict';
const { Wallets } = require('fabric-network');
const FabricCAServices = require('fabric-ca-client');
const fs = require('fs');
const path = require('path');
async function Enroll(user_id) {
try {
// load the network configuration
const ccpPath = path.resolve(__dirname, '..', '..', 'test-network', 'organizations', 'peerOrganizations', 'org1.example.com', 'connection-org1.json');
const ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'));
// Create a new CA client for interacting with the CA.
const caURL = ccp.certificateAuthorities['ca.org1.example.com'].url;
const ca = new FabricCAServices(caURL);
// Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = await Wallets.newFileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);
// Check to see if we've already enrolled the user.
const userIdentity = await wallet.get(user_id);
if (userIdentity) {
console.log(`An identity for the user ${user_id} already exists in the wallet`);
return;
}
// Check to see if we've already enrolled the admin user.
const adminIdentity = await wallet.get('admin');
if (!adminIdentity) {
console.log('An identity for the admin user "admin" does not exist in the wallet');
console.log('Run the enrollAdmin.js application before retrying');
return;
}
// build a user object for authenticating with the CA
const provider = wallet.getProviderRegistry().getProvider(adminIdentity.type);
const adminUser = await provider.getUserContext(adminIdentity, 'admin');
// Register the user, enroll the user, and import the new identity into the wallet.
const secret = await ca.register({
affiliation: 'org1.department1',
enrollmentID: user_id,
role: 'client'
}, adminUser);
const enrollment = await ca.enroll({
enrollmentID: user_id,
enrollmentSecret: secret
});
const x509Identity = {
credentials: {
certificate: enrollment.certificate,
privateKey: enrollment.key.toBytes(),
},
mspId: 'Org1MSP',
type: 'X.509',
};
await wallet.put(user_id, x509Identity);
console.log(`Successfully registered and enrolled admin user ${user_id} and imported it into the wallet`);
} catch (error) {
console.error(`Failed to register user ${user_id}: ${error}`);
process.exit(1);
}
}
module.exports = {
Enroll
}
api.js
const uuid = require('uuid');
const fabricUser = require('./fabricUser);
const UUID = uuid.v4();
let res = await fabricUser.Enroll(UUID);
console.log(res);

How to connect knex.js to PostgresSQL database?

Hi i'am trying to connect a database to server.js with Knex.js i have tried to add user as postgresql and i tried also to add host as localhost but that didn't work an i always get
Below is when i list all the databases!
Failed to load resource: the server responded with a status of 400 (Bad Request)
Below is a snapshot of my error when i tries to register me!
Below is my register.js that should help with the reigistering to the database!
const handleRegister = (req, res, db, bcrypt) => {
const { email, name, password } = req.body;
if (!email || !name || !password) {
return res.status(400).json('incorrect form submission');
}
const hash = bcrypt.hashSync(password);
db.transaction(trx => {
trx.insert({
hash: hash,
email: email
})
.into('login')
.returning('email')
.then(loginEmail => {
return trx('users')
.returning('*')
.insert({
email: loginEmail[0],
name: name,
joined: new Date()
})
.then(user => {
res.json(user[0]);
})
})
.then(trx.commit)
.catch(trx.rollback)
})
.catch(err => res.status(400).json('unable to register'))
}
module.exports = {
handleRegister: handleRegister
};
Here is my server.js file below!
const express = require('express');
const bodyParser = require('body-parser');
const bcrypt = require('bcrypt-nodejs');
const cors = require('cors');
const knex = require('knex');
const register = require('./controllers/register');
const signin = require('./controllers/signin');
const profile = require('./controllers/profile');
const image = require('./controllers/image');
const db = knex({
client: 'pg',
connection: {
host : 'localhost',
user : 'postgres',
database : 'smartbrain1'
}
});
const app = express();
app.use(cors())
app.use(bodyParser.json());
app.get('/', (req, res)=> { res.send(db.users) })
app.post('/signin', signin.handleSignin(db, bcrypt))
app.post('/register', (req, res) => { register.handleRegister(req, res, db, bcrypt) })
app.get('/profile/:id', (req, res) => { profile.handleProfileGet(req, res, db)})
app.put('/image', (req, res) => { image.handleImage(req, res, db)})
app.post('/imageurl', (req, res) => { image.handleApiCall(req, res)})
app.listen(3000, ()=> {
console.log('app is running on port 3000');
})
And here is my databases that i have created in postgreSQL in the terminal as a snapshot!
You should start by just trying to write standalone node app, that connects pg and runs a query. Then You can start integrating with other parts of your app when you know that connecting DB works as expected. Now the question has way too much irrelevant information.
First try to connect your SQL server from shell without using UNIX socket, but with TCP:
psql postgres://postgres#localhost/smartbrain1
If that fails, it probably means that your database is configured so that it does not allow any external TCP connections.
To allow access from localhost to postgres this should do it in pg_hba.conf by setting
host all all 127.0.0.1/32 trust
Also you may need to add password for your postgres user and try connecting with password enabled:
psql postgres://postgres:<password>#localhost/smartbrain1
When connecting from command line works you can try something like this in knex config:
const db = knex({
client: 'pg',
connection: 'postgres://postgres:<password>#localhost/smartbrain1'
});
Some more info for debugging this is found here Knex:Error Pool2 - error: password authentication failed for user and probably in tens of other generic postgres database connection problem questions.