How to Retrieve multiple data using specific field in Firebase Database - javascript

I am trying to follow the firebase tutorial to retrieve data and display in Google assistant.But I am not able to retrieve multiple data from database in Dialogflow fulfillment.I want to ask user to enter register id with that field, remaining fields of student details were fetched.
I tried firebase documentation. My database connection was successful,But I am not able to retrieve data and also I want to ask user to enter the student Id i.e Register number. Suppose if i enter 191611238 [RegId] It will retrieve FirstName,EmailId and year fields.
* This is my Dialogflow fulfillment code *
const functions = require('firebase-functions');
const { WebhookClient} = require('dialogflow-fulfillment');
// initialise DB connection
const admin = require('firebase-admin');
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: 'ws://******.firebaseio.com/'
});
process.env.DEBUG = 'dialogflow:debug';
exports.dialogflowFirebaseFulfillment =
functions.https.onRequest((request, response) => {
const agent = new WebhookClient({
request,
response
});
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
function getRegId(agent) {
const RegId = agent.parameters.RegId;
agent.add(`Thank you...`);
return
admin.database().ref('Table/').orderByChild('/RegId').equalTo("$RegId").once("value").then((snapshot) => {
var Email = snapshot.child("EmailId").val();
agent.add(`The student Mail is ` + Email);
var Regno = snapshot.child("RegId").val();
agent.add(`The student Register no is ` + Regno);
var name = snapshot.child("FirstName").val();
agent.add(`The student name is ` + name);
var year = snapshot.child("CourseName").val();
agent.add(`The student currently studying ` + year);
var Gradu = snapshot.child("GraduationTypeName").val();
agent.add(`The student Department is ` + Gradu);
});
}
// Run the proper function handler based on the matched Dialogflow
intent name
let intentMap = new Map();
intentMap.set('GetthedetailsofRegisternumber', getRegId);
agent.handleRequest(intentMap);
});
I want to get the details of student.but Iam getting Null i.e
The student Mail is null
The student Register no is null etc
I got error in Firebase console as
dialogflowFirebaseFulfillment
FIREBASE WARNING: Using an unspecified index. Consider adding ".indexOn": "RegId" at /Table to your security rules for better performance
Please provide me how to ask the user to enter RegId based on that I want to retrieve all fields.

function handleGetthedetailsofRegisternumber(agent){
const RegId = agent.parameters.RegId;
var ref = admin.database().ref().child("Table/");
var query = ref.orderByChild("RegId").equalTo(RegId.toString());
query.once("value", function(snapshot) {
snapshot.forEach(function(child) {
console.log(child.key);
// name field
console.log("FirstName: " + child.val().FirstName);
console.log("Mobile: " + child.val().MobileNumber);
console.log("Email: " + child.val().EmailId);
var name = snapshot.child("FirstName").val();
agent.add(`The student name is ` + name);
});
});

Related

Outlook Add-In that extracts internet headers

I'm trying to create an outlook add-in that extracts and then displays essential information along with the SPF, DKIM and DMARC. At the minute everything works perfectly except for the SPF, DKIM and DMARC.
Office.onReady((info) => {
if (info.host === Office.HostType.Outlook) {
document.getElementById("sideload-msg").style.display = "none";
document.getElementById("app-body").style.display = "flex";
document.getElementById("run").onclick = run;
}
});
export async function run() {
// Get a reference to the current message
const item = Office.context.mailbox.item;
//Finds SPF, DMARC and DKIM
var headers = item.getAllInternetHeadersAsync;
var spf = getHeaderValue(headers,'spf');
var dmarc = getHeaderValue(headers,'dmarc');
var dkim = getHeaderValue(headers,'dkim');
// Write message property value to the task pane
document.getElementById("item-subject").innerHTML = "<b>Subject:</b> <br/>" + item.subject;
document.getElementById("item-sender").innerHTML = "<b>Sender:</b> <br/>" + item.sender.emailAddress;
document.getElementById("item-date").innerHTML = "<b>Received:</b> <br/>" + item.dateTimeCreated;
document.getElementById("item-to").innerHTML = "<b>To:</b> <br/>" + JSON.stringify(item.to);
document.getElementById("item-spf").innerHTML = "<b>SPF:</b> <br/>" + spf;
document.getElementById("item-dmarc").innerHTML = "<b>DMARC:</b> <br/>" + dmarc;
document.getElementById("item-dkim").innerHTML = "<b>DKIM:</b> <br/>" + dkim;
}````
This is what I have so far and I feel like it has to do with the item.getAllInternetHeadersAsync as when I was testing it, nothing was being out. So Im just wondering if theres another way to extract header information or not.
Thanks
Ive tried most of the item. tags but none worked. All I need is to extract the SPF, DKIM and DMARC.

Is there a way to get a firebase-authenticated github user's username

I'm essentially trying to have a website which authenticates the user's GitHub account through firebase, and then saves their username in a database - I specifically need the username for this. I have the authentication working but it seems that firebase doesn't have a way to access the username, only things such as the email, display name, etc. Currently I just want to save the username as a variable
I've come across this: https://developer.github.com/v3/users/#get-the-authenticated-user
I assume "login" is the username?
I'm relatively new to things though, and can't find any clear examples of how I would access this information with my token from firebase.
For reference, I have an index.html, linked to app.js, which contains all of my authentication code.
var provider = new firebase.auth.GithubAuthProvider();
provider.addScope('read:user');
//get elements
const authenticateBtn = document.getElementById('authbtn');
//add login event
authenticateBtn.addEventListener('click', e=>{
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a GitHub Access Token. You can use it to access the GitHub API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
//what I want to get
//var Username = ;
//some data I am able to get
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var isAnonymous = user.isAnonymous;
var uid = user.uid;
var providerData = user.providerData;
//where I want to print the username
//console.log(userName);
// ...
}).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;
// ...
});
})
I really just need a beginners explanation of if what I want to do is possible and if so, exactly what code I'd need where in my project.
Thanks!
So I ended up getting some help from a friend, here is my solution:
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a GitHub Access Token. You can use it to access the GitHub API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
var username;
var obj;
const Http = new XMLHttpRequest();
Http.open("GET", "https://api.github.com/user?access_token="+token);
Http.send();
Http.onreadystatechange=function(){
if(this.readyState==4 && this.status==200){
obj = JSON.parse(Http.responseText);
username = obj.login;
console.log(username);
}
}
}

