Login a user to wordpress from external application - react-native

Hi I am building a React native app based on my wordpress website so I need to make a registration and login logic to get the user id and user data, thankfully I made the registration logic by creating new user using the rest api, but I need help in making the login thing since I find nothing helpful while searching Google.
I want to post the username or email and the password to authenticate that the user do exist in my site

register_rest_route(
'custom-plugin', '/login/',
array(
'methods' => 'POST',
'callback' => 'login',
)
);
}
function login($request){
$creds = array();
$creds['user_login'] = $request["username"];
$creds['user_password'] = $request["password"];
$creds['remember'] = true;
$user = wp_signon( $creds, false );
if ( is_wp_error($user) )
echo $user->get_error_message();
return $user;
}
add_action( 'after_setup_theme', 'custom_login' );
Then your API will be created as
http://www.url.com/wp-json/custom-plugin/login
Try it with Postman You will get 200 as a response and user info
body:
{
"username": ""fakmamail#gmail.com",//or the username
"password": "t433434533"
}

Related

mautic - I want to add contact in mautic via api

I want to add contact in mautic via an API. Below I have the code, but it's not adding the contact in mautic.
I have installed mautic in localhost. Studied the API form in the mautic documentation and tried to do it for at least 2 days, but I am not getting any results on it.
<?php
// Bootup the Composer autoloader
include __DIR__ . '/vendor/autoload.php';
use Mautic\Auth\ApiAuth;
session_start();
$publicKey = '';
$secretKey = '';
$callback = '';
// ApiAuth->newAuth() will accept an array of Auth settings
$settings = array(
'baseUrl' => 'http://localhost/mautic', // Base URL of the Mautic instance
'version' => 'OAuth2', // Version of the OAuth can be OAuth2 or OAuth1a. OAuth2 is the default value.
'clientKey' => '1_1w6nrty8k9og0kow48w8w4kww8wco0wcgswoow80ogkoo0gsks', // Client/Consumer key from Mautic
'clientSecret' => 'id6dow060fswcswgsgswgo4c88cw0kck4k4cc0wkg4gows08c', // Client/Consumer secret key from Mautic
'callback' => 'http://localhost/mtest/process.php' // Redirect URI/Callback URI for this script
);
/*
// If you already have the access token, et al, pass them in as well to prevent the need for reauthorization
$settings['accessToken'] = $accessToken;
$settings['accessTokenSecret'] = $accessTokenSecret; //for OAuth1.0a
$settings['accessTokenExpires'] = $accessTokenExpires; //UNIX timestamp
$settings['refreshToken'] = $refreshToken;
*/
// Initiate the auth object
$initAuth = new ApiAuth();
$auth = $initAuth->newAuth($settings);
/*
if( $auth->getAccessTokenData() != null ) {
$accessTokenData = $auth->getAccessTokenData();
$settings['accessToken'] = $accessTokenData['access_token'];
$settings['accessTokenSecret'] = 'id6dow060fswcswgsgswgo4c88cw0kck4k4cc0wkg4gows08c'; //for OAuth1.0a
$settings['accessTokenExpires'] = $accessTokenData['expires']; //UNIX timestamp
$settings['refreshToken'] = $accessTokenData['refresh_token'];
}*/
// Initiate process for obtaining an access token; this will redirect the user to the $authorizationUrl and/or
// set the access_tokens when the user is redirected back after granting authorization
// If the access token is expired, and a refresh token is set above, then a new access token will be requested
try {
if ($auth->validateAccessToken()) {
// Obtain the access token returned; call accessTokenUpdated() to catch if the token was updated via a
// refresh token
// $accessTokenData will have the following keys:
// For OAuth1.0a: access_token, access_token_secret, expires
// For OAuth2: access_token, expires, token_type, refresh_token
if ($auth->accessTokenUpdated()) {
$accessTokenData = $auth->getAccessTokenData();
echo "<pre>";
print_r($accessTokenData);
echo "</pre>";
//store access token data however you want
}
}
} catch (Exception $e) {
// Do Error handling
}
use Mautic\MauticApi;
//use Mautic\Auth\ApiAuth;
// ...
$initAuth = new ApiAuth();
$auth = $initAuth->newAuth($settings);
$apiUrl = "http://localhost/mautic/api";
$api = new MauticApi();
$contactApi = $api->newApi("contacts", $auth, $apiUrl);
$data = array(
'firstname' => 'Jim',
'lastname' => 'Contact',
'email' => 'jim#his-site.com',
'ipAddress' => $_SERVER['REMOTE_ADDR']
);
$contact = $contactApi->create($data);
echo "<br/>contact created";
Any help will be appreciated.
use Curl\Curl;
$curl = new Curl();
$un = 'mayank';
$pw = 'mayank';
$hash = base64_encode($un.':'.$pw);
$curl->setHeader('Authorization','Basic '.$hash);
$res = $curl->post(
'http://mautic.local/api/contacts/new',
[
'firstname'=>'fn',
'lastname'=>'ln',
'email'=>'t1#test.com'
]
);
var_dump($res);
This is something very simple i tried and it worked for me, please try cleaning cache and enable logging, unless you provide us some error it's hard to point you in right direction. Please check for logs in app/logs directory as well as in /var/logs/apache2 directory.
In my experience sometimes after activating the API in the settings the API only starts working after clearing the cache.
Make sure you have activated the API in the settings
Clear the cache:
cd /path/to/mautic
rm -rf app/cache/*
Then try again
If this didn't work, try to use the BasicAuth example (You have to enable this I the settings again and add a new User to set the credentials)
I suspect that the OAuth flow might be disturbed by the local settings / SSL configuration.
these steps may be useful:
make sure API is enabled(yes I know it's might be obvious but still);
check the logs;
check the response body;
try to send it as simple json via Postman
it may be one of the following problems:
Cache;
You are not sending the key:value; of the required custom field;
you are mistaken with authentication;
Good luck :)

How to do a Sign Up with OAuth (facebook, twitter, google)?

I use Laravel (5) as my php framework, it recently added a library for social authentication (facebook, google, twitter and github).
I've been wondering how would you do a Sign Up with OAuth, a login can easily be done by getting the user's email via OAuth, checking if it exists in your DB, and if it does, then log in that user. But how would you do the Sign Up?
Mathius - I've recently been working on a site doing something similar to what you've described and this is what has worked for me:
public function syncUserDetails($userData)
{
// First I check to see if there is a user in the DB
// with the oAuth email address
if ( $user = $this->user->where('email', $userData->email)->first() )
{
// If there is a user, I simply update their local info
// with what is on their oAuth account
$user->token = $userData->token;
$user->google_id = $userData->id;
$user->name = $userData->name;
$user->avatar = $userData->avatar;
$user->first_name = $userData->user['given_name'];
$user->last_name = $userData->user['family_name'];
$user->save();
return $user;
}
// Otherwise, if the user doesn't already exist,
// I create them in my local user's DB
return $this->user->firstOrCreate([
'email' => $userData->email,
'token' => $userData->token,
'google_id' => $userData->id,
'name' => $userData->name,
'avatar' => $userData->avatar,
'first_name' => $userData->user['given_name'],
'last_name' => $userData->user['family_name']
]);
}
This is what I'm using to log in a user. However, you could just as easily run this alongside your regular Laravel login method.

Google Apps Marketplace CustomerLicense Authorization Steps ?

We have recently create the google marketplace app and published as public .admin of the google apps domain users can able to install it .
i recently try to implement the CustomerLicense,LicenseNotification Apis in for my app
But i dont know how to send a Authorization for it Please suggest me to how to do this
My requirement :
1.I need to know whether the given domain has installed my marketplace app or not (My input is authorization,email id or domain name
2.If any user uninstall or revoke the data access for my marketplace app i need to get the notify (optional)
Here is sample code :
$appId = '';**//Where i get this**
$userid = '';**//It is emailid or domain name or user unique numeric id**/
$oauthOptions = array(
'requestScheme' => Zend_Oauth::REQUEST_SCHEME_HEADER,
'signatureMethod' => 'HMAC-SHA1',
'consumerKey' => '', **//Where i get this**
'consumerSecret' => "" **//Where i get this**
);
//We get from APP URL
try {
$userid = 'backup-testing.in';
$token = new Zend_Oauth_Token_Access();
$client = $token->getHttpClient($oauthOptions);
$url = "https://www.googleapis.com/appsmarket/v2/customerLicense/$appId/$userid";
$client->setMethod(Zend_Http_Client::GET);
$gdata_put = new Zend_Gdata($client);
$resultR = $gdata_put->get($url);
} catch (Exception $e) {
var_dump($e);
}
This is my marketplace app
in chrome westore : https://chrome.google.com/webstore/detail/gapps-backup/jmjnfmekbahcminibjmedfehecoihglj
Here you can find information about the Licensing API https://developers.google.com/google-apps/marketplace/v2/developers_guide which i think will be useful for what you want to do. hope it helps.

