I'm using handlebars as a view engine.
For routes :
app.get('/', function(req, res) {
if(req.user) {res.render('user'), {name:req.user.username, id:req.user.id}}
else
if(!req.user) {res.render('index')};
});
For passport.js
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
connection.query("SELECT * FROM users WHERE id = ? ",[id], function(err, rows){
done(err, rows[0]);
});
});
passport.use(
'local-signup',
new LocalStrategy({
usernameField : 'username',
passwordField : 'password',
passReqToCallback : true
},
function(req, username, password, done) {
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
connection.query("SELECT * FROM users WHERE username = ?",[username], function(err, rows) {
if (err)
return done(err);
if (rows.length) {
return done(null, false, {message: 'That username is already taken'});
} else {
var newUserMysql = {
username: username,
password: bcrypt.hashSync(password, null, null) // use the generateHash function in our user model
};
var insertQuery = "INSERT INTO users ( username, password ) values (?,?)";
connection.query(insertQuery,[newUserMysql.username, newUserMysql.password],function(err, rows) {
newUserMysql.id = rows.insertId;
return done(null, newUserMysql);
});
}
});
})
);
I'm trying to find a solution, but it doesn't work. Whenever I try to use this, handlebars won't show anything up.. I know that ejs uses something like <%= user.username %> that does work, but can't convert that to handlebars..
if(req.user) {res.render('user'), {name:req.user.username, id:req.user.id}}
I figured it out till the end, my object {} was outside the (), not inside like it was supposed to be. This is the right code:
if(req.user) {res.render('user', {name:req.user.username, id:req.user.id})}
Related
I developed a meteor app in which while registering I am fetching the user location at the client side, to do so I have added the packages listed below:
meteor add mdg:geolocation
meteor add jeremy:geocomplete
meteor aldeed:geocoder
meteor add jaymc:google-reverse-geocode
The code written at client side is as follows:
if (Meteor.isClient) {
Meteor.startup(() => {
GoogleMaps.load({
v: '3.26',
key: '',
libraries: 'geometry,places'
});
console.log("is GoogleMaps.loaded",GooglMaps.loaded());
});
Template.Registration.onRendered(function () {
Tracker.autorun(() => {
if (GoogleMaps.loaded()) {
$('#txt_address').geocomplete({country: "AU", type:
['()']});
}
});
var date = new Date();
$('#div_dob').datetimepicker({
format: 'DD/MM/YYYY',
maxDate : date,
ignoreReadonly: true
});
date=null;
});
Template.Registration.helpers({
location:function(){
$('input[name="txt_address"]').val(Session.get('location'));
}
});
Template.Registration.events({
'click #btn_findlocation':function(event){
alert('Find Location')
event.preventDefault();
function success(position) {
var crd = position.coords;
console.log(`Latitude0 : ${crd.latitude}`);
console.log(`Longitude0: ${crd.longitude}`);
var lat = crd.latitude;
var long = crd.longitude;
reverseGeocode.getLocation(lat, long, function(location)
{
console.log("Address",JSON.stringify(reverseGeocode.getAddrStr()));
Session.set('location', reverseGeocode.getAddrStr());
});
};// end of function success(position)
function error(err) {
console.warn('ERROR(' + err.code + '): ' + err.message);
};//end of function error(err)
// geolocation options
var options = {
enableHighAccuracy: true,
maximumAge: 0
};// end of var options
navigator.geolocation.getCurrentPosition(success, error,
options);
},
})
}
But I am getting false value for GoogleMaps.loaded() function and the following below error when I click a button to fetch the location.
Can't able to read formatted address of undefined.
Results are inconsistent as sometimes I was able to fetch the location other times not.
Please give any suggestions...
Yesterday my app was launched, Ionic v1, and a few users entered the wrong password and can't log into the app.
The app uses firebase authentication. I have a __refs file that points to the database and have tried numerous things trying to get the reset to work.
I've tried referencing $firebaseAuth, of course my __refs, $firebase then use $firebase.auth()...
I didn't write the authentication of this app so I'm not real sure how it works. I'm hoping that someone can help me.
My reset controller
angular.module('formulaWizard').controller('ResetPasswordCtrl',
function($scope, $ionicLoading, $firebaseAuth, __Refs) {
$scope.user = {
email: ''
};
$scope.errorMessage = null;
var fbAuth = $firebaseAuth(__Refs.rootRef);
$scope.resetPassword = function() {
$scope.errorMessage = null;
$ionicLoading.show({
template: 'Please wait...'
});
fbAuth.sendPasswordResetEmail($scope.user.email)
.then(showConfirmation)
.catch(handleError);
};
function showConfirmation() {
$scope.emailSent = true;
$ionicLoading.hide();
}
function handleError(error) {
switch (error.code) {
case 'INVALID_EMAIL':
case 'INVALID_USER':
$scope.errorMessage = 'Invalid email';
break;
default:
$scope.errorMessage = 'Error: [' + error.code + ']';
}
$ionicLoading.hide();
}
});
My Refs file
angular.module('formulaWizard')
.factory('__Refs', function ($firebaseArray, $firebaseObject) {
// Might use a resource here that returns a JSON arrayf
var ref = new Firebase('https://firebasedatabase.com/');
return {
rootRef: ref,
customers: ref.child('customers'),
}
});
I can't take credit for the answer it was provide by Abimbola Idowu on HackHands.
Since I paid for the answer I thought I would share it with anyone else that might also be stumped by this.
$scope.resetPassword = function() {
$scope.errorMessage = null;
$ionicLoading.show({
template: 'Please wait...'
});
__Refs.rootRef.resetPassword({ email: $scope.user.email }, function(error) {
if (error === null) {
showConfirmation();
} else {
handleError()
}
});
};
This is the __refs service
angular.module('formulaWizard')
.factory('__Refs', function ($firebaseArray, $firebaseObject) {
// Might use a resource here that returns a JSON arrayf
var ref = new Firebase('https://firebasedatabase.com/');
return {
rootRef: ref,
}
});
I am new to ionic.I want to add data into SQLite which is coming from remote server. I have successfully populated data into list.so how can i store this data into sqlite. here is my code. how do i pass this data to query.I am unable to do this.
service.js
angular.module('starter.service',[]).
factory('userServices',['$http',function($http){
var users = [];
return {
get: function(){
return $http.get("http://xxxxxxxxx-info").then(function(response){
users = response.data;
return users;
});
},
remove:function(content){
users.splice(users.indexOf(content),1);
},
getUser:function(chatId)
{
for(var i=0; i<users.length;i++){
if(users[i].content_id === parseInt(chatId)){
return users[i];
}
}
return null;
}
}
}]);
controller.js
angular.module('shoppingPad.controller', [])
.controller('ChatCtrl', function ($scope, userServices, $ionicModal, $cordovaSQLite) {
console.log('inside controller');
userServices.get().then(function (users) {
//users is an array of user objects
$scope.contents = users;
console.log($scope.contents);
var query = "INSERT INTO content (content_id, display_name) VALUES (?,?)";
$cordovaSQLite.execute(db, query, [users.content_id, users.display_name]).then(function (res) {
alert(res);
alert('Inserted');
}, function (e) {
alert('Error:' + e.message);
});
});
Where did you define db? It's necessary to wait until device is ready.
$ionicPlatform.ready(function () {
var db = $cordovaSQLite.openDB({ name: "my.db" });
// just first time you need to define content table
$cordovaSQLite.execute(db,"CREATE TABLE content (content_id integer, display_name text)");
userServices.get().then(function (users) {
//users is an array of user objects
$scope.contents = users;
console.log($scope.contents);
var query = "INSERT INTO content (content_id, display_name) VALUES (?,?)";
$cordovaSQLite.execute(db, query, [users.content_id, users.display_name]).then(function (res) {
alert(res);
alert('Inserted');
}, function (e) {
alert('Error:' + e.message);
});
});
});
Are you sure, that your object users look like
{
"content_id":12,
"display_name":"hello world"
}
and not like
[
{
"content_id":12,
"display_name":"hello world"
},
{
"content_id":13,
"display_name":"stackoverflow"
},
...
]
I just ask, because users sounds like more than one entry.
I am trying to publish all admin users from server
on server something like this:
Meteor.publish("users_with_roles", function (options, role) {
//{fields: {emails: 1, profile: 1}}
Counts.publish(this, 'numberOfUsers', Meteor.users.find({$and:[
{'roles.tripro': {$exists: true}},
{'roles.tripro': role}
]}),
{ noReady: true });
return Meteor.users.find({
$and:[
{'roles.tripro': {$exists: true}},
{'roles.tripro': role}
]
}, options);
});
Then on client side, I am trying to subscribe this:
$meteor.autorun($scope, function() {
$meteor.subscribe('users_with_roles', {
limit: parseInt($scope.getReactively('perPage')),
skip: (parseInt($scope.getReactively('page')) - 1) * parseInt($scope.getReactively('perPage')),
sort: $scope.getReactively('sort'),
fields: {emails: 1, profile: 1}
},'admin').then(function() {
$scope.usersCount = $meteor.object(Counts ,'numberOfUsers', false);
console.log('user counter:' + $scope.usersCount.count);
$scope.users.forEach( function (user) {
// user.onClicked = function () {
// //$state.go('userProfile', {userId: user._id});
// };
console.log(user._id);
});
},
function(error)
{
console.log(error);
}
);
});
$scope.users = $meteor.collection(function() {
console.log('looking for role: ' + role);
return Meteor.users.find({}, {
//sort : $scope.getReactively('sort')
});
});
However, from the logging, it appears that the client side received all users , but from the logging on server side, it does give correct result.
What am I missing here?
A couple things to think about here.
When you request users you will always have "you". So if the user you are logged into is not an admin, it will still show up in the collection.
Because you are using $meteor.subscribe instead of $scope.$meteorSubscribe you are not clearing the subscription when the scope is destroyed so it's possible that it's mixing with other subscriptions on the client side from other scopes.
I have a login validation function setup to check if a new user registered outside of the app. That users info is stored in a temporary collection. If the users info validates I want to be able to use Accounts.createUser on the Client side, but I can't figure out how to do that. The documentation says that "registered validate login callbacks are called with a single argument, the attempt info object", but I can't find any examples of how to do this.
environment.js
Accounts.config({
forbidClientAccountCreation : true
});
server.js
Accounts.validateLoginAttempt(function(info){
if (!info.allowed)
{
var userEmail = info.methodArguments[0].user['email'].toLowerCase();
var userPass = info.methodArguments[0].password['digest'];
// check if this is a temp user
if (tmpUsers.find({'email': userEmail}).count() == 1)
{
var user = tmpUsers.findOne({'email': userEmail})
// check for active
if (user.active == "Yes")
{
// check password
if (userPass == user.password)
{
var accountId = Accounts.createUser({
'password': userPass,
'email': userEmail,
'profile': ({'acctType': user.type})
});
return true;
} else {
throw new Meteor.Error(403, "Incorrect password.");
return false;
}
} else {
throw new Meteor.Error(403, "Your account has yet to be activated.);
return false;
}
} else {
throw new Meteor.Error(403, "Can not find user " + userEmail);
return false;
}
} else {
return true;
}
});
Update:
I ended up putting the Account.userCreate part on the server side and now it does get the user created but when I try to login I get "Email already exists." So it appears as though it doesn't expect the login to be successful and tries to create the user again.
{ // This user works
"_id" : "hCBLo3AJJwmtR6s62",
"createdAt" : ISODate("2014-12-26T20:27:58.44Z"),
"services" : {
"password" : {
"bcrypt" : "$2a$10$pxlEy.JFomgwQwV2cpm72.TBG4.llP98BF9ssTCptC4WsekLzJO9G"
},
"resume" : {
"loginTokens" : []
}
},
"emails" : [{
"address" : "demo#demo.com",
"verified" : false
}]
}
{ // This one does not
"_id" : "w6SGuqJJPs5LoCTTj",
"createdAt" : ISODate("2015-01-10T20:54:16.032Z"),
"services" : {
"password" : {
"bcrypt" : "$2a$10$VJFj0UOrQiLs7djfGWAeMeruDactDFrl1nlEsXh/r5Z/895C5ubAW"
}
},
"emails" : [{
"address" : "demo2#demo.com",
"verified" : false
}],
"profile" : {
"acctType" : null
}
}
Would something like this work for you?
var options = {
username: "username", // you'll need to fill this in
email: userEmail,
password: userPass,
profile: {name: "name"} // you'll need to fill this in
};
Accounts.createUser(options, function (error) {
if (error) {
console.log("Cannot create user");
}
});