error occur in second argument of signInWithPhoneNumber() and i am not able to fix this problem, in there is three method i used for send otp, verify otp and last on for captcha
methods:{
sendOTP(e){
e.preventDefault();
if(this.phoneNo.length!=10){
alert('Invalid No.');
}else{
let countryCode="+91"
let phoneNumber=countryCode+ this.phoneNo
let appVerifier=window.recaptchaVerifier
firebase.default.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
.then(function (confirmationResult){
console.log(confirmationResult);
window.confirmationResult=confirmationResult;
alert('SMS sent')
}).catch(function(err){
console.log(err);
alert('SMS not sent')
});
}
},
this method for verify OTP using firebase
verifyOTP(e){
e.preventDefault();
if(this.phoneNo.length!=10||this.otp.length!=6){
alert('Invalid format')
}
else{
let vm=this
let code=this.otp
//var user
window.confirmationResult.confirm(code).then(function (result){
console.log(result);
var user = user.result
vm.$router.push({path:'/home'})
})
}
},
here i initial the captcha method
initReCaptcha(){
setTimeout(()=>{
//let vm = this
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container', {
'size': 'invisible',
'callback': function() {
// reCAPTCHA solved, allow signInWithPhoneNumber.
// ...
},
'expired-callback': function() {
// Response expired. Ask user to solve reCAPTCHA again.
// ...
}
});
//
this.appVerifier = window.recaptchaVerifier
},1000)
},
here i created captcha
created(){
this.initReCaptcha()
}
Related
I am Creating an expo app in which a user can login using Gmail.
I followed this firebase documentation to implement that functionality but whenever I click on login, it doesn't neither save the data in the database nor return any error.
This is my firebase function:
isUserEqual = (googleUser, firebaseUser)=> {
if (firebaseUser) {
var providerData = firebaseUser.providerData;
for (var i = 0; i < providerData.length; i++) {
if (providerData[i].providerId === firebase.auth.GoogleAuthProvider.PROVIDER_ID &&
providerData[i].uid === googleUser.getBasicProfile().getId()) {
// We don't need to reauth the Firebase connection.
return true;
}
}
}
return false;
}
onSignIn = (googleUser)=> {
console.log('Google Auth Response', googleUser);
// We need to register an Observer on Firebase Auth to make sure auth is initialized.
var unsubscribe = firebase
.auth()
.onAuthStateChanged(function(firebaseUser) {
unsubscribe();
// Check if we are already signed-in Firebase with the correct user.
if (!this.isUserEqual(googleUser, firebaseUser)) {
// Build Firebase credential with the Google ID token.
var credential = firebase.auth.GoogleAuthProvider.credential(
googleUser.idToken,
googleUser.accessToken
);
// Sign in with credential from the Google user.
firebase.auth()
.signInAndRetrieveDataWithCredential(credential)
.then(function(result) {
console.log('User signed in');
})
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
} else {
console.log('User already signed-in Firebase.');
}
}.bind(this)
);
};
signInWithGoogleAsync = async() => {
try {
const result = await Expo.Google.logInAsync({
behavior: 'web',
androidClientId: '929952027781-5ao9pp7n5n0sj2n70i5tp7klfro88bgp.apps.googleusercontent.com',
iosClientId: '929952027781-7obs66o3kr59kdhp6ll0c9598ue3u8aa.apps.googleusercontent.com',
scopes: ['profile', 'email'],
});
if (result.type === 'success') {
this.onSignIn(result);
return result.accessToken;
} else {
return {cancelled: true};
}
} catch(e) {
return {error: true};
}
}
And this is my login button:
<TouchableOpacity style={styles.AuthOptionGmail} onPress={() => signInWithGoogleAsync()}>
<Ionicons color='#ffffff' style = {styles.BtnIcon} name="logo-google" size={25}/>
<Text style={{fontSize:16,color:'#ffffff', textAlign:'center'}}>Login with Gmail</Text>
</TouchableOpacity>
Can anyone tell me where I messed up please????
with Expo sdk 32 and above following worked for me , just install "expo-google-app-auth"
import * as Google from "expo-google-app-auth";
signInWithGoogleAsync = async () => {
console.log("signInWithGoogleAsync");
try {
//clientId
const { type, accessToken, user, idToken } = await Google.logInAsync({
behavior: "web",
androidClientId:
"your id",
iosClientId:
"your id",
scopes: ["profile", "email"]
});
if (type === "success") {
console.log("accessToken" + accessToken);
console.log("idToken" + idToken);
console.log(user);
return accessToken;
} else {
return { cancelled: true };
}
} catch (e) {
console.log(e);
return { error: true };
}
};
Introduction
Ok, I have Three functions. the first two generate data for the third.
Gets post data (email)
Gets API key
Uses API key, User_key and email and post them to the API
What I need
I need the third to print the following to my console providing the email is present.
else {
console.log("Login successful !");
console.log("API Key", api);
console.log("userKey", userkey);
console.log("useremail", login_email);
console.error("Third You have logged in !");
}
What I am getting
error null
I am getting this even though I post a email that exist. Dose anyone see where I am going wrong in my code ?
Node Code
var firstFunction = function () {
var promise = new Promise(function (resolve) { // may be redundant
setTimeout(function () {
app.post('/test.js', function (req, res) {
console.log(req.body);
// Get varibles from the post form
var login = req.body.LoginEmail;
// res.send(email_user);
res.send(login);
//resolve when get the response
resolve({
data_login_email: login
});
});
console.error("First done");
}, 2000);
});
return promise;
};
//---------------------------------- Function to get API key from Pardot (AUTHENTICATION) ------------------------------
//----------------------------------------------------------------------------------------------------------------------
var secondFunction = function () {
var promise = new Promise(function (resolve) {
setTimeout(function () {
nodePardot.PardotAPI({
userKey: userkey,
email: emailAdmin,
password: password,
DEBUG: false
}, function (err, client) {
if (err) {
// Authentication failed
console.error("Authentication Failed", err);
} else {
// Authentication successful
var api_key = client.apiKey;
console.log("Authentication successful !", api_key);
resolve({data_api: api_key});
}
});
console.error("Second done");
}, 2000);
});
return promise;
};
//---------------------------------- Function to post data to Pardot ---------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
function thirdFunction(result) {
var promise = new Promise(function () {
setTimeout(function () {
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded'
};
// Configure the request
var api = result[1].data_api;
var userEmail = result[0].data_login_email;
var options = {
url: 'https://pi.pardot.com/api/prospect/version/4/do/read',
method: 'POST',
headers: headers,
form: {
'email': userEmail,
'user_key': userkey,
'api_key': api
}
};
// Start the request
request(options, function (error, response) {
if (!error && response.statusCode == 200) {
console.log("error", error);
}
else {
console.log("Login successful !");
console.log("API Key", api);
console.log("userKey", userkey);
console.log("useremail", login_email);
console.error("Third You have logged in !");
}
});
}, 3000);
});
return promise;
}
// sequence of functions
Promise.all([firstFunction(), secondFunction()])
.then(thirdFunction);
When I login to my firebase v 2.4.1 app using email / password auth with an invalid email. Firebase throws an error internally and I can't seem to find a way to catch it.
The examples here work, but they are using v.1.1.1 and when I swap the libraries in my app to 1.1.1 it seems to work also
Am I missing something or is this a known issue?
http://jsfiddle.net/firebase/a221m6pb/embedded/result,js/
(function (jQuery, Firebase, Path) {
"use strict";
// the main firebase reference
var rootRef = new Firebase('https://docs-sandbox.firebaseio.com/web/uauth');
// pair our routes to our form elements and controller
var routeMap = {
'#/': {
form: 'frmLogin',
controller: 'login'
},
'#/logout': {
form: 'frmLogout',
controller: 'logout'
},
'#/register': {
form: 'frmRegister',
controller: 'register'
},
'#/profile': {
form: 'frmProfile',
controller: 'profile',
authRequired: true // must be logged in to get here
},
};
// create the object to store our controllers
var controllers = {};
// store the active form shown on the page
var activeForm = null;
var alertBox = $('#alert');
function routeTo(route) {
window.location.href = '#/' + route;
}
// Handle third party login providers
// returns a promise
function thirdPartyLogin(provider) {
var deferred = $.Deferred();
rootRef.authWithOAuthPopup(provider, function (err, user) {
if (err) {
deferred.reject(err);
}
if (user) {
deferred.resolve(user);
}
});
return deferred.promise();
};
// Handle Email/Password login
// returns a promise
function authWithPassword(userObj) {
var deferred = $.Deferred();
console.log(userObj);
rootRef.authWithPassword(userObj, function onAuth(err, user) {
if (err) {
deferred.reject(err);
}
if (user) {
deferred.resolve(user);
}
});
return deferred.promise();
}
// create a user but not login
// returns a promsie
function createUser(userObj) {
var deferred = $.Deferred();
rootRef.createUser(userObj, function (err) {
if (!err) {
deferred.resolve();
} else {
deferred.reject(err);
}
});
return deferred.promise();
}
// Create a user and then login in
// returns a promise
function createUserAndLogin(userObj) {
return createUser(userObj)
.then(function () {
return authWithPassword(userObj);
});
}
// authenticate anonymously
// returns a promise
function authAnonymously() {
var deferred = $.Deferred();
rootRef.authAnonymously(function (err, authData) {
if (authData) {
deferred.resolve(authData);
}
if (err) {
deferred.reject(err);
}
});
return deferred.promise();
}
// route to the specified route if sucessful
// if there is an error, show the alert
function handleAuthResponse(promise, route) {
$.when(promise)
.then(function (authData) {
// route
routeTo(route);
}, function (err) {
console.log(err);
// pop up error
showAlert({
title: err.code,
detail: err.message,
className: 'alert-danger'
});
});
}
// options for showing the alert box
function showAlert(opts) {
var title = opts.title;
var detail = opts.detail;
var className = 'alert ' + opts.className;
alertBox.removeClass().addClass(className);
alertBox.children('#alert-title').text(title);
alertBox.children('#alert-detail').text(detail);
}
/// Controllers
////////////////////////////////////////
controllers.login = function (form) {
// Form submission for logging in
form.on('submit', function (e) {
var userAndPass = $(this).serializeObject();
var loginPromise = authWithPassword(userAndPass);
e.preventDefault();
handleAuthResponse(loginPromise, 'profile');
});
// Social buttons
form.children('.bt-social').on('click', function (e) {
var $currentButton = $(this);
var provider = $currentButton.data('provider');
var socialLoginPromise;
e.preventDefault();
socialLoginPromise = thirdPartyLogin(provider);
handleAuthResponse(socialLoginPromise, 'profile');
});
form.children('#btAnon').on('click', function (e) {
e.preventDefault();
handleAuthResponse(authAnonymously(), 'profilex');
});
};
// logout immediately when the controller is invoked
controllers.logout = function (form) {
rootRef.unauth();
};
controllers.register = function (form) {
// Form submission for registering
form.on('submit', function (e) {
var userAndPass = $(this).serializeObject();
var loginPromise = createUserAndLogin(userAndPass);
e.preventDefault();
handleAuthResponse(loginPromise, 'profile');
});
};
controllers.profile = function (form) {
// Check the current user
var user = rootRef.getAuth();
var userRef;
// If no current user send to register page
if (!user) {
routeTo('register');
return;
}
// Load user info
userRef = rootRef.child('users').child(user.uid);
userRef.once('value', function (snap) {
var user = snap.val();
if (!user) {
return;
}
// set the fields
form.find('#txtName').val(user.name);
form.find('#ddlDino').val(user.favoriteDinosaur);
});
// Save user's info to Firebase
form.on('submit', function (e) {
e.preventDefault();
var userInfo = $(this).serializeObject();
userRef.set(userInfo, function onComplete() {
// show the message if write is successful
showAlert({
title: 'Successfully saved!',
detail: 'You are still logged in',
className: 'alert-success'
});
});
});
};
/// Routing
////////////////////////////////////////
// Handle transitions between routes
function transitionRoute(path) {
// grab the config object to get the form element and controller
var formRoute = routeMap[path];
var currentUser = rootRef.getAuth();
// if authentication is required and there is no
// current user then go to the register page and
// stop executing
if (formRoute.authRequired && !currentUser) {
routeTo('register');
return;
}
// wrap the upcoming form in jQuery
var upcomingForm = $('#' + formRoute.form);
// if there is no active form then make the current one active
if (!activeForm) {
activeForm = upcomingForm;
}
// hide old form and show new form
activeForm.hide();
upcomingForm.show().hide().fadeIn(750);
// remove any listeners on the soon to be switched form
activeForm.off();
// set the new form as the active form
activeForm = upcomingForm;
// invoke the controller
controllers[formRoute.controller](activeForm);
}
// Set up the transitioning of the route
function prepRoute() {
transitionRoute(this.path);
}
/// Routes
/// #/ - Login
// #/logout - Logut
// #/register - Register
// #/profile - Profile
Path.map("#/").to(prepRoute);
Path.map("#/logout").to(prepRoute);
Path.map("#/register").to(prepRoute);
Path.map("#/profile").to(prepRoute);
Path.root("#/");
/// Initialize
////////////////////////////////////////
$(function () {
// Start the router
Path.listen();
// whenever authentication happens send a popup
rootRef.onAuth(function globalOnAuth(authData) {
if (authData) {
showAlert({
title: 'Logged in!',
detail: 'Using ' + authData.provider,
className: 'alert-success'
});
} else {
showAlert({
title: 'You are not logged in',
detail: '',
className: 'alert-info'
});
}
});
});
}(window.jQuery, window.Firebase, window.Path))
I removed the 1.1.1 reference from your jsFiddle and added the 2.4.1 one (https://cdn.firebase.com/js/client/2.4.1/firebase.js) and then tried it with a random email and it reacted exactly the same as with the previous version. Can you give me more details on how to reproduce it? I was using Chrome.
I'm having quite a hard time understanding how to chain promises. I'm writing login function for my app, leverating Loopback's Angular SDK. The objective, upon validating a user's credentials, is to confirm that the user's account is active, then fetch some additional properties including the user's role and set a flag to true if the user has admin privileges.
Here's my code...
$scope.login = function (user) {
User.login(user).$promise.then(
function (data) {
$rootScope.activeUser = data;
$rootScope.user_id = $rootScope.activeUser.user.username;
console.log('Active User: ', $rootScope.activeUser.user.email);
console.log('Status: ', $rootScope.activeUser.user.status);
if ($rootScope.activeUser.user.status === 'Y') {
$scope.loginError = false;
function checkAdmin(eid) {
Se_user.findById({
id: eid
}).$promise.then(
function (data1) {
var user_properties = data1;
if (user_properties.role === 'Admin') {
$rootScope.isAdmin = true;
console.log('isAdminInside: ', $rootScope.isAdmin);
return true;
} else {
//$rootScope.isAdmin = false;
return false;
}
});
};
var isAdmin = checkAdmin($rootScope.user_id);
console.log('isAdminOutside: ', $rootScope.isAdmin);
$state.go('home');
} else {
$scope.loginError = true;
$scope.loginErrorMessage = "Your account has been disabled. Please contact BMT Support for assistance";
}
},
function (err) {
console.log('Error: ', err)
$scope.loginError = true;
$scope.loginErrorMessage = "You've entered an invalid User ID or Password. Please try again.";
});
};
I've been troubleshooting by writing to the console, here's a sample of the output...
Active User: user#email.com
Status: Y
isAdminOutside: undefined
isAdminInside: true
How should I restructure so that the result of checkAdmin is properly returned after a successful login of an active user?
Try changing this part of code :
function checkAdmin(eid) {
return Se_user.findById({
id: eid
}).$promise.then(
function(data1) {
var user_properties = data1;
if (user_properties.role === 'Admin') {
$rootScope.isAdmin = true;
console.log('isAdminInside: ', $rootScope.isAdmin);
return true;
} else {
//$rootScope.isAdmin = false;
return false;
}
});
};
var isAdmin = checkAdmin($rootScope.user_id)
.then(function(val) {
console.log('isAdminOutside: ', val);
$state.go('home');
});
Writing a Parse Cloud Function (which uses Parse Javascript SDK) and I am having trouble checking to see if the current user has role "Admin". I'm looking at the web view of the Role class and a role with the name "Admin" exists, if I click "View Relations" for users, it shows the current user. I doubt it should matter, but "Admin" is the only role and the current user is the only user with a role. Lastly, the "Admin" role has an ACL of Public Read, so that shouldn't be causing any issues either.
Code is as follows:
...
var queryRole = new Parse.Query(Parse.Role);
queryRole.equalTo('name', 'Admin');
queryRole.equalTo("users", Parse.User.current());
queryRole.first({
success: function(result) { // Role Object
var role = result;
role ? authorized = true : console.log('Shiet, user not Admin');
},
error: function(error) {
console.log("Bruh, queryRole error");
}
})
console.log('After test: Auth = ' + authorized);
if (!authorized) {
response.error("You ain't no admin, measly user");
return;
}
...
This results in the following in the log:
Before test: Auth = false
After test: Auth = false
Give this a shot:
var authorized = false;
console.log('Before test: Auth = ' + authorized);
var queryRole = new Parse.Query(Parse.Role);
queryRole.equalTo('name', 'Admin');
queryRole.first({
success: function(result) { // Role Object
console.log("Okay, that's a start... in success 1 with results: " + result);
var role = result;
var adminRelation = new Parse.Relation(role, 'users');
var queryAdmins = adminRelation.query();
queryAdmins.equalTo('objectId', Parse.User.current().id);
queryAdmins.first({
success: function(result) { // User Object
var user = result;
user ? authorized = true : console.log('Shiet, user not Admin');
}
});
},
error: function(error) {
console.log("Bruh, can't find the Admin role");
}
}).then(function() {
console.log('After test: Auth = ' + authorized);
});
I got a simpler solution, give this a try:
var adminRoleQuery = new Parse.Query(Parse.Role);
adminRoleQuery.equalTo('name', 'admin');
adminRoleQuery.equalTo('users', req.user);
return adminRoleQuery.first().then(function(adminRole) {
if (!adminRole) {
throw new Error('Not an admin');
}
});
For those of you looking for a Parse Server (2018) answer, see below:
Parse.Cloud.define('authorizedUserTest', function(request, response) {
if(!request.params.username){
//response.error('no username');
response.error(request.params);
}
var queryRole = new Parse.Query(Parse.Role);
queryRole.equalTo('name','Admin');
queryRole.first({ useMasterKey: true }).then(function(promise){
var role = promise;
var relation = new Parse.Relation(role, 'users');
var admins = relation.query();
admins.equalTo('username', request.user.get('username'));
admins.first({ useMasterKey: true }).then(function(user){
if(user){
response.success(true)
}
else {
response.success(false)
}
}, function(err){
response.error('User is not an admin')
})
}, function(err){
response.error(err)
})
});
request.params is equal to a dictionary {"username":inputUsernameHere}.
Feel free to comment if you have questions.