fahdgilani's avatar

Sharing login between Laravel & Wordpress

We are using wordpress as our store (using woocommerce). our backend use laravel where users who bought our services can use and manage the services they bought from us. we will eventually move to custom implementation of our store in laravel but right now we don't want to break anything. what i want is to integrate wordpress and laravels login so they don't have to login or register twice. something like github use (if you login at github you are automatically logged in at gist). both laravel and wordpress will use different database (or user tables at least). i can create a user in laravel when someone register at wordpress. but i have no clue how to share login session. why both ? we are using different readily available plugins of woocommerce (multiple subscriptions, addons, product variants etc) which will take a lot of time to port to laravel. any help would be great

0 likes
25 replies
Penderis's avatar

Think since wordpress the most of a little biatch, login with wordpress as the main one but when that hook triggers you just update the login details in laravels db and set your session _token the Auth::user().

Like a trigger laravel login plugin.

fahdgilani's avatar

thanks @Penderis . i am going for that approach. i have included "\bootstrap\autoload.php" in wordpress and created a function to login the user in my User class. but i am getting this error Fatal error: Call to a member function connection() on a non-object this happens only when i call $user = User::findOrFail($id); .

if i include everything from index.php of laravel it works but all the requests are routed to laravel in that case.

pmall's avatar

I don't think there is a reasonable way of doing this. You will spend way more time and headaches to make laravel and wordpress "communicate" than building your custom solution with laravel. This is a waste of time.

2 likes
fahdgilani's avatar

@pmall the thing is i am not very fluent in laravel yet and don't want to create a store with loopholes and/or security vulnerabilities, so i will let the wordpress handle this stuff for now as it is quite developed platform.

pmall's avatar

So learn how to use laravel. Trust me the laravel/wordpress solution will be hell.

RemiC's avatar

I'm researching this too as a client wants a wordpress backend to write their posts... I think that there are wordpress plugins supporting oauth, theorically it would be possible to use such with a laravel oauth server i think.

(i'm happy i covered myself by telling them it's probably not possible, though)

pmall's avatar

(i'm happy i covered myself by telling them it's probably not possible, though)

It is your duty to move users away from the wordpress beast.

1 like
RemiC's avatar

Believe me, the debate was rather intense... Hopefully it's only use for the blog content, everything else is handled by angular-laravel and a different subdomain. The only use case I would need auth would be blog post comment, so that won't be a big deal if it doesn't work.

RemiC's avatar

The wordpress popularity is hard to deal with, even with the best argument. 'everybody use it, so it must be good'... And the wordpress 'developer' are so fanatics to it sometimes it's almost scary...

1 like
fahdgilani's avatar
fahdgilani
OP
Best Answer
Level 2

@RemiC you can do this

Route::get('/wordpress', function(){
require('..\wordpress\wp-load.php');
return loginUser(Auth::user()->username);
});

in wordpress create a plugin or add loginFunction() to functions.php

 function loginFunction($username){
     $user_id = username_exists($username);
     $userdata = get_userdata($user_id);
     $user = set_current_user($user_id,$username);
     wp_set_auth_cookie($user_id);
    do_action('wp_login',$userdata->ID);
    // you can redirect the authenticated user to the "logged-in-page", define('MY_PROFILE_PAGE',1); f.e. first
    header("Location:".get_page_link(MY_PROFILE_PAGE));
}

Edit: now Laravel is maintaining the user DB, on creation of user a wordpress method is called which creates the same user and also login that user, same goes for login

5 likes
RemiC's avatar

Ok I see this can work, but how do I tell wordpress to use my login route on another subdomain ?

martinbean's avatar

You have two options: either modify WordPress’s authentication system to authenticate via credentials stored in your Laravel application’s database, or modify your Laravel application to authenticate via WordPress.

Personally, I’d take the latter approach whilst you’re still supporting the WooCommerce store. Laravel has a nicely-abstracted authentication system so you should be able to create a WordPress driver and use that instead of the Eloquent driver Laravel uses by default.

So in config/auth.php you would set driver to be wordpress, and then create a new WordPressUserProvider class that implements the UserProvider interface.

You’ll need to implement the methods defined in this interface, and delve into WordPress’s core as for what to do to retrieve a user by their ID, credentials etc.

Once you’re ready to turn off the WordPress-based site and move solely to Laravel, you can just migrate users to your Laravel application’s database in one fell swoop, although you may need to ask users to set new passwords due to the differences in how Laravel and WordPress hash passwords out of the box.

3 likes
RemiC's avatar

