Skip to content

Implement Verified Author Logic for Publishing Without Review (#1276) #1303

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions app/Http/Controllers/Admin/UsersController.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
use App\Jobs\DeleteUser;
use App\Jobs\DeleteUserThreads;
use App\Jobs\UnbanUser;
use App\Jobs\UnVerifyAuthor;
use App\Jobs\VerifyAuthor;
use App\Models\User;
use App\Policies\UserPolicy;
use App\Queries\SearchUsers;
Expand Down Expand Up @@ -60,6 +62,29 @@ public function unban(User $user): RedirectResponse
return redirect()->route('profile', $user->username());
}

public function verifyAuthor(User $user)
{
$this->authorize(UserPolicy::VERIFY_AUTHOR, $user);

$this->dispatchSync(new VerifyAuthor($user));

$this->success($user->name() . ' was verified!');

return redirect()->route('admin.users');
}

public function unverifyAuthor(User $user)

{
$this->authorize(UserPolicy::VERIFY_AUTHOR, $user);

$this->dispatchSync(new UnverifyAuthor($user));

$this->success($user->name() . ' was unverified!');

return redirect()->route('admin.users');
}

public function delete(User $user): RedirectResponse
{
$this->authorize(UserPolicy::DELETE, $user);
Expand Down
17 changes: 12 additions & 5 deletions app/Http/Controllers/Articles/ArticlesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -115,11 +115,7 @@ public function store(ArticleRequest $request)

$article = Article::findByUuidOrFail($uuid);

$this->success(
$request->shouldBeSubmitted()
? 'Thank you for submitting, unfortunately we can\'t accept every submission. You\'ll only hear back from us when we accept your article.'
: 'Article successfully created!'
);
$this->maybeFlashSuccessMessage($article, $request);

return $request->wantsJson()
? ArticleResource::make($article)
Expand Down Expand Up @@ -176,4 +172,15 @@ public function delete(Request $request, Article $article)
? response()->json([], Response::HTTP_NO_CONTENT)
: redirect()->route('articles');
}

private function maybeFlashSuccessMessage(Article $article, ArticleRequest $request): void
{
if ($article->isNotApproved()) {
$this->success(
$request->shouldBeSubmitted()
? 'Thank you for submitting, unfortunately we can\'t accept every submission. You\'ll only hear back from us when we accept your article.'
: 'Article successfully created!'
);
}
}
}
6 changes: 6 additions & 0 deletions app/Jobs/CreateArticle.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ public function handle(): void
'original_url' => $this->originalUrl,
'slug' => $this->title,
'submitted_at' => $this->shouldBeSubmitted ? now() : null,
'approved_at' => $this->canBeAutoApproved() ? now() : null,
]);
$article->authoredBy($this->author);
$article->syncTags($this->tags);
Expand All @@ -58,4 +59,9 @@ public function handle(): void
event(new ArticleWasSubmittedForApproval($article));
}
}

private function canBeAutoApproved(): bool
{
return $this->shouldBeSubmitted && $this->author->verifiedAuthorCanPublishMoreToday();
}
}
28 changes: 28 additions & 0 deletions app/Jobs/UnVerifyAuthor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

namespace App\Jobs;

use App\Models\User;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

class UnVerifyAuthor implements ShouldQueue
{
use Queueable;

/**
* Create a new job instance.
*/
public function __construct(private User $user)
{
//
}

/**
* Execute the job.
*/
public function handle(): void
{
$this->user->unverifyAuthor();
}
}
28 changes: 28 additions & 0 deletions app/Jobs/VerifyAuthor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

namespace App\Jobs;

use App\Models\User;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

class VerifyAuthor implements ShouldQueue
{
use Queueable;

/**
* Create a new job instance.
*/
public function __construct(private User $user)
{
//
}

/**
* Execute the job.
*/
public function handle(): void
{
$this->user->verifyAuthor();
}
}
2 changes: 1 addition & 1 deletion app/Models/Article.php
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ public function isShared(): bool

public function isAwaitingApproval(): bool
{
return $this->isSubmitted() && $this->isNotApproved() && $this->isNotDeclined();
return $this->isSubmitted() && $this->isNotApproved() && $this->isNotDeclined() && ! $this->author()->verifiedAuthorCanPublishMoreToday();
}

public function isNotAwaitingApproval(): bool
Expand Down
48 changes: 48 additions & 0 deletions app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,54 @@ public function delete()
parent::delete();
}

// === Verified Author ===

public function isVerifiedAuthor(): bool
{
return !is_null($this->verified_author_at);
}

public function isNotVerifiedAuthor(): bool
{
return !$this->isVerifiedAuthor();
}

public function verifyAuthor(): void
{
$this->verified_author_at = now();
$this->save();
}


public function unverifyAuthor(): void
{
$this->verified_author_at = null;
$this->save();
}

/**
* Check if the verified author can publish more articles today.
*
* Verified authors are allowed to publish up to 2 articles per day,
* but will start count from the moment they are verified.
*
* @return bool True if under the daily limit, false otherwise
*/

