How to disable automatically signin after create new user in Firebase? - firebase

The admin can only add a new user. My problem is when I created a new user, it automatically signin that user then it signouts the admin.
FYI. I didn't use the Admin SDK. Firebase
My code:
var password = $('#row' + x + 'cell1').val();
var fname = $('#row' + x + 'cell2').val();
var email = teacherID + "#gmail.com";
console.log(email + password);
firebase.auth().createUserWithEmailAndPassword(email, password).then(function(user) {
//Add to users table
var pushedUser = firebase.database().ref('users/' + user.uid).set({ role: "Teacher",
fullname: fname });
//Add name and default dp to the Authorization table
user.updateProfile({
displayName: fname,
photoURL: "default_dp",
});
var $rowFirst = $("table:first").find("tr:first");
var $rowNext = $('#tblCSVaccounts tr').eq(x);
//get all td's in row
var $tdsFirst = $rowFirst.find("td");
// loop all td
$.each($tdsFirst, function(i, el) {
//get value of each td
var txtEntity = $(this).find("input").val();
var $rowNext = $('#tblCSVaccounts tr').eq(x);
var $tdsNext = $rowNext.find("td:eq(" + i + ")");
$.each($tdsNext, function(i, el) {
//get value of each td
var txtValue = $(this).find("input").val();
//Update in database
const mySection = $('#sectionUpload').val();
var pushedRef = firebase.database().ref('Teachers/' + user.uid).update({ [txtEntity]: txtValue });
$('#alert-success').removeClass('hide');
});
});
}, function(error) {
// An error happened.
var errorCode = error.code;
var errorMessage = error.message;
});

you can use firebase.auth().onAuthStateChanged(...)
hope its help you, guy!

Related

setting parameter in firebase functions

Hi i am using below code in index.js. Here i want to set one value in "Default welcome intent" and i want to take in "Test Intent". How to do this. I want to pass this value in background and i want to use it
"use strict";
exports.__esModule = true;
var functions = require("firebase-functions");
var gApp = require("actions-on-google");
var WebhookClient = require('dialogflow-fulfillment').WebhookClient;
var _a = require('dialogflow-fulfillment'), Card = _a.Card, Suggestion = _a.Suggestion;
var app = gApp.dialogflow({ debug: true });
process.env.DEBUG = 'dialogflow:debug';
//exports.dialogflowSample = functions.https.onRequest((request, response) =>
//{
app.intent('Default Welcome Intent', function (conv, input) {
conv.ask("Welcome to my dialogFlow agent!");
});
app.intent('Test Intent', function (conv, input) {
conv.ask('<speak>Testing the application' + ("<say-as >" + input + "</say-as></speak>"));
conv.ask('<speak>Testing the application' + "<say-as >" + qNo + "</say-as></speak>");
});
exports.dialogflowSample = functions.https.onRequest(app);
//});

Data duplicates whenever its onclick link is clicked

So I have a table in html which displays all rentals from my database. The owner name and renter is retrieve from two different queries which is done inside the uery of retrieving data from rental table on database. The The problem is whenever I click the link that enables the function rentalhistory to run, data was added again resulting to duplicate the previous data.
var rentalref = db.ref('rental');
rentalref.once("value").then(function(snapshot) {
var history = [];
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key; // "ada"
var childData = childSnapshot.val();
console.log(childSnapshot.key);
childSnapshot.forEach(function(data) {
var pid = data.val().property_id;
var rid = data.val().renter_id;
var oid = data.val().owner_id;
var date = data.val().date_created;
var userref = db.ref('users/');
userref.orderByChild("user_id").equalTo(rid).once("child_added", function(dataa) {
console.log(dataa.val().username);
var rname = dataa.val().username;
var userref = db.ref('users/');
userref.orderByChild("user_id").equalTo(oid).once("child_added", function(dataa2) {
var oname = dataa2.val().username;
$("#rentaltable").append("<tr><td>" +pid+"</td><td>" +oname+"</td><td>" +rname+"</td><td>" +date+"</td></tr>");
});
});
});
});
});

Firebase infinite loop insert my item on child_added/set

