feat: password reset, email change with verification, and password change
Password reset: multi-app support with custom notification linking to correct frontend (app/portal/admin). Email change: self-service with password confirmation and admin-initiated, both sending verification to new address with 24h expiry. Confirmation sent to old email on completion. Password change: authenticated endpoint revoking other sessions. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
13
api/app/Enums/EmailChangeStatus.php
Normal file
13
api/app/Enums/EmailChangeStatus.php
Normal file
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
enum EmailChangeStatus: string
|
||||
{
|
||||
case PENDING = 'pending';
|
||||
case VERIFIED = 'verified';
|
||||
case EXPIRED = 'expired';
|
||||
case CANCELLED = 'cancelled';
|
||||
}
|
||||
55
api/app/Http/Controllers/Api/V1/AccountController.php
Normal file
55
api/app/Http/Controllers/Api/V1/AccountController.php
Normal file
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\Rules\Password;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
final class AccountController extends Controller
|
||||
{
|
||||
/**
|
||||
* POST /api/v1/me/change-password
|
||||
* Authenticated user changes their own password.
|
||||
*/
|
||||
public function changePassword(Request $request): JsonResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'current_password' => ['required'],
|
||||
'password' => ['required', 'confirmed', Password::min(8)->mixedCase()->numbers()],
|
||||
]);
|
||||
|
||||
$user = $request->user();
|
||||
|
||||
if (! Hash::check($validated['current_password'], $user->password)) {
|
||||
throw ValidationException::withMessages([
|
||||
'current_password' => ['Het huidige wachtwoord is onjuist.'],
|
||||
]);
|
||||
}
|
||||
|
||||
$user->update([
|
||||
'password' => Hash::make($validated['password']),
|
||||
]);
|
||||
|
||||
// Revoke all OTHER tokens (keep current session)
|
||||
$currentToken = $user->currentAccessToken();
|
||||
if ($currentToken instanceof \Laravel\Sanctum\PersonalAccessToken) {
|
||||
$user->tokens()->where('id', '!=', $currentToken->id)->delete();
|
||||
} else {
|
||||
// TransientToken (test) or no token — revoke all
|
||||
$user->tokens()->delete();
|
||||
}
|
||||
|
||||
activity()
|
||||
->causedBy($user)
|
||||
->performedOn($user)
|
||||
->log('user.password_changed');
|
||||
|
||||
return $this->success(message: 'Je wachtwoord is succesvol gewijzigd.');
|
||||
}
|
||||
}
|
||||
71
api/app/Http/Controllers/Api/V1/EmailChangeController.php
Normal file
71
api/app/Http/Controllers/Api/V1/EmailChangeController.php
Normal file
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Services\EmailChangeService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
final class EmailChangeController extends Controller
|
||||
{
|
||||
public function __construct(private readonly EmailChangeService $service) {}
|
||||
|
||||
/**
|
||||
* POST /api/v1/me/change-email
|
||||
* User requests to change their own email.
|
||||
*/
|
||||
public function request(Request $request): JsonResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'new_email' => ['required', 'email', 'max:255'],
|
||||
'password' => ['required'],
|
||||
'app' => ['required', 'in:app,portal,admin'],
|
||||
]);
|
||||
|
||||
// Verify current password
|
||||
if (! Hash::check($validated['password'], $request->user()->password)) {
|
||||
throw ValidationException::withMessages([
|
||||
'password' => ['Het huidige wachtwoord is onjuist.'],
|
||||
]);
|
||||
}
|
||||
|
||||
$frontendUrls = [
|
||||
'admin' => config('app.frontend_admin_url'),
|
||||
'app' => config('app.frontend_app_url'),
|
||||
'portal' => config('app.frontend_portal_url'),
|
||||
];
|
||||
|
||||
$this->service->requestChange(
|
||||
$request->user(),
|
||||
$validated['new_email'],
|
||||
$request->user(),
|
||||
$frontendUrls[$validated['app']],
|
||||
);
|
||||
|
||||
return $this->success(
|
||||
message: 'Er is een verificatiemail verstuurd naar ' . $validated['new_email'] . '.',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/v1/verify-email-change
|
||||
* Public endpoint — verifies the token from the email link.
|
||||
*/
|
||||
public function verify(Request $request): JsonResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'token' => ['required', 'string'],
|
||||
]);
|
||||
|
||||
$this->service->verifyChange($validated['token']);
|
||||
|
||||
return $this->success(
|
||||
message: 'Je e-mailadres is succesvol gewijzigd.',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,9 @@ use App\Http\Resources\Api\V1\MemberCollection;
|
||||
use App\Http\Resources\Api\V1\MemberResource;
|
||||
use App\Models\Organisation;
|
||||
use App\Models\User;
|
||||
use App\Services\EmailChangeService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
|
||||
final class MemberController extends Controller
|
||||
@@ -81,4 +83,30 @@ final class MemberController extends Controller
|
||||
|
||||
return response()->json(null, 204);
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/v1/organisations/{organisation}/members/{user}/change-email
|
||||
* Admin changes a member's email (sends verification to new address).
|
||||
*/
|
||||
public function changeEmail(Request $request, Organisation $organisation, User $user): JsonResponse
|
||||
{
|
||||
Gate::authorize('invite', $organisation);
|
||||
|
||||
$validated = $request->validate([
|
||||
'new_email' => ['required', 'email', 'max:255'],
|
||||
]);
|
||||
|
||||
$frontendUrl = config('app.frontend_app_url');
|
||||
|
||||
app(EmailChangeService::class)->requestChange(
|
||||
$user,
|
||||
$validated['new_email'],
|
||||
$request->user(),
|
||||
$frontendUrl,
|
||||
);
|
||||
|
||||
return $this->success(
|
||||
message: 'Er is een verificatiemail verstuurd naar ' . $validated['new_email'] . '.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@ declare(strict_types=1);
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\User;
|
||||
use App\Notifications\ResetPasswordNotification;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
@@ -15,34 +17,57 @@ final class PasswordResetController extends Controller
|
||||
{
|
||||
public function sendResetLink(Request $request): JsonResponse
|
||||
{
|
||||
$request->validate(['email' => 'required|email']);
|
||||
$request->validate([
|
||||
'email' => ['required', 'email'],
|
||||
'app' => ['required', 'in:app,portal,admin'],
|
||||
]);
|
||||
|
||||
Password::sendResetLink(['email' => strtolower($request->email)]);
|
||||
$frontendUrls = [
|
||||
'admin' => config('app.frontend_admin_url'),
|
||||
'app' => config('app.frontend_app_url'),
|
||||
'portal' => config('app.frontend_portal_url'),
|
||||
];
|
||||
|
||||
$frontendUrl = $frontendUrls[$request->input('app')];
|
||||
|
||||
Password::sendResetLink(
|
||||
['email' => strtolower($request->email)],
|
||||
function (User $user, string $token) use ($frontendUrl) {
|
||||
$user->notify(new ResetPasswordNotification($token, $frontendUrl));
|
||||
}
|
||||
);
|
||||
|
||||
// Always return success (don't leak whether email exists)
|
||||
return $this->success(
|
||||
message: 'Als dit emailadres bij ons bekend is, ontvang je een link om je wachtwoord te resetten.'
|
||||
message: 'Als dit e-mailadres bij ons bekend is, ontvang je een link om je wachtwoord te herstellen.'
|
||||
);
|
||||
}
|
||||
|
||||
public function resetPassword(Request $request): JsonResponse
|
||||
{
|
||||
$request->validate([
|
||||
'token' => 'required',
|
||||
'email' => 'required|email',
|
||||
'token' => ['required'],
|
||||
'email' => ['required', 'email'],
|
||||
'password' => ['required', 'confirmed', PasswordRule::min(8)->mixedCase()->numbers()],
|
||||
]);
|
||||
|
||||
$status = Password::reset(
|
||||
$request->only('email', 'password', 'password_confirmation', 'token'),
|
||||
function ($user, $password) {
|
||||
function (User $user, string $password) {
|
||||
$user->forceFill(['password' => Hash::make($password)])->save();
|
||||
|
||||
// Revoke all existing tokens (force re-login everywhere)
|
||||
$user->tokens()->delete();
|
||||
|
||||
activity()
|
||||
->causedBy($user)
|
||||
->performedOn($user)
|
||||
->log('user.password_reset');
|
||||
}
|
||||
);
|
||||
|
||||
if ($status === Password::PASSWORD_RESET) {
|
||||
return $this->success(message: 'Wachtwoord succesvol gewijzigd.');
|
||||
return $this->success(message: 'Je wachtwoord is succesvol gewijzigd. Je kunt nu inloggen.');
|
||||
}
|
||||
|
||||
return $this->error(__($status), 422);
|
||||
|
||||
43
api/app/Mail/EmailChangedConfirmationMail.php
Normal file
43
api/app/Mail/EmailChangedConfirmationMail.php
Normal file
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Mail\Mailables\Content;
|
||||
use Illuminate\Mail\Mailables\Envelope;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
final class EmailChangedConfirmationMail extends Mailable implements ShouldQueue
|
||||
{
|
||||
use Queueable;
|
||||
use SerializesModels;
|
||||
|
||||
public function __construct(
|
||||
public User $user,
|
||||
public string $oldEmail,
|
||||
public string $newEmail,
|
||||
) {}
|
||||
|
||||
public function envelope(): Envelope
|
||||
{
|
||||
return new Envelope(
|
||||
subject: 'Je e-mailadres is gewijzigd — Crewli',
|
||||
);
|
||||
}
|
||||
|
||||
public function content(): Content
|
||||
{
|
||||
return new Content(
|
||||
markdown: 'emails.email-changed-confirmation',
|
||||
with: [
|
||||
'userName' => $this->user->first_name,
|
||||
'newEmail' => $this->newEmail,
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
50
api/app/Mail/VerifyEmailChangeMail.php
Normal file
50
api/app/Mail/VerifyEmailChangeMail.php
Normal file
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Mail\Mailables\Content;
|
||||
use Illuminate\Mail\Mailables\Envelope;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
final class VerifyEmailChangeMail extends Mailable implements ShouldQueue
|
||||
{
|
||||
use Queueable;
|
||||
use SerializesModels;
|
||||
|
||||
public function __construct(
|
||||
public User $user,
|
||||
public string $newEmail,
|
||||
public string $token,
|
||||
public string $frontendUrl,
|
||||
public User $requestedBy,
|
||||
) {}
|
||||
|
||||
public function envelope(): Envelope
|
||||
{
|
||||
return new Envelope(
|
||||
subject: 'Bevestig je nieuwe e-mailadres — Crewli',
|
||||
);
|
||||
}
|
||||
|
||||
public function content(): Content
|
||||
{
|
||||
$verifyUrl = $this->frontendUrl . '/verify-email-change?token=' . $this->token;
|
||||
$isSelfChange = $this->user->id === $this->requestedBy->id;
|
||||
|
||||
return new Content(
|
||||
markdown: 'emails.verify-email-change',
|
||||
with: [
|
||||
'verifyUrl' => $verifyUrl,
|
||||
'userName' => $this->user->first_name,
|
||||
'isSelfChange' => $isSelfChange,
|
||||
'requestedByName' => $this->requestedBy->full_name,
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
58
api/app/Models/EmailChangeRequest.php
Normal file
58
api/app/Models/EmailChangeRequest.php
Normal file
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Enums\EmailChangeStatus;
|
||||
use Illuminate\Database\Eloquent\Concerns\HasUlids;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
final class EmailChangeRequest extends Model
|
||||
{
|
||||
use HasUlids;
|
||||
|
||||
protected $fillable = [
|
||||
'user_id',
|
||||
'current_email',
|
||||
'new_email',
|
||||
'token',
|
||||
'requested_by_user_id',
|
||||
'status',
|
||||
'expires_at',
|
||||
'verified_at',
|
||||
];
|
||||
|
||||
protected $hidden = ['token'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'status' => EmailChangeStatus::class,
|
||||
'expires_at' => 'datetime',
|
||||
'verified_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
public function requestedBy(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'requested_by_user_id');
|
||||
}
|
||||
|
||||
public function isExpired(): bool
|
||||
{
|
||||
return $this->expires_at->isPast();
|
||||
}
|
||||
|
||||
public function scopePending($query)
|
||||
{
|
||||
return $query->where('status', EmailChangeStatus::PENDING)
|
||||
->where('expires_at', '>', now());
|
||||
}
|
||||
}
|
||||
40
api/app/Notifications/ResetPasswordNotification.php
Normal file
40
api/app/Notifications/ResetPasswordNotification.php
Normal file
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Notifications;
|
||||
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Notifications\Messages\MailMessage;
|
||||
use Illuminate\Notifications\Notification;
|
||||
|
||||
final class ResetPasswordNotification extends Notification implements ShouldQueue
|
||||
{
|
||||
use Queueable;
|
||||
|
||||
public function __construct(
|
||||
private readonly string $token,
|
||||
private readonly string $frontendUrl,
|
||||
) {}
|
||||
|
||||
public function via(mixed $notifiable): array
|
||||
{
|
||||
return ['mail'];
|
||||
}
|
||||
|
||||
public function toMail(mixed $notifiable): MailMessage
|
||||
{
|
||||
$resetUrl = $this->frontendUrl . '/reset-password?token=' . $this->token
|
||||
. '&email=' . urlencode($notifiable->email);
|
||||
|
||||
return (new MailMessage)
|
||||
->subject('Wachtwoord herstellen — Crewli')
|
||||
->greeting('Hallo ' . $notifiable->first_name . ',')
|
||||
->line('Je ontvangt deze e-mail omdat we een verzoek hebben ontvangen om je wachtwoord te herstellen.')
|
||||
->action('Wachtwoord herstellen', $resetUrl)
|
||||
->line('Deze link is 60 minuten geldig.')
|
||||
->line('Als je geen wachtwoordherstel hebt aangevraagd, kun je deze e-mail negeren.')
|
||||
->salutation('Groeten, Crewli');
|
||||
}
|
||||
}
|
||||
157
api/app/Services/EmailChangeService.php
Normal file
157
api/app/Services/EmailChangeService.php
Normal file
@@ -0,0 +1,157 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Enums\EmailChangeStatus;
|
||||
use App\Mail\EmailChangedConfirmationMail;
|
||||
use App\Mail\VerifyEmailChangeMail;
|
||||
use App\Models\EmailChangeRequest;
|
||||
use App\Models\Person;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
final class EmailChangeService
|
||||
{
|
||||
/**
|
||||
* Request an email change. Sends verification to the NEW email.
|
||||
*/
|
||||
public function requestChange(
|
||||
User $user,
|
||||
string $newEmail,
|
||||
User $requestedBy,
|
||||
string $frontendUrl,
|
||||
): EmailChangeRequest {
|
||||
// Validate new email is not already in use
|
||||
if (User::where('email', $newEmail)->where('id', '!=', $user->id)->exists()) {
|
||||
throw ValidationException::withMessages([
|
||||
'new_email' => ['Dit e-mailadres is al in gebruik door een ander account.'],
|
||||
]);
|
||||
}
|
||||
|
||||
// Cancel any existing pending requests for this user
|
||||
EmailChangeRequest::where('user_id', $user->id)
|
||||
->where('status', EmailChangeStatus::PENDING)
|
||||
->update(['status' => EmailChangeStatus::CANCELLED->value]);
|
||||
|
||||
// Generate secure token
|
||||
$plainToken = Str::random(64);
|
||||
|
||||
$request = EmailChangeRequest::create([
|
||||
'user_id' => $user->id,
|
||||
'current_email' => $user->email,
|
||||
'new_email' => $newEmail,
|
||||
'token' => hash('sha256', $plainToken),
|
||||
'requested_by_user_id' => $requestedBy->id,
|
||||
'status' => EmailChangeStatus::PENDING,
|
||||
'expires_at' => now()->addHours(24),
|
||||
]);
|
||||
|
||||
// Send verification email to the NEW address
|
||||
Mail::to($newEmail)->send(new VerifyEmailChangeMail(
|
||||
user: $user,
|
||||
newEmail: $newEmail,
|
||||
token: $plainToken,
|
||||
frontendUrl: $frontendUrl,
|
||||
requestedBy: $requestedBy,
|
||||
));
|
||||
|
||||
activity()
|
||||
->causedBy($requestedBy)
|
||||
->performedOn($user)
|
||||
->withProperties([
|
||||
'current_email' => $user->email,
|
||||
'new_email' => $newEmail,
|
||||
'is_self_change' => $user->id === $requestedBy->id,
|
||||
])
|
||||
->log('user.email_change_requested');
|
||||
|
||||
return $request;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify and execute the email change.
|
||||
*/
|
||||
public function verifyChange(string $plainToken): EmailChangeRequest
|
||||
{
|
||||
$hashedToken = hash('sha256', $plainToken);
|
||||
|
||||
$request = EmailChangeRequest::where('token', $hashedToken)
|
||||
->where('status', EmailChangeStatus::PENDING)
|
||||
->first();
|
||||
|
||||
if (! $request) {
|
||||
throw ValidationException::withMessages([
|
||||
'token' => ['Ongeldige of verlopen verificatielink.'],
|
||||
]);
|
||||
}
|
||||
|
||||
if ($request->isExpired()) {
|
||||
$request->update(['status' => EmailChangeStatus::EXPIRED]);
|
||||
throw ValidationException::withMessages([
|
||||
'token' => ['Deze verificatielink is verlopen. Vraag opnieuw een e-mailwijziging aan.'],
|
||||
]);
|
||||
}
|
||||
|
||||
// Final check: new email still not in use
|
||||
if (User::where('email', $request->new_email)
|
||||
->where('id', '!=', $request->user_id)->exists()) {
|
||||
$request->update(['status' => EmailChangeStatus::CANCELLED]);
|
||||
throw ValidationException::withMessages([
|
||||
'new_email' => ['Dit e-mailadres is inmiddels in gebruik door een ander account.'],
|
||||
]);
|
||||
}
|
||||
|
||||
$user = $request->user;
|
||||
$oldEmail = $user->email;
|
||||
|
||||
DB::transaction(function () use ($request, $user) {
|
||||
// Update user email
|
||||
$user->update(['email' => $request->new_email]);
|
||||
|
||||
// Mark request as verified
|
||||
$request->update([
|
||||
'status' => EmailChangeStatus::VERIFIED,
|
||||
'verified_at' => now(),
|
||||
]);
|
||||
});
|
||||
|
||||
// Send confirmation to the OLD email address
|
||||
Mail::to($oldEmail)->send(new EmailChangedConfirmationMail(
|
||||
user: $user,
|
||||
oldEmail: $oldEmail,
|
||||
newEmail: $request->new_email,
|
||||
));
|
||||
|
||||
// Revoke all tokens (force re-login with new email)
|
||||
$user->tokens()->delete();
|
||||
|
||||
// Log linked person email context
|
||||
$persons = Person::where('user_id', $user->id)->get();
|
||||
foreach ($persons as $person) {
|
||||
activity()
|
||||
->causedBy($user)
|
||||
->performedOn($person)
|
||||
->withProperties([
|
||||
'old_user_email' => $oldEmail,
|
||||
'new_user_email' => $request->new_email,
|
||||
'person_email_unchanged' => $person->email,
|
||||
])
|
||||
->log('person.linked_user_email_changed');
|
||||
}
|
||||
|
||||
activity()
|
||||
->performedOn($user)
|
||||
->withProperties([
|
||||
'old_email' => $oldEmail,
|
||||
'new_email' => $request->new_email,
|
||||
])
|
||||
->log('user.email_changed');
|
||||
|
||||
return $request;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user