Skip to content

Commit

Permalink
Merge pull request #87 from openfoodfoundation/feature/improve-onboar…
Browse files Browse the repository at this point in the history
…ding

Feature: Improved onboarding password reset experience
  • Loading branch information
ok200paul authored Jan 29, 2025
2 parents cae3fb1 + 5514b53 commit 52caff7
Show file tree
Hide file tree
Showing 111 changed files with 3,282 additions and 1,339 deletions.
254 changes: 254 additions & 0 deletions app/Http/Controllers/Api/V1/ApiMyProfileController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,254 @@
<?php

namespace App\Http\Controllers\Api\V1;

use App\Enums\ApiResponse;
use App\Exceptions\DisallowedApiFieldException;
use App\Http\Controllers\Api\HandlesAPIRequests;
use App\Http\Controllers\Controller;
use App\Models\User;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rules\Password;
use Knuckles\Scribe\Attributes\Authenticated;
use Knuckles\Scribe\Attributes\BodyParam;
use Knuckles\Scribe\Attributes\Endpoint;
use Knuckles\Scribe\Attributes\Group;
use Knuckles\Scribe\Attributes\QueryParam;
use Knuckles\Scribe\Attributes\Response;
use Knuckles\Scribe\Attributes\Subgroup;

#[Group('App Endpoints')]
#[Subgroup('/my-profile', 'Manage your profile.')]
class ApiMyProfileController extends Controller
{
use HandlesAPIRequests;

/**
* Set the related data the GET request is allowed to ask for
*/
public array $availableRelations = [

];

public static array $searchableFields = [];

/**
* GET /
*
* @return JsonResponse
*
* @throws DisallowedApiFieldException
*/
#[Endpoint(
title : 'GET /',
description : 'Retrieve your user profile.',
authenticated: true
)]
#[Authenticated]
#[QueryParam(
name : 'cached',
type : 'bool',
description: 'Request the response to be cached. Default: `true`.',
required : false,
example : true
)]
#[QueryParam(
name : 'fields',
type : 'string',
description: 'Comma-separated list of database fields to return within the object.',
required : false,
example : 'id,created_at'
)]
#[Response(
content : '{
"meta": {
"responseCode": 200,
"limit": 50,
"offset": 0,
"message": "",
"cached": true,
"cached_at": "2024-08-13 08:58:19",
"availableRelations": []
},
"data": {"id": 1234, "name": "Your name", "email":"[email protected]", "created_at": "2024-01-01 00:00:00"}
}',
status : 200,
description: ''
)]
public function index(): JsonResponse
{
$this->query = User::with($this->associatedData);
$this->query = $this->updateReadQueryBasedOnUrl();
$this->data = $this->query->find(Auth::id());

return $this->respond();
}

/**
* POST /
*
* @hideFromAPIDocumentation
*
* @return JsonResponse
*/
public function store(): JsonResponse
{
$this->responseCode = 403;
$this->message = ApiResponse::RESPONSE_METHOD_NOT_ALLOWED->value;

return $this->respond();
}

/**
* GET /{id}
*
* @param string $id
*
* @return JsonResponse
*
* @throws DisallowedApiFieldException
*/
#[Endpoint(
title : 'GET /{id}',
description : 'Retrieve your profile. Alias of GET /',
authenticated: true,
)]
#[Authenticated]
#[QueryParam(
name : 'cached',
type : 'bool',
description: 'Request the response to be cached. Default: `true`.',
required : false,
example : 1
)]
#[QueryParam(
name : 'fields',
type : 'string',
description: 'Comma-separated list of database fields to return within the object.',
required : false,
example : 'id,created_at'
)]
#[Response(
content : '{
"meta": {
"responseCode": 200,
"limit": 50,
"offset": 0,
"message": "",
"cached": true,
"cached_at": "2024-08-13 08:58:19",
"availableRelations": []
},
"data": {"id": 1234, "name": "Your name", "email":"[email protected]", "created_at": "2024-01-01 00:00:00"}
}',
status : 200,
description: ''
)]
public function show(string $id)
{
$this->query = User::with($this->associatedData);
$this->query = $this->updateReadQueryBasedOnUrl();
$this->data = $this->query->find(Auth::id());

return $this->respond();
}