I got an infinite loop inserting an item to my Firebase, so when I click on my post form, it inserts my item until I kill the process. Can you help me how to solve it?
PS : I'm using VueJS
var usersRef = new Firebase('https://xxxxxxxxxxxxxxxxxx.firebaseio.com/userslist/');
var vm = new Vue({
el: '#list1',
data: function () {
return{
// Initialisation du tableau de users
users: [],
sortKey: 'id',
reverse: 1,
nextKey: null
};
},
ready: function () {
// this works
//this.sortKey = 'name';
},
methods: {
updateUsers: function () {
},
removeUser: function (item) {
usersRef.child(item.id).remove();
},
addItem: function (e) {
e.preventDefault();
// get form data as Json
var jsonData = ConvertFormToJSON('form_add');
//console.log(jsonData);//test ok
//get the last item id and save it to next key
usersRef.limitToLast(1).on('child_added', function (snapshot) {
var lastKey = parseInt(snapshot.key());
this.nextKey = lastKey + 1;
console.log('nextKey ' + nextKey);//test ok
//
// save data to firebase
usersRef.child(this.nextKey).set(jsonData, function (snap) {
//console.log('add success');//test
//Notification par Jquery
var itemAdded = snap.val();
$.notify(itemAdded.firstname + " " + itemAdded.name + " à été ajouté", "success", {position: "top right"});
this.pendingKey = 0;
});
});
},
// Tri des colonnes
sortBy: function (_sortKey) {
this.reverse = (this.reverse == -1) ? 1 : -1;
this.sortKey = _sortKey;
console.log("SortKey " + this.sortKey);
}
}
});
usersRef.on('child_added', function (snapshot) {
var item = snapshot.val();
item.id = snapshot.key();
console.log('id ' + item.id);
vm.users.push(item);
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
thanks for your help
OK I've found a solution :
//get the last item id and save it to next key
var _nextKey = this.nextKey;
usersRef.limitToLast(1).on('child_added', function (snapshot) {
var lastKey = parseInt(snapshot.key());
_nextKey = lastKey + 1;
});
this.nextKey = _nextKey;
console.log('nextKey ' + this.nextKey);//test ok
// save data to firebase
usersRef.child(this.nextKey).set(jsonData, function (snap) {
//console.log('add success');//test
//Notification par Jquery
var itemAdded = snap.val();
$.notify(itemAdded.firstname + " " + itemAdded.name + " à été ajouté", "success", {position: "top right"});
});
May it help someone!

Login with gmail api in my website in asp.net

I have to add the functionality of login with gmail account on my website. Users only with my domain should be validated and users trying to login with other domain should be redirected to google login page and shown an message. If user logs in successfully via gmail then he should also get logged in into membership table. How to do this in asp.net. Here is my code:
<script language="javascript" type="text/javascript">
var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=';
var SCOPE = 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email';
var CLIENTID = '7480000038683-rhs9hdsc31uu2avuq8avlsed5i7hk.apps.googleusercontent.com';
var REDIRECT = 'http://localhost:0000/default.aspx?company=xyz';
var LOGOUT = 'http://accounts.google.com/Logout';
var TYPE = 'token';
var HD = "ranosys.com";
var _url = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE + '&login_hint=' + LOGINHINT + '&hd='+ HD;
var acToken;
var tokenType;
var expiresIn;
var user;
var hd;
var loggedIn = false;
function login() {
var win = window.open(_url,"_self");
var pollTimer = window.setInterval(function () {
try {
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
win.close();
validateToken(acToken);
}
}
catch (e) {
}
}, 500);
}
function validateToken(token) {
$.ajax(
{
url: VALIDURL + token,
data: null,
success: function (responseText) {
getUserInfo();
loggedIn = true;
$('#loginText').hide();
$('#logoutText').show();
},
dataType: "jsonp"
});
}
function getUserInfo() {
debugger;
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
data: null,
success: function (resp) {
user = resp;
var email = user.email;
alert(email);
console.log(user);
$('#uName').text('Welcome ' + user.name);
$('#imgHolder').attr('src', user.picture);
},
dataType: "jsonp"
});
}
//credits: http://www.netlobo.com/url_query_string_javascript.html
function gup(url, name) {
namename = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\#&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(url);
if (results == null)
return "";
else
return results[1];
}
function startLogoutPolling() {
$('#loginText').show();
$('#logoutText').hide();
loggedIn = false;
$('#uName').text('Welcome ');
$('#imgHolder').attr('src', 'none.jpg');
}
</script>
You need the lastest JQuery like this
Follow the last example here : http://www.gethugames.in/blog/2012/04/authentication-and-authorization-for-google-apis-in-javascript-popup-window-tutorial.html
This is my code working
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=';
var SCOPE = 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email';
var CLIENTID = '716569014051.apps.googleusercontent.com';
var REDIRECT = 'http://www.gethugames.in/proto/googleapi/oauth/'
var LOGOUT = 'http://accounts.google.com/Logout';
var TYPE = 'token';
var _url = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
var acToken;
var tokenType;
var expiresIn;
var user;
var loggedIn = false;
function login() {
var win = window.open(_url, "windowname1", 'width=800, height=600');
var pollTimer = window.setInterval(function() {
try {
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
win.close();
validateToken(acToken);
}
} catch(e) {
}
}, 500);
}
function validateToken(token) {
$.ajax({
url: VALIDURL + token,
data: null,
success: function(responseText){
getUserInfo();
loggedIn = true;
$('#loginText').hide();
$('#logoutText').show();
},
dataType: "jsonp"
});
}
function getUserInfo() {
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
data: null,
success: function(resp) {
user = resp;
console.log(user);
$('#uName').text('Welcome ' + user.name);
$('#imgHolder').attr('src', user.picture);
},
dataType: "jsonp"
});
}
//credits: http://www.netlobo.com/url_query_string_javascript.html
function gup(url, name) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\#&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
if( results == null )
return "";
else
return results[1];
}
function startLogoutPolling() {
$('#loginText').show();
$('#logoutText').hide();
loggedIn = false;
$('#uName').text('Welcome ');
$('#imgHolder').attr('src', 'none.jpg');
}
</script>
</head>
<body>
<a href='#' onClick='login();' id="loginText"'> Click here to login </a>
Click here to logout
<iframe name='myIFrame' id="myIFrame" style='display:none'></iframe>
<div id='uName'></div>
<img src='' id='imgHolder'/>
</body>
</html>

