How to create users client side? - meteor

I'm working on a intern document-sharing project for a small company. I want to do this with meteor. I'm very common with html/javascript but not with databases.
My problem is to handle the users. Because of my researches here I'm not sure if it's already possible to create users on client side. The official documentation shows some methodes how to deal with users but no examples.
I tried to create a list on server side like this:
Users = new Meteor.Collection("users");
Then I want to insert a user on startup like this:
//on Client side
if (Meteor.isClient) {
var username = "My Name";
Meteor.call("create_user", username, function(error, user_id) {
Session.set("user_id", user_id);
});
}
//on Server side
if(Meteor.is_server) {
Meteor.methods({
create_user: function(username) {
console.log("CREATING USER");
var USER_id = Users.insert({name: username});
return user_id;
},
});
}
But reading the username in the html template doesn't work...
Are there any good examples with a register and login?
Cheers

Adding the accounts functionality is very easy in Meteor.. may it be simple email, password, or by using facebook connect/twitter etc..
do the following to get a simple meteor app with user accounts set up..
meteor create simpleapp
cd simpleapp
add the accounts-ui and accounts-password packages
meteor add accounts-ui
meteor add accounts-password
you simply add other accounts related packages for implementing facebook/twitter/github/google login etc
to list other available meteor packages use this command
meteor list
now edit your simpleapp.html file to this to add login buttons etc..
<head>
<title>simpleapp</title>
</head>
<body>
{{> hello}}
</body>
<template name="hello">
<h1>Hello World!</h1>
{{greeting}}
<input type="button" value="Click" />
{{loginButtons}}
</template>
I simply added {{loginButtons}} to the default html file to add the default login buttons..
now run the meteor app and go to localhost:3000
meteor
you implemented the login functionality without doing much work. 4-5 lines of code, it even takes care of things like forgot password, registering new user etc
next thing is you need to display a particular html when the user is signed in.
you do this using the {{currentUser}} global
you implement it accordingly
<template name="hello">
<h1>Hello World!</h1>
{{greeting}}
<input type="button" value="Click" />
{{loginButtons}}
{{#if currentUser}}
{{> loggedInTemplate}}
{{else}}
{{> loggedOutTemplate}}
{{/if}}
</template>
<template name="loggedInTemplate">
<!-- user is logged in -->
</template>
<template name="loggedOutTemplate">
<!-- user is logged out -->
</template>

You don't need to create a user system manually. Just use the accounts package:
The Meteor Accounts system builds on top of the userId support in publish and methods. The core packages add the concept of user documents stored in the database, and additional packages add secure password authentication, integration with third party login services, and a pre-built user interface.
Your code should work, though. But you're not exposing the username property to the client, so maybe that's why you can't see it in your template.

Ok thank you, that's easy. But so I can not modify the loggedInTemplate or the loggedOutTemplate.
I show you what I've got:
//the html
<head>
<title>myApp | documents</title>
</head>
<body>
<div id="headerBox">
{{> header}}
</div>
<div id="sideBox">
{{> side}}
</div>
<div id="contentsBox">
{{> contents}}
</div>
</body>
<template name="header">
<h1>Company name</h1>
</template>
<template name="contents">
{{#if currentUser}}
<p>Welcome to documents</p>
{{else}}
<h3>Hello! Please log in!</h3>
<p><input type="text" id="username" placeholder="Username"><input type="text" id="password" placeholder="Password"><input type="button" value="log me in!"></p>
{{/if}}
</template>
<template name="side">
<p>Hello {{ activeUser }}</p>
<p><input type="button" value="Create New Document" onclick="createPage()"></p>
<h3>Documents:</h3>
</template>
and
//client.js
Pages = new Meteor.Collection("pages");
Meteor.startup(function() {
Session.set("activeUser", "please log in!");
});
Template.side.activeUser = function() {
return Session.get("activeUser");
};
and
//server.js
Meteor.startup(function() {
Accounts.createUser({username: "MyName", email: "me#example.com", password: "123456"});
});
and I'm searching for a manual way to log this user created on startup in. And of course later to allow this user to create new users...
The problem is adding
// Returns an event_map key for attaching "ok/cancel" events to
// a text input (given by selector)
var okcancel_events = function (selector) {
return 'keyup '+selector+', keydown '+selector+', focusout '+selector;
};
// Creates an event handler for interpreting "escape", "return", and "blur"
// on a text field and calling "ok" or "cancel" callbacks.
var make_okcancel_handler = function (options) {
var ok = options.ok || function () {};
var cancel = options.cancel || function () {};
return function (evt) {
if (evt.type === "keydown" && evt.which === 27) {
// escape = cancel
cancel.call(this, evt);
} else if (evt.type === "keyup" && evt.which === 13) {
// blur/return/enter = ok/submit if non-empty
var value = String(evt.target.value || "");
if (value)
ok.call(this, value, evt);
else
cancel.call(this, evt);
}
};
};
Template.contents.events = {};
Template.contents.events[okcancel_events('#password')] = make_okcancel_handler({
ok: function (text, event){
var usernameEntry = document.getElementById('username');
var passwordEntry = document.getElementById('password');
Meteor.loginWithPassword({usernameEntry, passwordEntry});
event.target.value = "";
}
});
to the client doesn't work...

Related

Iron Router / User details issue in Meteor

I am relatively new to Meteor and have been stuck on an issue for awhile. I have a /users/:_id route that is supposed to display details specific to that user id. However, whenever I hit that route, it displays information for the currently logged in user, NOT of the user whose details I want to view.
Here's my route:
Router.route('/users/:_id', {name: 'Users', controller: 'usersDetailController'});
Here's my usersDetailController:
usersDetailController = RouteController.extend({
waitOn: function () {
Meteor.subscribe('userProfileExtended', this.params._id);
},
onBeforeAction: function () {
var currUserId = Meteor.userId();
var currUser = Meteor.users.findOne({_id: currUserId});
console.log('admin? ' + currUser.isAdmin);
if (!currUser.isAdmin) {
this.render('accessDenied');
} else {
this.next();
}
},
action: function() {
this.render('Users');
}
});
And here's my server/publish:
Meteor.publish('userProfileExtended', function() {
return Meteor.users.find({_id: this.userId});
});
User Details template:
<template name="Users">
<form>
{{#with user}}
<div class="panel panel-default">
<div class="panel-heading">{{profile.companyName}} Details</div>
<div class="row">
<div class="col-md-4">
<div class="panel-body">
<p><label>Company: </label><input id="Company" type="text" value={{profile.companyName}}></p>
<p><label>Email: </label><input id="Email" type="text" value={{emails.address}}></p>
<p><label>Phone: </label><input id="Phone" type="text" value={{profile.phoneNum}}></p>
<p><label>Tire Markup: </label><input id = "tireMarkup" type="text" value={{profile.tireMarkup}}></p>
<p><button class="saveUserDetails">Save</button></p>
<p><button class="deleteUser">Delete User</button></p>
</div>
</div>
</div>
</div>
{{/with}}
Here's my Template Helper:
Template.Users.helpers({
user: function() {
return Meteor.users.findOne();
}
});
Can someone help? I think the issue is the way i reference "this.userId"...
Thank you!!
You need to change your publish function to use the userId parameter you specify when subscribing :
Meteor.publish('userProfileExtended', function(userId) {
return Meteor.users.find(userId,{
fields:{
'username':1,
'profile.firstName':1,
'profile.lastName'
}
});
});
In the publish function, userId will equal whatever value you call Meteor.subscribe with, in this case it will hold this.params._id.
Beware of using the proper syntax for route parameters, if you declare a path of /users/:_id, you need to reference the param using this.params._id.
Also note that it's insecure to publish the whole user document to the client if you only need to show specific fields in the interface, that's why you want to use the fields option of Collection.find to only publish a subset of user documents.
EDIT :
I would recommend using the route data function to specify the data context you want to apply when rendering your template, something like this :
data: function(){
return {
user: Meteor.users.findOne(this.params._id)
};
}

removed autopublish and insecure: now i can't retrive data by MongoDB

I'm starting to learn Meteor.js and, when I've removed autopublish and insecure, my application doesn't work any longer.
I can insert data to database but I can't retrive anything by database.
No errors in console.
This is my code:
client/main.html
<head>
<title>Blog Test</title>
</head>
<body>
<h1>Blog Test</h1>
{{>blog}}
{{>ListBlogs}}
</body>
<template name="blog">
<form class="blog-post" id="blog-post" role="form">
<label id="label-title" class="label-title">Titolo:</label>
<input id="input-title" class="input-title" placeholder="Titolo">
<br>
<label id="label-text" class="label-text">Testo:</label>
<textarea id="input-text" class="input-text" placeholder="Testo"></textarea>
<br>
<button type="submit" class="blog-btm">Submit</button>
</form>
</template>
<template name="ListBlogs">
{{#each posts}}
<h2>{{title}}</h2>
<p>{{text}}</p>
{{/each}}
</template>
client/main.js
Template.blog.events({
'submit #blog-post':function (e){
e.preventDefault();
var title = $('.input-title').val();
var text = $('.input-text').val();
Meteor.call('submitPost',title,text);
}
});
Meteor.subscribe('posts');
server/server.js
Meteor.methods({
'submitPost':function(title, text){
console.log("Titolo: " + title);
console.log("Testo:" + text);
Blogs.insert({title:title, text:text});
}
});
Meteor.publish('posts', function() {
return Blogs.find();
});
lib/blog.js
Blogs = new Meteor.Collection('blogs');
We fixed this in IRC I believe :-)
The problem is that your template ListBlogshas no idea what posts means. You will have to define a helper, so that the {{#each posts}} block gets a meaning.
Fortunately this only requires a very quick fix:
Template.ListBlogs.posts = function(){
return Blogs.find().fetch();
}
Put this in your client/main.js and all posts appear in realtime.
your code it's ok, though you must to try subscribe on collection of this way
Tracker.autorun(function () {
Meteor.subscribe("posts");
});
http://docs.meteor.com/#tracker_autorun
and after that you must to create the helpers, for example...
Template.blog.helpers({
})
Template.ListBlogs.helpers({
posts: function(){
return Posts.find({});
}
})

Content wrapped in currentUser re-rendering when user updated

I'm using Meteor and having an issue where my content is being re-rendered when I don't want it to.
I have my main content wrapped in a currentUser if statement which I feel is fairly standard.
{{#if currentUser}}
{{> content}}
{{/if}}
The problem with this is my content template is being re-rendered when I update my user object. Is there any way around this? I don't reference users anywhere inside the content template.
Thank you!
Here's a sample app to replicate my problem:
HTML
<head>
<title>Render Test</title>
</head>
<body>
{{loginButtons}}
{{> userUpdate}}
{{#if currentUser}}
{{> content}}
{{/if}}
</body>
<template name="userUpdate">
<p>
<input id="updateUser" type="button" value="Update User Value" />
User last update: <span id="lastUpdated">{{lastUpdated}}</span>
</p>
</template>
<template name="content">
<p>Render count: <span id="renderCount"></span></p>
</template>
JavaScript
if (Meteor.isClient) {
Meteor.startup(function() {
Session.set("contentRenderedCount", 0);
});
Template.content.rendered = function() {
var renderCount = Session.get("contentRenderedCount") + 1;
Session.set("contentRenderedCount", renderCount);
document.getElementById("renderCount").innerText = renderCount;
};
Template.userUpdate.events = {
"click #updateUser": function() {
Meteor.users.update({_id: Meteor.userId()}, {$set: {lastActive: new Date()}});
}
};
Template.userUpdate.lastUpdated = function() {
return Meteor.user().lastActive;
};
}
if (Meteor.isServer) {
Meteor.users.allow({
'update': function () {
return true;
}
});
}
Update:
I should've explained this example a little. After creating a user, clicking the Update User Value button, causes the render count to increment. This is because it's wrapped in a {{#if currentUser}}. If this is if is removed, you'll notice the render count remains at 1.
Also, you'll need to add the accounts-ui and accounts-password packages to your project.
Meteor will re-render any template containing reactive variables that are altered. In your case the {{currentUser}} is Meteor.user() which is an object containing the user's data. When you update the users profile, the object changes and it tells meteor to re-calculate everything reactive involving the object.
We could alter the reactivity a bit so it only reacts to changes in whether the user logs in/out and not anything within the object itself:
Meteor.autorun(function() {
Session.set("meteor_loggedin",!!Meteor.user());
});
Handlebars.registerHelper('session',function(input){
return Session.get(input);
});
Your html
{{#if session "meteor_loggedin"}}
{{> content}}
{{/if}}

Template reuse in meteor

I'm trying to reuse some control elements in my Meteor app. I'd like the following two templates to toggle visibility and submission of different forms.
<template name='addControl'>
<img class='add' src='/images/icon-plus.png' />
</template>
<template name='okCancelControl'>
<img class='submit' src='/images/icon-submit.png' />
<img class='cancel' src='/images/icon-cancel.png' />
</template>
I'll call these templates in another:
<template name='insectForm'>
{{#if editing}}
<!-- form elements -->
{{> okCancelControl}}
{{else}}
{{> addControl}}
{{/if}}
</template>
editing is a Session boolean.
What's a good way to wire up the controls to show, hide and "submit" the form?
The main problem is finding the addInsect template (where the data is) from the control templates (where the "submit" event fires). Here's what I did:
First, the controls:
<template name='addControl'>
<section class='controls'>
<span class="add icon-plus"></span>
</section>
</template>
<template name='okCancelControl'>
<section class='controls'>
<span class="submit icon-publish"></span>
<span class="cancel icon-cancel"></span>
</section>
</template>
Now the javascripts. They simply invoke a callback when clicked.
Template.addControl.events({
'click .add': function(event, template) {
if (this.add != null) {
this.add(event, template);
}
}
});
Template.okCancelControl.events({
'click .cancel': function(event, template) {
if (this.cancel != null) {
this.cancel(event, template);
}
},
'click .submit': function(event, template) {
if (this.submit != null) {
this.submit(event, template);
}
}
});
I then connected the callbacks using handlebars' #with block helper.
<template name='addInsect'>
{{#with controlCallbacks}}
{{#if addingInsect}}
<section class='form'>
{{> insectErrors}}
<label for='scientificName'>Scientific Name <input type='text' id='scientificName' /></label>
<label for='commonName'>Common Name <input type='text' id='commonName' /></label>
{{> okCancelControl}}
</section>
{{else}}
{{> addControl}}
{{/if}}
{{/with}}
</template>
And the corresponding javascript that creates the callbacks relevant to this form.
Session.set('addingInsect', false);
Template.addInsect.controlCallbacks = {
add: function() {
Session.set('addingInsect', true);
Session.set('addInsectErrors', null);
},
cancel: function() {
Session.set('addingInsect', false);
Session.set('addInsectErrors', null);
},
submit: function() {
var attrs, errors;
attrs = {
commonName: DomUtils.find(document, 'input#commonName').value,
scientificName: DomUtils.find(document, 'input#scientificName').value
};
errors = Insects.validate(attrs);
Session.set('addInsectErrors', errors);
if (errors == null) {
Session.set('addingInsect', false);
Meteor.call('newInsect', attrs);
}
}
};
Template.addInsect.addingInsect = function() {
Session.get('addingInsect');
};
Template.addInsect.events = {
'keyup #scientificName, keyup #commonName': function(event, template) {
if (event.which === 13) {
this.submit();
}
}
};
In the submit callback I had to use DomUtils.find rather than template.find because template is an instance of okCancelControl, not addInsect.
You can use Session for this. You Just need a template helper that returns a boolean flag that indicates whether you are editing the form fields. And manipulate the DOM based on the Session value set by this template helper.
Assume you have one text input, now when you are entering text in it, set the Session flag as true. This will trigger the helper to return true flag, Based on that, one of your two templates will be rendered in the DOM.
The isEditing is the helper that triggers whenever you change the Session value.
This helper function is the main part here, it returns true/false based on the session value you have set.
Template.insectForm.isEditing = function(){
if(Session.get('isEditing')){
return true;
}
else{
return false;
}
}
Remember to set the Session to false at the start-up as:
$(document).ready(function(){
Session.set('isEditing', false);
})
This will render the default add template in the html, Now when you click on ADD, you need to display another template, for that, set Session to true as:
'click .add' : function(){
Session.set('isEditing', true);
}
Accordingly when you click on CANCEL, set the session to false, this will make the isEditing to return false and the default add template will be displayed.
So your complete html will look something like this:
<template name='insectForm'>
{{#if isEditing}}
<!-- form elements -->
<input type="text" id="text" value="">
{{> okCancelControl}}
{{else}}
{{> addControl}}
{{/if}}
</template>
<template name='addControl'>
<img class='add' src='/images/icon-plus.png' />
</template>
<template name='okCancelControl'>
<img class='submit' src='/images/icon-submit.png' />
<img class='cancel' src='/images/icon-cancel.png' />
</template>
[UPDATE]
To get the instance of the template, you'll need to pass the additional parameter in the event handler that represents the template.
So update your event handler as:
Template.insectForm.events = {
'click .submit' : function(event, template){
//your event handling code
}
}
The parameter template is the instance of the template from which the event originates.
Note that, although the event fires form the image that is inside the okCancelControl template, the parameter will still contain the instance of the insectForm template. This is because we are calling the event handler as Template.insectForm.events = {} .
Also see this answer for template instances.

returning findOne object to template

Having troubles understanding how to return and use an object from findOne().
my code is this:
Html:
<head>
<title>count</title>
</head>
<body>
{{> hello}}
</body>
<template name="hello">
{{showcount}}
</template>
Js:
var Database = new Meteor.Collection("counters");
if(Meteor.is_client) {
Template.hello.showcount = function () {
var c = Database.findOne();
return c;
};
}
if (Meteor.is_server) {
Meteor.startup(function () {
if(Database.find().count() === 0)
{
Database.insert({name: "counter", value: 0});
}
});
}
Now I'm wondering if there is any way I can access the data from my object.
changing from {{showcount}} to {{showcount.name}} doesn't seem to work at all.
This same issue got me a few times when I started out with Meteor...
When the Meteor client connects to the server the template is being rendered before the collections have finished being synchronised. i.e. The client collection is empty at the point you are calling findOne.
To see this in action stick a console.log(c) after your findOne call then try reloading the page. You will see two log entries; Once on initial page load and then again when the collection has finished being synchronised.
To fix this all you need to do is update your hello template to handle the fact the collection might not have been synchronised.
{{#if showcount}}
{{showcount.name}}
{{/if}}
I tested your code with the above change and it works.
The proper way to do this is with the #with tag.
<template name="hello">
{{#with showcount}}
{{name}}
{{/with}}
</template>
See the documentation below for more info on the #with tag
https://github.com/meteor/meteor/blob/devel/packages/spacebars/README.md

Resources