I want only one announce my firebase database reference object
so I try this....
index.php
(javascript)
var auth, database, userInfo;
var Attendances_monthlyRef, Attendances_dailyRef, UsersRef;
database = firebase.database();
auth = firebase.auth();
var authProvider = new firebase.auth.GoogleAuthProvider(); //구글 인증창 선언
auth.onAuthStateChanged(function(user){
if (user) { //인증 성공 → need for login?
userInfo = user;
Attendances_dailyRef = database.ref('Attendances_daily/'+userInfo.uid );
document.GetValue.Database.value = JSON.stringify(Attendances_dailyRef);
} else {
auth.signInWithPopup(authProvider);
}
})
(html)
<form action="TimeSheet.php" name="GetValue" method="post">
<input type=submit style='font-size:16pt' value="シフト画面に行こう"/>
<input type=textarea name="Database" style='font-size:16pt'/>
</form>
TimeSheet.php
(php)
<?php
$AuthUser = json_decode($_POST["Database"]); //Ref
print_r($AuthUser);
?>
(javascript)
<script src="https://www.gstatic.com/firebasejs/4.13.0/firebase.js"> </script>
<script>
function DBmodify() {
var buttonText = document.getElementById("modify").value;
if(buttonText == "修正終了") {
var Ref='<?=$AuthUser?>';
console.log(Ref);
Ref.on('value', function(data){
alert(data.val());
});
}
}
but it doesn't work. because of Ref type.
I send it JSON type, but it sended just text type(http address)
I want to know how can i send firebase database reference in web to other page.
is there any way?
(of course I know way
-> other firebase init in other page, but I want to use just one object)
==== edit ====
unfortunately my server native is php5.6 so I CAN'T USE FIREBASE PHP SDK
Related
As the title says, i cant seem to understand why im getting this error for an on change event on a model driven app form. i have to be honest, im using code snippits and chatGPT to try and formulate this because i haven't got a clue!! but i think im close 😁
for context, when i search for the client in a new enquiry for the code is to get the account manager from the clients record in another table and put it in the enquiry form.
var SDKEnquiry = window.Sdk || {}; (function(){ // This function is called when the customer lookup field on the form is changed this.function = onChangeCustomer(executionContext){ // Get the form context var formContext = executionContext.getFormContext();
// Get the value of the customer lookup field on the enquiry form
var customerLookup = formContext.getAttribute("customerlookup_on_enquiry_form").getValue();
// Check if a customer is selected
if(customerLookup){
// Retrieve the customer account record using the WebApi
Xrm.WebApi.retrieveRecord("account",
customerLookup[0].id, "?$select=accountmanagerid_on_customer_record").then(
function success(result) {
// Get the account manager id from the response
var accountManagerId = result.accountmanagerid_on_customer_record;
// Set the account manager id on the enquiry form
formContext.getAttribute("accountmanagerid_on_enquiry_form").setValue(accountManagerId);
},
function (error) {
// Show an error message
alert(error.message);
}
);
}
} }).call(SDKEnquiry);
This is the error im getting from Power Apps when i run the app and try and use the form. posted as image because im getting a spam warning
Error
Edit:
OKay so i think ive fixed the code, im not getting any errors anymore anyway but when i select the client the field does not pupulate?
var SDKEnquiry = {};
(function(){
this.onChangeCustomer = function(executionContext) {
var formContext = executionContext.getFormContext();
var customerLookup = formContext.getAttribute("w3c_clientcompany").getValue();
if (!customerLookup) {
alert("No customer selected.");
return;
}
Xrm.WebApi.retrieveRecord("account",
customerLookup[0].id, "?$select=w3c_AccountManager")
.then(function success(result) {
var accountManagerId = result.w3c_AccountManager;
formContext.getAttribute("w3c_cam").setValue(accountManagerId);
})
.catch(function (error) {
alert(error.message);
});
};
}).call(SDKEnquiry);
I'm not sure I'm even attempting the right thing. Heres my issue.
I'm loading data to a screen if the user is authenticated. Its a summary screen. I can click a item and it will send me to a new "details" page (window.location) . I'm passing the ID in the URL and then doing a GET request to get the details to display. When I implement my rules on the firebase DB, (".read": "auth != null"), I get a "401 Unauthorized" error in the console.
So somehow I need to either pass the user to the details.js or set Persistence somehow. Anyone have any suggestions?
THIS IS THE CODE FROM THE MAIN.JS
auth.onAuthStateChanged(user => {
console.log(user);
if (user) {
database.on('value', function(data) {
myData = data.val()
keys = Object.keys(myData)
buildProperties();
})
// tempBuild()
} else {
$('.eachProperty').empty()
$('.eachProperty').append($(`<h1>You must be signed in to view properties</h1>`))
}
})
$('body').on('click', '.singleProp', function() {
id = $(this).attr('id')
window.location = "/details.html?id=" + id
})
THIS IS THE CODE FROM THE DETAILS.JS
var myLocation = location.search.slice(4)
$.get(`https://XXXXXX.firebaseio.com/property/${myLocation}/.json`).then(myProperty)
function myProperty(prop) {
$('.propAddress').text(prop.address)
$('.zip').text(prop.zip)
if(prop.pictures){
for (var i = 0; i < prop.pictures.length; i++) {
var myImg = prop.pictures[i]
$('.imgContainer').append($(`<div class="eachPicDiv"><img src="${myImg}" alt="0" class="detailPic">
<ion-icon class="rBtn" name="arrow-redo-outline"></ion-icon>
</div`))
}
} else {
$('.imgContainer').append($(`<h1>THERE WERE NO PICTURES</h1>`))
}
}
You are using jQuery to fetch your data from Firebase Database,
$.get is a jQuery method, and for that to succeed you need to have some sort of auth token.
Firebase already provides best in class access, read more about access here.
Learn by example here.
In my code, I get the first_name, last_name, email and password from the user. Then, I get the location of the user with his/her consent in the second page. So, I save all the information of the first page as session variables. Then, I have a button that looks like this:
<button onclick="signUp()" class="btn btn-primary"> Let's go! </button>
And, the signUp function looks like this:
function signUp(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.post("/sign-up-user",
{
user_latitude: latitude,
user_longitude: longitude
}, function(data){
alert(data);
});
}
And, I have the route for the request as:
Route::post("/sign-up-user", "PagesController#signUpFinalUser");
And, my PagesController function signUpFinalUser looks like this:
// Finally acquire the user with location and store him/her in the database
public function signUpFinalUser(Request $request){
// Get all required variables
$final_first_name = Session::get("user_first_name");
$final_last_name = Session::get("user_last_name");
$final_email = Session::get("user_email");
$final_password = Session::get("user_password");
$final_latitude = (float) $request->user_latitude;
$final_longitude = (float) $request->user_longitude;
// Create a new instance of the User model
$user = new User;
// Fill all the required columns of the database of the user
$user->first_name = $final_first_name;
$user->last_name = $final_last_name;
$user->email = $final_email;
$user->password = $final_password;
$user->latitude = $final_latitude;
$user->longitude = $final_longitude;
// Save the user i.e store the user in the database
$user->save();
// Get the id of the user
$user_id = $user->id;
// Destroy all the sessions variable
Session::destroy();
// Create a session variable named 'user_id'
Session::put("user_id", $user_id);
// Return a response back
return 1;
}
But, the problem is, it shows an error that looks like this:
jquery.min.js:2 POST http://localhost:8000/sign-up-user 500 (Internal Server Error)
But, the surprising thing is, when I comment out the database query and run it again, the response data i.e "1" gets alerted. So, what am I doin wrong?
You destroed session before put user_id
// Destroy all the sessions variable
Session::destroy();
// Create a session variable named 'user_id'
Session::put("user_id", $user_id);
I am trying to use the Gmail API to access the email in a web application. I have tried the example at https://developers.google.com/gmail/api/quickstart/php and is working fine. Now I want to get the access token using javascript API and use in the above example.
gapi.auth2.authorize({
client_id: 'CLIENT_ID.apps.googleusercontent.com',
scope: 'email profile openid',
response_type: 'id_token permission'
}, function(response) {
if (response.error) {
// An error happened!
return;
}
// The user authorized the application for the scopes requested.
var accessToken = response.access_token;
var idToken = response.id_token;
// You can also now use gapi.client to perform authenticated requests.
});
When I manually add the response from javascript API in the php script it is showing error
Uncaught exception 'LogicException' with message 'refresh token must be passed in or set as part of setAccessToken' in D:\wamp\www\gmailexample\google-api-php-client-2.2.0\src\Google\Client.php:267
Below is the php script I am using.
<?php
require_once '/google-api-php-client-2.2.0/vendor/autoload.php';
define('APPLICATION_NAME', 'Gmail API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/gmail-php-quickstart.json');
define('CLIENT_SECRET_PATH', 'client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/gmail-php-quickstart.json
define('SCOPES', implode(' ', array(
Google_Service_Gmail::GMAIL_READONLY)
));
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient() {
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
$accessToken= json_decode('{"access_token":"asdfsasdfsasdfsasdfs","expires_in":2255,"expires_at":254877}', true);
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
/**
* Expands the home directory alias '~' to the full path.
* #param string $path the path to expand.
* #return string the expanded path.
*/
function expandHomeDirectory($path) {
$homeDirectory = getenv('HOME');
if (empty($homeDirectory)) {
$homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
}
return str_replace('~', realpath($homeDirectory), $path);
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Gmail($client);
// Print the labels in the user's account.
$user = 'me';
$results = $service->users_labels->listUsersLabels($user);
if (count($results->getLabels()) == 0) {
print "No labels found.\n";
} else {
print "Labels:\n";
foreach ($results->getLabels() as $label) {
printf("- %s\n", $label->getName());
}
}
Please help.
Ok my friend, here is your solution. To make sure you understand this, I worked an example. First, inside your working directory, make sure you have the Google PHP Client library and two other files. The first one should be called index.php and paste the following code inside that file:
<html>
<head>
<title>JS/PHP Google Sample</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script type="text/javascript">
function handleClientLoad() {
// Loads the client library and the auth2 library together for efficiency.
// Loading the auth2 library is optional here since `gapi.client.init` function will load
// it if not already loaded. Loading it upfront can save one network request.
gapi.load('client:auth2', initClient);
}
function initClient() {
// Initialize the client with API key and People API, and initialize OAuth with an
// OAuth 2.0 client ID and scopes (space delimited string) to request access.
gapi.client.init({
apiKey: 'YOUR API KEY GOES HERE',
clientId: 'YOUR CLIENT ID GOES HERE',
scope: 'email profile https://www.googleapis.com/auth/gmail.readonly',
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
});
}
function updateSigninStatus(isSignedIn) {
// When signin status changes, this function is called.
// If the signin status is changed to signedIn, we make an API call.
if (isSignedIn) {
$("#signout-button").show();
$("#signin-button").hide();
makeApiCall();
} else {
$("#signin-button").show();
$("#signout-button").hide();
}
}
function handleSignInClick(event) {
// Ideally the button should only show up after gapi.client.init finishes, so that this
// handler won't be called before OAuth is initialized.
gapi.auth2.getAuthInstance().signIn();
}
function handleSignOutClick(event) {
var host = "http://"+window.location.hostname;
gapi.auth2.GoogleUser.prototype.disconnect();
window.open(host, "_self");
}
function makeApiCall() {
// Make an API call to the People API, and print the user's given name.
var accsTkn = gapi.auth2.getAuthInstance().$K.Q7.access_token;
var formData = new FormData();
formData.append("access_token", accsTkn); //send access token
$.ajax({
url : 'listEmails.php',
type : 'POST',
data : formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success : function(html) {
$("#myLabels").append(html);
}
});
}
</script>
<style>
#signin-button{
display: none;
}
#signout-button{
display: none;
}
#myLabels{
width: 80%;
min-height: 350px;
}
</style>
</head>
<body>
<center>
<h1>Google OAuth Gmail Example with Javascript and PHP</h1><br>
<button id="signin-button" onclick="handleSignInClick()">Sign In</button>
<br><br><br>
<div id="myLabels">
Emails list: <br><br>
</div>
<br><br>
<button id="signout-button" onclick="handleSignOutClick()">Sign Out</button>
</center>
<script async defer src="https://apis.google.com/js/api.js" onload="this.onload=function(){};handleClientLoad()" onreadystatechange="if (this.readyState === 'complete') this.onload()"> </script>
</body>
</html>
Next, the second file should be named listEmails.php and paste the following code inside:
<?php session_start();
require_once "path_to_php_client_lib/vendor/autoload.php"; //include php client library
//set the required parameteres
$scopes = array("https://www.googleapis.com/auth/gmail.readonly");
$client = new Google_Client();
$client->setRedirectUri('http://'.$_SERVER['HTTP_HOST'].'listEmails.php');
$client->setAuthConfig("client_secret.json");
$client->addScope($scopes);
$client->setAccessToken($_POST["access_token"]);
$service = new Google_Service_Gmail($client); // define service to be rquested
$pageToken = NULL;
$messages = array();
$opt_param = array("maxResults" => 5);
try {
$messagesResponse = $service->users_messages->listUsersMessages("me", $opt_param);
if ($messagesResponse->getMessages()) {
$messages = array_merge($messages, $messagesResponse->getMessages());
}
} catch (Exception $e) {
print 'An error occurred: ' . $e->getMessage();
}
foreach ($messages as $message) {
$msgId = $message->getId();
$optParams = array("format" => "full");
$uniqueMsg = $service->users_messages->get("me", $msgId, $optParams);
print 'Message with ID: ' . $uniqueMsg->id . '<br>';
print 'Message From: ' . $uniqueMsg->getPayload()->getHeaders()[18]->value . '<br><br>**************************<br><br>';
}
?>
Understanding the example:
The documentation here clearly explains
This OAuth 2.0 flow is called the implicit grant flow. It is designed for applications that access APIs only while the user is present at the application. These applications are not able to store confidential information.
That means that using the Javascript authentication flow you will NOT be able to get offline access. Having that in mind, we can move on.
As you can then see on the php script, you are not required to refresh the token since this will be managed by the Javascript client library; And there you go... I hope this helps!
Is it possible to programmatically add contacts to the adress book/ people app in Windows 10 like it is possible in Android?
I have a server on which contact information is stored, and I would like to make an app to synchronise my contacts with Windows 10.
I tried several things, but it didn't really work out. This is how far I've come:
Successfully download the contact data.
put the contact data in a Contact object.
This is what I've tried:
contacts.ContactManager.requestStoreAsync().done(function (contactStore) {
contactStore.createContactListAsync("name").done(function (contactList) {
for (i = 0; i < data.length; i++) {
var contact = new contacts.Contact;
//populate Contact item
contactList.saveContactAsync(contact);
}
contactList.saveAsync;
});
});
But I'm getting an acces denied error.
Any help would be appreciated. Thanks in advance!
Firstly, ensure you have added the contacts capability in app manifest.
<Capabilities>
<Capability Name="internetClient" />
<uap:Capability Name="contacts"/>
</Capabilities>
You will also get the access denied error if you had not request the read/write permission to the contact store.
ContactStoreAccessType enumeration
In this case, you can request the “appContactsReadWrite” permission.
But as I tested, there will be some API issues when calling the createContactListAsync method.
The current workaround is adding windows Runtime Component wrapper:
public sealed class ContactManagerWrapper
{
public IAsyncAction AddContactAsync(string userName, string email)
{
return AsyncInfo.Run(async (token) =>
{
var store = await ContactManager.RequestStoreAsync(ContactStoreAccessType.AppContactsReadWrite);
var contactLists = await store.FindContactListsAsync();
var contactList = contactLists.FirstOrDefault();
var contact = new Contact();
contact.Name = userName;
contact.Emails.Add(new ContactEmail() { Address = email, Kind = ContactEmailKind.Personal });
await contactList.SaveContactAsync(contact);
});
}
}
WinJS Project:
document.getElementById('click_me').addEventListener("click", function () {
var mgr = new UWPRuntimeComponent.ContactManagerWrapper();
mgr.addContactAsync('Jeffrey', 'jeffrey.chen#example.com').done(function () {
console.log("add contact successfully");
});
});
Try this
contacts.ContactManager.requestStoreAsync(ContactStoreAccessType.AppContactsReadWrite);
instead of this
contacts.ContactManager.requestStoreAsync()
you open the default store and I think its not accessible by developer.