Wonka

Wonka

Member Since 7 Months Ago

Experience Points 160
Experience Level 1

4,840 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed 0
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

04 Feb
6 months ago

Wonka started a new conversation Laravel 5.6 - Backup MySql Database To S3?

I am trying to backup an entire mysql database to S3 like this:

<?php
    namespace App\Console\Commands;

    use Carbon\Carbon;
    use Illuminate\Console\Command;
    use Illuminate\Support\Facades\Storage;
    use Symfony\Component\Process\Process;

    class DatabaseBackup extends Command {
        /**
         * The name and signature of the console command.
         *
         * @var string
         */
        protected $signature = 'backup:database';
        /**
         * The console command description.
         *
         * @var string
         */
        protected $description = 'Take a backup of the entire DB and upload to S3.';
        /**
         * Create a new command instance.
         *
         * @return void
         */
        public function __construct()
        {
            parent::__construct();
        }
        /**
         * Execute the console command.
         *
         * @return mixed
         */
        public function handle()
        {
            $date = Carbon::now()->format('Y-m-d_h-i');
            $user = env('DB_USERNAME');
            $password = env('DB_PASSWORD');
            $database = env('DB_DATABASE');
            $command = "mysqldump --user={$user} -p{$password} {$database} > {$date}.sql";
            $process = new Process($command);
            $process->start();
            while ($process->isRunning()) {
                $s3 = Storage::disk('s3');
                $s3->put('gallery-app-db/' . $date . ".sql", file_get_contents("{$date}.sql"));
                unlink("{$date}.sql");
            }
        }
    }

But when running php artisan backup:database and then looking at the bucket .sql file, and downloading the .sql file locally, it shows like this instead of the actual database/tables being in the file:

https://imgur.com/a/Qc1OsKX

Any idea how to have the .sql dump actually work and backup the real database along with all its tables instead of the usage file?

18 Jan
7 months ago

Wonka left a reply on Laravel 5.6 - How To Authenticate API Using Sessions For Same Folder SPA?

Good news! I figured it out, so in config/session.php I had the last variable 'same_site' => 'strict' after changing it to 'same_site' => null the 401 error went away, and everything works perfectly.

I really appreciate all the help guys, thank you all so much!

Wonka left a reply on Laravel 5.6 - How To Authenticate API Using Sessions For Same Folder SPA?

@stevecove all routes are under routes/web.php looks like this:

// api routes
Route::group(['prefix' => 'api'], function() {
    
    Route::group([], function() {
        // Public Routes Here
    });

    Route::group(['middleware' => 'auth'], function() {
        // Private Routes Here
    });

});

// other web routes

Hmmm... so after page refresh, any auth protected ajax calls return 401 (but they work prior to refresh with no issues). When I printed out the Auth::user()->email in index.blade.php it shows no auth email before and after login, on page refresh after login, it shows the user email, but get the 401 ajax issue, then refresh page again and it shows no auth email, and for all future refreshes no auth email, and ofcourse the persistent 401 for ajax calls to auth protected routes, non protected routes always load data perfectly via ajax.

Wonka left a reply on Laravel 5.6 - How To Authenticate API Using Sessions For Same Folder SPA?

@stevecove I can see the cookie being set, both XSRF-TOKEN and my_domain_session, for both request and response. Everything seems working until the page refresh, then any protected auth middleware routes ajax GET/POST requests return a 401 Unauthenticated as it seems to fail like in my issue #2 above in the Illuminate/Auth/GuardHelpers.php

Also to note, after page refresh any GET requests to non auth protected routes return data normally. It is just the auth routes that return 401 after page refresh when fetched via axios.

@jlrdw The answer linked only works until you refresh the page, then it doesn't work as stated above when accessing any auth protected endpoints with axios, which is why I posted an update there and posted the issue here as well. But both links seem to show that people have successfully done laravel auth without passport if the js/laravel app are not separate and both in same project, with the js being the only consumer of the api data.

