Pages
- Export tabe Excel in Asp.net
- CSS
- Date Picker in Jquery
- SQL
- Sort Self Code
- JavaScript(Print Page)
- Web Services Part-4(How to make changes to wcf ser...
- WCF Services Part-3( WCF service implementing mult...
- Home
- WCF Services Part-2(configuration web.config)
- WCF Services Part-1
- Web Services part-1 (introduction)
- Web Service PART-5 ( Call Web Service using JQuery...
- Web Service PART-4 ( Calling asp net web service f...
- Web Service PART-3 (WebMethod attribute properties...
- Web Service PART-2 (Session State )
Tuesday, 5 January 2021
Create and verify jwt tocken in nodeJs
========================Create
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
exports.login = async (req, res, next) => {
const email = req.query.email;
const password = req.query.password;
let loadedUser;
try {
var user = await User.findOne({ email: email });
if (!user) {
res.status(200).json({ Message: 'A user with this email(' + email + ') could not be found.', Result: false });
}
loadedUser = user;
var isEqual = await bcrypt.compare(password, user.password);
if (!isEqual) {
const error = new Error('Wrong password!');
error.statusCode = 200;
res.status(200).json({ Message: "'Wrong password!'", Result: false });
throw error;
};
const token = jwt.sign(
{
email: loadedUser.email,
userId: loadedUser._id.toString()
},
'somesupersecretsecret',
{ expiresIn: '1h' }
);
res.status(200).json({
token: token, userId: loadedUser._id.toString(), Result: true,
cdata: {
email: loadedUser.email,
password: loadedUser.password,
_id: loadedUser._id,
name: loadedUser.name
}
});
} catch (error) {
res.status(201).json({ Message: error.message, response: error, Result: false });
}
};
===================== Verify
const jwt = require('jsonwebtoken');
module.exports = (req, res, next) => {
try {
const authHeader = req.get('Authorization');
if (!authHeader) {
const error = new Error('Not authenticated.');
error.statusCode = 401;
throw error;
}
const token = authHeader.split(' ')[1];
let decodedToken;
try {
decodedToken = jwt.verify(token, 'somesupersecretsecret');
} catch (err) {
err.statusCode = 500;
throw err;
}
if (!decodedToken) {
const error = new Error('Not authenticated.');
error.statusCode = 401;
throw error;
}
req.userId = decodedToken.userId;
next();
} catch (error) {
res.status(500).json({ Message: error.message, response: error, Result: false });
}
};
($toObjectId) stiing convert to ObjectId in MongoDb/Mongoose
Signal
// .find({ subscriberId: req.query.subscriberId })
.aggregate([
{ "$addFields": { "mentorId0": { "$toString": "$mentorId" } } },
{ "$addFields": { "mentorIdObj": { "$toObjectId": "$mentorId" } } },
// { "$match": {"subscriberId": subscriberId } },
{
"$lookup": {
"from": "subscribementors",
"localField": "mentorId0",
"foreignField": "mentorId",
"as": "mentor"
},
},
{
$match: {
// "mentorId": "5fdb1f7b807d6916186428bf",
"mentor.subscriberId": subscriberId
// "mentor.mentorId": "5fdb1f7b807d6916186428bf"
// }
// "subscriberId": "5fdb1b4890d271394844e20a"
// "mentor":[{"subscriberId":subscriberId}]
}
},
{
"$lookup": {
"from": "mentors",
"foreignField": "_id",
"localField": "mentorIdObj",
"as": "mentorDetail"
}
},
// { "$project":{$cond:{"mentor":{"subscriberId":subscriberId}}} }
// {"$project":{"subscriberId":1,"mentorId":1,"mentor":{name:1,email:1,status:1}}}
])
.then(mySignal => {
res.send({ mySignal: mySignal });
}).catch(err => {
res.status(500).send({ Message: err.message, Result: false, data: err });
})
($toString)ObjectId convert to string in MongoDb /Mongoose
Signal
// .find({ subscriberId: req.query.subscriberId })
.aggregate([
{ "$addFields": { "mentorId0": { "$toString": "$mentorId" } } },
{ "$addFields": { "mentorIdObj": { "$toObjectId": "$mentorId" } } },
// { "$match": {"subscriberId": subscriberId } },
{
"$lookup": {
"from": "subscribementors",
"localField": "mentorId0",
"foreignField": "mentorId",
"as": "mentor"
},
},
{
$match: {
// "mentorId": "5fdb1f7b807d6916186428bf",
"mentor.subscriberId": subscriberId
// "mentor.mentorId": "5fdb1f7b807d6916186428bf"
// }
// "subscriberId": "5fdb1b4890d271394844e20a"
// "mentor":[{"subscriberId":subscriberId}]
}
},
{
"$lookup": {
"from": "mentors",
"foreignField": "_id",
"localField": "mentorIdObj",
"as": "mentorDetail"
}
},
// { "$project":{$cond:{"mentor":{"subscriberId":subscriberId}}} }
// {"$project":{"subscriberId":1,"mentorId":1,"mentor":{name:1,email:1,status:1}}}
])
.then(mySignal => {
res.send({ mySignal: mySignal });
}).catch(err => {
res.status(500).send({ Message: err.message, Result: false, data: err });
})
Monday, 4 January 2021
$project in MogooDb/Mongoose
SubscribeMentor
// .find({ subscriberId: req.query.subscriberId })
.aggregate([
{ "$addFields": { "mentorId": { "$toObjectId": "$mentorId" } } },
{ "$match": { "subscriberId": req.query.subscriberId } },
{
"$lookup": {
"from": "mentors",
"foreignField": "_id",
"localField": "mentorId",
"as": "mentor"
}
},
{ "$project": { "subscriberId": 1, "mentorId": 1, "mentor": { name: 1, email: 1, status: 1 } } }
])
.then(mymenotrs => {
res.send({ myMentors: mymenotrs });
}).catch(err => {
res.status(500).send({ Message: err.message, Result: false, data: err });
})
updateOne({ }) in MogoDb/ mongoose
Mentor.updateOne({ _id: req.body.id }, req.body)
.then(result => {
if (result.ok == 1) {
res.status(201).json({ Message: 'Mentor Updated!', response: result, Result: true });
} else {
res.status(201).json({ Message: 'Note Mentor Updated!', response: result, Result: false });
}
})
.catch(err => {
if (!err.statusCode) {
err.statusCode = 500;
}
next(err);
});
deleteOne({}) in MogoDb
Mentor.deleteOne({ _id: req.query._id })
.then(result => {
if (result.ok == 1) {
res.status(201).json({ Message: 'Mentor Remove!', response: result, Result: true });
} else {
res.status(201).json({ Message: 'Note Mentor Remove!', response: result, Result: false });
}
})
.catch(err => {
if (!err.statusCode) {
err.statusCode = 500;
}
next(err);
});
momentJs in NodeJs (Date change)
const moment = require('moment');
var sDate = moment();
var eDate = "";
// 1">Day
if (durationType == "1") {
eDate = moment(sDate, "DD-MM-YYYY").add('days', duration);
} // 2">Week
else if (durationType == "2") {
eDate = moment(sDate, "DD-MM-YYYY").add('week', duration);
} // 3">Month
else if (durationType == "3") {
eDate = moment(sDate, "DD-MM-YYYY").add('month', duration);
} // 4">Year
else if (durationType == "4") {
eDate = moment(sDate, "DD-MM-YYYY").add('year', duration);
}
save() in MongoDb/Mongoose
subscriberPlan.save()
.then(result => {
if (result._id) {
res.status(201).json({ Message: 'Plan created!', response: result, Result: true });
} else {
res.status(201).json({ Message: 'Plan Not created!', response: result, Result: false });
}
})
.catch(err => {
if (!err.statusCode) {
// err.statusCode = 500;
res.status(201).json({ response: err, Message: err.message, Result: false });
}
next(err);
});
find() in MongoDb
Subscriber.find()
.then(user => {
loadedUser = user;
res.status(200).json({ users: loadedUser });
})
.catch(err => {
if (!err.statusCode) {
err.statusCode = 500;
}
next(err);
});
bcrypt.compare Password in nodeJs
Subscriber.findOne({ email: email })
.then(user => {
if (!user) {
res.status(200).json({ Message: 'A user with this email(' + email + ') could not be found.', Result: false });
// const error = new Error('A user with this email(' + email + ') could not be found.');
// error.statusCode = 401;
// throw error;
}
loadedUser = user;
console.log("user", user)
return bcrypt.compare(password, user.password);
})
.then(isEqual => {
if (!isEqual) {
const error = new Error('Wrong password!');
error.statusCode = 200;
res.status(200).json({ Message: "'Wrong password!'", Result: false });
throw error;
}
const token = jwt.sign(
{
email: loadedUser.email,
userId: loadedUser._id.toString()
},
// 'somesupersecretsecret',
'asas',
{ expiresIn: '1h' }
);
res.status(200).json({
token: token, userId: loadedUser._id.toString(), Result: true,
cdata: {
email: loadedUser.email,
// password:loadedUser.password,
_id: loadedUser._id,
name: loadedUser.name,
phone: loadedUser.phone,
address: loadedUser.address,
status: loadedUser.status,
plans: loadedUser.plans,
}
});
})
.catch(err => {
if (!err.statusCode) {
err.statusCode = 500;
}
next(err);
});
bcrypt password in nodeJs
bcrypt
.hash(password, 12)
.then(hashedPw => {
const subscriber = new Subscriber({
email: email,
password: hashedPw,
name: name,
status: 0
});
return subscriber.save();
})
.then(result => {
res.status(201).json({ message: 'User created!', userId: result._id, Result: true });
})
.catch(err => {
if (!err.statusCode) {
err.statusCode = 500;
}
next(err);
});
aggregate in mongoDb 1 collection connect with 2 collection
Signal
// .find({ subscriberId: req.query.subscriberId })
.aggregate([
{ "$addFields": { "mentorId0": { "$toString": "$mentorId" } } },
{ "$addFields": { "mentorIdObj": { "$toObjectId": "$mentorId" } } },
// { "$match": {"subscriberId": subscriberId } },
{
"$lookup": {
"from": "subscribementors",
"localField": "mentorId0",
"foreignField": "mentorId",
"as": "mentor"
},
},
{
$match: {
// "mentorId": "5fdb1f7b807d6916186428bf",
"mentor.subscriberId": subscriberId
// "mentor.mentorId": "5fdb1f7b807d6916186428bf"
// }
// "subscriberId": "5fdb1b4890d271394844e20a"
// "mentor":[{"subscriberId":subscriberId}]
}
},
{
"$lookup": {
"from": "mentors",
"foreignField": "_id",
"localField": "mentorIdObj",
"as": "mentorDetail"
}
},
// { "$project":{$cond:{"mentor":{"subscriberId":subscriberId}}} }
// {"$project":{"subscriberId":1,"mentorId":1,"mentor":{name:1,email:1,status:1}}}
])
.then(mySignal => {
res.send({ mySignal: mySignal });
}).catch(err => {
res.status(500).send({ Message: err.message, Result: false, data: err });
})
3 level object in MongoDb Condition
SubscribePlan.aggregate([
{ $match: { "subscriberId": subscriberId } },
{ "$addFields": { "planId1": { "$toString": "$planId" } } },
{
"$lookup": {
"from": "Signal",
// "let": { "planId0": "$package_id", "mentorId": "$mentorId" },
"let": { "planId0": "$planId" },//privous collection
"pipeline": [
{ "$match": { "$expr": { "$eq": ["$package_id", "$$planId0"] } } },
{
"$lookup": {
"from": "mentors",
"let": { "mentorId0": { "$toObjectId": "$mentorId" } }, //privous collection
"pipeline": [
{ "$match": { "$expr": { "$eq": ["$_id", "$$mentorId0"] } } }
],
"as": "mentorDetail",
}
},
{ "$unwind": "$mentorDetail" }
],
"as": "signal",
}
},
{ "$unwind": "$signal" }
])
.then(mySignal => {
res.send({ myPlamSignals: mySignal });
}).catch(err => {
res.status(500).send({ Message: err.message, Result: false, data: err });
})
Subscribe to:
Comments (Atom)
IIS deployment support details
Node JS - IIS deployment support details node: http://go.microsoft.com/?linkid=9784334 IISNode: https://github.com/azure/iisnode/releases/...
Pages
- Home
- Export tabe Excel in Asp.net
- CSS
- Sort Self Code
- SQL
- JavaScript(Print Page)
- Date Picker in Jquery
- WCF Services Part-3( WCF service implementing mult...
- Web Services Part-4(How to make changes to wcf ser...
- WCF Services Part-2(configuration web.config)
- WCF Services Part-1
- Web Services part-1 (introduction)
- Web Service PART-5 ( Call Web Service using JQuery...
- Web Service PART-4 ( Calling asp net web service f...
- Web Service PART-3 (WebMethod attribute properties...
- Web Service PART-2 (Session State )
-
@ NgModule ({ declarations: [ GrdFilterPipe ] }) import { Pipe , PipeTransform } from '@angular/core' ; @ Pipe...
-
======Angular onFileChange(event: any) { var reader: any = new FileReader(); if (event.target.files && event.target.files.l...
-
public void MailSant( string Subject, string message_text, string to1) { //------------ Mail Code Start here .....