Add Service worker to a vuejs/firebase web application - node.js

am tryind to add a service worker to my vuejs application. and this is what i get:
ServiceWorker registration failed: TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script.
i have searching a lot but i can't figure out where the problem is.
the reason of adding a service worker is to save the Token of any device logged in the app and be able to send them notification.
in index.html : static/manifest.json">
// app.js
var config = {
apiKey: '',
authDomain: '',
databaseURL: '',
projectId: '',
storageBucket: '',
messagingSenderId: ''
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
let userToken = null,
isSubscribed = false
window.addEventListener('load', () => {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register("firebase-messaging-sw.js", {scope: "firebase-cloud-messaging-push-scope"}).then(function (registration) {
const messaging = firebase.messaging();
messaging.useServiceWorker(registration);
}).catch(function (err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
})
} else {
}
});
messaging.requestPermission().then(function() {
//getToken(messaging);
return messaging.getToken();
}).then(function(token){
console.log(token);
})
.catch(function(err) {
console.log('Permission denied', err);
});
messaging.onMessage(function(payload){
console.log('onMessage: ',payload);
});
// firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js');
self.addEventListener('notificationclick', event => {
console.log(event)
event.notification.close()
event.waitUntil(
self.clients.openWindow('/')
)
})
var config = {
apiKey: '',
authDomain: '',
databaseURL: '',
projectId: '',
storageBucket: '',
messagingSenderId: ''
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
//manifest.json
{
"name": "Du",
"short_name": "Du",
"icons": [
{
"src": "/static/img/icons/cro-icon-64x64.png",
"sizes": "64x64",
"type": "image/png"
},
{
"src": "/static/img/icons/cro-icon-128x128.png",
"sizes": "128x128",
"type": "image/png"
}
],
"start_url": "/",
"display": "fullscreen",
"orientation": "portrait",
"background_color": "#2196f3",
"theme_color": "#2196f3",
"gcm_sender_id": ""
}
console project folder console2

Related

Problem with CORS in Nest.js app after deployment on Vercel

POST request in my Nest.js app not working after deployment on Vercel and I receive CORS error, but cors in my app is enable and when I send GET request all working. When I test my request in postman all working. I am not sure but maybe this error can happen through that I use React Query or problem with vercel and I not right deployment my app.
I receive such error:
Access to XMLHttpRequest at 'https://server-store.vercel.app/api/auth/login' from origin 'https://next-store-liard-three.vercel.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
And I enabled CORS such method:
app.enableCors({
origin: ['http://localhost:3000', 'https://next-store-liard-three.vercel.app'],
allowedHeaders: ['Accept', 'Content-Type'],
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
preflightContinue: false,
optionsSuccessStatus: 204,
credentials: true,
});
This is my file vercel.json:
{
"version": 2,
"name": "next-store-server",
"buildCommand": "npm start",
"installCommand": "npm install",
"builds": [
{
"src": "dist/main.js",
"use": "#vercel/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "dist/main.js",
"methods": ["GET", "POST", "PATCH", "PUT", "DELETE"]
}
]
}
Also I try enable CORS other way, but it is not help me.
I try enable CORS, such method:
const app = await NestFactory.create(AppModule, { cors: true });
On client I using Next.js, reactQuery and axios for sending request
import axios from "axios";
import { FAuth, IUser } from "./Auth.types";
const AuthService = {
async registration(dto: IUser) {
const { data } = await axios.post<FAuth>(
`${process.env.NEXT_PUBLIC_SERVER_API_URL}/api/auth/registration`,
dto,
);
return data;
},
async login(dto: IUser) {
const { data } = await axios.post<FAuth>(`${process.env.NEXT_PUBLIC_SERVER_API_URL}/api/auth/login`, dto);
return data;
},
};
This my custom useMutation hooks
export const useRegistration = () =>
useMutation((dto: Omit<IUser, "_id">) => AuthService.registration(dto), {
onSuccess: () => {
toast.success("Success", {
theme: "colored",
});
},
onError: (data: any) => {
toast.error(data.response.data.message, {
theme: "colored",
});
},
});
export const useLogin = () =>
useMutation((dto: Omit<IUser, "_id">) => AuthService.login(dto), {
onSuccess: () => {
toast.success("Success", {
theme: "colored",
});
},
onError: (data: any) => {
toast.error(data.response.data.message, {
theme: "colored",
});
},
});
Try to add "OPTIONS" into methods, this worked for me
vercel.json:
{
"version": 2,
"builds": [{ "src": "src/main.ts", "use": "#vercel/node" }],
"routes": [
{
"src": "/(.*)",
"dest": "src/main.ts",
"methods": ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]
}
]
}

