How do I login a user with Meteor - meteor

I've added accounts-password and useraccounts:unstyled
I've included the signin template in my footer.html -
{{#if showSignIn}}
{{> atForm state="signIn"}}
{{/if}}
I'm hard coding the creation of users as the app starts up -
import { Accounts } from 'meteor/accounts-base'
if (!Acounts.findUserByEmail('aidan#gmail.com')) {
Accounts.createUser({
username: 'Aidan',
email: 'aidan#gmail.com',
password: 'securePassword'
});
}
It's just that I can't work out how to actually log my user in. I've tried simply entering the password and email address into the form. That doesn't work (the form error says 'Login Forbidden').
I've tried adding the following line (to the same file as my account creation code) -
accountsServer.validateLoginAttempt(()=>{return true;});
Unsurprisingly that doesn't do anything.
I've tried add a submit event into my footer.js file -
Template.footer.events({
'submit form'(event) {
console.log('submitted');
const email = document.getElementById('at-field-email').value;
const password = document.getElementById('at-field-password').value;
Meteor.loginWithPassword(email, password);
},
});
I can see that the event is firing, but when I try Meteor.user() in the console I still get null.

There's typo in if (!Acounts.findUserByEmail('aidan#gmail.com')) (it should have been Accounts). The user isn't being created.
To get a super simple functional login with a single hard coded user -
Add the accounts-password package and the ui user accounts package.
> meteor add accounts-password
> meteor add useraccouts:unstyled
The accounts-password package handles the actual logging in. The user accounts:unstyled packages provides a set of templates for accounts management.
Then add the login form to a template.
<template name="templateWithLogin">
{{> atForm state="signIn"}}
</template>
Lastly create a user (e.g. in /server/main.js).
import { Accounts } from 'meteor/accounts-base';
if (!Accounts.findUserByEmail('user#gmail.com')) {
Accounts.createUser({
username: 'User',
email: 'user#gmail.com',
password: 'securePassword'
});
}
This should be everything needed to get a functional login form. There's loads of tutorials online for creating additional functionality. The main documentation is here.

you can use {{>loginButtons}} to get the ui and {{#if currentUser }} for the functionality.

Related

Stripe payment with JMSPaymentBundle "The source parameter is required"

I already integrated JMSPaymentBundle, with paypal every thing works fine!
When I tried to change with stripe from this link for JMS
and using ruudk/PaymentStripeBundle from github, it's actually the same.
But there is a thing. I'm receiving this error: The source parameter is required
In the issues of the bundle, I found that I must use stripe form
<form action=""
method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="MYPUBLISHEDKEY"
data-amount="999"
data-name="Demo Site"
data-description="Widget"
data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
data-locale="auto">
</script>
</form>
This form generates a Token. What I need to know is :
1- Where to put that published token used by JMSPaymentBundle?
2- What action in the form should I do? Is it the same for paypal?
it's hard to say what's going on here but it seems like https://github.com/ruudk/PaymentStripeBundle/ is lacking some necessary documentation.
From what I can tell it's adding a token hidden field to your forms:
https://github.com/ruudk/PaymentStripeBundle/blob/master/src/Form/CheckoutType.php#L12
However, the Checkout embed code you're using won't save the token to that field. I don't see any additional Javascript embedded in this library, so you'll need to build your own using the custom Stripe Checkout integration:
https://stripe.com/docs/checkout#integration-custom
Something like this should work:
var handler = StripeCheckout.configure({
key: 'pk_test_6pRNASCoBOKtIshFeQd4XMUh',
image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
locale: 'auto',
token: function(token) {
// NOTE: assuming that the field injected by the library has an ID of "token"--you'll have to check your DOM and possibly adjust this
var field = document.getElementById('token');
field.value = token.id;
// TODO: submit form and send to your backend
}
});
document.getElementById('customButton').addEventListener('click', function(e) {
// Open Checkout with further options:
handler.open({
name: 'Stripe.com',
description: '2 widgets',
zipCode: true,
amount: 2000
});
e.preventDefault();
});
// Close Checkout on page navigation:
window.addEventListener('popstate', function() {
handler.close();
});

Display list of user email addresses in Meteor

I'm trying to get a list of all users in meteor using Metor.methods
This is my code :
server/main.js
Meteor.methods({
'createUser': function(){
if (Meteor.users.find({}).count()===0) {
for (i = 0; i <= 5; i++){
let id = Accounts.createUser({
email: Meteor.settings.ADMIN_USE,
password: Meteor.settings.ADMIN_PASSWORD,
profile: { firstName: Meteor.settings.ADMIN_FIRSTNAME, lastName: Meteor.settings.ADMIN_LASTNAME }
});
}
}
},
'returnmail': function(){
return Meteor.users.findOne().emails[0].address;
}
});
then i call this function in another file called Listusers.js:
Template.ListUsers.helpers({
email: function(){
Meteor.call('returnmail');
},
});
I'm trying to display the value of email using this code but it doesn't work
Client/ListUsers.html
<Template name="ListUsers">
<input id="mail" type="text" value="{{email}}" />
</Template>
Several problems. I strongly recommend you go through the tutorial at least. The Discover Meteor ebook is also invaluable. One of the first steps in understanding Meteor is moving from a traditional XHR request-response model to publish-subscribe.
Your email helper needs to return a value.
Meteor.call() doesn't return anything. Normally you use it with a callback that gives you an error status and the result. However you can't use that in a helper unless you use a Session variable or a promise because the return value from the call is at the wrong context level.
Your returnmail method is only returning a single email address from findOne() and not any specific one either, just a quasi-random one (you can't guarantee which document findOne() is going to return!)
You're creating 5 identical users with the same email address and password. 2-5 are going to fail because of a uniqueness constraint on the email field.
Now on to the solution.
On the server, publish the Users collection including only the emails field (which is an array of objects)
On the client, subscribe to that publication.
On the client, iterate over the users collection and get the email address from a helper.
server:
Meteor.publish('allEmails',function(){
// you should restrict this publication to only be available to admin users
return Meteor.users.find({},{fields: { emails: 1 }});
});
client js:
Meteor.subscribe('allEmails');
Template.ListUsers.helpers({
allUsers(){ return Meteor.users.find({}); },
email(){ return this.emails[0].address; }
});
client html:
<Template name="ListUsers">
{{#each allUsers}}
<input id="mail" type="text" value="{{email}}" />
{{/each}}
</Template>

How to delete users from account-ui meteor

I'm making a meteor app and using accounts ui and bootstrap and all that stuff but I'm wondering if there is a way I can be like an admin and delete users because recently people have been making inappropriate usernames and such..
Well you can delete users pretty easy like. having a template protected just to admin accounts and on that template have a list with the users, based on that create an event like this.
Template.example.events({
'click #deleteAccount':function(){
meteor.users.remove({_id:this._id})
}
})
and use an allow method like this.
Meteor.allow({
remove:function(){
//if is admin return true;
}
})
But thats not a good practice, why? check this David Weldon -common-mistakes
if there is a way I can be like an admin?
For accomplish this on a better way use the meteor-roles package,
With this you can can protect templates with
{{if isInRole 'Admin'}}
<!--show admin stuff-->
{{else}}
<!--sorry just admin stuff here -->
{{/else}}
and create basic admin accounts.
if(Meteor.users.find().count() === 0){
var users = [
{name:"Admin Example",email:"supersecretaccount#gmail.com",roles:['Admin']}
];
_.each(users, function (user) {
var id;
id = Accounts.createUser({
email: user.email,
password: "amore251327",
profile: { name: user.name }
});
if (user.roles.length > 0) {
Roles.addUsersToRoles(id, user.roles);
}
});
}
Try it

Meteor: How to keep showing profile avatar after logged out?

After reading Discover Meteor, I'm trying to customize microscope to further practice my meteor skills.
I am using accounts-twitter and hope to display the user's twitter profile pic on each of their post submission. I user the following helper to get the post's author id in post_item.js
Template.postItem.helpers({
username: function () {
owner = this.userId;
var user = Meteor.users.findOne({
_id: owner
});
return user;
}
});
And then in post_item.html I use the following to display the profile pic:
<img class="pull-right" src="{{username.profile.avatar}}">
If I've logged in my account, I can see my profile pic next to all of my submitted posts. However, when I log out, all the profile pics will be disappeared.
Sorry for the newbie questions. Any pointers are welcome.
Thanks for your help.
Stupid me. I forgot that by default, Meteor only publishes the logged in user. Hopefully the following answer will help other meteor newbies.
Server:
Meteor.publish("allUsers", function () {
return Meteor.users.find({}, {
fields: {
profile: 1
}
});
});
Client:
Meteor.subscribe('allUsers');
Then you will be able to load all the user's profile pics using the following:
<img src="{{username.profile.avatar}}">

Detecting logout event of {{> loginButtons}} in Meteor

I am working on project using meteor 0.8.2 and i have added "accounts-ui" and "accounts-password" for login functionality in the project. The login module works perfect. I am curious to know that, How to detect the logout event? Is there any function like,
Template.loginButtons.events({
'click .logout'=function(e)
{
console.log("I logged out!");
}
});
There is no official callback like Meteor.onLogout, but the standard way to handle this is as follow :
In templates :
{{#if currentUser}}
<p>logged in</p>
{{else}}
<p>logged out</p>
{{/if}}
currentUser is a standard Spacebars helper that simply returns the current user, if there is none, it returns a falsy value.
http://docs.meteor.com/#template_currentuser
In javascript :
Deps.autorun(function(computation){
var currentUser=Meteor.user();
if(currentUser){
console.log("logged in");
}
else if(!computation.firstRun){
console.log("logged out");
}
});
We can mirror the tempate code by registering a new Deps.Computation that references Meteor.user() which happens to be a reactive data-source returning the current user.
Whenever this variable change (ie on login/logout) the computation will rerun and we can inject our own custom code to handle login/logout in our webapp.
EDIT : as Neil said, the computation is run immediately following the declaration, in a state where the login resuming process maybe uncomplete resulting in a useless systematic logout detection on app startup, which might be an inconvenience.
We can detect the first run of the computation using the built in firstRun property and execute the logout logic only when it's NOT the first run.
You want watch the reactive function Meteor.userId for changes using Deps.autorun.
var started = false;
Deps.autorun(function () {
if (started && !Meteor.userId())
console.log('I logged out!');
started = true;
});
The function runs once immediately so started prevents that from being interpreted as a logout.

Resources