I want to make a small invite system (User send an email to the friend with an ivitation code --> friend clicks on the public website everyone can go --> puts his invitation code in the text field and meteor searches for this code if it can find the code all is fine and he can continue but when meteor cant find the code he is one random internet user and he shouldnt can continue
So I need something which compares the inputted value with the data in the collection
this is my js file maybe some good things are already inside of it ;)
Template.Invite.onCreated(function() {
this.subscribe('invites');
});
Template.Invite.events({
'submit .Invite'(event) {
event.preventDefault();
var Invite = event.target.Invite.value;
}
});
Template.Invite.helpers({
results: function(){
return Invites.find({
code: Session.get('Invite'),
if (Invite = Invite)
{
FlowRouter.go('/');
}
});
}
});
my publish part in the main.js
Meteor.publish("invites", function() {
return Invites.find();
})
and the not important html
<template name="Invite">
<form class="Invite" >
<input type="text" name="Invite" placeholder="Invite Code" />
<input type="submit" value="Bestätigen" />
</form>
</template>
the insert in the Invite Collection works already but not the find and the compare
Thank you for your time and help ;)
I've created an invitation system a few times and this is how I did it.
When the user sends an invitation, you create a new document in the Invitation collection like this:
import { Random } from 'meteor/random';
const code = Random.hexString(16);
invitation = {
'code': code,
'sentTo': 'user#website.com',
'accepted': false,
}
Then when a user tries to sign up you need to call a method that grabs their invitation code and compares it to the code in the database
Meteor.methods({
'acceptInvitation'(code) {
check(code, String);
// find invitation in database
let invitation = Invitations.findOne({ 'code': code});
//check if invitation exists and if it hasn't already been accepted
if(invitation && invitation.accepted == false) {
//update invitation to now be accepted
Invitations.update(
{ '_id': invitation._id},
{ $set: { accepted: true }
);
return true;
} else {
throw new Meteor.Error('invalid', 'Your invitation code is not valid');
}
}
});
To make your invitation system even better, when you are sending the invitation email you can pass the invitation code as a parameter in the URL. Then when the user clicks the invitation link you can grab the code from the URL and automatically put it in the registration form for them. This prevents them making mistakes when they copy/paste it!
Related
I am trying to implement a simple login form using JavaScript and HTML. When I submit the form, I want to check the username and password against a list of valid credentials.
If the credentials are valid, I want to redirect the user to the home page. Otherwise, I want to show an error message. I have written the following code, but it is not working as expected. Can someone please help me debug this issue?
<form id="login-form">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
<script>
const form = document.getElementById('login-form');
const username = document.getElementById('username');
const password = document.getElementById('password');
form.addEventListener('submit', function(event) {
event.preventDefault();
const validCredentials = [
{ username: 'user1', password: 'pass1' },
{ username: 'user2', password: 'pass2' }
];
for (const credential of validCredentials) {
if (credential.username === username.value && credential.password === password.value) {
window.location.href = '/home';
} else {
alert('Invalid username or password');
}
}
});
</script>
I am implement a simple login form using JavaScript and HTML.
The expected outcome of the code is that when the user enters a valid username and password and clicks the submit button, they will be redirected to the home page. If the username and password are invalid, an error message should be displayed.
First of all, don't do this if you want to use this code for real users and production web app. It's not a good approach to hardcore users or passwords in a JavaScript script. If you are using this code for learning purposes, it's okay!
Secondly, the code has two meaningful problems. The alert inside the else block is running after every iteration of the for loop. You have to add a return statement to stop the loop and exists the function. Place the alert after the for loop, because the intention of the alert (I guess) is: if you don't find any coincidence, show to the user that the username and password are invalid.
for (const credential of validCredentials) {
if (credential.username === username.value && credential.password === password.value) {
return window.location.href = '/home';
}
} //end of the loop
alert('Invalid username or password');
}); //end of the callback function
});
On the other hand, in window.location.href = '/home', the string is a malformed URI. You have to send user to a completed URI like, https://google.com/ or http:/yoursite.com/home
I have a simple input box asking for users emails.
I want them to input something, for me to check it is a string, and then send a verification email to their email address entered.
Then once verified within users mail client and the link is clicked, I want the user to be added to my Firebase users.
At the moment, I am just testing without any email sending via SMTP, just adding data to Firebase. However, no emails I add are being added to my Firebase database.
Current code in the bottom of the body of the HTML, before the other script tags (should this be in the head?):
<script src="https://www.gstatic.com/firebasejs/3.6.1/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "myapikey",
authDomain: "mydomain.firebaseapp.com",
databaseURL: "https://mydomain.firebaseio.com",
storageBucket: "mydomain.appspot.com",
messagingSenderId: "mymessagesenderid"
};
firebase.initializeApp(config);
</script>
<script src="assets/js/saveEmail.js" type="text/javascript"></script>
Then I have an input box:
<div class="mtb">
<h2 class="signup-title">Sign up for updates on our project</h2>
<p id="signup-success" class="text-success"></p>
<p id="signup-error" class="text-danger"></p>
<form class="signup-form form-inline" id="signup-form" role="form" onsubmit="return signup(this)">
<div id="div">
<input type="email" name="email" class="subscribe-input" placeholder="Enter your e-mail address..." required>
<button class='btn btn-conf btn-yellow' id="signup-button" type="submit">Submit
</button>
</div>
</form>
</div>
And this is saveEmail.js:
var signupForm = document.getElementById('signup-form');
var signupSuccess = document.getElementById('signup-success');
var signupError = document.getElementById('signup-error');
var signupBtn = document.getElementById('signup-button');
var onSignupComplete = function (error) {
signupBtn.disabled = false;
if (error) {
signupError.innerHTML = 'Sorry. Could not signup.';
} else {
signupSuccess.innerHTML = 'Thanks for signing up!';
// hide the form
signupForm.style.display = 'none';
}
};
function signup(formObj) {
// Store emails to firebase
var myFirebaseRef = new Firebase("https://mydomain.firebaseio.com/signups");
myFirebaseRef.push({
email: formObj.email.value,
}, onSignupComplete);
signupBtn.disabled = true;
return false;
}
I know that the signup function is being called as I tried a simple JS alert, which does pop up when the submit button is clicked. However, I am seeing nothing change in my Firebase data dashboard under the /signups section. Also, the URL changes to:
http://localhost:5000/?email=theemailthatwasputintothebox
I modified my rules to:
{"rules":
{".read": true,
".write": true
}
}
So I assume this is not about rules as I have enabled everything for testing purposes.
How can I achieve what I want to achieve (without, and then with the email confirmation part)?
What is going wrong with the existing setup, without email confirmation via SendGrid etc?
I have a simple input box asking for users emails.
I want them to input something, for me to check it is a string, and
then send a verification email to their email address entered.
Then once verified within users mail client and the link is clicked, I want the user to be added to my Firebase users.
I do not think Firebase works that way. Unless the user is registered, you cannot send a verification email to an arbitrary email address. The sendEmailVerification method works on a currentUser.
According to the docs:
You can send an address verification email to a user with the sendEmailVerification method
Now, to your snippet, aren't you simply trying to take a user input and save it to the database? With the recent SDK, you can try this, as per docs
....
var database = firebase.database();
function signup(formObj) {
// Store emails to firebase
database.ref('signups')
.push({
email: formObj.email.value,
})
.then(function(res) {
console.log(res)
// call whatever callback you want here
})
.catch( .... )
}
FYI if you are using Firebase email verification think about testing it during your end-to-end or smoke tests.
Use a service like emaile2e.com to generate random email addresses during a test which you can send and receive from. That way you can verify users during a test programmatically.
I am trying to implement the facebook accountkit using javascript. I followed the documentation on https://developers.facebook.com/docs/accountkit/web/integrating.
AccountKit login form
Enter country code (e.g. +1):
<input type="text" id="country_code" />
Enter phone number without spaces (e.g. 444555666):
<input type="text" id="phone_num"/>
<button onclick="phone_btn_onclick();">Login via SMS</button>
Enter email address
<input type="text" id="email"/>
<button onclick="email_btn_onclick();">Login via Email</button>
Below is the javascript code on my app
<script src="https://sdk.accountkit.com/en_US/sdk.js"></script>
<script>
// initialize Account Kit with CSRF protection
AccountKit_OnInteractive = function(){
AccountKit.init(
{
appId:'facebook_app_id',
state:"csrf",
version:"accountkit_version"
}
);
};
// login callback
function loginCallback(response) {
console.log(response);
if (response.status === "PARTIALLY_AUTHENTICATED") {
document.getElementById("code").value = response.code;
document.getElementById("csrf_nonce").value = response.state;
document.getElementById("my_form").submit();
}
else if (response.status === "NOT_AUTHENTICATED") {
// handle authentication failure
}
else if (response.status === "BAD_PARAMS") {
// handle bad parameters
}
}
// phone form submission handler
function phone_btn_onclick() {
var country_code = document.getElementById("country_code").value;
var ph_num = document.getElementById("phone_num").value;
AccountKit.login('PHONE',
{countryCode: country_code, phoneNumber: ph_num}, // will use default values if this is not specified
loginCallback);
}
// email form submission handler
function email_btn_onclick() {
var email_address = document.getElementById("email").value;
AccountKit.login('EMAIL', {emailAddress: email_address}, loginCallback);
}
</script>
After setting the required values for appId, state and version. I tried filling the form but I was redirecting to account kit page saying
we are sorry, something went wrong, try again
Any help in the implementation will be highly appreciated. Thanks in advance
The problem has been resolved. On account kit page on facebook developer site, I pointed the server url on web login settings to all occurrence of the domain i.e http://domain.com, http://www.domain.com including https if available. This resolved the problem. THANKS ALL.
I'm trying to build out a system so that the default accounts sytem built into MeteorJS will have a friends list. Unfortunately, this just isn't working, and I can't figure out why. I'm currently attempting to simply add a friendList array to the user.profile, and then simply append the added user to the end of that list.
Here's the code:
Server:
Meteor.methods({
addFriend: function(friendUsername){
friendUserId = Meteor.users.findOne({username:friendUsername});
if(friendUserId){
Meteor.users.update({_id:Meteor.userId()}, {$set:{"profile.friendList":Meteor.user().profile['friendList'].push(friendUserId)}});
return 1;
}
else return 0;
}
});
Client:
Template.addFriendPage.events({
"keypress .addFriendByUsername": function(event, template){
if(event.which == 13){
event.preventDefault();
var user = Meteor.userId();
var friendUsername = template.find(".addFriendByUsername").value;
console.log(friendUsername);
console.log(user);
console.log(Meteor.call("addFriend",friendUsername));
if(Meteor.call("addFriend", friendUsername)){
alert("successfully added friend!");
template.find(".addFriendByUsername").value = "";
} else alert("not a valid username");
}
}
});
The html is just a template that I can put a username into. And I know I have to add in the part where I add the current user to the other user's friend list, but I want to get this working first.
Your main problem is you're setting a push. Instead, you need to use $push.
var userId = Meteor.user();
Meteor.users.update(userId, {$push:'profile.friendList':friendUserId});
Second, I'd consider it a moderately bad idea to store friends on the user profile. Consider creating a friends collection.
I have a page which takes only one input from the user: passcode
Now I want to verify this entered passcode and then redirect the user to the next page (let's say the order page). For security I would like to know if the user entered the passcode and came to the order page or just typed the URL in the address bar.
For example:
// Client code
Template.Home.events({
'click #btnGoToOrderForm' : function() {
var passcode = $('#inptPasscode').val();
if ( passcode ) {
Meteor.call('cehckPasscode', passcode, function(error, result) {
if ( result == true ) {
Router.go('order');
}
});
}
}
});
// Server code
Meteor.methods({
'checkPasscode' : function(passcode) {
console.log(passcode);
if ( passcode == 'welcome' ) {
return true;
}
else {
return false;
}
}
});
HTML code:
<div class="input-group">
<input id="inptPasscode" type="password" class="form-control" placeholder="Enter the passcode...">
<span class="input-group-btn">
<button id="btnGoToOrderForm" class="btn btn-primary" type="password">Go!</button>
</span>
</div>
How can I do it?
You could save the value to the Session - but still people could modify the session and break your 'security'.
I would recommend going with HTTP authentication on that specific URL.
https://github.com/Jabbslad/basic-auth
I would recommend using something like a bcrypt library to generate a salted hash before passing it between client/server:
https://atmospherejs.com/meteor/npm-bcrypt
The doc for the package is completely missing, but it is actually the same as: https://www.npmjs.com/package/bcrypt