Facebook C# SDK, problems getting user email

I'm using Facebook C# SDK and got a sample on how to set up a login and get some user information to register im my website. However, I stuck in email information. It's always null.
I've checked some posts related in here, but none solve my problem. All the information I need is coming right, only email and birthday is missing.
My code in shtml partial page is like this:
<div id="fb-root"></div>
<fb:login-button id="fblogin" onlogin="window.open('http://' + location.host + '/Facebook/LogOn', '_self')" perms='email'></fb:login-button>
<script>
window.fbAsyncInit = function () {
FB.init({
appId: '#Facebook.FacebookApplication.Current.AppId',
cookie: true,
xfbml: true,
oauth: true
});
function facebooklogin() {
FB.login(function (response) {
if (response.authResponse) {
// user authorized
//window.location.reload();
window.open("http://" + location.host + "/Facebook/LogOn", "_self")
} else {
// user cancelled
}
}, { scope: '#ViewBag.ExtendedPermissions' });
};
$(function () {
// make the button is only enabled after the facebook js sdk has been loaded.
$('#fblogin').attr('disabled', false).click(facebooklogin);
});
};
(function () {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
} ());
</script>
And my code in Facebook Controller:
public ActionResult LogOn()
{
var fbWebContext = new FacebookWebContext(); // or FacebookWebContext.Current;
if (fbWebContext.IsAuthorized())
{
var fb = new FacebookWebClient();
dynamic me = fb.Get("me");
//Creating new User with Facebook credentials
var id = 0;
var nickname = me.first_name;
var password = "";
var email = me.email;
var picture = string.Format("http://graph.facebok.com/{0}/picture?type=large", me.id);
var thumbnail = string.Format("http://graph.facebok.com/{0}/picture?type=normal", me.id);
var fullName = me.name;
var gender = "";
if (me.gender == "male") gender = "Masculino";
if (me.gender == "female") gender = "Feminino";
var birthdate = Convert.ToDateTime(me.birthday);
//Does the user already exist?
if (DAUser.UserAlreadyExists(email))
{
ViewBag.Message = "O seu e-mail já foi cadastrado em nosso site. Por favor, cadastre outro e-mail.";
return View("~/Views/Shared/Erro.cshtml");
}
else
{
id = DAUser.Create(nickname, email, password, "facebook");
}
//Updating created user information
User user = db.User.Find(id);
TryUpdateModel(user);
user.Picture = picture;
user.Thumbnail = thumbnail;
user.Nickname = nickname;
user.FullName = fullName;
user.Gender = gender;
if (!String.IsNullOrEmpty(birthdate))
{
user.Birthdate = Convert.ToDateTime(birthdate);
}
db.SaveChanges();
Session["loginType"] = "Facebook";
return RedirectToAction("Mural", "Home");
}
else
{
ViewBag.Message = "Não foi possível completar o seu login via Facebook.";
return View("~/Views/Shared/Erro.cshtml");
}
}
If I put these lines, as shown in the sample:
[FacebookAuthorize(Permissions = ExtendedPermissions)]
if (fbWebContext.IsAuthorized(ExtendedPermissions.Split(',')))
My app stop works.
Anybody has a solution? O another sample codes to get authorized to request email and birthday?
Edit
The problem was this line:
}, { scope: '#ViewBag.ExtendedPermissions' });
In my App should be:
}, { scope: 'email,user_birthday,user_hometown' }); //alter to get permission to access user data
I didn't set a scope (perms) to facebook access... but now, I have another question.
My culture DateTime is dd/MM/yyyy and Facebook birthday is set up as MM/dd/yyyy, I tried this:
var birthdate = DateTime.Parse(me.birthday, CultureInfo.CreateSpecificCulture("pt-BR"));
Cuz my culture in Brazilian, but I still get DateTime error:
String was not recognized as a valid DateTime.
Anyone know how to solve that?
This line make everything works fine with Facebook Birthday
var birthdate = DateTime.ParseExact(me.birthday, "MM/dd/yyyy", CultureInfo.InvariantCulture);

Resources