Retrieving current user data from firebase

I'm able to retrieve the data but it's only showing the data of the last user in the database. The users are listed by their uid. Below are the code and screenshot of the data from firebase. Help me out, guys!
var database = firebase.database().ref('users');
database.on("child_added", function(snapshot) {
var snapVal = snapshot.val();
displayName.innerHTML = snapVal.mUsername;
console.log(snapVal);
var badge = document.createElement('span');
badge.textContent = 'view details';
badge.setAttribute('class','badge');
var list = document.createElement('a');
list.textContent = snapVal.mUsername;
list.setAttribute('href', '#');
list.setAttribute('class', 'list-group-item');
patientList.appendChild(list);
list.appendChild(badge);
var userIcon = document.createElement('i');
userIcon.setAttribute('class','far fa-user');
list.insertBefore(userIcon, list.childNodes[0])
},
function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
You should refer to the specific user's node to retrieve the information.
Your code should look like:
var userRef = firebase.database().ref(`users/${user_node_key}`); // user_node_key should be the node containing the user info.
You should be able to get the node key using the current user's object.
and then call once on the userRef if you just need to get the detail once or on if you need to listen all the changes on that user.
The code should look like:
userRef.once('value').then(function(snapshot) {
//use snapshot to get the users data
});

Why does base64 code changes when inserted into mongodb?

I am working on generating unique email links for my users, trying to generate a code bye concatenating the user email and the Date timestamp.
The code generated looks like this
bUBzLnBvazE0NjM2ODc3MDg0MTA=3D
while in the mongodb it doesn't have 3D in it, bUBzLnBvazE0NjM2ODc3MDg0MTA=, and that's why URLs don't work.
I am using cryptoJS to encode string into base64.
const BASE_SERVER_URL = "http://localhost:3000/";
const INVITE_URL = BASE_SERVER_URL+"login/";
let uniqueCode = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(pmGroupUser.email+Date.now()));
let emailText = "Hello " + pmGroupUser.first_name + " click the following url to register your self ";
emailText += INVITE_URL;
emailText += uniqueCode;
Meteor.call('sendEmail',"to", "from","Subject", emailText, (err, res) => {
if(!err) {
Invites.insert({
code: uniqueCode
});
}
});

how to retrive User name/login name from gmail?

I am using google login for custom website. here i wrote the code for it
var sOAuthServiceEndPoint = "https://accounts.google.com/o/oauth2/auth?scope=http://gdata.youtube.com https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email&response_type=token&";
var sOAuthRedirectURL = "http://example.com/testpage/test.html";
var termsAndCondURL = "termsandcondition.html";
var sOAuthClientID = "294016263542.apps.googleusercontent.com";
var sAuthenticationURL = sOAuthServiceEndPoint + "redirect_uri=" + sOAuthRedirectURL + "&client_id=" + sOAuthClientID;
even i got an access token using below function
function fnOnLoad() {
//alert("Form Loaded");
var sAccessToken = '';
var params = {}, queryString = location.hash.substring(1),regex = /([^&=]+)=([^&]*)/g, m;
while (m = regex.exec(queryString)) {
params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
if(params.error){
if(params.error == "access_denied"){
sAccessToken = "access_denied";
alert(sAccessToken);
}
}else{
sAccessToken = params.access_token;
alert(sAccessToken);
}
window.opener.fnAuthorisationSuccess(sAccessToken);
window.close();
}
It's working succesfully and redirect into the other page where I want. but my problem is how to retrive user login name..?
I am using javascript for it.
Thanks in Advance
This can be found in the documentation.
After your application acquires an access token and has (if necessary) verified it, you can use that access token when making requests to a Google API. If the https://www.googleapis.com/auth/userinfo.profile scope was included in the access token request, then you may use the access token to acquire the user's basic profile information by calling the UserInfo endpoint.
Endpoint: https://www.googleapis.com/oauth2/v1/userinfo
Returns basic user profile information, including name, userid, gender, birthdate, photo, locale, and timezone. If the https://www.googleapis.com/auth/userinfo.email scope was present in the request, then the user's email will also be present in the response. If the email has been verified, then there is also a field that indicates the email is a verified address.

Categories

Resources