App Engine (PHP) connection to Cloud SQL failed - php

I used the environment of the "hello world" app engine example by google to create my own php app. Then i configured the existing app.yaml file to this:
runtime: php55
api_version: 1
handlers:
- url: /
script: index.php
env_variables:
MYSQL_DSN: mysql:dbname=sampledb;unix_socket=/cloudsql/sampleproject:europe-west3:sampleinstance
MYSQL_USER: root
MYSQL_PASSWORD: admin
My index.php is a typical login page. I want to load user data from my cloud sql to check, whether the user is allowed to enter the next page or not. The next page is a dashboard which includes company data. I also want to load this data from my cloud sql databse.
That's my php code to read the data (i copied it from the google bookshelf tutorial, because i am completly new into these things..)
<?php
$dsn = getenv('MYSQL_DSN');
$user = getenv('MYSQL_USER');
$password = getenv('MYSQL_PASSWORD');
if (!isset($dsn; $user) || false=== $password) {
throw new Exception('Set MYSQL_DSN');
}
$db = new PDO($dsn, $user, $password);
$statement = $db->prepare("SELECT clicks from display_inbox");
$statement->execute();
$all = $statement->fetchAll();
foreach ($all as $data) {
echo $data["clicks"], "<br>";
}
?>
It's not a specific query,i just want to check the connection.
After deploying my app i get the following result:
HTTP-500 error: sampleproject.appspot.com is currently unable to handle this request.
I simply don't get if it's my app.yaml or my php code. Would be very helpful if anybody has an example code for a app.yaml file and a typical query to read the cloud sql data.

You have some syntax errors in your app.yaml and index.php files
Try this:
app.yaml:
runtime: php55
api_version: 1
threadsafe: true
handlers:
- url: /.*
script: index.php
# [START env]
env_variables:
MYSQL_DSN: mysql:unix_socket=/cloudsql/sampleproject:europe-west3:sampleinstance;dbname=sampledb
MYSQL_USER: root
MYSQL_PASSWORD: admin
# [END env]
index.php:
<?php
$dsn = getenv('MYSQL_DSN');
$user = getenv('MYSQL_USER');
$password = getenv('MYSQL_PASSWORD');
if (!isset($dsn, $user) || false === $password) {
throw new Exception('Set MYSQL_DSN');
}
$db = new PDO($dsn, $user, $password);
$statement = $db->prepare("SELECT clicks from display_inbox");
$statement->execute();
$all = $statement->fetchAll();
foreach ($all as $data) {
echo $data["clicks"]."<br>";
}
?>

Related

404 Not Found (Source not found on the server) Slim Framework