Google + sign in with laravel

I have been struggling a lot for G+ sign-in with laravel, I have downloaded the php-sdk using composer. I am also using JavaScript to sign-in, once the once the user signs in I redirect him to a route from JavaScript to /gLogin?email=abc#gmail.com&name=John Doe where I have following code.
$user_profile['email']=Input::get('email');
$user_profile['name']=Input::get('name');
$user_id=DB::table('users') -> where('dyp_user_email', $user_profile['email'])-> pluck('dyp_user_id');
if($user_id)
{
$user_to_be_logged_in=new user();
$user_to_be_logged_in = User::find($user_id);
}
else
{
$password=$token = str_random(16);
$hash=Hash::make($password);
$user_to_be_logged_in = user::create(array('dyp_user_type' => 'IN', 'dyp_name' => $user_profile['name'], 'dyp_user_email' => $user_profile['email'], 'dyp_mobile_number' => '','dyp_password'=> $hash,'dyp_user_status' => 'VF'));
$data = array('name' => $user_to_be_logged_in -> dyp_name, 'password' => $password);
Mail::send('emails.fbUserRegistration', $data, function($message) use ($user_to_be_logged_in) {
$message -> to($user_to_be_logged_in->dyp_user_email, $user_to_be_logged_in->dyp_name) -> subject('Thanks for registering with dreamyourproperty.com');
});
}
Auth::login($user_to_be_logged_in);
There is a serious security problem here, that I am not able to validate the user's session.
I someone manually hits the url /gLoin?email=abc#gmail.com&name=xyz then also my code will authenticate him.
In comparison to G+ signin FB login was pretty simple.Can someone provide me guidance, I am seriously stuck with this part.
They way you want to handle this is /gLogin?access_token=xyz where xyz is the users Google+ access_token. Make a request to people.get authenticated with that access token. That way you have server side validation the current user is validated for the specific Google+ profile.