Deploy Angular App w/ Proxy for One Route

I have an Angular app w/ a proxy that's working well in local. There's one route that utilizes it with a Node API call.
Node.js
const express = require('express');
const api_service = require('./apiService');
const app = express();
app.get('/getData/:date', (req, res) => {
const date = req.params.date;
api_service.fetchData(...)
.then(response => {
res.json(response)
})
.catch(error => {
res.send(error)
})
})
app.listen(3000, () => {
console.log("Server started in port 3000!");
});
Function in my Angular Service:
fetchData(date: string) {
const requestOptions: Object = {
responseType: 'text',
};
this._http
.get<string>('/api/getData/' + date)
.pipe(
map((data) => {
this.result = data;
})
)
.subscribe((data) => {
this.mediaSource.next(this.result);
if (Object.keys(this.result).length != 0) {
this.history.push(this.result);
}
});
}
proxy-prod.config.json
{
"/api/*": {
"target": "https://example.com",
"secure": false,
"changeOrigin": true,
"logLevel": "debug",
"pathRewrite": { "^/api": "" }
}
}
proxy-local.conf.json
{
"/api/*": {
"target": "http://localhost:3000",
"pathRewrite": {
"^/api": ""
},
"secure": false,
"changeOrigin": true,
"logLevel": "debug"
}
}
angular.json
"serve": {
"builder": "#angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "ui-dev:build",
"proxyConfig": "proxy-local.conf.json"
},
"configurations": {
"production": {
"browserTarget": "ui-dev:build:production",
"proxyConfig": "proxy-prod.config.json"
}
}
},
ng serve works perfectly.
ng serve --prod and ng build --aot --prod --output-hashing none do not.
The error I'm getting is:
headers: d, status: 200, statusText: 'OK', url: 'myexample.com', ok: false
I've tried this in my request but they cause errors too:
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
{ headers, responseType: 'text'}
Been searching, testing, and dissecting code for many hours and not sure how to proceed. Can you anyone assist?
Thanks

Trouble connecting express api to nuxt app and mongodb

