wordpress create user from facebook login plugin - wordpress

How do I call this function from my wordpress theme. It is supposed to be called when the one who comments logs in via facebook login function.
function myfb_do_login() {
global $wpdb;
// cookie
$cookie = get_facebook_cookie();
// get user data
$fbuser = get_facebook_user($cookie);
$username = sanitize_user($fbuser->first_name);
// put everything in nice array
$userdata = array(
'user_pass' => wp_generate_password(),
'user_login' => $username,
'user_nicename' => $username,
'user_email' => $fbuser->email,
'display_name' => $fbuser->name,
'nickname' => $username,
'first_name' => $fbuser->first_name,
'last_name' => $fbuser->last_name,
'role' => 'subscriber'
);
// create new user
$new_user = wp_insert_user($userdata);
// set the auth cookie to current user id
wp_set_auth_cookie($new_user, true);
// log the user in
wp_set_current_user($new_user);
// do redirect here
wp_safe_redirect(get_permalink(). '#response');
}

if you have user info at hand, create an array of user data an pass it to wp_insert_user, what userdata should contains refers to wp_insert_usercodex.
code example:
//insert new user to db
$wpuid=wp_insert_user($userdata);
//set the auth cookie to current user id
wp_set_auth_cookie($wpuid,true);
//log the user in
wp_set_current_user($wpuid);
//do redirect here....
wp_safe_redirect($location);

Related

Login WP - Connect single field to an external api