FB.login returns Invalid OAuth access token

I've been developing an app for the past few weeks and up until now there have been no issues. Just a couple days ago a strange bug has started occurring:
My application uses the PHP SDK and implements the Javascript SDK for user authorization. The user is allowed to roam the application freely, but when they click on a video, FB.login is called to request permissions from the user and get an access token.
jQuery Code
FB.login(function(response) {
if (response.authResponse) {
//Set global vars
fb_uid = response.authResponse.userID;
fb_token = response.authResponse.accessToken;
//If user has already authorized the app
if (response.status === 'connected') {
//Create the user record
$.ajax(site_url + '/facebook/create_fb_user', {
type: 'POST',
dataType: 'json',
data: {fb_uid: fb_uid, token: fb_token},
success: function (data) {
user = data.resp.fb_user;
viewVideo(item);
}
});
};
};
}, {scope: "publish_stream"});
PHP Code
try {
$this->_fb->setAccessToken($this->request->post('token'));
$data = $this->_fb->api("/me");
$model = new Model_Fbuser;
$model->data = array(
'fb_uid' => $data['id'],
'fb_token' => $extended_token
);
$resp = $model->update();
return $this->render_json(array(
'success' => TRUE,
'resp' => $resp
));
} catch (Exception $e) {
return $this->render_json(array(
'success' => FALSE,
'error' => $e->getMessage(),
'token' => $this->request->post('token')
));
}
The first time the user does this, the FB.login call returns a valid access token, the PHP SDK is able to set the token, and everything works as expected.
However, should the user revoke the application's access in their App Settings, and then return to the application, they are presented with the FB.login once more, but this time, the call returns the same access token they were previously given, which has already had its access revoked. Trying to set the access token with the PHP SDK throws the exception: "Invalid OAuth access token."
Yet if I then check the token in the Facebook debugger, is says it is valid.
Edit:
Further investigation reveals that the user is issues the same access token every time in the same session. If the user logs out, then logs back in, then they will receive a new valid token. But if they try to get a new token without logging out first, Facebook reissues them the same invalid one. When trying to use this access token to query information about the user, this is the response:
{"error":{"type":"OAuthException","message":"Error validating access token: The session was invalidated explicitly using an API call."}}
If you get the "Invalid OAuth access token" error in this way, I usually call FB.logout() and then immediately call FB.login() in the callback.
FB.logout(function(response) {
// user is now logged out
FB.login(...)
});
Not ideal, but the best way to fix such a use-case.