adamtomat

adamtomat

Member Since 3 Years Ago

Developer at Rareloop

Experience Points 3,110
Experience Level 1

1,890 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 29
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

13 Jun
1 year ago

adamtomat left a reply on 5.2 - Password Reset For Multiple Tables

I was building an API which handles password resets slightly differently to Laravel's out-the-box controllers.

To create a new token for an admin in the correct table, you can do this in your own controller (or anywhere):

// Find an admin
$admin = Admin::where('email', $request->input('email'))->first();

// Resolves an instance of "Illuminate\Auth\Passwords\PasswordBrokerManager", which lets you pick which broker you wish to use
$broker = app('auth.password')->broker('admins')->getRepository();

// Create the token
$token = $broker->create($admin);
23 Oct
3 years ago

adamtomat left a reply on Excluding URI From CSRF Protection Not Working

Thanks for clarifying why the cookie is needed and I get that we need the token for those methods you mentioned. But in the context of an API we're never using the token and end up sending unnecessary bytes down the wire on every request. That's why I would like to remove it. Just for API requests.

Even with $except = ['*'], it still adds the token to the headers for GET requests. I'd expect it to disable all CSRF related stuff for the given uri, including the setting of the Set-Cookie header.

22 Oct
3 years ago

adamtomat started a new conversation Excluding URI From CSFR Protection Not Working

According to the docs (5.1) it's possible to exclude URI's easily with the protected $except property, like so:

    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'api/*'
    ];

Here I am trying to exclude the Set-Cookie :XSRF-TOKEN from API requests. However, this isn't working.

So I dug into Illuminate\Foundation\Http\Middleware\VerifyCsrfToken and became really confused. By the looks of it, the exclude will be ignored on any GET request, and therefore you get a cookie set. Here's the handle method:

    public function handle($request, Closure $next)
    {
        if ($this->isReading($request) || $this->shouldPassThrough($request) || $this->tokensMatch($request)) {
            return $this->addCookieToResponse($request, $next($request));
        }

        throw new TokenMismatchException;
    }

isReading() will return true if the request is GET, rendering the results of shouldPassThrough() pointless. There is only 2 outcomes to this method too: 1) you get a cookie set, 2) you get an exception. I'd expect a third outcome of no cookie if the request matches an except item, right?

Also, looking at shouldPassThrough() seems backwards too. It returns true if the request matches an except item:

    /**
     * Determine if the request has a URI that should pass through CSRF verification.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function shouldPassThrough($request)
    {
        foreach ($this->except as $except) {
            if ($request->is($except)) {
                return true;
            }
        }

        return false;
    }

The method docs suggest that if it returns true it should pass through CSFR verification...i.e. get a cookie. But it only returns true if it matches an except item i.e. we don't want a cookie.

To get the behaviour I expect, I had to create my own addCookieToResponse method which only adds a cookie if the request doesn't match any except items;

    protected function addCookieToResponse($request, $response)
    {
        if (!$this->shouldPassThrough($request)) {
            $response = parent::addCookieToResponse($request, $response);
        }

        return $response;
    }

Can somebody either validate this (as a bug?), or explain to me how it is intended to work please? Because what the docs (and code) imply don't make sense to me.

22 May
3 years ago

adamtomat left a reply on Catching All Exceptions Thrown In My API

I've dug into the Request class and found a wantsJson method, which looks like it solves my issue in a better way. So if the request wants JSON, we return the exception in a JSON format. Much better!

Any feedback on the Response::json stuff though is appreciated still too.

public function render($request, Exception $e)
{
    // Determine if the current request is asking for JSON in return
    if($request->wantsJson()) {
        return Response::json([
            'status' => 'error',
            'error' => $e->getMessage(),
            'name' => get_class($e)
        ]);
    }

    return parent::render($request, $e);
}

And for reference, here's what wantsJson is doing under the hood:

/**
 * Determine if the current request is asking for JSON in return.
 *
 * @return bool
 */
public function wantsJson()
{
    $acceptable = $this->getAcceptableContentTypes();

    return isset($acceptable[0]) && $acceptable[0] == 'application/json';
}

adamtomat started a new conversation Catching All Exceptions Thrown In My API

I'm building a small app, that has an API and an admin dashboard. My API routes are all prefixed with api/v1. I want to be able to catch all Exceptions that have been thrown by an API request, so I can return JSON instead of a view.

Reading online, I've seen people suggesting to do something like this:

if ($e instanceof APIException){
    return response(['success' => false, 'data' => [], 'message' => $e->getMessage(), 401);
}

But that only works if you know every Exception being thrown in your API, which in my opinion isn't very maintainable if your API is using plugins which are likely to throw their own Exceptions.

So my solution is to do the following in the app\Exceptions\Handler:render() method:

public function render($request, Exception $e)
{
// All Exceptions thrown by the API
    if($request->segment(1) === 'api') {
        return Response::json([
            'status' => 'error',
            'error' => $e->getMessage(),
            'name' => get_class($e)
        ]);
    }

    return parent::render($request, $e);
}

Is checking the request segment a good way of doing it?

Bonus points for a better way to return the json response with the correct HTTP status code too.