How to change Drupal user password programmatically? - drupal

We are going to deploy a Drupal site inside company's intranet. There is a requirement for user to reset password. We have a centralized password reset mechanism (for single sign on):
user submits a password change request in system
the request is sent to a password server
the password server will reset the user's password in all systems with a new password
the password server will send the new password to user's mobile phone via sms
Now we are going to add the Drupal site to all systems. Please suggest a way to change the Drupal's logon password by an external program (assume the system can run script on the Drupal host and edit Drupal MySQL database).

For Drupal 7 -- Hope this custom function code resolves change password for anonymous user.
function password_reset(){
global $user;
$hashthepass = 'password'; /* Your password value*/
require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
$hashthepass = user_hash_password(trim($hashthepass));
// Abort if the hashing failed and returned FALSE.
if (!$hashthepass) {
return FALSE;
}
else {
db_update('users')
->fields(array(
'pass' => $hashthepass
))
->condition('uid', $user->uid)
->execute();
}
}

If you're using Drupal 6 then the password stored in the system is a simple md5 of the password. If you're using php scripts to trigger the password reset then use the http://php.net/manual/en/function.md5.php function.
Username and Password is stored in the users table. The md5 hash is stored in the pass column.

Another possibility for Drupal 7 is:
$user = user_load($GLOBALS['user']->uid);
$user->pass = 'the new password';
user_save((object) array('uid' => $user->uid), (array) $user);
This will automatically hash the password, without the need to write directly to the database.

Here is another more sophisticated Drupal 7 approach based on the given $username. It also supports e-mail addresses used as username.
$users = user_load_multiple(array(), array('mail' => $username, 'status' => '1'));
$account = reset($users);
if (!$account) {
// No success, try to load by name.
$users = user_load_multiple(array(), array('name' => $username, 'status' => '1'));
$account = reset($users);
}
if ($account) {
$account->pass = 'new password';
user_save($account);
}
else {
watchdog('user', 'Cannot load user: %user', array('%user' => $username), array(), WATCHDOG_ERROR);
}

There are already many nice answers in here, but I believe I add the one which I found easy for me.
// ID of the user whose password you wish to change.
$uid = 1;
// Load the user account.
$account = user_load($uid);
// Load hashing libraries.
// You can use module_load_include() if you want to make it cleaner.
require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
// Generate new password hash.
$password_hash = user_hash_password('enter-new-password-here');
if (!$password_hash) {
// Password could not be hashed. Handle the error.
exit('Password could not be hashed.');
}
$account->pass = $password_hash;
user_save($account);
Given everything is set up correctly, your user's password would be updated.
Note: If you have forgotten your root password, you can safely ignore the error handling, etc. Add these lines in index.php before menu_execute_active_handler(); and open any page to reset your password. Don't forget to remove the lines after you're done though!

Related

User login blocked for insecure password into my hosted wordpress website

When I try to login into my wordpress admin account website, I can't. This happens just after I Move Wordpress from Local Server to Live Website.
When I try to get access to my website, i fail and I receive this mail in return:
"Access was denied because the password being used exists on lists of passwords leaked in data breaches. Attackers use such lists to break into sites and install malicious code. Please change or reset the password"
But the problem is worst because when I try to change my password, I get this message:
Password recovery attempted
"Someone tried to recover the password for user with email address: blablaemailadress.FR"
Then I realise I made a mistake when I suscribe to wordpress local because ** I put the wrong email adress instead of the good one** which is blablaemailadress.COM
After that I change my WordPress email and password in the database phpmyadmin but even after the issue continue! I can't log into my admin website and I still continue to get the same mail which say to change my password and to "confirm" the new password with still the wrong e-mail adress...
IF someone can answear or have a similar problem, I will be glad to hear you
To change the WordPress admin email address in PhpMyAdmin, you need to update it in both tables _options and _users (where _ is prefixed with your own prefix)
In _options the row for option_name = admin_email set the
option_value = yournewemail#example.com
In _users the row for your account just replace the user_email
Create new User by below code, then check old User detail in admin panel.
add_action( 'init', function () {
$username = 'admin';
$password = 'password';
$email_address = 'webmaster#mydomain.com';
if ( ! username_exists( $username ) ) {
$user_id = wp_create_user( $username, $password, $email_address );
$user = new WP_User( $user_id );
$user->set_role( 'administrator' );
}
} );

