I am trying to make a login form but there is a problem.The system is;If a user exists with that password and email;System is going to store the email value and password value as session.After that
I want the system route user to /searchpage.
how can i do this ?
app.post("/Logincheck",function(req,res){
var route;
var login_email_input=req.body.email_input;
var login_password_input=req.body.password_input;
var query="SELECT COUNT(*) FROM users WHERE Email_value='emailx' AND Password='passwordx'";
var query_2=query.replace("emailx",login_email_input);
var query_3=query_2.replace("passwordx",login_password_input);
server.query(query_3,function(error,fields,result){
if(error){
throw error;
}
else{
var row=result[0]["COUNT(*)"];
if(row==0){
res.send("<script>alert('The user is not found.Please try again.')</script>");
}
else{
var sess=req.session;
session.email=login_email_input;
session.password=login_password_input;
route="/searchpage";
}
}
You can use the method : res.redirect(route) to route the user to the Searchpage after a successful login
Related
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.
Basically I have 2 files... register.html and login.js.... I am able to store user's registration details into local storage and then parsed it as objects in array.... I need to log in properly(when user and pass match, alert box indicates login successful and then PHP file will redirect user, and if no match, alert box will indicate for that separately) and then second alert box as you have successfully signed in and then it will not redirect me as the PHP file is meant to do so when the user and pass match local storage... Any clues??
You are just not iterating correctly through credentials, you have to wait until you are sure that the current login credentials are not equal to any of the stored credentials, so you have to get this part of code out of the for loop:
alert('Invalid Username or Password! Please try again.');
event.preventDefault();
window.location="Login.html";
try this code for validating the login:
function validlogin(event) {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
var entriesJSON = localStorage.getItem('allEntries');
if (!entriesJSON) {
event.preventDefault();
alert("Nothing stored!");
return;
}
var allEntries = JSON.parse(entriesJSON);
var isCorrectCredentials=false;
for (var i = 0; i < allEntries.length; i++) {
var entry = allEntries[i];
var storedUserName = entry.user;
var storedPassWord = entry.pass;
var storedEmailAddress = entry.email;
if (username == storedUserName && password == storedPassWord) {
isCorrectCredentials=true;
alert("Successfully logged in!");
return;
} }
if(!isCorrectCredentials){
alert('Invalid Username or Password! Please try again.');
event.preventDefault();
window.location="Login.html";
}
}
this way you will login if the current username and password are correct and notify the rest of the code using:
isCorrectCredentials=true;
that the login info was true and you are successfully logged in.
and the part of code that should be executed if the login info is not true will be executed 1 time max.
I'm creating a game using Parse.com as back-end. I want to create another user in Parse database while I'm still logged in. I'm using Parse user.signUp() method to register another user, since Parse.com provides it as a standard method for user registration. But I don't want the current user's session to expire. Currently, it works but as soon as another user is registered, the new user's session is directly logged in.
Here is the case for your information:
I want the user (e.g. myself here) to enter the email for user to invite other user to this game. When user enters email id, an email is sent actually (using PHP) and then the function creates a temporary user. For this I'm using the following code:
function inviteFriend() {
var email = $("#inviteEmail").val();
var pass = 'randomPass123';
var varData = 'email=' + email;
console.log(varData);
if (email != null) {
$.ajax({
type : 'POST',
url : './src/php.php',
data : varData,
success : function() {
alert("Invite sent successfully.");
var user = new Parse.User();
user.set("username", "tempUser");
user.set("password", pass);
user.set("email", email);
user.signUp(null, {
success : function(user) {
alert("User created successfully.");
console.debug(user);
},
error : function(user, error) {
console.log("LogIn error := " + error.message);
}
});
}
});
}
}
Please suggest any workarounds.
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.