I made a plugin that requires the user to validate their email address. It creates "activation_key" meta key with random string for the user and sets it to '' once the user validates. So far so good. But now I need to hook into login and check that activation_key == ''.
This is what I thought should be, but it doesn't get to here.
add_filter( 'authenticate', 'check_if_activated', 10, 3 );
function check_if_activated($user, $username, $password)
{
// check if user has activated their email
return $user;
}
Wordpress already adds filters to authenticate, so you have to register your lower.
add_filter( 'authenticate', 'check_if_activated', 50);
function check_if_activated($user)
{
// If we have an error, no need to check the activation key
// (Wrong credentials, for instance)
if (is_wp_error($user))
{
return $user;
}
// Checks the meta and returns an error if needed
$validation_key = get_user_meta($user->ID, 'activation_key', true);
return empty($validation_key) ? $user : new WP_Error('your_plugin_error_code', 'your error message');
}
Related
I'm trying to implement a custom login authentication and am using the authenticate filter.
However, my code doesn't seem to be firing and after many tests I still can't figure out why.
I've tried stripping my code down to the essentials, but it still doesn't fire and I'm logged in every time instead of being rufused.
This is my stripped down code and it is inside my own plugin that is definitely being activated OK, as shown by a display messages I've put elsewhere in the code and it's definitely in the wp_filters array.
Can anyone see why it isn't being fired?
<?php
/**
* Login functions
*/
add_filter('authenticate', 'ii_login_test', 30, 3);
/*
* Custom Login
*/
function ii_login_test($user, $username, $password) {
//return get_userdata(username_exists($username));
return new WP_Error( 'authentication_failed', __( 'ERROR: No user record found.' ));
}
You can try assigning $user to WP_error() and then return the user.
try out this code :-
<?php
/**
* Login functions
*/
add_filter('authenticate', 'ii_login_test', 30, 3);
/*
* Custom Login
*/
function ii_login_test($user, $username, $password)
{
//return get_userdata(username_exists($username));
$user = new WP_Error('authentication_failed', __('ERROR: No user record found.'));
return $user;
}
In the BuddyPress, I want to allow register and log in using only one email domain. For instance, xxx#myemaildomain.com restore all will be disallowed.
I have checked in the BuddyPress source and found that BuddyPress is using bp_core_validate_user_signup( $user_name, $user_email ) for sign up that has a filter
return apply_filters( 'bp_core_validate_user_signup', $result );
So I have tried to use the filter to modify the user_email filed as in the code below. But it is not working.
function wf_validate_email_domain($result)
{
$email = $result[ 'user_email' ];
// make sure we've got a valid email
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// split on # and return last value of array (the domain)
$domain = array_pop(explode('#', $email));
if ($domain != 'mydomain.com') {
$result[ 'user_email' ] = '';
}
}
return $result;
}
add_filter('bp_core_validate_user_signup', 'wf_validate_email_domain', 9999);
Question:
How can I validate email so it allows to register and login only from
one specific email domain?
The $result should contain an errors field, according to the documentation:
https://www.buddyboss.com/resources/reference/functions/bp_core_validate_user_signup/
Therefore, you should add an error instead of setting the mail address to an empty string like so:
function wf_validate_email_domain($result)
{
$allowed_domain = 'apolloblake.com';
$email = $result[ 'user_email' ];
// make sure we've got a valid email
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// split on # and return last value of array (the domain)
$domain = array_pop(explode('#', $email));
if ($domain != $allowed_domain) {
$result[ 'errors' ]->add( 'user_email',
"You may only register with mail addresses on #${allowed_domain}." );
}
}
return $result;
}
You may have to make this message multilingual, but that depends on your WP setup.
[update1] I am using the ClassiCraft theme and I have no idea where to customize the login and register forms
[update2] I know that the registration process does not go through wp_authenticate because I redefined it inside a plugin of mine
I am quite new in the Wordpress world (actually just got my hands on it for the first time yesterday) and I am having some difficulties finishing up a little project I am working on.
The project is rather simple (or so I thought) and consists in adding a confirmation link to email received upon registration in order to validate the email address provided to prevent using fake emails that the registrar does not even own.
I am about all done except that once I hit the register button it leads to log in the freshly created user.
I googled stuff like "wp disable auto login on registration" and whatnot but I have not been able to find anything that worked. I even tested a few plugins supposed to be doing exactly what I need but none of them worked.
Also, I am not using any plugins for the registration/login forms and it appears that the code in the wp-login.php file is actually not even used...
Would anyone have an idea? Thanks
Okay, so without an access to the theme, i can't really answer you.
But i can tell you what I would try.
1. Add action on user_register hook, to add a post meta that will be useful to check if user has confirm his email.
add_action( 'user_register', 'add_has_confirm_email_user_meta');
function add_has_confirm_email_user_meta( $user_id ) {
update_user_meta( $user_id, 'has_confirm_email', 0 );
}
2. Prevent the user from log in automatically after registration.
Here i can't tell you the hook that will works for you. For example, the hook for the wordpress registration is user_register, but if you have woocommerce, the hook I will use, would be woocommerce_registration_redirect. So try to find what hook is available after the registration with your theme.
In all case, the code in the function would be something like :
function custom_registration_redirect() {
// Log out the user
wp_logout();
// The login url could be an other, with woocommerce for example it is : get_permalink(get_option('woocommerce_myaccount_page_id')
$login_url = wp_login_url();
// Redirect on it
wp_redirect( $login_url);
exit;
}
It will also be necessary, to add a message on this page to alert the user, that he will receive an email to confirm his account.
3. Prevent user from login when he submit the log in form
Add action on wp_login hook to achieve that.
add_action('wp_login', 'prevent_user_from_login', 10, 2);
function prevent_user_from_login($user_login, $user = null ) {
if ( !$user ) {
$user = get_user_by('login', $user_login);
}
if ( !$user ) {
// not logged in
return;
}
// Get user meta
$has_confirm_email = get_user_meta( $user->ID, 'has_confirm_email', true );
if ( $has_confirm_email == '0' ) {
// Clear cookies, a.k.a log user out
wp_clear_auth_cookie();
$login_url = wp_login_url();
$login_url = add_query_arg( 'has_confirm_email', '0', $login_url);
wp_redirect( $login_url );
exit;
}
}
4. Add message on log in page if we get the has_confirm_email to 0
add_filter('login_message', 'has_not_confirm_email_login_message');
function has_not_confirm_email_login_message($message) {
if ( isset( $_GET['has_confirm_email'] ) && $_GET['has_confirm_email'] == 0 ) {
$message = '<div id="login_error">You have not confirmed your email.</div>';
}
return $message;
}
5. Send the email with a link to confirm his email.
You will need to generate a token to add to the url.
For the hook to change the default email sent by Wordpress, you can use wp_new_user_notification_email that is available since the 4.9 of Wordpress.
In the function itself you could do something like :
function wp_new_user_notification_email( $wp_new_user_notification_email, $user, $blogname) {
// Generate the token (there is other function available with php 7, but this one works great)
$token = bin2hex(openssl_random_pseudo_bytes(16));
// Add the token to the user
update_user_meta( $user->id, 'confirm_email_token', $token );
// Get your login url
$log_in_url = wp_login_url();
// Add user id and token to the url
$url = add_query_arg(
array(
'token' => $token,
'user_id' => $user->id
),
$log_in_url
);
//
$wp_new_user_notification_email['subject'] = 'Welcome on our website, please confirm your email';
$wp_new_user_notification_email['message'] = 'Blablabla... the url to confirm is: '. $url;
return $wp_new_user_notification_email;
}
6. Hook on the login page to check the $_GET, looking for user_id and token.
Here we check the token and the user. If everything is okay, update the user meta has_confirm_email to 1, so the user can connect, and add a message : "Your email has been confirmed, you can now log in"
add_action( 'login_init', 'custom_login_init');
function custom_login_init(){
if(!empty($_GET['token']) && !empty($_GET['user_id'])) {
if(get_the_author_meta( 'confirm_email_token', $_GET['user_id']) === $_GET['token']) {
// Set the has_confirm_email to 1 so the user can now log in
update_user_meta( $user_id, 'has_confirm_email', 1);
update_user_meta( $user_id, 'confirm_email_token', '');
echo 'Your email has been confirmed, you can now log in';
}
}
}
7. Time for thinking
Okay, after all of his, i'm gonna think a little, and read what i have tell you, to check if there is no mistake ^^. Tell me if you need more explanations.
I think this is a good start for you, and if you find the right hooks, you will achieve this rapidly.
Be careful on some hooks that i have used, because your theme may have use a custom registration or something.
Here is what I did:
added a column in the table wp_users to receive the email confirmation code
built a plugin (details here) called user-emails that allows me to bypass the first email sent upon registration by redefining the function wp_new_user_notification (in which I generate the confirmation code, add it to the user in the DB and send a confirmation email of my own sauce)
redefined the wp_authenticate function inside the same plugin user-emails to allow me to check if the email has been confirmed (column value not null)
created a page for the confirmation with the email and code passed to it that, in case of success, display a message and a link to the home page in order to login
finally got my hands on that one tiny line of code responsible for the auto login after registration located in the page user_auth.php inside the theme folder itself (that file also contains the layout for the login and registration form)
wp_set_auth_cookie( $user_id, true, $secure_cookie );
made sure to display a message after registration informing the user to check his email for the confirmation email
So I'm looking for a way to prevent a specific email from registering an account on my website. It's a wordpress.org site.
I tried the Ban Hammer plugin, but it won't work.
I'm not looking for Comments, but for the site proper. Like a code I can put in functions.php or someplace and when this specific email is used to try and register an account on my site, to get an error.
Not an entire email domain, for example, #gmail.com. But a specific email, for example, stack#gmail.com.
Anyone knows how to do that?
EDIT: I found this tutorial here: http://www.davidtiong.com/block-spam-registrations-on-wordpress/
I tried adding this in Functions.php file right above the last ?> at the very bottom of the file:
function dtwd_blocked_emails($user_email) {
$dtwd_blocked_list = array("slojehupri#thrma.com", );
$user_email_split = explode('#', $user_email); $user_email_domain = $user_email_split[1];
if (in_array($user_email_domain, $dtwd_blocked_list)) {
//Return 1, for detection
return 1;
} else {
//Return 0 for no detection
return 0;
}
}
And I also added this in register.php of my theme:
elseif ( dtwd_blocked_emails( $user_email ) == 1) {
$errors->add( 'blocked_email', __( '<strong>ERROR</strong>: This email is not allowed.' ) );
}
And I added the same code in login.php of my theme.
And then I tried registering an account with this email (which should be blocked now): slojehupri#thrma.com
The site allowed me to register, and it allowed me to login. The email should've been blocked now and return an error when I try to register and/or login with it.
I'm not really sure how that function is supposed to work (it's not even hooked into anything...). I haven't tested this, but it sounds as simple as validating the email when the registration_errors filter hook is run. From the Codex:
The registration_errors filter hook filters the errors encountered when a new user is being registered. If any errors are present in $errors, this will abort the user's registration.
This sounds exactly like what you want to do (abort registration if the user email is in your blacklist). Again, this hasn't been tested, but I'd try something like the following in functions.php:
function so_32767928_blacklisted_user( $errors, $sanitized_user_login, $user_email ) {
// One or more blacklisted emails to validate against
$blacklist = array( 'slojehupri#thrma.com', );
// If the user trying to register is in the blacklist, add an error message
if ( in_array( $user_email, $blacklist ) ) {
$errors->add( 'blacklist_error', '<strong>ERROR</strong>: This email is not allowed to register on this site.' );
}
// Always return $errors, even if there are none
return $errors;
}
add_filter( 'registration_errors', 'so_32767928_blacklisted_user', 10, 3 );
Iam working with buddypress,
I have a two user roles,
1-student
2-faculty
and i have set default user role as subscriber.
when user registers and activates account by clicking on link sent through mail.User role changes to default(subscriber).
Any idea what is the issue? Below is the code assigning role to user on sign up.
add_action('bp_core_signup_user', 'ad_user_signup_usermeta', 10, 5);
function ad_user_signup_usermeta($user_id, $user_login, $user_password, $user_email, $usermeta) {
if(isset($_POST['signup_membership']) && !empty($_POST['signup_membership']))
update_user_meta($user_id, 'membership', $_POST['signup_membership']);
$userdata = array();
$userdata['ID'] = $user_id;
if(!empty($_POST['signup_usertype'])) {
if($_POST['signup_usertype'] == 'student') {
$userdata['role'] = 'student';
}
if($_POST['signup_usertype'] == 'instructor') {
$userdata['role'] = 'instructor';
}
}
if ($userdata['role']){
wp_update_user($userdata);
}
}
Upon activation, BuddyPress (at least version 2.0.2) updates the user's role to the default role.
https://buddypress.trac.wordpress.org/browser/tags/2.0.2/bp-members/bp-members-functions.php#L1560
You can comment out that line, or write some code to work around it. I'm using "WP Roles At Registration" and ran across the same problem. I ended up adding a filter on bp_core_signup_user to save the original role but you'll want to add something like this to your ad_user_signup_usermeta:
update_user_meta($user_id, 'temp_role', $role_name)
then reset it back in a filter for bp_core_activated_user
public function after_bp_activated_user($user_id, $key, $user) {
$user = get_userdata($user_id);
$role = get_user_meta($user_id, 'temp_role');
if ($role) {
$user->set_role($role[0]);
}
}
add_filter('bp_core_activated_user', array($this, 'after_bp_activated_user'), 30, 3);