Facebook Accountkit JAVASCRIPT Implementation - javascript

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.

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!

Firebase email verification workflow

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.

Meteor server only variables/security keys

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

Categories

Resources