I am willing to get a json response whether an administrator is registered or not. So I made this get function with these parameters shown below:
$app->get('/admin/:email/:password', function($email, $password){
$password = md5($password);
$databaseObject = new DatabaseLayer();
$isRegistered = $databaseObject->isAdminExist($email, $password);
$app = \Slim\Slim::getInstance();
if ($isRegistered){
$app->response->setStatus('200');
$app->response->headers->set('Content_Type', 'application/json');
echo json_encode(Array('isLogin' => '1'));
} else {
echo json_encode(Array('isLogin' => '0'));
}
});
My problem is when I add a point to the email parameter, it doesn't work.
Here is a screenshot with no point in the email param:
Here is a second screenshot with a point in the email param:
Please can I get some help, this is for a project I am making.
Thank you.
For more further information, I am using Slim version 2.*
Your route should be like this:
$app->get('/admin/{email}/{password}', function($email, $password){

Openfire RestAPI for PHP Configuration

I am trying to connect to my Openfire Server using RestAPI from Github
Now I have installed RestAPI plugin in Openfire folder.
I am on Centos 7.
<?php
include "vendor/autoload.php";
$api = new \Gnello\OpenFireRestAPI\API();
//Set the required config parameters
$api->Settings()->setSecret("YWRtaW46YWRtaW4");
$api->Settings()->setHost("localhost");
$api->Settings()->setServerName("localhost");
//Default values
$api->Settings()->setPort("9090");
$api->Settings()->setSSL(false);
$api->Settings()->setPlugin("/plugins/restapi/v1");
Now WhenI try to connect it shows error:
if($result['response']) {
echo $result['output'];
} else {
echo 'Error!';
}
In httpd logs it says undefined $result which is obvious.
But I followed the steps as it were mentioned on its repository.
Can Any One please guide me how to use this ?
#Udated
include "vendor/autoload.php";
$api = new \Gnello\OpenFireRestAPI\API();
//Enable debug mode
$api->Settings()->setDebug(true);
$requests = \Gnello\OpenFireRestAPI\Debug\Request::getRequests();
//var_dump($api);
//var_dump($requests);
$result = $api->users();
//var_dump($api);
$username ="test2";
$results = $api->getuser($username);
if($result['response'])
{
echo $result['output'];
}
else
{
echo 'Error!';
}
https://github.com/gnello/php-openfire-restapi
Easy Php REST API Client for the Openfire REST API Plugin which provides the ability to manage Openfire instance by sending an REST/HTTP request to the server
Please read documentation for further information on using this application.
Installation
composer require gnello/php-openfire-restapi
Authentication
There are two ways to authenticate:
Basic HTTP Authentication
$authenticationToken = new \Gnello\OpenFireRestAPI\AuthenticationToken('your_user', 'your_password');
Shared secret key
$authenticationToken = new \Gnello\OpenFireRestAPI\AuthenticationToken('your_secret_key');
Start
$api = new \Gnello\OpenFireRestAPI\API('your_host', 9090, $authenticationToken);
Users
//Add a new user
$properties = array('key1' => 'value1', 'key2' => 'value2');
$result = $api->Users()->createUser('Username', 'Password', 'Full Name', 'email#domain.com', $properties);
//Delete a user
$result = $api->Users()->deleteUser('Username');
//Ban a user
$result = $api->Users()->lockoutUser('Username');
//Unban a user
$result = $api->Users()->unlockUser('Username');
Then print Result.
Open Link Fore more.
https://github.com/gnello/php-openfire-restapi

Trouble with configuring users and connecting to Mongo with PHP

I installed mongo 3.0.0 on my ubuntu server.
I tried to use PHP (with appropriate lib installed) to connect to mongo to learn sth new. Unfortunaltey I cannot go any further.
My user configuration looks like this:
> use testdb
switched to db testdb
> show users
{
"_id" : "testdb.testdb",
"user" : "testdb",
"db" : "testdb",
"roles" : [
{
"role" : "readWrite",
"db" : "testdb"
}
]
}
Then I try to execute the following PHP code:
try{
$uri = "mongodb://testdb:password#xxx.xxx.xxx.xxx:27017/testdb";
$options = array("connectTimeoutMS" => 30000);
$client = new MongoClient($uri, $options );
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
die();
}
$db = $client->selectDB("testdb");
I get "Message: Failed to connect to: xxx.xxx.xxx.xxx:27017: Authentication failed on database 'testdb' with username 'testdb': auth failed".
In /etc/mongod.conf I have "auth = true" uncommented
I also verified the conncetion with:
> nc -w 3 -v xxx.xxx.xxx.xxx 27017 Connection to xxx.xxx.xxx.xxx 27017
> port [tcp/*] succeeded!
I dig through Internet, i spent few hours already on this, I even re-installed mongo and set everything up again without any success.
Could you point to where to look for solution?
The authentication schema of 3.0 is not compatible with 2.x drivers. One way you should be able to make it work is by downgrading the authentication mechanism:
use "admin"
var schema = db.system.version.findOne({"_id" : "authSchema"})
schema.currentVersion = 3
db.system.version.save(schema)
Then create a user and you should be able to connect with it.

cant connect user to google cloud sql database

I am attempting to connect to a database in an instance on Google cloud sql but it is telling me access is denied.
Im just wondering am I missing something here...
I have requested an IP and inserted that into the authorized networks
I have created a database and set a user using SQL prompt (found in original view of Google APIs Console) and granted all privileges to that user for that database.
I have listed the users in that database to make sure "adrian" exists and that I have done that correctly.
I have insured the app being used to connect is authorized in the access control
I have set a root password in the access control section.
Here is my app.yaml file...
application: guestbookadrian12
version: 1
runtime: php
api_version: 1
handlers:
- url: .*
script: main.php
env_variables:
DEVELOPMENT_DB_HOST: ''
DEVELOPMENT_DB_USERNAME: 'root'
DEVELOPMENT_DB_PASSWORD: 'password'
DEVELOPMENT_DB_NAME: 'guestbookadrian12'
PRODUCTION_CLOUD_SQL_INSTANCE: '/cloudsql/guestbookadrian12:my-cloudsql-instance'
PRODUCTION_DB_USERNAME: 'adrian'
PRODUCTION_DB_PASSWORD: 'password'
PRODUCTION_DB_NAME: 'guestbookadrian12'
Here is some php code where it creates the connection...
if (strpos(getenv('SERVER_SOFTWARE'), 'Development') === false) {
$conn = mysqli_connect(null,
getenv('PRODUCTION_DB_USERNAME'),
getenv('PRODUCTION_DB_PASSWORD'),
null,
null,
getenv('PRODUCTION_CLOUD_SQL_INSTANCE'));
$db = getenv('PRODUCTION_DB_NAME');
//echo 'Database = : '.$db;
} else {
$conn = mysqli_connect(getenv('DEVELOPMENT_DB_HOST'),
getenv('DEVELOPMENT_DB_USERNAME'),
getenv('DEVELOPMENT_DB_PASSWORD'));
$db = getenv('DEVELOPMENT_DB_NAME');
}
if ($conn->connect_error) {
die("Could not connect to database: $conn->connect_error " .
"[$conn->connect_errno]");
}
if ($conn->query("CREATE DATABASE IF NOT EXISTS $db") === FALSE) {
die("Could not create database: $conn->error [$conn->errno]");
}
The error Im getting is
Could not create database: Access denied for user 'adrian'#'localhost' to database 'guestbookadrian12' [1044]
Thank you

Prevent local duplicates with the External Database Authentication Plugin on Moodle

I'm using Moodle's external database plugin and am having a very annoying problem. Here's an example:
username: johndoe#gmail.com logs in with his password and both are saved in an external DB. Moodle grabs that data (username, password) and saves it locally (mysql) with that user's external DB id. Keep in mind the external DB is the main DB where everything happens, Moodle is only for authorized users that need to take tests. So in Moodle, I have:
username: johndoe#gmail.com
password: blabla
userid: 1234
It works great, except for when johndoe#gmail.com decides to update his username/email on the external DB, so he wants it to be johndoe#hotmail.com now. When he tries to log in, it logs in fine, since Moodle checks with the external DB for both username/password. Problem: A new record is created within Moodle for johndoe#hotmail.com with same password AND userid.
My question is: Where can I safely check with the local DB if userid already exists and NOT create a new record? I do not want to update the moodlelib doc because I don't want to have upgrading problems in the future. I can update the External DB plugin, but can't figure out where would be best.
Here's a workaround someone did - https://moodle.org/mod/forum/discuss.php?d=232163 - but it's done in a cron job instead of immediately on Login.
UPDATE:
It looks like I'll have to update moodlelib and the external db plugin, I'll post my solution if nobody posts.
Since nobody replied, this is the best I could come up with. I have my own comments with *UPDATED so you know where I updated the code.
Under \moodle\lib\moodlelib.php
(Unfortunately I had to update this file because of an authentication call that would trigger the duplicate creation).
1) Update function authenticate_user_login(); replace line 4342 - 4382 with:
$authsenabled = get_enabled_auth_plugins();
// *UPDATED - begin
$authplugin = get_auth_plugin('DB');
$userinfo = ($authplugin->get_userinfo($username)) ? $authplugin->get_userinfo($username) : 0;
// *UPDATED - end
// *UPDATED - added second elseif
if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
// Use manual if auth not set.
$auth = empty($user->auth) ? 'manual' : $user->auth;
if (!empty($user->suspended)) {
add_to_log(SITEID, 'login', 'error', 'index.php', $username);
error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
$failurereason = AUTH_LOGIN_SUSPENDED;
return false;
}
if ($auth=='nologin' or !is_enabled_auth($auth)) {
add_to_log(SITEID, 'login', 'error', 'index.php', $username);
error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
// Legacy way to suspend user.
$failurereason = AUTH_LOGIN_SUSPENDED;
return false;
}
$auths = array($auth);
}
elseif ($user = get_complete_user_data('idnumber', $userinfo['idnumber'], $CFG->mnet_localhost_id)) {
$auth = empty($user->auth) ? 'manual' : $user->auth; // use manual if auth not set
if (!empty($user->suspended)) {
add_to_log(SITEID, 'login', 'error', 'index.php', $username);
error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
$failurereason = AUTH_LOGIN_SUSPENDED;
return false;
}
if ($auth=='nologin' or !is_enabled_auth($auth)) {
add_to_log(SITEID, 'login', 'error', 'index.php', $username);
error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
$failurereason = AUTH_LOGIN_SUSPENDED; // Legacy way to suspend user.
return false;
}
$auths = array($auth);
}
else {
// Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
$failurereason = AUTH_LOGIN_NOUSER;
return false;
}
// Do not try to authenticate non-existent accounts when user creation is not disabled.
if (!empty($CFG->authpreventaccountcreation)) {
add_to_log(SITEID, 'login', 'error', 'index.php', $username);
error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".$_SERVER['HTTP_USER_AGENT']);
$failurereason = AUTH_LOGIN_NOUSER;
return false;
}
// User does not exist.
$auths = $authsenabled;
$user = new stdClass();
$user->id = 0;
}
2) Same function, replace line 4408 - 4427 with:
if ($user->id) {
// User already exists in database.
if (empty($user->auth)) {
// For some reason auth isn't set yet.
// *UPDATED $DB->set_field('user', 'auth', $auth, array('username'=>$username));
$DB->set_field('user', 'auth', $auth, array('idnumber'=>$user->idnumber));
$user->auth = $auth;
}
// If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
// the current hash algorithm while we have access to the user's password.
update_internal_user_password($user, $password);
if ($authplugin->is_synchronised_with_external()) {
// Update user record from external DB.
// *UPDATED $user = update_user_record($username);
$user = $authplugin->update_user_record($username, $user->idnumber);
}
} else {
// Create account, we verified above that user creation is allowed.
$user = create_user_record($username, $password, $auth);
}
Under \moodle\auth\db\auth.php (External DB plugin Lib)
1) Update function update_user_record() to receive the IDNUMBER parameter:
function update_user_record($username, $idnumber='', $updatekeys=false) {
2) Replace line 512 with:
$user = $DB->get_record('user', array('idnumber'=>$idnumber, 'mnethostid'=>$CFG->mnet_localhost_id));
So now, the main function under the moodle lib will check if user exists by username, if not, checks if user ID exists...if so, it will update the user's info with the new info coming from the external DB. It works fine on Moodle 2.4 and 2.6 for me.
This is quite an old answer, but there's an alternative that requires no manual patching.
The OP uses email addresses (instead of arbitrary usernames) to identify users. This behaviour can be maintained by setting Site administration > Plugins > Authentication > Manage authentication > Allow log in via email (authloginviaemail) to true. Now the username can be populated by the (stable) external database ID. Changing email addresses hence won't result in new accounts.

Categories