I made a plugin to allow wordpress login with external api.
Everything works, now what I have to do is that when a user logs in for the first time, the plugin checks to see if it is already present on wp, and where it was not already present, it creates a new user by taking behind username, email and password.
The new user is created but I would like it to bring with it also the id field from the external api saving it in an ACF field.
This is the code created so far:
function au_auth($user, $username, $password)
{
$options = get_option('au_options');
$endpoint = $options['au_apiurl'];
$user_email_key = 'email';
$password_key = 'password';
// Makes sure there is an endpoint set as well as username and password
if (!$endpoint || $user !== null || (empty($username) && empty($password))) {
return false;
}
// Check user exists locally
$user_exists = wp_authenticate_username_password(null, $username, $password);
if ($user_exists && $user_exists instanceof WP_User) {
$user = new WP_User($user_exists);
return $user;
}
// Build the POST request
$login_data = array(
$user_email_key => $username,
$password_key => $password
);
$auth_args = array(
'method' => 'POST',
'headers' => array(
'Content-type: application/x-www-form-urlencoded'
),
'sslverify' => false,
'body' => $login_data
);
$response = wp_remote_post($endpoint, $auth_args);
// Token if success; Not used right now
$response_token = json_decode($response['response']['token'], true);
$response_code = $response['response']['code'];
if ($response_code == 400) {
// User does not exist, send back an error message
$user = new WP_Error('denied', __("<strong>Error</strong>: Your username or password are incorrect."));
} else if ($response_code == 200) {
// External user exists, try to load the user info from the WordPress user table
$userobj = new WP_User();
// Does not return a WP_User object but a raw user object
$user = $userobj->get_data_by('email', $username);
if ($user && $user->ID) {
// Attempt to load the user with that ID
$user = new WP_User($user->ID);
}
} else {
// The user does not currently exist in the WordPress user table.
// Setup the minimum required user information
$userdata = array(
'user_email' => $username,
'user_login' => $username,
'user_pass' => $password
);
// A new user has been created
$new_user_id = wp_insert_user($userdata);
// Assign editor role to the new user (so he can access protected articles)
wp_update_user(
array(
'ID' => $new_user_id,
'role' => 'editor'
)
);
// Load the new user info
$user = new WP_User ($new_user_id);
}
}
// Useful for times when the external service is offline
remove_action('authenticate', 'wp_authenticate_username_password', 20);
return $user;
}
Anyone have any way how to help me?
Resolved! I hope this will help those who have found themselves in the same situation as me:
add_filter('authenticate', 'au_auth', 10, 3);
add_filter('register_new_user', 'au_registration', 10, 3);
// add_filter('profile_update', 'au_profile_update', 10, 3);
// add_filter('edit_user_profile_update', 'au_profile_edit', 10, 3);
function au_auth($user, $username, $password)
{
$options = get_option('au_options');
$endpoint = $options['au_apiurl'];
// Makes sure there is an endpoint set as well as username and password
if (!$endpoint || $user !== null || (empty($username) && empty($password))) {
return false;
}
$auth_args = [
'method' => 'POST',
'headers' => [
'Content-type: application/x-www-form-urlencoded',
],
'sslverify' => false,
'body' => [
'email' => $username,
'password' => $password,
],
];
$response = wp_remote_post($endpoint, $auth_args);
// Token if success; Not used right now
$response_token = json_decode($response['response']['token'], true);
$body = json_decode($response['body'], true);
$response_status_code = $response['response']['code'];
$success = $body !== 'KO';
if (!$success) {
// User does not exist, send back an error message
$user = new WP_Error('denied', __('<strong>Error</strong>: Your username
or password are incorrect.'));
} elseif ($success) {
$idExternal = $body['Id'];
$nome = $body['Name'];
$cognome = $body['Surname'];
$email = $body['Email'];
$userobj = new WP_User();
$user = $userobj->get_data_by('email', $email);
if ($user && $user->ID) {
$user = new WP_User($user->ID);
} else {
$userdata = [
'user_email' => $email,
'user_login' => join(' ', [$name, $surname]),
'user_pass' => '----',
];
$new_user_id = wp_insert_user($userdata);
$new_user_composite_id = 'user_' . $new_user_id;
update_field('field_60084ad3970a8', $idExternal, $new_user_composite_id);
update_field('field_5f22ca201c7b0', $name, $new_user_composite_id);
update_field('field_5f22ccd498f40', $surname, $new_user_composite_id);
update_field('field_5f22ce7b7c1db', $email, $new_user_composite_id);
$user = new WP_User($new_user_id);
}
}
remove_action('authenticate', 'wp_authenticate_username_password', 20);
return $user;
}

Validate wordpress password repeat with REST api

I have a registeration form with some custom fields and need to register users with Wordpress REST api,
$('#user_register_form').submit(function(e){
e.preventDefault();
var form = $(this),
rest = new DwREST();
rest.registerUser({
first_name: '',
last_name: '',
username: 'amin',
name : 'amin',
email : 'aaaa#amin.ev',
password: '11111',
// passwrod2: '11111' -confirm password field
// custom_field1: ''
// ....
}, function( res ){
console.log( res );
});
});
The user registeration works fine but the problem is i can't confirm wether password repeat matches or not, i searched a lot and didn't find an action to modify to /users/ validation
the second question is is it possible to automatically login user created with REST api after registeration?
i appreciate any help.
I searched in rest-api source codes, sadly i didn't find any proper hook to do what i needed, there's just a rest_pre_insert_user hook which getting it to do what i intend to do is a bit tricky, but here's the work around, in case some one has the same problem:
add_filter('rest_pre_insert_user', function( $user, $request ){
$params = $request->get_params();
if( $params['password'] !== $params['password2'] ) {
$error = new WP_Error( 'rest_no_matching_passwords', __( 'Passwords don\'t match' ), array( 'status' => 400 ) );
foreach( $error->error_data as $data ) {
http_response_code( $data['status'] );
}
header('Content-Type: application/json; charset=utf-8;');
foreach( $error->errors as $key => $val ){
$json = json_encode([
'code' => $key,
'type' => 'error',
'message' => $val[0]
]);
}
die( $json );
}
return $user;
}, 10, 2 );
Reference

How to get current logged-in user details of a blog in wordpress?

When I logged into the specific multi-site blog, I am trying to get current login user details, I already used below one but this function returning null. How, can I get currents logged in user information. I am actually trying to get user email
$logged_in_user = wp_get_current_user();
wp_get_current_user(); is return below object with empty values
WP_User object {
back_compat_keys => array(6) (
[user_firstname] => (string) first_name
[user_lastname] => (string) last_name
[user_description] => (string) description
[user_level] => (string) wp_user_level
[wp_usersettings] => (string) wp_user-settings
[wp_usersettingstime] => (string) wp_user-settings-time
)
data => stdClass object
ID => (int) 0
caps => array(0)
cap_key => null
roles => array(0)
allcaps => array(0)
filter => null
};
//email is
if($logged_in_user->ID != 0){
$email = $logged_in_user->user_email;
}
First, comment out this line:
wp_get_current_user(); is return below object with empty values
Then, to get user details do this:
$userID = $logged_in_user->ID;
$userEmail = $logged_in_user->user_email;
//and so on from there.
You can find more examples in this tutorial here.

Alfresco Community Rest api, add user to group

I am using Alfresco rest api to create users as administrator. When i post data from my form it creates the user but does not assign this user to the group.
public function adduser($user, $pass, $userName, $password, $firstName, $lastName, $email, $group){
$data = array(
"urlPath" => "/people"
);
$params = array(
"userName" => $userName,
"password" => $password,
"firstName" => $firstName,
"lastName" => $lastName,
"email" => $email,
"group" => $group
);
return $this->callAPI($user, $pass, 'POST', $data, $params);
}
Can you help me, what i am missing here?
The problem is that the groups property should be an array, not a simple string. For example, the following JSON can be POSTed successfully to /alfresco/s/api/people:
{
'userName': 'test6',
'password': 'test6',
'firstName': 'test6',
'lastName': 'test6',
'email': 'test6#email.vom',
'groups': ['GROUP_ALFRESCO_ADMINISTRATORS']
}

Create a symfony2 remember me cookie manually (FOSUserBundle)

Could somebody explain how you can manually create a remember me cookie in a controller?
I want the users to stay logged in after they pressed the "register"
button, without having to login with their credentials afterwards.
I've tried to create a cookie manually but i'm guessing the cookie
value is incorrect, and therefor the "remember me" functionality
doesn't work.
A cookie with the correct name gets set. I've checked that.
The remember me functionality works as expected when using the normal
login procedure with the user's credentials.
security.yml
security.yml remember me
security:
firewalls:
main:
remember_me:
lifetime: 86400
domain: ~
path: /
key: myKey
This is what I have now, even though the cookie is set, it doesn't work.
$um = $this->get('fos_user.user_manager');
$member = $um->createUser();
… Form stuff with bindRequest etc.
$um->updatePassword($member);
$um->updateUser($member);
$providerKey = $this->container->getParameter('fos_user.firewall_name');
$securityKey = 'myKey';
$token = new RememberMeToken($member, $providerKey, $securityKey,
$member->getRoles());
$this->container->get('security.context')->setToken($token);
$redirectResponse = new RedirectResponse($url);
$redirectResponse->headers->setCookie(
new \Symfony\Component\HttpFoundation\Cookie(
'REMEMBERME',
base64_encode(implode(':', array($member->getUsername(),
$member->getPassword()))),
time() + 60*60*24
)
);
return $redirectResponse;
Update:
I've also tried working with the
PersistentTokenBasedRememberMeServices class with reflection but it does not work. a cookie gets set but it's not working
$token = $this->container->get('security.context')->getToken();
$providerKey = $this->container->getParameter('fos_user.firewall_name');
$securityKey = 'myKey';
$persistenService = new
PersistentTokenBasedRememberMeServices(array($um), $providerKey,
$securityKey, array('path' => '/', 'name' => 'REMEMBERME', 'domain' =>
null, 'secure' => false, 'httponly' => true,
'lifetime' => 86400));
$persistenService->setTokenProvider(new InMemoryTokenProvider());
$method = new \ReflectionMethod('Symfony\Component\Security\Http\RememberMe\PersistentTokenBasedRememberMeServices',
'onLoginSuccess');
$method->setAccessible(true);
$method->invoke($persistenService, $request, $redirectResponse, $token);
I'm using Symfony v2.0.5 and FOSUserBundle 1.0
UPDATE 2:
I've tried a 3rd way. The same as above but without reflection:
$token = $this->container->get('security.context')->getToken();
$providerKey = $this->container->getParameter('fos_user.firewall_name');
$securityKey = 'myKey';
$persistenService = new PersistentTokenBasedRememberMeServices(array($um), $providerKey, $securityKey, array('path' => '/', 'name' => 'REMEMBERME', 'domain' => null, 'secure' => false, 'httponly' => true, 'lifetime' => 31536000, 'always_remember_me' => true, 'remember_me_parameter' => '_remember_me'));
$persistenService->setTokenProvider(new InMemoryTokenProvider());
$persistenService->loginSuccess($request, $redirectResponse, $token);
Here is how I did it. I'm not using the FOSUserBundle and I'm using Doctrine Entity User Provider, but it should be trivial to adjust to your needs. Here is a general solution:
// after registration and persisting the user object to DB, I'm logging the user in automatically
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
// but you can also get the token directly, if you're user is already logged in
$token = $this->container->get('security.context')->getToken();
// write cookie for persistent session storing
$providerKey = 'main'; // defined in security.yml
$securityKey = 'MySecret'; // defined in security.yml
$userProvider = new EntityUserProvider($this->getDoctrine()->getEntityManager(), 'MyCompany\MyBundle\Entity\User', 'username');
$rememberMeService = new TokenBasedRememberMeServices(array($userProvider), $securityKey, $providerKey, array(
'path' => '/',
'name' => 'MyRememberMeCookie',
'domain' => null,
'secure' => false,
'httponly' => true,
'lifetime' => 1209600, // 14 days
'always_remember_me' => true,
'remember_me_parameter' => '_remember_me')
);
$response = new Response();
$rememberMeService->loginSuccess($request, $response, $token);
// further modify the response
// ........
return $response;
Just remember you have to set always_remember_me option to true (like I did in the code above) or have it in your $_POST parameters somehow, otherwise method isRememberMeRequested of AbstractRememberMeServices will return false and the cookie won't be stored.
You were pretty close to the correct solution though :) What you did wrong (in the 3rd attempt) is that you've changed the order of parameters here:
$persistenService = new PersistentTokenBasedRememberMeServices(array($um), $providerKey, $securityKey, array('path' => '/', 'name' => 'REMEMBERME', 'domain' => null, 'secure' => false, 'httponly' => true, 'lifetime' => 31536000, 'always_remember_me' => true, 'remember_me_parameter' => '_remember_me'));
Take a look at __construct() in AbstractRememberMeServices.php. You should pass a $securityKey as 2nd argument and $providerKey as 3rd argument, not the other way around like you did by mistake ;)
What I don't know yet, is how to get parameters from security.yml directly in the controller not to duplicate it. By using $this->container->getParameter() I can get parameters stored under parameters key in config.yml, but not the ones places higher in the configuration tree. Any thoughts on this?
If you are setting the rememberme cookie directly, you have to use the following format:
base64_encode(<classname>:base64_encode(<username>):<expiry-timestamp>:<hash>)
where the hash will be:
sha256(<classname> . <username> . <expiry-timestamp> . <password> . <key>)
the key is the key you have entered in your security(.xml/.yml) in the remember_me section.
This is taken from processAutoLoginCookie() method in the Symfony/Component/Security/Http/RememberMe/TokenBasedRememberMeService.php file.
This is all done by the generateCookieValue() method in the same class.
However, I would not recommend on using doing it this way directly, but try to see if you can call the TokenBasedRememberMeService::onLoginSuccess() method, which sets this cookie for you to make the code more robust and portable.
For me the easiest solution was extend a BaseTokenBasedRememberMeServices and let it handle
namespace AppBundke\Security\Http;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\Security\Http\RememberMe\TokenBasedRememberMeServices as BaseTokenBasedRememberMeServices;
class TokenBasedRememberMeServices extends BaseTokenBasedRememberMeServices
{
protected $options_new = array('name' => 'REMEMBERME', 'domain' => null, 'path' => '/');
public function __construct($userProvider, $secret, $providerKey, array $options = array(), LoggerInterface $logger = null)
{
return parent::__construct(array($userProvider), $secret, $providerKey, array_merge($this->options_new, $options));
}
public function generateCookie($user, $username, $expires, $password)
{
$cookie = new Cookie(
$this->options['name'],
parent::generateCookieValue(get_class($user), $username, $expires, $password),
$expires,
$this->options['path'],
$this->options['domain'],
$this->options['secure'],
$this->options['httponly']
);
return $cookie;
}
}
and in controller;
$user = $this->getUser();
$providerKey = $this->getParameter('fos_user.firewall_name');
$secret = $this->getParameter('secret');
$cookie_life_time = $this->getParameter('cookie_life_time');
$remember_me_service = new TokenBasedRememberMeServices($user, $secret, $providerKey );
$remember_me_cookie = $remember_me_service->generateCookie($user, $user->getUsername(),(time() + $cookie_life_time), $user->getPassword());
then response set cookie to $remember_me_cookie
I hope its works with you 2.
I had the same issue when I tried to set REMEMBERME cookie an User after a connection by token, using Guard Authentication.
In this situation I had no Response object to be able to use $response->headers->setCookie() and needs to use setcookie().
And in this situation, create a RedirectResponse is not appropriate.
This needs to be refactored but I post the raw procedural on which I based my service
$expires = time() + 2628000;
$hash = hash_hmac(
'sha256',
get_class($user).$user->getUsername().$expires.$user->getPassword(), 'secret in parameters.yml'
);
$value = base64_encode(implode(':', [get_class($user), base64_encode($user->getUsername()), $expires, $hash]));
setcookie(
'REMEMBERME',
$value,
$expires,
'/',
'host',
'ssl boolean',
true
);

Resources