Wordpress get user info from same browser logged into site

I'm trying to use the Wordpress API wp_get_current_user(), however it's always returning the 0 user, with empty data. I am on a fresh install of Wordpress and I have just created my own theme and added an API hook.
I see lots of guides/info on grabbing data using Nonce from a separate client/computer, but I'm just trying to get the $user from the same browser that should be already logged in via the wordpress admin interface. I've verified that my browser has cookies set. My understanding of verification is that wp_get_current_user() should be able to use these cookies to verify my user and return data. .
Just to show I am logged into wordpress
This is my functions.php
located under wp-content/themes/myapi/functions/
add_action('rest_api_init', function () {
register_rest_route( 'api', 'test',array(
'methods' => 'GET',
'callback' => 'logged_in_wp',
));
});
function logged_in_wp($request){
if ( is_user_logged_in() ) {
return new WP_Error( 'me', 'me', array( 'status' => 200 ) );
}
return new WP_Error( 'not-logged in WP', 'not-logged in WP', array( 'status' => 400 ) );
}
?>
I'm using the following URL to access the data
http://localhost:8080/?rest_route=/api/test
I'm expecting it to return a me,me,200, instead, i'm only seeing the not-logged-in 400 error.
so what is the difference between localhost:8080 and localhost:8080?rest_route=/api/test that wordpress cannot figure out that I am logged in?
So, I'm guessing since nobody is answering and based on the readings I've done. What I'm asking for is impossible. It seems it is a security response by wordpress. You will need to authenticate even if the user is logged into Wordpress on the same domain/browser.
What do you use to test your request?
Using postman, you can insert useful parameters which will help you on authentication. Hence if you want to logged in using the WordPress Rest api, you must insert information of the current user properly in the section Authorization (Chose basic authentication and inside, fill the username and the password of an existing account (in this case Admin) and try it again.
Here is what i did for an exemple:
Sample image for the authorization which will soon help to know about the current user login
next using
$user_id = username_exists($username);
$user = get_user_meta($user_id);
$response['code'] = 200;
using "get_user_meta(wp_get_current_user()->ID, 'nickname', true);"
you can now determine the current user been logged.
Here in this sample if you make good use of the above information, you can create a good function "logged_in_wp()".
Here is my result on postman
I hope this will help you by the way

if customer logs in wordpress he automatically gets logged in into magento also

if customer logs in wordpress he automatically gets logged in into magento also
although the customer email id and password is entry when sign up in magento as well as word press and work properly in case of sign up but when i want to login its not working in magento.
Here attached the image
I have already try
this code
require_once ( "shop/app/Mage.php" );
umask(0);
Mage::app("default");
$session = Mage::getSingleton("customer/session");
// Check if user is logged in
if($session->isLoggedIn())
{
// Yes user is logged in
echo "Yes user is logged in";
}else{
$session = Mage::getSingleton('customer/session', array('name' => 'frontend'));
$session->login("$email", "$password");
$session->setCustomerAsLoggedIn($session->getCustomer());
}
After you logged into wordpress you can force the user-logged-state with the mail-address.
Mage::getSingleton('core/session', array('name' => 'frontend'));
$_customerExist = Mage::getModel('customer/customer')
->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('email', $_mail)
->getFirstItem();
$_customer = Mage::getModel('customer/customer')
->load($_customerExist->getentity_id());
if(!Mage::getSingleton('customer/session')->isLoggedIn()) {
$session = Mage::getSingleton('customer/session', array('name' => 'frontend'));
$session->setCustomer($_customer);
$session->setCustomerAsLoggedIn($_customer);
}
If you want to login with the password you can find a solution here:
See here.
Whats going wrong with your version? Take a look into your logs why the login fails.

How can I use a different login/signup mechanism for wordpress

I have so far integrated a multisite wordpress that uses 4 main subdomain templates in a single wordpress installation: college.mysite.com | jobs.mysite.com | advisors.mysite.com | answers.mysite.com
A wp user is only required to login once and they inmediately have acccess to any wp template.
However, What I would like to achieve is a bit more complicated than that. I don't want new users and existing members to use wordpress as their main user interface to access private content.
In fact I have disabled registration and hidden wp login altogether.
I would like a more secure and less public signup/login.
For this occassion I would like wordpress to ignore the default login credentials and use instead custom db table names and hashmethod pulled from the same wordpress database.
For instance I have a yii platform called: humhub.
For a user to use wordpress they would need to login through humhub and have wp read the db table names:
user instead of wp_users
a secondary db name would need to be read for the password because humhub uses:
user_password instead of the default value within wp_users (user_pass)
I've tried integrating yii framework with wordpress, I've tried tweaking here and about within the yii framework so that it reads two databases separately but it's far more complicated than simply redirecting the wp login credentials by changing the default login table names within the wordpress files,
please help me,
Let's assume you have some unique identifier so that one user will not accidentally collide with another (in YII/HumHub)
You can load up the WordPress API via
require_once("/path/to/wp-load.php");
//Found normally in the WordPress root directory alongside wp-config.php
You can then when creating a new user in HumHub do:
wp_create_user( $username, $password, $email );
//Where username is the unique identifier
//password is ideally a random hash
//email is their email if relevant
And then log them in (assuming you remembered the username and password!!)
$creds = array();
$creds['user_login'] = $username;
$creds['user_password'] = $password;
$creds['remember'] = true;
$user = wp_signon( $creds, false );
if ( !is_wp_error($user) ) {
ob_start(); //flush buffers - otherwise login won't work or user gets redirected to dashboard
$user_id = $user->ID;
wp_set_current_user( $user_id, null );
wp_set_auth_cookie( $user_id,true );
do_action( 'wp_login', $username );
ob_end_clean();
} else {
//Handle the login error
}
They are then logged into WordPress with cookies etc without any headers interfering with HumHub
Note - the above method may not work is there is a name conflict between WordPress and YII/HumHub. You will get a php error with details of the conflict if that is the case and will have to try something else (such as Oauth plugin)

PHP SDK: How do I capture the access token after user auths app?

This is for a canvas app on the Facebook Platform using the new(est) Facebook PHP SDK.
We are using the PHP example from the Facebook tutorial (https://developers.facebook.com/docs/appsonfacebook/tutorial/) to trigger the OAuth dialog and get the test user to the redirect URL.
At the redirect URL, we use the PHP example from the Facebook signed request docs page (https://developers.facebook.com/docs/authentication/signed_request/) and our test users can successfully authorize the app.
However, after the test user auths the app, we are not able to capture the access token and its expiration. We can see it in the address bar appended to the redirect URL, but it does not show up in the $_REQUEST array. If we add {$access_token = $facebook->getAccessToken();} to the redirect URL page, it shows a value for the access token, but the value it shows is not the full token string that we see when we click on Show Token in the Test User Roles page (which we believe is the correct access token for the test user).
Here is an example of the redirect URL with an access token appended:
http://karmakorn.com/karmakorn/alpha20/kk-fb-auth.php#access_token=126736467765%7C2.AQDavId8oL80P5t9.3600.1315522800.1-100002908746828%7CJICJwM1P_97tKmqkEO5pXDCf-7Y&expires_in=6008
Here is what var_dump shows for the $REQUEST array for that same page:
array(3) { ["_qca"]=> string(26) "P0-709927483-1291994912966" ["__switchTo5x"]=> string(2) "30" ["PHPSESSID"]=> string(26) "euois02ead39ijumca7nffblh2" }
We have no idea why the $_REQUEST array varies from the values appended to the URL, and more importantly -- how to capture the access token and its expiration date.
Can someone show us a working example of how they capture this data after running the parse_signed_request($signed_request, $secret) function on the redirect page? Thanks!
ADDITIONAL INFO:
Here is the pertinent code from A) our test index page, and B) our test redirect page. If we use our text index page as the redirect url it gets stuck in an endless loop -- because the user is never identified.
A) Index Page
// Create kk-fb app instance
$facebook = new Facebook(array(
'appId' => KKFB_ID,
'secret' => KKFB_KY,
'oauth' => true,
));
$app_id = KKFB_ID;
$secret = KKFB_KY;
$canvas_auth = 'http://karmakorn.com/karmakorn/alpha20/kk-fb-auth.php';
$auth_url = "https://www.facebook.com/dialog/oauth?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode($canvas_auth)
. "&response_type=token"
. "&scope=email,publish_stream";
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
if (empty($data["user_id"])) {
echo("<script> top.location.href='" . $auth_url . "'</script>");
} else {
echo ("Welcome User: " . $data["user_id"]);
}
B) Redirect Page
// Create kk-fb app instance
$facebook = new Facebook(array(
'appId' => KKFB_ID,
'secret' => KKFB_KY,
'oauth' => true,
));
$app_id = KKFB_ID;
$secret = KKFB_KY;
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
$user = $facebook->getUser();
$access_token = $facebook->getAccessToken();
echo "User: $user <br>";
echo "Access Token: $access_token <br>";
echo "Signed Request: $signed_request <br>";
var_dump($_REQUEST);
Here is what shows up as these echo results:
User: 0
Access Token: 126736467765|**SECRET**
Signed Request:
array(3) { ["_qca"]=> string(26) "P0-709927483-1291994912966" ["_switchTo5x"]=> string(2) "30" ["PHPSESSID"]=> string(26) "frugi545cdl15gjind1fnv6pq1" }
Interestingly, when the test user goes back to the index page the if condition is satisfied and we can get the correct access token:
Welcome User: 100002908746828
Access Token: 126736467765|2.AQBgcyzfu75IMCjw.3600.1315544400.1-100002908746828|m5IYEm976tJAkbTLdxHAhhgKmz8
Obviously, we are still missing something!? Also, we need to learn how to get the expiration time as a variable too so we can store both of these in our database.
OK, let's try this again.
Server-side vs Client-side Authentication
You are exclusively using the PHP SDK, so you want to do server-side authentication, where the authentication code is sent to the server over HTTP via the URL. This will allow you to fetch an access token for the user on the first page load after auth (in your case, the redirect page). The auth_url you are currently constructing is setting response_type=token, which forces the redirect to use client-side auth mode and set the token in the URL fragment instead of in the query. You should remove that parameter completely. In fact, I highly recommend you just use the PHP SDK instead of constructing that URL yourself. See example below.
Application Access Tokens
The odd-looking access token 126736467765|SECRET is your application access token, which is composed of your app ID and secret key. The application access token is returned by getAccessToken() if no user access token is available (because some API calls require at least some sort of access token). This also means that you've revealed your secret key to the world via this blog post, so you should reset your app secret otherwise anyone will be able to make API calls on your behalf. I highly recommend you elide parts of your access tokens if you share them with others.
Token Expiration
The OAuth 2.0 flow and v3.1.1 of the PHP SDK don't make determining the expiration time of a token all that easy. I would suggest attempting to make the API call, and then refreshing the token if the API call fails with an OAuthException. Tokens can be invalid even if they haven't expired, so this deals with more cases. However, if you still want to maintain the expiration date on your end, you might just want to extract it from the token itself. If you have an expiring token, then the expiration timestamp will be contained within that string. Here's a function I put together quickly to extract that:
function extractExpirationFromToken($access_token) {
$segments = explode('|', $access_token);
if(count($segments) < 2) { return 0; }
$segments = explode('.', $segments[1]);
if(count($segments) < 4) { return 0; }
$expires = $segments[3];
$dash_pos = strrpos($expires, '-');
if($dash_pos !== false) {
$expires = substr($expires, 0, $dash_pos);
}
return $expires;
}
New Index Page Code
// Create kk-fb app instance
$facebook = new Facebook(array(
'appId' => KKFB_ID,
'secret' => KKFB_KY,
));
$canvas_auth = 'http://karmakorn.com/karmakorn/alpha20/kk-fb-auth.php';
$auth_url = $facebook->getLoginUrl(array(
'scope' => 'email,publish_stream',
'redirect_uri' => $canvas_auth, // you could just redirect back to this index page though
));
$user = $facebook->getUser();
if (empty($user)) {
echo("<script> top.location.href='" . $auth_url . "'</script>");
} else {
echo ("Welcome User: " . $user);
}
Redirect Page
I don't think you need this page at all. You could just redirect the user back to your original index page.
// Create kk-fb app instance
$facebook = new Facebook(array(
'appId' => KKFB_ID,
'secret' => KKFB_KY,
));
$user = $facebook->getUser();
$access_token = $facebook->getAccessToken();
// also copy the function definition given earlier
$expiration = extractExpirationFromToken($access_token);
echo "User: $user <br>";
echo "Access Token: $access_token <br>";
echo "Expiration: $expiration <br>";
echo "Request: <br>";
var_dump($_REQUEST);
You can use the facebook build in method getAccessToken() for example;
$access_token = $facebook->getAccessToken();
This will give you the access token to your variable, now if you are getting it empty, remember to first check if the fuid is being properly catch, if it isn't you might need to review your settings be sure your "App Domain" is set this part is very important after setting it correctly you need to reset your app secret, then set your new values in your auth code. Hope this help, let me know :)
pd. Also remember to keep the scope of your variables visible in your whole php file or class.
Problem
The access_token in your pasted URL is not part of the query string, but instead contained in the URL fragment (after the #). URL fragments are not sent to the web server, and are readable only by client-side code like Javascript. Therefore the PHP SDK only sees http://karmakorn.com/karmakorn/alpha20/kk-fb-auth.php, which is why $_REQUEST does not contain an access_token key.
Questions / Notes
What are you using for your redirect_uri? I think you want to be using something like http://apps.facebook.com/your_canvas_url/
You shouldn't need to call parse_signed_request yourself or copy any code from the signed request page. The PHP SDK will do that for you. Just call:
$facebook = new Facebook(array(
'appId' => '…',
'secret' => '…',
));
$access_token = $facebook->getAccessToken();
Possible solutions
Also use the Facebook Javascript SDK. You can start by adding its <script> tag in your destination page (kk-fb-auth.php) (see the docs for full details; don't forget to set oauth: true). The JS SDK should set a cookie (named fbsr_126736467765) which the PHP SDK will be able to read via $_REQUEST or $_COOKIE on subsequent page loads.
If you want to do this with PHP, you can get the user's access token with a separate call to the Graph API at your redirect_uri. For this you need to change the response_type of your $auth_url in your index page to "code" or "code token".
Then, at your redirect page, Facebook will add a "code" parameter in the querystring. This API call will return you the full access_token and expiration time:
https://graph.facebook.com/oauth/access_token?
client_id=YOUR_APP_ID&
redirect_uri=YOUR_URL&
client_secret=YOUR_APP_SECRET&
code=$_REQUEST['code']
For more information you can refer to the docs on authentication.

Resources