hybridauth - can not restore google login - hybridauth

I have made login script with HybridAuth. I'm loged in my website with "providers" Facebook, Google, Twitter. When PHP sessions time out, I want to restore my connected "providers".
I use this code :
$connected_adapters_list = $hybridauth->getConnectedProviders();
if( count( $connected_adapters_list ) ){
foreach( $connected_adapters_list as $adapter_id ){
echo $adapter_id . "<br>";
}
}
HybridAuth can restore my Facebook and Twitter connection, but not Google. This is code error output. How to solve it ?
Ooophs, we got an error: User profile request failed! Google returned an invalid response:stdClass::__set_state(array( 'error' => stdClass::__set_state(array( 'errors' => array ( 0 => stdClass::__set_state(array( 'domain' => 'global', 'reason' => 'authError', 'message' => 'Invalid Credentials', 'locationType' => 'header', 'location' => 'Authorization', )), ), 'code' => 401, 'message' => 'Invalid Credentials', )), )) Error code: 6

I also has this problem,
it could be sloved by using "logoutAllProviders()" function
there is code :
try{
$hybridauth = new Hybrid_Auth( $config );
$adapter = $hybridauth->authenticate( "Google" );
$user_profile = $adapter->getUserProfile();
}
catch( Exception $e ){
$hybridauth->logoutAllProviders();
$hybridauth = new Hybrid_Auth( $config );
$adapter = $hybridauth->authenticate( "Google" );
$user_profile = $adapter->getUserProfile();
}
}
good luck for you !

Related

How can I migrate to an alternative flow (OAuth 2.0 for Desktop apps)?

I get authorization error, when trying connect my calendar to "Google" calendar. I added a photo of my problem.
How can I fix my code?
Here is my PHP code:
// Default data
$data = array(
'redirect_uri' => 'urn:ietf:wg:oauth:2.0:oob',
'scope' => 'https://www.googleapis.com/auth/calendar',
'access_type' => 'offline',
'response_type' => 'code',
'grant_type' => 'authorization_code',
'client_id' => '',
'client_secret' => '',
'code' => '',
'access_token' => '',
'refresh_token' => '',
);
And here is my JS code:
function gcal_access_link() {
var obj = {
client_id : jQuery('#client_id').val(),
response_type : 'code',
redirect_uri : 'urn:ietf:wg:oauth:2.0:oob',
scope : 'https://www.googleapis.com/auth/calendar',
access_type : 'offline',
};
return 'https://accounts.google.com/o/oauth2/auth?' + jQuery.param(obj);
}
jQuery('#access_link').attr( 'href', gcal_access_link() ); // insert on page load
jQuery('body').on('change', '#client_id', function() {
jQuery('#access_link').attr( 'href', gcal_access_link() );
});
I need help to fix my code.
change your redirect uri from urn:ietf:wg:oauth:2.0:oob to http://127.0.0.1
The authorization code will come back as before
http://127.0.0.1/?code=COPY_THIS_CODE.
If you dont have a web server running on that host you will see an error in the browser but the code should still be there.

Microsoft Graph - Get Token from Authorisation Response

I am following the instructions here:
https://learn.microsoft.com/en-us/graph/auth-v2-user?view=graph-rest-1.0#3-get-a-token
I get the authorisation response and therefore the required code, but when I request the token I get a "HTTP/1.1 401 Unauthorized" response.
This is my code (not for production, just for me to get the flow/code right first):
<?php
/*
Auth
https://learn.microsoft.com/en-us/graph/auth-v2-user?view=graph-rest-1.0
*/
define("HOST", 'https://login.microsoftonline.com');
define("TENANT", 'common');
define("AUTH_ENDPOINT", HOST.'/'.TENANT.'/oauth2/v2.0/authorize');
define("TOKEN_ENDPOINT", HOST.'/'.TENANT.'/oauth2/v2.0/token');
define("CLIENT_ID", '<< FROM AZURE PORTAL >>');
define("CLIENT_SECRET", '<< FROM AZURE PORTAL >>');
define("ALL_SCOPES", rawurlencode('offline_access user.read mail.read'));
define("CALLBACK", rawurlencode('http://localhost:300/graph2/auth.php'));
// Build URL
$url = AUTH_ENDPOINT."?client_id=".CLIENT_ID;
$url .= "&response_type=code";
$url .= "&redirect_uri=".CALLBACK;
$url .= "&response_mode=query";
$url .= "&scope=".ALL_SCOPES;
echo "<a href=$url>$url</a>";
if (isset($_GET))
{
echo '<pre>';print_r($_GET);echo'</pre>';
if (isset($_GET['code']))
{
// Got authorisation code - now need token
$response = requestAccessTokenByVerifier($_GET['code']);
echo ">".$response;
}
}
function requestAccessTokenByVerifier($verifier)
{
return requestAccessToken(
array(
'client_id' => CLIENT_ID,
'redirect_uri' => CALLBACK,
'client_secret' => CLIENT_SECRET,
'code' => $verifier,
'grant_type' => 'authorization_code',
'scope' => ALL_SCOPES
)
);
}
function requestAccessToken($content)
{
$response = sendRequest(TOKEN_ENDPOINT, 'POST', $content);
if ($response !== false)
{
$authToken = json_decode($response);
if (!empty($authToken) && !empty($authToken->{ACCESSTOKEN})) return $authToken;
}
die("No access token");
return false;
}
function sendRequest($url, $method = 'GET', $data = array(), $headers = array('Content-Type: application/x-www-form-urlencoded'))
{
$context = stream_context_create(
array(
'http' => array(
'method' => $method,
'header' => $headers,
'content' => buildQueryString($data)
)
)
);
echo "URL: $url<br>";
echo '<pre>';print_r($data);echo '</pre>';
echo buildQueryString($data)."<br>";
$response = file_get_contents($url, false, $context);
echo '<pre>';var_dump($http_response_header);echo '</pre>';
return $response;
}
function buildQueryString($array)
{
$result = '';
foreach ($array as $k => $v)
{
if ($result == '') $prefix = ''; else $prefix = '&';
$result .= $prefix . $k . '=' . $v;
}
return $result;
}
?>
As you will see I've put a few basic diagnostics in there which show I am getting the code required successfully, but then not being able to get a token from the code.
Can anybody suggest what to try next, I wonder either from a debugging point of view or alternative approaches.
Thanks.
OK, after digging around I realised I'd made a stupid mistake, but just in case anybody else does the same - you need to use the client secret value not id!
I've deleted that client secret :)
Hope that helps somebody else bashing their head against a brick wall.