public function verifiedAuthorCanPublishMoreToday(): bool
{
$limit = 2; // Default limit for verified authors
if ($this->isNotVerifiedAuthor()) {
return false;
}
$publishedTodayCount = $this->articles()
->whereDate('submitted_at', today())
->where('submitted_at', '>', $this->verified_author_at)->count(); // to ensure we only count articles published after verify the author
return $publishedTodayCount < $limit;
}

// === End Verified Author ===

public function countSolutions(): int
{
return $this->replyAble()->isSolution()->count();
Expand Down
9 changes: 9 additions & 0 deletions app/Policies/UserPolicy.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ final class UserPolicy

const DELETE = 'delete';

const VERIFY_AUTHOR = 'verifyAuthor';


public function admin(User $user): bool
{
return $user->isAdmin() || $user->isModerator();
Expand All @@ -25,6 +28,12 @@ public function ban(User $user, User $subject): bool
($user->isModerator() && ! $subject->isAdmin() && ! $subject->isModerator());
}

public function verifyAuthor(User $user, User $subject): bool
{
return ($user->isAdmin() && ! $subject->isAdmin()) ||
($user->isModerator() && ! $subject->isAdmin() && ! $subject->isModerator());
}

public function block(User $user, User $subject): bool
{
return ! $user->is($subject) && ! $subject->isModerator() && ! $subject->isAdmin();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->timestamp('verified_author_at')
->nullable()
->after('email_verified_at')
->comment('Indicates if the user is a verified author');
});
}

/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('verified_author_at');
});
}
};
Binary file added laravel
Binary file not shown.
31 changes: 31 additions & 0 deletions resources/views/admin/users.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,37 @@
<p>All the threads from this user will be deleted. This cannot be undone.</p>
</x-modal>
@endcan

{{-- Toggle Verified Author --}}
@can(App\Policies\UserPolicy::VERIFY_AUTHOR, $user)
@if ($user->isVerifiedAuthor())
<button title="Unverify {{ $user->name() }} as author"
@click="activeModal = 'unverifyAuthor{{ $user->getKey() }}'"
class="text-yellow-600 hover:text-yellow-800">
<x-heroicon-o-x-circle class="w-5 h-5 inline" />
</button>
<x-modal type="update" identifier="unverifyAuthor{{ $user->getKey() }}"
:action="route(
'admin.users.unverify-author',
$user->username(),
)" title="Unverify {{ $user->username() }} as Author">
<p>This will remove the verified author status from this user.</p>
</x-modal>
@else
<button title="Verify {{ $user->name() }} as author"
@click="activeModal = 'verifyAuthor{{ $user->getKey() }}'"
class="text-green-600 hover:text-green-800">
<x-heroicon-o-check-circle class="w-5 h-5 inline" />
</button>
<x-modal type="update" identifier="verifyAuthor{{ $user->getKey() }}"
:action="route(
'admin.users.verify-author',
$user->username(),
)" title="Verify {{ $user->username() }} as Author">
<p>This will mark this user as a verified author.</p>
</x-modal>
@endif
@endcan
</x-tables.table-data>
</tr>
@endforeach
Expand Down
2 changes: 2 additions & 0 deletions routes/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,8 @@
Route::get('users', [UsersController::class, 'index'])->name('.users');
Route::put('users/{username}/ban', [UsersController::class, 'ban'])->name('.users.ban');
Route::put('users/{username}/unban', [UsersController::class, 'unban'])->name('.users.unban');
Route::put('users/{username}/verify-author', [UsersController::class, 'verifyAuthor'])->name('.users.verify-author');
Route::put('users/{username}/unverify-author', [UsersController::class, 'unverifyAuthor'])->name('.users.unverify-author');
Route::delete('users/{username}', [UsersController::class, 'delete'])->name('.users.delete');

Route::delete('users/{username}/threads', [UsersController::class, 'deleteThreads'])->name('.users.threads.delete');
Expand Down
8 changes: 8 additions & 0 deletions tests/CreatesUsers.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,12 @@ protected function createUser(array $attributes = []): User
'github_username' => 'johndoe',
], $attributes));
}

protected function createVerifiedAuthor(array $attributes = []): User
{
return $this->createUser(array_merge($attributes, [
'verified_author_at' => now(),
]));
}

}
29 changes: 29 additions & 0 deletions tests/Feature/ArticleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -576,3 +576,32 @@
->assertSee('My First Article')
->assertSee('10 views');
});

test('verified authors can publish two articles per day with no approval needed', function () {
$author = $this->createVerifiedAuthor();

Article::factory()->count(2)->create([
'author_id' => $author->id,
'submitted_at' => now()->addMinutes(1), // after verification
]);

expect($author->verifiedAuthorCanPublishMoreToday())->toBeFalse();
});

test('verified authors skip the approval message when submitting new article', function () {

$author = $this->createVerifiedAuthor();
$this->loginAs($author);

$response = $this->post('/articles', [
'title' => 'Using database migrations',
'body' => 'This article will go into depth on working with database migrations.',
'tags' => [],
'submitted' => '1',
]);

$response
->assertRedirect('/articles/using-database-migrations')
->assertSessionMissing('success');

});