Meteor server only variables/security keys - javascript

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

Related

Simple Login Form

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

Javascript XMLHttpRequest and Jquery $.ajax both are returning the current page HTML code

The problem
Hello i want to start off hoping all of y'all are having a fantastic day! I'm having a really weird problem that i have never came across before. I have a bootstrap navigation form with two fields, an input for a email and a field for the password.
When the user submits the form it calls to an AddEventListener which is waiting for a click of the login button. and after that is called it validates(Server Side Validation) the form of the entered data. After both the email_validated and password_validated is both equal to true it calls to a function called checkLogin(email, password){email = entered email in field, password = entered password in field}. In the checkLogin function it called to a JQuery $.ajax({}) call which sends the email and password field to a php document located in /scripts/checkLogin.php. However instead of it returning "Hello"(For testing purposes) is returns the entire HTML code for the current page(As shown above)
JQuery $.ajax({}) code
Here i have the code for the $.ajax({}) call.
Console
I'm not getting any errors in the console except for the XHR finished loading: POST
Other Pictures
Here are some other pictures that i am including to hopefully give yall a better idea of the structure.
Note
I just want to add that i have checked Stackoverflow for similar problems and other people have had this problem but they solutions did not work on my code. I have also tried just using a regular XMLHttpRequest and the same problem occurred, i'm honestly not sure what is wrong with the code for i have never had this problem before. Thank you for taking the time to read this i appreciate any help that i can get with solving this. I'm not the best with $.ajax({}) or XMLHttpRequest and im willing to make any changed to the code to try to get this to work. Below is my code for the entire javascript validation(server side).
Code
<form class="form-inline my-2 my-lg-0" method="POST">
<input class="form-control mr-sm-2 nav-login" type="text" autocomplete="off" placeholder="Email" name="email" value="trest#gmail.com" id="email">
<input type="password" name="password" autocomplete="off" class="form-control nav-login mr-sm-2" placeholder="Password" value="password" name="password" id="password">
<button class="btn btn-success my-2 my-sm-0 nr" type="button" name="login_button" id="login_button">Login <i class="fas fa-sign-in-alt"></i></button>
</form>
<script>
document.getElementById('login_button').addEventListener('click', (e) => {
e.preventDefault();
// const email_regex = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
let email_validated = true;
let password_validated = true;
let email = document.getElementById('email');
let password = document.getElementById('password');
// let email_length = email.value.length;
// let password_length = password.value.length;
//
//
// if(!email_length){
// email.classList.add('is-invalid');
// }else{
// if(!email_regex.test(email.value)){
// email.classList.add('is-invalid');
// }else{
// email.classList.remove('is-invalid');
// email.classList.add('is-valid');
// email_validated = true;
//
// }
// }
// if(!password_length){
// password.classList.add('is-invalid');
// }else{
// password.classList.remove('is-invalid');
// password.classList.add('is-valid');
// password_validated = true;
// }
if(email_validated === true && password_validated === true){
checkLogin(email.value, password.value);
}
});
function checkLogin(email, password){
$.ajax({
type: "POST",
url: '/scripts/checkLogin.php',
data: {
'email': email,
'password': password
},
contentType: "application/json; charset=utf-8",
success: (result) => {
alert(result);
}
});
}
</script>
Links to the other StackOverFlow question
ajax returns the html code of current page instead of json
I was the way my server was configured with xammp as t.niese said.

Meteor How to create a Invite system

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!

Facebook Accountkit JAVASCRIPT Implementation

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.

Validate form's textarea - jQuery

I am trying to develope a plugin for an application that let the users invite their friends to use the application by just sending an email. Juts like Dropbox does to let the users invite friends and receive extra space.
I am trying to validate the only field I have in the form (textarea) with JQuery (I am new to JQuery) before submiting it and be handled by php.
This textarea will contain email addresses, separated by commas if more than one. Not even sure if textarea is the best to use for what I am trying to accomplish. Anyway here is my form code:
<form id="colleagues" action="email-sent.php" method="POST">
<input type="hidden" name="user" value="user" />
<textarea id="emails" name="emails" value="emails" placeholder="Example: john#mail.com, thiffany#mail.com, scott#mail.com..."></textarea>
</br><span class="error_message"></span>
<!-- Submit Button -->
<div id="collegues_submit">
<button type="submit">Submit</button>
</div>
</form>
Here is what I tried in Jquery with no success:
//handle error
$(function() {
$("#error_message").hide();
var error_emails = false;
$("#emails").focusout(function() {
check_email();
});
function check_email() {
if(your_string.indexOf('#') != -1) {
$("#error_message").hide();
} else {
$("#error_message").html("Invalid email form.Example:john#mail.com, thiffany#mail.com, scott#mail.com...");
$("#error_message").show();
error_emails = true;
}
}
$("#colleagues").submit(function() {
error_message = false;
check_email();
if(error_message == false) {
return true;
} else {
return false;
}
});
I hope the question was clear enough, if you need more info please let me know.
Many thanks in advance for all your help and advises.
var array = str.split(/,\s*/);
array.every(function(){
if(!validateEmail(curr)){
// email is not valid!
return false;
}
})
// Code from the famous Email validation
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
Few errors as I noted down:
The code snippet posted here has missing braces }); at the end.
Also, what is your_string variable in the function check_email.
Also, error_message is assigned false always so the submit method will return true always.
Fixing this issues should help you.
I would use, as I commented above, append() or prepend() and just add fields. As mentioned in another post, client side use jQuery validation, but you should for sure validate server-side using a loop and filter_var($email, FILTER_VALIDATE_EMAIL). Here is a really basic example of the prepend():
<form id="colleagues" action="" method="POST">
<input type="hidden" name="user" value="user" />
<input name="emails[]" id="starter" placeholder="Email address" />
<div id="addEmail">+</div>
</br><span class="error_message"></span>
<!-- Submit Button -->
<div id="collegues_submit">
<button type="submit">Submit</button>
</div>
</form>
<script>
$(document).ready(function() {
$("#addEmail").click(function() {
$("#colleagues").prepend('<input name="emails[]" placeholder="Email address" />');
});
});
</script>
Hi please use below js code,
$('#emails').focusout(function(e) {
var email_list = $('#emails').val();
var email_list_array = new Array();
email_list_array = email_list.split(",");
var invalid_email_list=' ';
$.each(email_list_array, function( index, value ) {
if(!validEmail(value))
{
invalid_email_list=invalid_email_list+' '+value+',';
}
});
console.log(invalid_email_list+' is not correct format.');
alert(invalid_email_list+' is not correct format.');
})
function validEmail(v) {
var r = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
return (v.match(r) == null) ? false : true;
}
If you need to check more REGEX just do it validEmail() function. I hope this will help to sort out.
thank you
Your code might look correct, but you are using bad technique. My advice is to use jquery validation plugin that would handle textarea validation.for you. Also notice. There might be many solutions for this problem, but you should stick with simple one. And the first problem i see stright away is: button tag doesnt have type attribute. You are changing #error_message html, not text. Etc...

Categories

Resources