SQS RedrivePolicy PHP SDK

Iam new to SQS php SDK, Iam not able to override RedrivePolicy using setQueueAttributes method :(
json string is not accepted as an attribute and I cannot find any clear resources to help me.
Have a look at the below example code:
$queueUrl = "QUEUE_URL";
$client = new SqsClient([
'profile' => 'default',
'region' => 'us-west-2',
'version' => '2012-11-05'
]);
try {
$result = $client->setQueueAttributes(array(
'Attributes' => [
'ReceiveMessageWaitTimeSeconds' => 20
],
'QueueUrl' => $queueUrl, // REQUIRED
));
var_dump($result);
} catch (AwsException $e) {
// output error message if fails
error_log($e->getMessage());
}
Full code:
https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/php/example_code/sqs/LongPollingSetQueueAttributes.php

Silex "There is no user provider for user" how to configure security

$app->register(new SecurityServiceProvider(), array(
'security.firewalls' => array(
'admin' => array(
'pattern' => '^/',
'form' => array(
'login_path' => '/login',
'check_path' => '/login_check',
'always_use_default_target_path' => true,
'default_target_path' => '/profile'
),
'logout' => true,
'anonymous' => true,
'users' => function () use ($app) {
return new \App\UserProvider($app['dbs']['mysql']);
},
),
),
'security.access_rules' => array(
array('^/profile', 'ROLE_USER')
)
));
In a Silex 2 application I have been able to authenticate a users credentials in the login_check, but then on redirect is the dreaded (for me) Runtime exception "ContextListener.php line 74 There is no user provider for user "Symfony\Component\Security\Core\User\User".
(my 'standard' User provider class)
class UserProvider implements UserProviderInterface {
private $conn;
public function __construct(Connection $conn)
{
$this->conn = $conn;
}
public function loadUserByUsername($username)
{
// $app['monolog']->addInfo(sprintf("User '%s' registered.", $username));
$stmt = $this->conn->executeQuery('SELECT * FROM users_wet4 WHERE email = ?', array(strtolower($username)));
if (!$user = $stmt->fetch()) {
throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username));
}
return new User($user['email'], $user['password'], explode(',', $user['roles']), true, true, true, true);
}
public function refreshUser(UserInterface $user)
{
if (!$user instanceof \App\Security\User) {
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
}
return $this->loadUserByUsername($user->getUsername());
}
public function supportsClass($class)
{
return $class === 'Symfony\Component\Security\Core\User\User';
}
}
I've searched across it seems every instance of this issue, and it looks like the most common resolution in a Symfony installation is configuring security to point to the custom user provider, but I have not seen any examples for silex differently than the way above:
'users' => function () use ($app) {
return new \App\UserProvider($app['dbs']['mysql']);
},
(I've seen this in a security.xml file for symfony, is this kind of provider config what is missing?)
providers:
main:
entity: { class: FredUtilisateurBundle:User, property: login }
Is there anyone who can help me with the logic of the 'no user provider' after being authenticated?
Ok solved it, problem was actually here:
if (!$user instanceof \App\Security\User) {
should have just been User.
if (!$user instanceof User) {
or whatever Custom User you might have created.
\App\MyUser

get_permalink to attachment not working

I have following code:
<?php
$args = array(
'post_type' => 'attachment',
'numberposts' => 12,
'post_status' => null
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
echo '<li><a href="'.get_permalink( $attachment->ID ).'">';
echo wp_get_attachment_image( $attachment->ID, array('100', '100') );
echo '</a></li>';
}
}
?>
The point of this script is to show last added 12 photos (thumbs of it). And this works perfect. But I want to add second funcionality - link to the page where it comes from (usually native gallery embed into post/page)
The problem is that in this case the link is corrupted. It always links to the very first post. What I am doing wrong?
Try get_attachment_link($attachment->ID).
Or the_attachment_link($attachment->ID) to directly print the anchor tag with the URL
Here is the final version:)
<?php
$args = array(
'post_type' => 'attachment',
'numberposts' => 12,
'post_status' => null
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$url = get_permalink( $attachment->ID );
echo '<li><a href="'.strstr($url, '/attachment', true).'">';
echo wp_get_attachment_image( $attachment->ID, array('100', '100') );
echo '</a></li>';
}
}
?>
/attachment is the starting point from which we want to remove everything from the url.

Resources