Search code examples
laravellaravel-5laravel-authorization

Laravel Change Password Reset Token duration for specific tokens


In my application, user's will have their accounts created for them by other people, so I want to send a password reset email to them so they can set their password and log in. The problem is I don't want these links to expire after 60 minutes like the default password reset emails. Now I could change the expiry time, but I want regular password resets to stay at 60 minutes, but the welcome email link to either never expire or expire after some long amount of time.

How can I go about doing this without implementing a second token system, I can't seem to find anything about this.

I suppose I could also just allow the user to re-send the welcome email if their token expires, but that is kind of annoying.


Solution

  • The expiration duration is defined in auth.php. You can simply define another configuration with a different expiration time:

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],
        'users_welcome' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 120,
        ],
    ],
    

    And when you're generating the mail you can use that new broker:

    \Illuminate\Support\Facades\Password::broker('users_welcome')->sendResetLink($user->email);
    

    To check whether the token is expired, Laravel uses the created_at of the reset and the defined expiration duration:

        /**
         * Determine if the token has expired.
         *
         * @param  string  $createdAt
         * @return bool
         */
        protected function tokenExpired($createdAt)
        {
            return Carbon::parse($createdAt)->addSeconds($this->expires)->isPast();
        }
    

    https://github.com/laravel/framework/blob/5.8/src/Illuminate/Auth/Passwords/DatabaseTokenRepository.php#L139