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

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);

Related

How do i connect to csgo's community 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);
});

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

Android Enterprises Device Enrollment Stuck with NodeJs Generated QR Code with Service Account Authentication

As mentioned in the google documents i have tested the following process
URL to quick start: https://colab.research.google.com/github/google/android-management-api-samples/blob/master/notebooks/quickstart.ipynb#scrollTo=pjHfDSb8BoBP
Create Enterprise
Create Policy
Enroll the device
Then I have used the NODEJS API of Android Enterprises to develop the server based solution, which is working fine as per the documentation for all the functions such as get, create, delete the policy, devices, enterprises.
The issue i am facing is with the QR code generated from NODE application, when i scan the QR code generated from NODEJS application, the device got stuck at system update.
Following is my Policy update function
router.post('/update/:id', async function(req, res) {
const {title,policy_body,update_mask,enroll_url} = req.body;
// here we are callng the android managment API to and then the response we will update to database
const amApiBody = {
name: policy_body.name,
updateMask:update_mask,
requestBody:policy_body
}
const policy_update_response = await amApi.updatePolicy(amApiBody);
const p = await policyModel.update(req.params.id,title,policy_update_response,enroll_url);
res.json(p)
});
AmAPI file
this.updatePolicy = async function (body)
{
const auth = new google.auth.GoogleAuth({
scopes: ['https://www.googleapis.com/auth/androidmanagement'],
});
const authClient = await auth.getClient();
google.options({auth: authClient});
// Get the list of available policies
const res = await androidmanagement.enterprises.policies.patch(body);
console.log('requestFinalBody=',body);
return res.data;
}
Following is my policy data obtained by running above function
policy_create_response= {
name: 'enterprises/LC019rjnor/policies/policy1',
version: '14',
applications: [
{
packageName: 'com.google.samples.apps.iosched',
installType: 'FORCE_INSTALLED',
autoUpdateMode: 'AUTO_UPDATE_HIGH_PRIORITY'
},
{
packageName: 'com.dekaisheng.courier',
installType: 'FORCE_INSTALLED',
autoUpdateMode: 'AUTO_UPDATE_HIGH_PRIORITY'
}
],
keyguardDisabledFeatures: [ 'KEYGUARD_DISABLED_FEATURE_UNSPECIFIED' ],
defaultPermissionPolicy: 'GRANT',
uninstallAppsDisabled: true,
keyguardDisabled: true,
tetheringConfigDisabled: true,
dataRoamingDisabled: true,
networkEscapeHatchEnabled: true,
bluetoothDisabled: true,
debuggingFeaturesAllowed: true,
funDisabled: true,
kioskCustomLauncherEnabled: true
}
Note i have exported the variable to the terminal as follows before running the app, the auth.json is the service account credential file.
export GOOGLE_APPLICATION_CREDENTIALS="/Users/Mac/Projects/wajid/mdm/server/env/auth.json"
Thanks for the help in advance
I figured out that in nodeJS API I was passing wrong property name of Policy value in the request body.
Code before fix
parent: this.getParent(policyName),
requestBody:{
“name”: “my_policy"
}
Code after fix
parent: this.getParent(policyName),
requestBody:{
"policyName”: “my_policy"
}

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.

Why isn't my Firebase app connecting to Google Secret Manager?

I can't figure out why I keep getting the error: Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
firebase login from my command line returns that I am already logged in and
I have configured my-app#appspot.gserviceaccount.com to be a Secret Manager Secret Accessor in the GCP IAM admin dashboard within the same project.
Here's the code I'm using:
const { SecretManagerServiceClient } = require("#google-cloud/secret-manager");
const client = new SecretManagerServiceClient();
const gcpSecretsLoader = async (secretName: string) => {
try {
const secret = await client.accessSecretVersion({
name: `projects/my-app/secrets/${secretName}/versions/latest`,
});
const payload = secret.payload.data.toString("utf8");
console.info(`Payload: ${payload}`);
} catch (err) {
console.log(err);
}
};
gcpSecretsLoader("CLIENT_ID"); // CLIENT_ID matched a secret name within the secret manager