I have three database i.e, main_db it is default load database. I want load database after login.
Database are:-
main_db
->user_collection
psm_2017_db
->abc_collection
->xyz_collection
psm_2018_db
->abc_collection
->xyz_collection
Here is my project structure
here is my login script.
client
|->login
|->login.js
Template.login.rendered = function(){
SessionStore.set("login_user",false);
};
Template.login.events({
'submit #formLogin': function (event, target){
event.preventDefault();
var email = target.find('#loginEmail').value;
var password = target.find('#loginPassword').value;
// console.log(email +" "+password);
Meteor.loginWithPassword(email, password, function(err){
if(err){
console.log(err);
alert("Invalid Login!");
}
else {
SessionStore.set("login_user",true);
console.log('successfully')
Router.go("/dashboard")
}
});
}
});
Template.layout.helpers({
"isLoggedin": function () {
return SessionStore.get("login_user");
}
});
here is my load collection file
lib
|->collection.js
abcCollection=new Mongo.Collection("abc_collection");
xyzCollection=new Mongo.Collection("xyz_collection");
You can connect to multiple dbs using the below approach.
var database = new MongoInternals.RemoteCollectionDriver("<<mongo url>>");
MyCollection = new Mongo.Collection("collection_name", { _driver: database });
<<mongo_url>> is your standard mongodb url.
Eg. mongodb://127.0.0.1:27017/database_name
Now, in your specific scenario, main_db contains the user collection (I'm under the assumption that this is pertaining to meteor user collection). You need to have this loaded at all times. You can't have it load after login since user information - which is required for logging in resides in that db!
Once you take care of the above, connecting to the remaining two dbs can be done on login as below:
/lib/dbconnection.js (this will be common to both server and clinet)
Meteor.methods({
loadDB: function(){
if(Meteor.userId()){ // if a user has logged in
var database = new MongoInternals.RemoteCollectionDriver("<<mongo url>>");
MyCollection = new Mongo.Collection("collection_name", { _driver: database });
}
}
})
Meteor.call("loadDB");
loadDB will get called each time a user logs in. But I fear that it will be run each time any user logs in. In order to avoid it being re-initialized for each user login, you might want to do a check on whether database or myCollection already exists.
Related
As the title says, i cant seem to understand why im getting this error for an on change event on a model driven app form. i have to be honest, im using code snippits and chatGPT to try and formulate this because i haven't got a clue!! but i think im close 😁
for context, when i search for the client in a new enquiry for the code is to get the account manager from the clients record in another table and put it in the enquiry form.
var SDKEnquiry = window.Sdk || {}; (function(){ // This function is called when the customer lookup field on the form is changed this.function = onChangeCustomer(executionContext){ // Get the form context var formContext = executionContext.getFormContext();
// Get the value of the customer lookup field on the enquiry form
var customerLookup = formContext.getAttribute("customerlookup_on_enquiry_form").getValue();
// Check if a customer is selected
if(customerLookup){
// Retrieve the customer account record using the WebApi
Xrm.WebApi.retrieveRecord("account",
customerLookup[0].id, "?$select=accountmanagerid_on_customer_record").then(
function success(result) {
// Get the account manager id from the response
var accountManagerId = result.accountmanagerid_on_customer_record;
// Set the account manager id on the enquiry form
formContext.getAttribute("accountmanagerid_on_enquiry_form").setValue(accountManagerId);
},
function (error) {
// Show an error message
alert(error.message);
}
);
}
} }).call(SDKEnquiry);
This is the error im getting from Power Apps when i run the app and try and use the form. posted as image because im getting a spam warning
Error
Edit:
OKay so i think ive fixed the code, im not getting any errors anymore anyway but when i select the client the field does not pupulate?
var SDKEnquiry = {};
(function(){
this.onChangeCustomer = function(executionContext) {
var formContext = executionContext.getFormContext();
var customerLookup = formContext.getAttribute("w3c_clientcompany").getValue();
if (!customerLookup) {
alert("No customer selected.");
return;
}
Xrm.WebApi.retrieveRecord("account",
customerLookup[0].id, "?$select=w3c_AccountManager")
.then(function success(result) {
var accountManagerId = result.w3c_AccountManager;
formContext.getAttribute("w3c_cam").setValue(accountManagerId);
})
.catch(function (error) {
alert(error.message);
});
};
}).call(SDKEnquiry);
I want to add some session storage values to the database and then redirect the page to another html file. But when i insert the redirecting code, the data are not getting saved to firebase but when i comment the code to redirect the page, the data are getting stored in firebase just as expected. How do i redirect to another html file after these data are stored in firebase?
function bookingConfirm(){
var id = 4;
var firebaseRootRef = firebase.database().ref().child("Orders");
var firebaseIdRef = firebaseRootRef.child(id);
firebaseIdRef.child("id").set(id);
firebaseIdRef.child("user").set(sessionStorage.getItem("userName"));
firebaseIdRef.child("movie").set(sessionStorage.getItem("movie"));
firebaseIdRef.child("date").set(sessionStorage.getItem("date"));
firebaseIdRef.child("seats").set(sessionStorage.getItem("seats"));
firebaseIdRef.child("snacks").set(sessionStorage.getItem("snacks"));
firebaseIdRef.child("ticket price").set(sessionStorage.getItem("total"));
firebaseIdRef.child("snack price").set(sessionStorage.getItem("snackPrice"));
firebaseIdRef.child("total price").set(sessionStorage.getItem("finalPrice"));
alert(" Your booking is done! ");
// location.href = "main.html";
// document.getElementById("quithref").setAttribute("href","main.html");
}
Add a completion callback, like so:
firebaseIdRef.child("total price").set("I'm writing data", function(error) {
if (error) {
alert("Data could not be saved." + error);
} else {
alert("Data saved successfully.");
}
});
From the docs: https://firebase.google.com/docs/database/admin/save-data#section-completion-callback
I want to know when a user logs in successfully onto Facebook he is redirected to home page with its first name and last name being part of the url.
How is that process being carried out and how to do the same using nodejs.
var checkSession=require('./../custom-modules/sessionManager');
var express=require('express');
var router = express.Router();
var builtLoginMaster=require('./../custom-modules/BuiltLoginMaster');
var scripts=require('./../cdnscripts.json');//cdn scripts
//handle login authentication
router.post('/logincheck',function(req,res,next){
console.log("got hit on authenticate url");
var session=req.session;
var email = req.body.email;
var pass = req.body.password;
builtLoginMaster.authenticateUser(email,pass,function(object){
if(object!==null)
{
console.log('Rendering chat page and result');
console.log("setting session");
// console.log(session);
session.user=object.toJSON();//set user object in session
//here home page
//here only home page rendered with same '/logincheck' whereas i want something "http://example.com/firstname.lastname"
res.render('home',{title:"Twiddle",
url:scripts,
user:object.toJSON()});
}
else{
session.err="Invalid credentials";
}
});
});
//=============================Root file===========================
router.get('/',checkSession,function(req,res,next){
console.log("after checked session");
console.log(req.session);
if(!req.isLoggedIn)
{
console.log('user not logged in');
res.render('login',{ title:'Login Page',
url:scripts,
session:req.session});
}
else
{
res.render('home',{title:"Twiddle",
url:scripts,
user:req.session}) ;
console.log("redirect to home");
}
});
router.get('/register',function(req,res,next){
res.render('register',{ title:'Registration',
url:scripts});
});
router.get('/test',function(req,res,next){
res.render('test',{ title:'test',
url:scripts});
});
module.exports = router;
Instead of
res.render('home...
what you wanna do instead is
res.redirect('/user/' + user.username);
Note, you should use /user/:username instead of just /:username because that could get tricky and handling that kind of "unified" path would not be very efficient. You'll essentially be querying the database on every request /xyz to check whether xyz is a valid user/name or just another path.
Now from the /logincheck you assigned the user object in session so it'll be available in req.session.user on each new request. So you can in a way just continue on from there.
You then want to define the path /user/:username
app.get('/user/:username', function(req, res, next){
// Here, if you don't want just anybody to view this page, you can verify
if(req.session.user.username != req.params.username) return res.status(401).send('Unauthorized!');
// Then continue to render whatever you like
res.render('home',{title:"Twiddle", user:req.session.user});
});
Some resources for more info on the following:
req.session,
req.params
A bit of a newbie here. I've been looking for an answer that works and found some similarities in a Jade problem but I'm not using Jade. I have passed an "user" attribute into an HTML view as so:
app.get('/profile', isLoggedIn, function(req, res) {
res.render('profilePage/profilePage.html', {
user : req.user // get the user out of session and pass to template
});
});
Then, in my profile HTML, I can access my user property like so:
<%=user.local.firstname%>'s Profile
However, I want to allow Stripe to send the user's credit card info via the Stripetoken. I have managed to include a variable amount from a text field the user inputs. However, I want to append the user property so I can use it in my callback. Here is the javascript/jquery that's included in the profile html:
<!-- New section -->
<script type="text/javascript">
<!-- Fill in your publishable key -->
Stripe.setPublishableKey('pkkey');
var stripeResponseHandler = function(status, response) {
var $form = $('#contactForm');
var $amount = $('#amount').val();
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// token contains id, last4, and card type
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
$form.append($('<input type="hidden" name="amount" />').val($amount));
// and re-submit
$form.get(0).submit();
}
};
jQuery(function($) {
$('#contactForm').submit(function(e) {
var $form = $(this);
// Disable the submit button to prevent repeated clicks
$form.find('button').prop('disabled', true);
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from submitting with the default action
return false;
});
});
</script>
As you can see, I have managed to append the $amount variable so I can access it in the callback:
module.exports = function(app, passport) {
app.post('/stripe', function(req,res) {
// =====STRIPETOKEN======
var transaction = req.body;
var stripeToken = transaction.stripeToken;
var donationAmount = transaction.amount;
stripe.customers.create({
source : stripeToken,
account_balance : 0
},function(err, customer) {
if (err) {
console.log(err);
} else {
console.log("Success!");
}});
// ====CREATE CHARGE======
var charge =
{
amount : donationAmount,
currency : 'USD',
card : stripeToken
};
stripe.charges.create(charge, function(err, charge) {
if(err)
console.log(err);
else
{
res.json(charge);
console.log('Successful charge sent to Stripe!');
console.log(charge);
};
});
// ====PROFILE PAGE REDIRECT=====
res.render('profilePage/profilePage.html', {
});
});
So here's my problem. I want to pass the user's information, kind of like I did the amount, into the post method so when it redirects on success, I can pass it back in the res.render function, as well as send it to Stripe for description purposes. The only thing I can think of is to put the user info in a hidden field in HTML and access it like that, but that sounds messy and not proper.
This is my first time posting here so I apologize if it was too lengthy or not specific enough. Thanks!
The answer was in the way I was declaring passport and stripe in my application. Make sure you declare passport after everything to make the user variable available to stripe and all views.
I have a registration form, and when the user clicks the submit button the value in every textbox will be sent to server to insert that data, and return true/false.
Client:
Template.cust_register.events({
'click button': function(){
var email = $('#tbxCustEmail').val();
var msg = $('#tbxCustMsg').val();
var isSuccess = insertMsg(email,msg);
if(isSuccess){
alert("Success");
}else alert("Try again");
}
});
Server:
function insertMsg(email,msg){
Messages.insert({Email:email,Message:msg});
return true;
}
This turned out to not work.
How to solve this?
Many people said "use publish/subscribe", but I don't understand how to use that.
First, watch the introductory screencast and read the Data and security section of the docs.
Your code in a publish/subscribe model would look like this:
Common:
Messages = new Meteor.Collection('messages');
Client:
Meteor.subscribe("messages");
Template.cust_register.events({
'click button': function(){
var email = $('#tbxCustEmail').val();
var msg = $('#tbxCustMsg').val();
Messages.insert({Email:email,Message:msg});
}
});
Server:
Meteor.publish("messages", function() {
return Messages.find();
});
An alternative solution is to use Meteor.call('yourMethodName') (on the client).
Then, on the server, you can have
Meteor.methods({
yourMethodName: function() { /* validate input + return some data */ }
});
You can consider setting a session variable to the return value.
Meteor.call('yourMethodName', function (err, data) {
if (!err) {
Session.set('myData', data);
}
});
And then in some some template...
Template.whatever.helpers({
messages: function() {
return Session.get('myData');
}
});
Why do all this?
1) You can explicitly deny all direct `insert/update/find` queries from the client, and force usage of pre-defined Meteor methods.
2) You can manually determine when certain data is "refreshed".
Obviously, this methodology undermines the value of the subscription/publication model, and it should only be used in cases where real-time data isn't required.