I can't, the Laravel application is already built with a complex role based system.

Doesn't wordpress support oauth as a client ????

Penderis's avatar

Have you tried themosis framework? http://framework.themosis.com/ not to say do not use laravel you should but if you need wordpress backend themosis has laravel syntax with a wordpress backend.

2 likes
fahdgilani's avatar

@martinbean thank you so much. do you have any link to a tutorial ? or existing laravel class which i can use as a reference. thanks again.

@Penderis that might do it. will definetly check thanks

Penderis's avatar

sorry if of base here, but reading the original question again wordpress has majority share, and as a hack if wordpress could very well handle the login, you can just add a session with username and email that laravel takes and creates the user in the database without making wordpress or laravel jump through hoops , once this is done having the laravel side on a subdomain can have you manage it as a separate application , woocommerce has a restful api that can come in handy also.

http://grossi.io/2014/working-with-laravel-4-and-wordpress-together/ http://ilikekillnerds.com/2014/09/using-laravel-4-eloquent-with-wordpress/

dberry's avatar

Here's the thing about Wordpress, yes, it's ugly code, it can be a pain to work with, but it is the most widely used blogging system out there. Roughly ^^17%-19% of the INTERNET** is backed by Wordpress. think about that, that's a HUGE number.

We as develops don't care for it much, but end-users love it. It's interface is simple for them to use, there is support everywhere for it. It's a good, solid choice in certain situations.

So I have to completely disagree with @pmall and other comments like

it's your duty to steer customers away from Wordpress

To those na-sayers, I say show me a better option for those situations where WordPress completely fits the bill. I mean even Taylor uses Wordpress, I use Wordpress for my blogging and have been known to standup Wordpress instances for really simple CMS cases.

dberry's avatar

@pmall haha, sorry... hey you never know. I've had this debate so many times and have heard that exact phrase over and over,,,

bbloom's avatar

If you want to use WordPress, then go use WordPress. This is not a WordPress forum, so don't go looking for affirmation here about how wonderful WordPress is here.

I happen to think that the counsel offered here by fellow subscribers has been very gracious and generous.

I also happen to have serious concerns about WordPress, to the extent that in many cases I consider it unethical to recommend WordPress. Just one case: WooCommerce lacks a normalized database -- which doesn't bother many people, but it doesn't bother me.

I am creating my own Laravel based software as a response to my frustrations with what is out there. I am intrigued by the upcoming Drupal. I think the new Grav offers a very potentially unique and wonderful value proposition.

My own sites were all WordPress. But, now I'm running 'em on v1 of my blog app. Except my Media site, which I will convert to my upcoming Laravel podcast app later this year.

Ah, back to work now...!

dberry's avatar

^^ good example of what I was talking about.

Look forward to seeing this blog app you speak of.

shadowWalker's avatar

I have a solution, it is not the cleanest but it works. You said that you can create a laravel user when someone register in wordpress, so :

  • When someone create an account on wordpress you take the wordpress user id and store it in the laravel row when you create the laravel user. At this stage we have a link between the two platforms.

  • When someone login in wordpress we use his wordpress id to identify his laravel account and we collect the laravel username and password.

  • Make a request using curl to the login route in laravel with the proper laravel credentials. Also you need to send the PHPSESSID from wordpress in the curl request (otherwise it will not work) This an example of a curl request

$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER  => true,
    CURLOPT_USERAGENT       => 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)',
    CURLOPT_URL             => 'your login url in laravel',
    CURLOPT_REFERER         => 'referer if you need that',
    CURLOPT_POST            => true,
    CURLOPT_COOKIE          => 'PHPSESSID=' . $_COOKIE['PHPSESSID'] . '; path=/',
    CURLOPT_POSTFIELDS      => array(
                                'username' => 'laravel username',
                                'password' => 'the laravel password',
                            )
));

$resp = curl_exec($curl);

curl_close($curl);

Now in order for this to work, passwords stored in the laravel table must be reversible. Out of the box laravel hash passwords and that hash can't be reversed. What you should do is make a new implementation of the HasherContract and then swipe the laravel service provider Illuminate\Hashing\HashServiceProvider with the server provider of you implementation.

You can use any reversible algorithm, for example the base64

One more thing out of the box laravel provides csrf protection, so when submitting the curl request from wordpress you should take that into consideration.

1 like
clubcouleurs's avatar

@fahdgilani Hello Dear fahdgilani, is this solution still working with laravel 7 ? thanks a lot for your response

Please or to participate in this conversation.