/**
* PUT/ {id}
*
* @param string $id
*
* @return JsonResponse
*/
#[Endpoint(
title : 'PUT /{id}',
description : 'Update your profile.',
authenticated: true
)]
#[Authenticated]
#[BodyParam(
name : 'password',
type : 'string',
description: 'Your new password. Must conform to password validation requirements.',
required : false
)]
#[Response(
content : '{
"meta": {
"responseCode": 200,
"limit": 50,
"offset": 0,
"message": "",
"cached": true,
"cached_at": "2024-08-13 08:58:19",
"availableRelations": []
},
"data": {"id": 1234, "name": "Your name", "email":"[email protected]", "created_at": "2024-01-01 00:00:00"}
}',
status : 200,
description: ''
)]
public function update(string $id)
{
$validationArray = [
'password' => [
'sometimes',
Password::min(8)
->letters()
->mixedCase()
->numbers()
->symbols(),
],

];

$validator = Validator::make($this->request->all(), $validationArray);

if ($validator->fails()) {

$this->responseCode = 400;
$this->message = $validator->errors()
->first();

}
else {

try {

Auth::user()->password = $this->request->get('password');
Auth::user()->requires_password_reset = 0;
Auth::user()->save();

$this->data = Auth::user();
}
catch (Exception $e) {

$this->responseCode = 500;
$this->message = ApiResponse::RESPONSE_ERROR->value . ': "' . $e->getMessage() . '".';

}
}

return $this->respond();
}

/**
* DELETE / {id}
*
* @hideFromAPIDocumentation
*
* @param string $id
*
* @return JsonResponse
*/
public function destroy(string $id)
{
$this->responseCode = 403;
$this->message = ApiResponse::RESPONSE_METHOD_NOT_ALLOWED->value;

return $this->respond();
}
}
2 changes: 1 addition & 1 deletion app/Http/Controllers/ProfileController.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class ProfileController extends Controller
*/
public function edit(Request $request): Response
{
return Inertia::render('Profile/Edit', [
return Inertia::render('App/Profile/Edit', [
'mustVerifyEmail' => $request->user() instanceof MustVerifyEmail,
'status' => session('status'),
]);
Expand Down
37 changes: 37 additions & 0 deletions app/Http/Middleware/CheckIfPasswordUpdateRequired.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

/** @noinspection PhpUndefinedFieldInspection */

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Symfony\Component\HttpFoundation\Response;

class CheckIfPasswordUpdateRequired
{
protected array $except = [
'profile.set-password',
];

/**
* Handle an incoming request.
*
* @param Request $request
* @param Closure(Request): (Response) $next
*
* @return Response
*/
public function handle(Request $request, Closure $next): Response
{
if (Auth::user() && Auth::user()->requires_password_reset == 1 && ($request->route()->uri != 'profile/set-password')) {

return Redirect::to('/profile/set-password');
}

return $next($request);

}
}
3 changes: 2 additions & 1 deletion app/Jobs/TeamUsers/SendTeamUserInvitationEmail.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ public function handle(): void
$userToNotify = User::find($this->teamUser->user_id);

if ($userToNotify) {
$userToNotify->current_team_id = $this->teamUser->team_id;
$userToNotify->requires_password_reset = 1;
$userToNotify->current_team_id = $this->teamUser->team_id;
$userToNotify->saveQuietly();

$userToNotify->notify(new SendTeamUserInvitationEmailNotification($this->teamUser));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

use App\Models\Team;
use App\Models\TeamUser;
use App\Models\User;
use App\Services\BounceService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
Expand Down Expand Up @@ -41,13 +43,19 @@ public function toMail(object $notifiable): MailMessage
{
$team = Team::find($this->teamUser->team_id);

$urlToVisit = BounceService::generateSignedUrlForUser(
user : User::find($notifiable->id),
expiry : now()->addDays(2),
redirectPath: '/dashboard'
);

return (new MailMessage())
->subject('You have been invited to join ' . $team->name . ' - ' . config('app.name'))
->line('You have been invited to join team "' . $team->name . '" on ' . config('app.name') . '.')
->line('An account has been created for you on the team, but if you have never logged in to use the system, you may need to reset your password in order to log in.')
->line('Please follow the button below to reset your password and log in.')
->action('Reset your password & log in', url('/forgot-password'))
->line('Thank you for using our application!');
->line('An account has been created for you on the team, but if you have never logged in to use the system, you will need to set your password in order to log in.')
->line('This link will expire after 24 hours.')
->line('Please follow the button below.')
->action('Set your password & log in', $urlToVisit);
}

/**
Expand Down
Loading

0 comments on commit 52caff7

Please sign in to comment.