¿Puedo iniciar sesión mediante programación con un usuario sin contraseña?
-
-
Creo quepuede asignarel objeto de usuario del usuario que acaba de crear a la variableglobal current_userI think you can just assign the user object of the user you just created to the current_user global variable
- 0
- 2012-05-28
- onetrickpony
-
6 respuestas
- votos
-
- 2012-05-28
wp_set_auth_cookie()
iniciará la sesión de un usuario sintener que saber su contraseña.wp_set_auth_cookie()
will log a user in without having to know their password.-
Estofuncionómuybien.Sinembargo,cuando lo uso,el condicional `is_user_logged_in ()`noparecefuncionar.¿Sabes siestámirando algo diferente a las cookies?This worked great. However, when I use it, the conditional `is_user_logged_in()` doesn't seem to work. Do you know if it's looking at something different than the cookies?
- 0
- 2012-05-28
- emersonthis
-
@Emerson: ¿en quégancho lesestás conectando?tiene que ser antes de que seenvíen losencabezados.tambiénintente [`wp_set_current_user`] (http://codex.wordpress.org/Function_Reference/wp_set_current_user) antes deiniciar sesión.@Emerson - what hook are you logging them in on? it has to be before headers are sent. also try to [`wp_set_current_user`](http://codex.wordpress.org/Function_Reference/wp_set_current_user) before logging them in.
- 2
- 2012-05-28
- Milo
-
En realidad,no loestaba llamando desde unganchoen absoluto.Acabo de agregar `wp_set_auth_cookie ()`en mifunción deinicio de sesión.Supongo quenecesito repensareso.Tambiénbuscaré wp_set_current_usere informaré.¡Muchasgraciasportu ayudaen esto!I actually wasn't calling it from a hook at all. I just added `wp_set_auth_cookie()` into my signin function. I guess I need to rethink that. I'll also lookup wp_set_current_user and report back. Thank you very much for your help on this!
- 0
- 2012-05-28
- emersonthis
-
Bueno,¿esposibleiniciar sesiónen un usuario sin que sus datosexistanen labase de datos?¿Basta con configurar algunas cookiesen elnavegador através de un script?Porfavor hagamelo saber.Well, is it possible to login a user without having his details exist in database? Just setting few cookies in browser through script is enough? Please let me know.
- 0
- 2014-02-06
- shasi kanth
-
- 2014-01-03
¡El siguiente código haceeltrabajoparaelinicio de sesión automático,sin contraseña!
// Automatic login // $username = "Admin"; $user = get_user_by('login', $username ); // Redirect URL // if ( !is_wp_error( $user ) ) { wp_clear_auth_cookie(); wp_set_current_user ( $user->ID ); wp_set_auth_cookie ( $user->ID ); $redirect_to = user_admin_url(); wp_safe_redirect( $redirect_to ); exit(); }
The following code does the job for automatic login, without any password!
// Automatic login // $username = "Admin"; $user = get_user_by('login', $username ); // Redirect URL // if ( !is_wp_error( $user ) ) { wp_clear_auth_cookie(); wp_set_current_user ( $user->ID ); wp_set_auth_cookie ( $user->ID ); $redirect_to = user_admin_url(); wp_safe_redirect( $redirect_to ); exit(); }
-
Bueno,funcionamuybien.Soloelnombre de usuarioes suficiente,queno distingueentremayúsculas yminúsculas.Well, it works great. Just the username is enough, which is case insensitive.
- 0
- 2014-02-06
- shasi kanth
-
`get_user_by ()` devuelvefalsoen caso defalla,por lo que debe verificar siesfalsoen lugar del objeto WP_Error`get_user_by()` returns false on failure, so you should check for false instead of the WP_Error object
- 1
- 2016-04-14
- somebodysomewhere
-
@Sjoerd Linders,¿dóndepuedo conectar su scriptpara obligar a un usuario a conectarse?@Sjoerd Linders, where can I hook your script in order to force a user to be connected?
- 0
- 2016-08-31
- RafaSashi
-
¿Dóndeguardoestebloque de códigoen qué archivo?Where do I keep this block of code in which file?
- 0
- 2019-05-28
- sgiri
-
- 2014-07-31
Encontré otra solución aquí que utiliza unenfoquemejor (almenosen mi opinión ...). Noesnecesario configurarninguna cookie,utiliza la API de Wordpress:
/** * Programmatically logs a user in * * @param string $username * @return bool True if the login was successful; false if it wasn't */ function programmatic_login( $username ) { if ( is_user_logged_in() ) { wp_logout(); } add_filter( 'authenticate', 'allow_programmatic_login', 10, 3 ); // hook in earlier than other callbacks to short-circuit them $user = wp_signon( array( 'user_login' => $username ) ); remove_filter( 'authenticate', 'allow_programmatic_login', 10, 3 ); if ( is_a( $user, 'WP_User' ) ) { wp_set_current_user( $user->ID, $user->user_login ); if ( is_user_logged_in() ) { return true; } } return false; } /** * An 'authenticate' filter callback that authenticates the user using only the username. * * To avoid potential security vulnerabilities, this should only be used in the context of a programmatic login, * and unhooked immediately after it fires. * * @param WP_User $user * @param string $username * @param string $password * @return bool|WP_User a WP_User object if the username matched an existing user, or false if it didn't */ function allow_programmatic_login( $user, $username, $password ) { return get_user_by( 'login', $username ); }
Creo queel código seexplicapor símismo:
Elfiltrobuscael objeto WP_Userparaelnombre de usuario dado y lo devuelve. Una llamada a lafunción
wp_set_current_user
conel objeto WP_User devueltoporwp_signon
,una verificación con lafunciónis_user_logged_in
para asegurarse de que hayainiciado sesión,yesoestodo!¡Un código agradable y limpioen mi opinión!
I have found another solution here that uses a better approach (at least in my opinion...). No need to set any cookie, it uses the Wordpress API:
/** * Programmatically logs a user in * * @param string $username * @return bool True if the login was successful; false if it wasn't */ function programmatic_login( $username ) { if ( is_user_logged_in() ) { wp_logout(); } add_filter( 'authenticate', 'allow_programmatic_login', 10, 3 ); // hook in earlier than other callbacks to short-circuit them $user = wp_signon( array( 'user_login' => $username ) ); remove_filter( 'authenticate', 'allow_programmatic_login', 10, 3 ); if ( is_a( $user, 'WP_User' ) ) { wp_set_current_user( $user->ID, $user->user_login ); if ( is_user_logged_in() ) { return true; } } return false; } /** * An 'authenticate' filter callback that authenticates the user using only the username. * * To avoid potential security vulnerabilities, this should only be used in the context of a programmatic login, * and unhooked immediately after it fires. * * @param WP_User $user * @param string $username * @param string $password * @return bool|WP_User a WP_User object if the username matched an existing user, or false if it didn't */ function allow_programmatic_login( $user, $username, $password ) { return get_user_by( 'login', $username ); }
I think the code is self explanatory:
The filter searches for the WP_User object for the given username and returns it. A call to the function
wp_set_current_user
with the WP_User object returned bywp_signon
, a check with the functionis_user_logged_in
to make sure your are logged in, and that's it!A nice and clean piece of code in my opinion!
-
¿Dónde usarprogrammatic_login?where to use programmatic_login?
- 0
- 2016-08-31
- RafaSashi
-
¡Respuestaperfecta!Perfect answer!
- 0
- 2017-07-08
- Maximus
-
@Shebo Tu comentarionoparece ser correcto.Laprimera línea de lafunción comprueba si lamatriz `$ credentials`está vacía ono.Si lamatriznoestá vacía (queesel casoen mi respuesta),los valores de lamatriz se utilizanpara autenticar al usuario.@Shebo Your comment doesn't seem to be correct. The first line of the function checks whether the array `$credentials` is empty or not. If the array is not empty (which is the case in my answer), the values from the array are used to authenticate the user.
- 0
- 2017-09-04
- Mike
-
@ Mike wow,¿cómome loperdí? Mimal,lo sientoporengañar.Eliminarémi primer comentarioparaevitar confusiones.Sinembargo,gran solución :)@Mike wow, how do I missed it... My bad, sorry for misleading. I'll delete my first comment, to avoid confusion. Great solution though :)
- 0
- 2017-09-04
- Shebo
-
Podría valer lapenaincluir `wp_signon ()`en unbloquetry y llamar a `remove_filter`en elbloquefinalmente.Esto deberíagarantizar queelfiltro siempre se retire.It might be worthwhile to enclose `wp_signon()` in a try block and call `remove_filter` in the finally block. This should ensure that the filter is always removed.
- 0
- 2020-07-23
- Leukipp
-
- 2015-06-09
Estome funcionabien:
clean_user_cache($user->ID); wp_clear_auth_cookie(); wp_set_current_user($user->ID); wp_set_auth_cookie($user->ID, true, false); update_user_caches($user);
This works well for me:
clean_user_cache($user->ID); wp_clear_auth_cookie(); wp_set_current_user($user->ID); wp_set_auth_cookie($user->ID, true, false); update_user_caches($user);
-
- 2016-08-31
Además de Mike,Paul y Sjoerd:
Paramanejarmejor las redirecciones de
login.php
://---------------------Automatic login-------------------- if(!is_user_logged_in()){ $username = "user1"; if($user=get_user_by('login',$username)){ clean_user_cache($user->ID); wp_clear_auth_cookie(); wp_set_current_user( $user->ID ); wp_set_auth_cookie( $user->ID , true, false); update_user_caches($user); if(is_user_logged_in()){ $redirect_to = user_admin_url(); wp_safe_redirect( $redirect_to ); exit; } } } elseif('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] == wp_login_url()){ $redirect_to = user_admin_url(); wp_safe_redirect( $redirect_to ); exit; }
Para colocarloen
wp-config.php
justo después derequire_once(ABSPATH . 'wp-settings.php');
FYI×
Basadoen la solución anterior,he lanzado un complementoparamantener al usuario conectado de un wordpress a otro sincronizando los datos del usuario y la sesión de cookies:
In addition to Mike, Paul and Sjoerd:
To better handle
login.php
redirections://---------------------Automatic login-------------------- if(!is_user_logged_in()){ $username = "user1"; if($user=get_user_by('login',$username)){ clean_user_cache($user->ID); wp_clear_auth_cookie(); wp_set_current_user( $user->ID ); wp_set_auth_cookie( $user->ID , true, false); update_user_caches($user); if(is_user_logged_in()){ $redirect_to = user_admin_url(); wp_safe_redirect( $redirect_to ); exit; } } } elseif('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] == wp_login_url()){ $redirect_to = user_admin_url(); wp_safe_redirect( $redirect_to ); exit; }
To be placed in
wp-config.php
just afterrequire_once(ABSPATH . 'wp-settings.php');
FYI
Based on the above solution, I have released a plugin to keep the user logged in from one wordpress to another by synchronizing user data and cookie session:
-
- 2020-05-22
Esbastanteextraño,pero la únicaformaen quefuncionaparamíes si redirijo ymuero () después:
clean_user_cache($user->ID); wp_clear_auth_cookie(); wp_set_current_user( $user_id, $user->user_login ); wp_set_auth_cookie( $user_id, true, true ); update_user_caches( $user ); if ( is_user_logged_in() ) { $redirect_to = $_SERVER['REQUEST_URI']; header("location:".$redirect_to ); die(); }
Strange enough but the only way it works for me is if I redirect and die() after:
clean_user_cache($user->ID); wp_clear_auth_cookie(); wp_set_current_user( $user_id, $user->user_login ); wp_set_auth_cookie( $user_id, true, true ); update_user_caches( $user ); if ( is_user_logged_in() ) { $redirect_to = $_SERVER['REQUEST_URI']; header("location:".$redirect_to ); die(); }
Estoy creando usuariosmanualmentemedianteprogramación y quieroiniciar sesiónen el usuario recién creado.WPfacilitael acceso a la contraseña hash,perono a la versión detexto sinformato.¿Hay algunaforma de usar wp_signon () sin la contraseña detextoplano?
Encontré a unapersona que afirma haber hechoesto aquí ,peronofue así.nofuncionaparamí.
¡GRACIAS!