@jekinney @jlrdw When trying Passport initially, I was stuck on it for a month as you can see here (https://stackoverflow.com/questions/53678019/laravel-5-6-passport-jwt-httponly-cookie-spa-authentication-for-self-consuming) and after not having any answer covering the chart in update 3 (which included access/refresh/csrf integration), I had to rethink the authentication, which led me to some people saying they successfully implemented default laravel session based authentication for their js app when it was in the same folder. But when I tried that, it worked perfectly until page refresh. And since the cookies are stored in the browser, I had to post here again to see how to proceed when I hit those 2 issues.

17 Jan
7 months ago

Wonka left a reply on Laravel 5.6 - How To Authenticate API Using Sessions For Same Folder SPA?

@jekinney So based on this answer (https://stackoverflow.com/a/54210281/485961), since the javascript frontend is on the same domain/part of the laravel project folder, it should be possible to use sessions with the built in auth. Also this reddit thread (https://www.reddit.com/r/laravel/comments/8rrs6s/why_is_it_so_hard_to_authenticate_an_api_using/) says the same, that it should be possible.

The default laravel auth handles the httpOnly/CSRF security really well, but I can't find anywhere online that does the same for passport. The closest thing is (http://esbenp.github.io/2017/03/19/modern-rest-api-laravel-part-4/) which shows the httpOnly cookie part but no mention of CSRF. Since we are the only consumer of this api, and it is part of the same project folder, I feel like it should be possible.

With the page refresh, the httpOnly cookie should still be there, since it's in the browser, and I save all fetched data in local stores, with exception to the token, since it's not secure in local storage. So since the browser is what contains the httpOnly cookie, I feel like this should work, just don't know how 100%.

Wonka left a reply on Laravel 5.6 - How To Authenticate API Using Sessions For Same Folder SPA?

@cmdobueno So I put all api routes in web instead, was able to log in via the api by posting to the custom LoginController normally and access auth protected routes with no problem. But as soon as I refresh the page, any api calls to protected routes return the 401 Unauthenticated and the sessions table still adds entries before login even on page load. So basically the 2 issues are still present.

This is so hard to figure out, has been 2 days so far and no clear way of solving it after everything I tried.

Wonka left a reply on Laravel 5.6 - How To Authenticate API Using Sessions For Same Folder SPA?

@cmdobueno You mean just move all the api routes to the web routes file, just have auth for the protected routes, and continue using axios for the calls? Do I need to keep passing the X-Requested-With/X-CSRF-TOKEN with the axios requests?

Wonka started a new conversation Laravel 5.6 - How To Authenticate API Using Sessions For Same Folder SPA?

I have a React SPA in the same Laravel project. The login/signup/logout and all other js views are in the js folder and use axios api calls for all POST/GET requests. I want to use the default Laravel session based web authentication for the embedded SPA, since it's in the same project folder and it will be the only javascript client accessing it. This api does not need to be open to the public, just for this react app, and it's an SPA for the speed and good user experience instead of full page reloads.

I do not want to deal with Passport tokens, access tokens, refresh tokens, revoking tokens, CSRF, etc. Just the out of the box simple Laravel session based auth that works so easily on web, but want it to work on my react app. The only blade file is the index.blade.php which includes the react app.js

Someone on Stack Overflow guided me to:

You have to add the various Session/Cookie middlewares in app/Http/Kernel.php (stuff like \Illuminate\Session\Middleware\StartSession::class) to the API routes.

Based on that suggestion, I added to $middlewareGroups.api to match the web middleware in app/Http/Kernel.php:

'api' => [
    'throttle:60,1',
    'bindings',
    // Newly added middleware to match web middleware
    \App\Http\Middleware\EncryptCookies::class
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\VerifyCsrfToken::class,
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

I realized there are two issues that occurred:

  1. In the sessions table, even if not logged in, when loading app home page (or any page), multiple sessions are inserted into the sessions table. Shouldn't a new single session be inserted into this table only after user login?

  2. After user log in, when refreshing the page manually in the browser and a call is made to a protected route, I get a 401 Unauthenticated which points me to this method in Illuminate/Auth/GuardHelpers.php:

     public function authenticate() {
         if (! is_null($user = $this->user())) {
             return $user;
         }
    
         throw new AuthenticationException; // throws this 401 exception on logged in page refresh when fetching data from private route
     }
    

Some additional notes:

  • In config/auth.php I updated the guards.api.driver to session instead of token.

  • In routes/api.php I have the protected routes wrapped in auth middleware like this: Route::group(['middleware' => 'auth'], function() { PRIVATE ROUTES HERE }

  • In config/session.php I have 'domain' => '.mydomain.com'

  • I am sending back these headers with each axios api request like this:

      window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
      let token = document.head.querySelector('meta[name="csrf-token"]');
      window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
    

Any idea how we can fix these 2 issues?