It's been seriously 10 days since i'm trying to deploy my web app online. i've gone back and forth between heroku and digital ocean. nothing solved. i've asked questions here all i get is a long post with technical terms i' not able to understand. Here's my problem :
i have a nuxt app with express.js in the backend and mongodb as the database. At first i had trouble with configuring host and port for my nuxt app. once i fixed it, anoither problem appeared : i'm not receiving data from the database. i don't if it's something related to database connection or with the express api configuration.
here's my nuxt config
export default {
ssr: false,
head: {
titleTemplate: 'Lokazz',
title: 'Lokazz',
meta: [
{ charset: 'utf-8' },
{
name: 'viewport',
content: 'width=device-width, initial-scale=1'
},
{
hid: 'description',
name: 'description',
content:
'Lokazz'
}
],
link: [
{
rel: 'stylesheet',
href:
'https://fonts.googleapis.com/css?family=Work+Sans:300,400,500,600,700&amp;subset=latin-ext'
}
]
},
css: [
'swiper/dist/css/swiper.css',
'~/static/fonts/Linearicons/Font/demo-files/demo.css',
'~/static/fonts/font-awesome/css/font-awesome.css',
'~/static/css/bootstrap.min.css',
'~/assets/scss/style.scss'
],
plugins: [
{ src: '~plugins/vueliate.js', ssr: false },
{ src: '~/plugins/swiper-plugin.js', ssr: false },
{ src: '~/plugins/vue-notification.js', ssr: false },
{ src: '~/plugins/axios.js'},
{ src: '~/plugins/lazyLoad.js', ssr: false },
{ src: '~/plugins/mask.js', ssr: false },
{ src: '~/plugins/toastr.js', ssr: false },
],
buildModules: [
'#nuxtjs/vuetify',
'#nuxtjs/style-resources',
'cookie-universal-nuxt'
],
styleResources: {
scss: './assets/scss/env.scss'
},
modules: ['#nuxtjs/axios', 'nuxt-i18n','vue-sweetalert2/nuxt', '#nuxtjs/auth-next', "bootstrap-vue/nuxt"],
bootstrapVue: {
bootstrapCSS: false, // here you can disable automatic bootstrapCSS in case you are loading it yourself using sass
bootstrapVueCSS: false, // CSS that is specific to bootstrapVue components can also be disabled. That way you won't load css for modules that you don't use
},
i18n: {
locales: [
{ code: 'en', file: 'en.json' },
],
strategy: 'no_prefix',
fallbackLocale: 'en',
lazy: true,
defaultLocale: 'en',
langDir: 'lang/locales/'
},
router: {
linkActiveClass: '',
linkExactActiveClass: 'active',
},
server: {
port: 8080, // default: 3000
host: '0.0.0.0' // default: localhost
},
auth: {
strategies: {
local: {
token: {
property: "token",
global: true,
},
redirect: {
"login": "/account/login",
"logout": "/",
"home": "/page/ajouter-produit",
"callback": false
},
endpoints: {
login: { url: "/login", method: "post" },
logout: false, // we don't have an endpoint for our logout in our API and we just remove the token from localstorage
user:false
}
}
}
},
};
here's my package.json
{
"name": "martfury_vue",
"version": "1.3.0",
"description": "Martfury - Multi-purpose Ecomerce template with vuejs",
"author": "nouthemes",
"private": true,
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"start": "nuxt start",
"generate": "nuxt generate"
},
"config": {
"nuxt": {
"host": "0.0.0.0",
"port": "8080"
}
},
}
here's my repository.js file
import Cookies from 'js-cookie';
import axios from 'axios';
const token = Cookies.get('id_token');
const baseDomain = 'https://lokazzfullapp-8t7ec.ondigitalocean.app';
export const customHeaders = {
'Content-Type': 'application/json',
Accept: 'application/json'
};
export const baseUrl = `${baseDomain}`;
export default axios.create({
baseUrl,
headers: customHeaders
});
export const serializeQuery = query => {
return Object.keys(query)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(query[key])}`)
.join('&');
};
an example of an api call i make locally that works without a problem :
import Repository, { serializeQuery } from '~/repositories/Repository.js';
import { baseUrl } from '~/repositories/Repository';
import axios from 'axios'
const url = baseUrl;
export const actions = {
async getProducts({ commit }, payload) {
const reponse = await axios.get(url)
.then(response => {
commit('setProducts', response.data);
return response.data;
})
.catch(error => ({ error: JSON.stringify(error) }));
return reponse;
},
}
here's my index.js (express file)
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose')
const cors = require('cors');
//const url = 'mongodb://localhost:27017/lokazz'
const url = 'mongodb+srv://lokazz:zaki123456#cluster0.hsd8d.mongodb.net/lokazz?retryWrites=true&w=majority'
const jwt = require('jsonwebtoken')
const con = mongoose.connection
mongoose.connect(url, {useNewUrlParser:true}).then(()=>{
const app = express();
// middlleware
app.use(express.json())
app.use(cors());
//products routes
const products = require('./product/product.router');
app.use('/', products)
//users routes
const users = require('./user/user.router');
app.use('/', users)
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
}).catch(error => console.log(error.reason));
con.on('open', () => {
console.log('connected...')
})
My directory structure
the error i get after the api request, meaning it's not receving any data.
ebd1ecd.js:2 TypeError: Cannot read properties of undefined (reading 'username')
at f.<anonymous> (c88240c.js:1)
at f.t._render (ebd1ecd.js:2)
at f.r (ebd1ecd.js:2)
at wn.get (ebd1ecd.js:2)
at new wn (ebd1ecd.js:2)
at t (ebd1ecd.js:2)
at f.In.$mount (ebd1ecd.js:2)
at init (ebd1ecd.js:2)
at ebd1ecd.js:2
at v (ebd1ecd.js:2)
idk if it's a problem with mongodb connection cluster or the api call.

How to deploy API gateway, Lambda(Node.js) and DynamoDB using SAM CLI?

I am trying to create an application in my local system and deploy it to the AWS cloud using SAM CLI. The basic outline of this application is given in the diagram.
I have created a directory named myproj for this application and all the sub-folders and files are shown in the following diagram.
The template.yaml file consists of the following code -
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
myDB:
Type: AWS::Serverless::SimpleTable
Properties:
TableName: tabmine
PrimaryKey:
Name: id
Type: String
ProvisionedThroughput:
ReadCapacityUnits: 5
WriteCapacityUnits: 5
LambdaWrite:
Type: AWS::Serverless::Function
Properties:
CodeUri: functionWrite/
Handler: write.handler
Runtime: nodejs12.x
Events:
apiForLambda:
Type: Api
Properties:
Path: /writedb
Method: post
Policies:
DynamoDBWritePolicy:
TableName: !Ref myDB
LambdaRead:
Type: AWS::Serverless::Function
Properties:
CodeUri: functionRead/
Handler: read.handler
Runtime: nodejs12.x
Events:
apiForLambda:
Type: Api
Properties:
Path: /readdb
Method: post
Policies:
DynamoDBReadPolicy:
TableName: !Ref myDB
In the functionRead folder, package.json has the following contents -
{
"name": "myproj",
"version": "1.0.0",
"description": "",
"main": "read.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"aws-sdk": "^2.783.0"
}
}
And the read.js file contains the following code -
var AWS = require('aws-sdk');
var ddb = new AWS.DynamoDB.DocumentClient();
exports.handler = function(event, context, callback) {
var ID = event.id;
var params = {
TableName: 'tabmine',
Key: {
'id': ID
}
};
ddb.get(params, callback);
};
In functionWrite folder, the file package.json has the following content -
{
"name": "myproj",
"version": "1.0.0",
"description": "",
"main": "write.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"aws-sdk": "^2.783.0"
}
}
And the file write.js has the following content -
var AWS = require('aws-sdk');
var ddb = new AWS.DynamoDB.DocumentClient();
exports.handler = function(event, context, callback) {
var ID = event.id;
var NAME = event.name;
var params = {
TableName: 'tabmine',
Item: {
'id': ID,
'name': NAME
}
};
ddb.put(params, callback);
};
Then, I have navigated back to the myproj directory in the terminal and ran the command sam build.
After building was done, I ran the command sam deploy --guided and followed the steps to deploy the stack to the cloud. Then, I checked the console to confirm the deployment and it was successful.
Then, in the terminal, I ran curl -X POST -d '{"id":"one","name":"john"}' https://0000000000.execute-api.ap-south-1.amazonaws.com/Prod/writedb. But I got {message : 'Internal server Error'}.
To confirm if the lambda and dynamoDB are correctly linked or not, I went to Lambda console and created a test event for the lambda function with name write.js with the same payload {"id":"one","name":"john"}.It ran successfully and entered the those two items into the dyanmoDB table. Similarly, I have created another test event for the lambda function with name read.js and with payload {"id":"one"}. It also ran successfully and displayed the datas.
To confirm if the API gateway and the lambdas are are correctly linked or not, I ran the test in API gateway for both the resources /writedb and /readdb, but it is giving me {message : 'Internal server Error'}.
Please help me out of this problem.
The event object that will come from the API gateway invocation will have the following structure -
{
resource: '/func1',
path: '/func1',
httpMethod: 'POST',
headers: {
accept: '*/*',
'content-type': 'application/x-www-form-urlencoded',
Host: '0000000000.execute-api.ap-south-1.amazonaws.com',
'User-Agent': 'curl/7.71.1',
'X-Amzn-Trace-Id': 'Root=1-5fa018aa-60kdfkjsddd5f6c6c07a2',
'X-Forwarded-For': '178.287.187.178',
'X-Forwarded-Port': '443',
'X-Forwarded-Proto': 'https'
},
multiValueHeaders: {
accept: [ '*/*' ],
'content-type': [ 'application/x-www-form-urlencoded' ],
Host: [ '0000000000.execute-api.ap-south-1.amazonaws.com' ],
'User-Agent': [ 'curl/7.71.1' ],
'X-Amzn-Trace-Id': [ 'Root=1-5fa018aa-603d90fhgdhdgdjhj6c6dfda2' ],
'X-Forwarded-For': [ '178.287.187.178' ],
'X-Forwarded-Port': [ '443' ],
'X-Forwarded-Proto': [ 'https' ]
},
queryStringParameters: null,
multiValueQueryStringParameters: null,
pathParameters: null,
stageVariables: null,
requestContext: {
resourceId: 'scsu6k',
resourcePath: '/func1',
httpMethod: 'POST',
extendedRequestId: 'VYjfdkjkjfjkfuA=',
requestTime: '02/Nov/2020:14:33:14 +0000',
path: '/test/func1',
accountId: '00000000000',
protocol: 'HTTP/1.1',
stage: 'test',
domainPrefix: 'f8h785q05a',
requestTimeEpoch: 1604327594697,
requestId: '459e0256-9c6f-4a24-bcf2-05520d6bc58a',
identity: {
cognitoIdentityPoolId: null,
accountId: null,
cognitoIdentityId: null,
caller: null,
sourceIp: '178.287.187.178',
principalOrgId: null,
accessKey: null,
cognitoAuthenticationType: null,
cognitoAuthenticationProvider: null,
userArn: null,
userAgent: 'curl/7.71.1',
user: null
},
domainName: '000000000.execute-api.ap-south-1.amazonaws.com',
apiId: 'lkjfslkfj'
},
body: '{"id":"1","name":"John"}',
isBase64Encoded: false
}
From the above event which is JSON object, we need the body. Since, the body is a string, so we need to convert it into JSON object.
So, write.js should be modified to -
var AWS = require('aws-sdk');
var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'});
exports.handler = async (event) => {
try {
//console.log(event);
//console.log(event.body);
var obj = JSON.parse(event.body);
//console.log(obj.id);
//console.log(obj.name);
var ID = obj.id;
var NAME = obj.name;
var params = {
TableName:'tabmine',
Item: {
id : {S: ID},
name : {S: NAME}
}
};
var data;
var msg;
try{
data = await ddb.putItem(params).promise();
console.log("Item entered successfully:", data);
msg = 'Item entered successfully';
} catch(err){
console.log("Error: ", err);
msg = err;
}
var response = {
'statusCode': 200,
'body': JSON.stringify({
message: msg
})
};
} catch (err) {
console.log(err);
return err;
}
return response;
};
Similarly, read.js will get modified to -
var AWS = require('aws-sdk');
var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'});
exports.handler = async (event) => {
try {
//console.log(event);
//console.log(event.body);
var obj = JSON.parse(event.body);
//console.log(obj.id);
//console.log(obj.name);
var ID = obj.id;
var params = {
TableName:'tabmine',
Key: {
id : {S: ID}
}
};
var data;
try{
data = await ddb.getItem(params).promise();
console.log("Item read successfully:", data);
} catch(err){
console.log("Error: ", err);
data = err;
}
var response = {
'statusCode': 200,
'body': JSON.stringify({
message: data
})
};
} catch (err) {
console.log(err);
return err;
}
return response;
};
So, this will solve the problem. And template.yaml file is also correct.

Getting error while doing users registration in fabric using SDK

I am trying to register the multiple user at one time however I am getting error while doing it as
"error: [FabricCAClientService.js]: Failed to enroll 0006, error:%o message=Enrollment failed with errors [[{"code":20,"message":"Authentication failure"}]], stack=Error: Enrollment failed with errors [[{"code":20,"message":"Authentication failure"}]]
at IncomingMessage.response.on (/vagrant/Dfarm-app/node/node_modules/fabric-ca-client/lib/FabricCAClient.js:470:22)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:139:11)
at process._tickCallback (internal/process/next_tick.js:181:9)
Failed to register user: Error: Enrollment failed with errors [[{"code":20,"message":"Authentication failure"}]]"
I am trying to implement with one user its running fine we I am trying to implement with multiple user its giving error.
Can anyone suggest me how can multiple user can register in Blockchain.
Please see below registerUser.js file
'use strict';
const { FileSystemWallet, Gateway, X509WalletMixin } = require('fabric-network');
const fs = require('fs');
const path = require('path');
// capture network variables from config.json
// var configPath = path.join(process.cwd(), 'config.json');
// const configJSON = fs.readFileSync(configPath, 'utf8');
var configJSON = fs.readFileSync('config.json');
var config = JSON.parse(configJSON);
var connection_file = config.connection_file;
var appAdmin = config.appAdmin;
var orgMSPID = config.orgMSPID;
var userName = config.userName;
var gatewayDiscovery = config.gatewayDiscovery;
const ccpPath = path.join(process.cwd(), connection_file);
const ccpJSON = fs.readFileSync(ccpPath, 'utf8');
const ccp = JSON.parse(ccpJSON);
async function main() {
try {
var userDetails = config.userDetails;
// console.log('test', userDetails)
// 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}`);
// Check to see if we've already enrolled the user.
for(var i=0; i< userDetails.length;i++){
// console.log('test',walletPath)
let userExists = await wallet.exists(userDetails[i].userName);
if (userExists) {
// console.log('test',userDetails[0].userName)
console.log(`An identity for the user ${userDetails[i].userName} already exists in the wallet`);
return;
}
}
// console.log('test',walletPath)
// Check to see if we've already enrolled the admin user.
const adminExists = await wallet.exists(appAdmin);
if (!adminExists) {
console.log(`An identity for the admin user ${appAdmin} does not exist in the wallet`);
console.log('Run the enrollAdmin.js application before retrying');
return;
}
// Create a new gateway for connecting to our peer node.
const gateway = new Gateway();
await gateway.connect(ccp, { wallet, identity: appAdmin, discovery: gatewayDiscovery });
// Get the CA client object from the gateway for interacting with the CA.
const ca = gateway.getClient().getCertificateAuthority();
const adminIdentity = gateway.getCurrentIdentity();
// Register the user, enroll the user, and import the new identity into the wallet.
for(var i=0; i< userDetails.length;i++){
var secret = await ca.register({ enrollmentID:userDetails[i].enrollmentID,userName:userDetails[i].userName, role:userDetails[i].role }, adminIdentity);
var enrollment = await ca.enroll({ enrollmentID:userDetails[i].enrollmentID, enrollmentSecret: userDetails[i].enrollmentSecret });
var userIdentity = X509WalletMixin.createIdentity(orgMSPID, enrollment.certificate, enrollment.key.toBytes());
wallet.import(userDetails[i].userName, userIdentity);
console.log('Successfully registered and enrolled admin user ' + userDetails[i].userName + ' and imported it into the wallet');
}
} catch (error) {
console.error(`Failed to register user: ${error}`);
process.exit(1);
}
}
main();
The config.json file
{
"connection_file": "connection.json",
"appAdmin": "admin",
"appAdminSecret": "adminpw",
"orgMSPID": "DfarmadminMSP",
"caName": "ca.dfarmadmin.com",
"userDetails": [{"username":"user1","enrollmentID":"0006","role":"client","enrollmentSecret": "1234"},
{"username":"user2", "enrollmentID":"0002","role":"client","enrollmentSecret": "abcs" },
{"username":"user3", "enrollmentID":"0003","role":"client","enrollmentSecret": "9807" },
{"username":"user4","enrollmentID":"0004","role":"client","enrollmentSecret": "abcd" }
],
"gatewayDiscovery": { "enabled": false }
}
The connection.json file
{
"name": "basic-network",
"version": "1.0.0",
"client": {
"tlsEnable": false,
"adminUser": "admin",
"adminPassword": "adminpw",
"enableAuthentication": false,
"organization": "dfarmadmin",
"connection": {
"timeout": {
"peer": {
"endorser": "300"
},
"orderer": "300"
}
}
},
"channels": {
"dfarmchannel": {
"orderers": [
"orderer.dfarmadmin.com"
],
"peers": {
"peer0.dfarmadmin.com": {
"endorsingPeer": true,
"chaincodeQuery": true,
"ledgerQuery": true,
"eventSource": true
},
"connection": {
"timeout": {
"peer": {
"endorser": "6000",
"eventHub": "6000",
"eventReg": "6000"
}
}
},
"peer0.dfarmretail.com": {
"endorsingPeer": false,
"chaincodeQuery": true,
"ledgerQuery": true,
"eventSource": false
}
}
}
},
"organizations": {
"dfarmadmin": {
"mspid": "DfarmadminMSP",
"peers": [
"peer0.dfarmadmin.com"
],
"certificateAuthorities": [
"ca.dfarmadmin.com"
]
},
"dfarmretail": {
"mspid": "DfarmretailMSP",
"peers": [
"peer0.dfarmretail.com"
],
"certificateAuthorities": [
"ca.dfarmadmin.com"
]
}
},
"orderers": {
"orderer.dfarmadmin.com": {
"url": "grpc://localhost:7050",
"eventUrl": "grpc://localhost:7053"
}
},
"peers": {
"peer0.dfarmadmin.com": {
"url": "grpc://localhost:7051"
},
"peer0.dfarmretail.com": {
"url": "grpc://localhost:8051"
}
},
"certificateAuthorities": {
"ca.dfarmadmin.com": {
"url": "http://localhost:7054",
"caName": "ca.dfarmadmin.com"
}
}
}
AdminIdentiy console
adminIdentity User {
_name: 'admin',
_roles: null,
_affiliation: '',
_enrollmentSecret: '',
_identity:
Identity {
_certificate: '-----BEGIN CERTIFICATE-----\nMIIB/jCCAaSgAwIBAgIUdrt0WjnSmGsX1WuBWvXVTizqFKUwCgYIKoZIzj0EAwIw\nbzELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNh\nbiBGcmFuY2lzY28xFzAVBgNVBAoTDmRmYXJtYWRtaW4uY29tMRowGAYDVQQDExFj\nYS5kZmFybWFkbWluLmNvbTAeFw0xOTA4MTQxMTEyMDBaFw0yMDA4MTMxMTE3MDBa\nMCExDzANBgNVBAsTBmNsaWVudDEOMAwGA1UEAxMFYWRtaW4wWTATBgcqhkjOPQIB\nBggqhkjOPQMBBwNCAARXptenPPGpVnJsEFv0wmJeybDYNoClJCyAv3GcRPb04WLR\nAynEoSXf+jwYIjypV98oeR127haGcDo7jHUn0DnBo2wwajAOBgNVHQ8BAf8EBAMC\nB4AwDAYDVR0TAQH/BAIwADAdBgNVHQ4EFgQUW1YmLO6OaZB7FwXv6Gu7yc9jhNMw\nKwYDVR0jBCQwIoAgeD1bXE22u42++Y2v96xX+EKLzk8JkEcheGl5g8XGRkkwCgYI\nKoZIzj0EAwIDSAAwRQIhALluXWayFpylTOLCDIp925yn0rrtl77D/rM8AkOksTsE\nAiAEQ+w5pElSLFBINH/c0N1CgGN1snsdK1LRkUNjCk29Fg==\n-----END CERTIFICATE-----\n',
_publicKey: ECDSA_KEY { _key: [Object] },
_mspId: 'DfarmadminMSP',
_cryptoSuite:
CryptoSuite_ECDSA_AES {
_keySize: 256,
_hashAlgo: 'SHA2',
_cryptoKeyStore: [Object],
_curveName: 'secp256r1',
_ecdsaCurve: [Object],
_hashFunction: [Function],
_hashOutputSize: 32,
_ecdsa: [Object] } },
_signingIdentity:
SigningIdentity {
_certificate: '-----BEGIN CERTIFICATE-----\nMIIB/jCCAaSgAwIBAgIUdrt0WjnSmGsX1WuBWvXVTizqFKUwCgYIKoZIzj0EAwIw\nbzELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNh\nbiBGcmFuY2lzY28xFzAVBgNVBAoTDmRmYXJtYWRtaW4uY29tMRowGAYDVQQDExFj\nYS5kZmFybWFkbWluLmNvbTAeFw0xOTA4MTQxMTEyMDBaFw0yMDA4MTMxMTE3MDBa\nMCExDzANBgNVBAsTBmNsaWVudDEOMAwGA1UEAxMFYWRtaW4wWTATBgcqhkjOPQIB\nBggqhkjOPQMBBwNCAARXptenPPGpVnJsEFv0wmJeybDYNoClJCyAv3GcRPb04WLR\nAynEoSXf+jwYIjypV98oeR127haGcDo7jHUn0DnBo2wwajAOBgNVHQ8BAf8EBAMC\nB4AwDAYDVR0TAQH/BAIwADAdBgNVHQ4EFgQUW1YmLO6OaZB7FwXv6Gu7yc9jhNMw\nKwYDVR0jBCQwIoAgeD1bXE22u42++Y2v96xX+EKLzk8JkEcheGl5g8XGRkkwCgYI\nKoZIzj0EAwIDSAAwRQIhALluXWayFpylTOLCDIp925yn0rrtl77D/rM8AkOksTsE\nAiAEQ+w5pElSLFBINH/c0N1CgGN1snsdK1LRkUNjCk29Fg==\n-----END CERTIFICATE-----\n',
_publicKey: ECDSA_KEY { _key: [Object] },
_mspId: 'DfarmadminMSP',
_cryptoSuite:
CryptoSuite_ECDSA_AES {
_keySize: 256,
_hashAlgo: 'SHA2',
_cryptoKeyStore: [Object],
_curveName: 'secp256r1',
_ecdsaCurve: [Object],
_hashFunction: [Function],
_hashOutputSize: 32,
_ecdsa: [Object] },
_signer: Signer { _cryptoSuite: [Object], _key: [Object] } },
_mspId: 'DfarmadminMSP',
_cryptoSuite:
CryptoSuite_ECDSA_AES {
_keySize: 256,
_hashAlgo: 'SHA2',
_cryptoKeyStore:
CryptoKeyStore {
logger: [Object],
_store: [Object],
_storeConfig: [Object],
_getKeyStore: [Function] },
_curveName: 'secp256r1',
_ecdsaCurve:
PresetCurve {
curve: [Object],
g: <EC Point x: 6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296 y: 4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5>,
n: <BN: ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551>,
hash: [Object] },
_hashFunction: [Function],
_hashOutputSize: 32,
_ecdsa:
EC {
curve: [Object],
n: <BN: ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551>,
nh: <BN: 7fffffff800000007fffffffffffffffde737d56d38bcf4279dce5617e3192a8>,
g: <EC Point x: 6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296 y: 4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5>,
hash: [Object] } } }
2019-08-14T11:17:28.526Z - error: [FabricCAClientService.js]: Failed to enroll 005, error:%o message=Enrollment failed with errors [[{"code":20,"message":"Authentication failure"}]], stack=Error: Enrollment failed with errors [[{"code":20,"message":"Authentication failure"}]]
at IncomingMessage.response.on (/vagrant/Dfarm-app/Node/node_modules/fabric-ca-client/lib/FabricCAClient.js:470:22)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:139:11)
at process._tickCallback (internal/process/next_tick.js:181:9)
Failed to register user: Error: Enrollment failed with errors [[{"code":20,"message":"Authentication failure"}]]
Error: Authentication failure
It is clear that you are providing wrong credentials which means the wrong secret
For enrollment, we need ID & Secret
Double-check the secret and make sure that you have registered before proceeding for the enrolment
I suspect the issue is because you have a coding error (or error in your JSON :-)). The code is looking for userNamefield in an element, but your JSON array has a field username (lc). You could easily change your JSON to match.
If a user is to be enrolled for multiple times, you will need to specify maxEnrollments in the json of ca.register. Otherwise, ca.enroll will prompt { code: 20, message: 'Authentication failure'}.
For example, for registration you may have
var secret = await ca.register({
enrollmentID: userDetails[i].enrollmentID,
userName: userDetails[i].userName,
role: userDetails[i].role,
maxEnrollments: -1 // -1 means no limit on number of enrollments after registration
}, adminIdentity);

Resources