Skip to content

Commit

Permalink
finishing the authentification
Browse files Browse the repository at this point in the history
  • Loading branch information
lfarssi committed Oct 5, 2024
1 parent a0282cb commit bcbc51c
Show file tree
Hide file tree
Showing 22 changed files with 254 additions and 112 deletions.
19 changes: 17 additions & 2 deletions app/Http/Controllers/Auth/LoginController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

use Illuminate\Support\Facades\Log;

class LoginController extends Controller
{
Expand All @@ -16,6 +16,21 @@ public function index()

public function store(Request $request)
{
return redirect()->route('home');
// Validate the request
$request->validate([
'email' => 'required|email',
'password' => 'required',
]);

// Attempt to log the user in
if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
return redirect()->intended(route('home'))->with('message', 'You are logged in!');
}
Log::info('Available guards', ['guards' => config('auth.guards')]);
Log::warning('Failed login attempt', ['email' => $request->email]);

return back()->withErrors([
'email' => 'The provided credentials do not match our records.',
])->withInput($request->only('email'));
}
}
13 changes: 11 additions & 2 deletions app/Http/Controllers/Auth/LogoutController.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,23 @@
namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LogoutController extends Controller
{
public function logout()
public function logout(Request $request)
{
// Logout the user
Auth::logout();

return redirect()->route('home');
// Invalidate the session
$request->session()->invalidate();

// Regenerate CSRF token
$request->session()->regenerateToken();

// Redirect to the home page
return redirect()->route('home')->with('message', 'You have been logged out successfully.');
}
}
41 changes: 22 additions & 19 deletions app/Http/Controllers/Auth/RegisterController.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,26 +16,29 @@ public function index()
}

public function store(Request $request)
{
//validate
$this->validate($request, [
'username' => 'required|max:255',
'email' => 'required|email|max:255',
'password' => 'required|confirmed'
]);
{
// Validate the request
$this->validate($request, [
'username' => 'required|max:255|unique:users', // Ensure username is unique
'email' => 'required|email|max:255|unique:users', // Ensure email is unique
'password' => 'required|string|min:8|confirmed', // Password must match confirmation
]);

//store user
User::create([
'username' => $request->username,
'email' => $request->email,
'password' => Hash::make($request->password)
]);
// Create and store the user with default values
$user = User::create([
'username' => $request->username,
'email' => $request->email,
'password' => Hash::make($request->password), // Hash the password
'xp' => 0, // Starting XP
'rank' => 'Quiz Apprentice', // Default rank for new users based on initial XP
'total_correct_answers' => 0, // No correct answers at start
'total_questions_answered' => 0, // No questions answered at start
'percentage_correct' => 0, // No percentage data at start
]);

//sign user in
$credentials = $request->only('email', 'password');
Auth::attempt($credentials);
// Automatically log in the user after registration
Auth::login($user);

//redirect
return redirect()->route('home');
}
return redirect()->route('profile');
}
}
14 changes: 13 additions & 1 deletion app/Http/Controllers/LeaderboardController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,24 @@

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class LeaderboardController extends Controller
{
public function index()
{
return view('leaderboard',);
// Fetch the top 10 users ordered by XP, including the sum of correct answers from quizzes
$users = User::with('quizzes') // Eager load the quizzes
->select('id', 'username', 'xp')
->withCount(['quizzes as total_correct_answers' => function ($query) {
$query->select(DB::raw('COALESCE(SUM(correct_answers), 0)'));
}])
->orderBy('xp', 'desc')
->take(10)
->get();

return view('leaderboard', compact('users'));
}
}
20 changes: 20 additions & 0 deletions app/Http/Controllers/ProfileController.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,24 @@ public function index()

return view('profile', ['art' => $art, 'geography' => $geography, 'history' => $history, 'science' => $science, 'sports' => $sports]);
}
public function show()
{
$user = Auth::user(); // Fetch the logged-in user's data

// Calculate the user's rank based on XP
if ($user->xp >= 10000) {
$rank = 'Quiz Master';
} elseif ($user->xp >= 5000) {
$rank = 'Epic Quizer';
} elseif ($user->xp >= 1500) {
$rank = 'Average Quizer';
} else {
$rank = 'Quiz Apprentice';
}

return view('profile', [
'user' => $user,
'rank' => $rank
]);
}
}
4 changes: 3 additions & 1 deletion app/Http/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,12 @@ class Kernel extends HttpKernel
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
// \App\Http\Middleware\Authenticate::class
// 'checkLoggedIn' => \App\Http\Middleware\CheckUserLoggedIn::class,
],

'api' => [
Expand Down
2 changes: 2 additions & 0 deletions app/Http/Middleware/Authenticate.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Support\Facades\Log;

class Authenticate extends Middleware
{
Expand All @@ -15,6 +16,7 @@ class Authenticate extends Middleware
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
Log::info('Redirecting to login - Not authenticated');
return route('login');
}
}
Expand Down
24 changes: 24 additions & 0 deletions app/Http/Middleware/CheckUserLoggedIn.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class CheckUserLoggedIn
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (!Auth::check()) {
return redirect()->route('login'); // Redirect to the login page if not authenticated
}

return $next($request);
}
}
20 changes: 18 additions & 2 deletions app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,18 @@ class User extends Authenticatable
'xp',
'rank'
];

public function getRankAttribute()
{
if ($this->xp < 1500) {
return 'Quiz Apprentice';
} elseif ($this->xp >= 1500 && $this->xp < 5000) {
return 'Average Quizer';
} elseif ($this->xp >= 5000 && $this->xp < 10000) {
return 'Epic Quizer';
} else {
return 'Quiz Master';
}
}
public function leaderboard()
{
$topPlayers = User::orderBy('xp', 'desc')->take(10)->get();
Expand All @@ -49,8 +60,13 @@ public function leaderboard()
'email_verified_at' => 'datetime',
];

public function quizes()
public function quizzes()
{
return $this->hasMany(Quiz::class);
}

public function categoryScores()
{
return $this->hasMany(CategoryScore::class);
}
}
6 changes: 2 additions & 4 deletions config/auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
*/

'defaults' => [
'guard' => 'web',
'guard' => 'web',
'passwords' => 'users',
],

Expand All @@ -35,19 +35,17 @@
|
*/

'guards' => [
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],

'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],

/*
|--------------------------------------------------------------------------
| User Providers
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class CreateQuestionsTable extends Migration
*/
public function up()
{
Schema::create('question', function (Blueprint $table) {
Schema::create('questions', function (Blueprint $table) {
$table->id();
$table->foreignId('category_id')->constrained()->onDelete('cascade');
$table->text('text');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class CreateAnswersTable extends Migration
*/
public function up()
{
Schema::create('answer', function (Blueprint $table) {
Schema::create('answers', function (Blueprint $table) {
$table->id();
$table->foreignId('question_id')->constrained()->onDelete('cascade');
$table->text('answer_text');
Expand Down
15 changes: 15 additions & 0 deletions node_modules/public-encrypt/test/test_rsa_privkey.pem

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion resources/css/app.css
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@tailwind utilities;
38 changes: 34 additions & 4 deletions resources/views/app.blade.php
Original file line number Diff line number Diff line change
@@ -1,16 +1,46 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mister Quiz</title>

<!-- Tailwind CSS -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css" rel="stylesheet">

<!-- Boxicons CSS -->
<link href='https://unpkg.com/[email protected]/css/boxicons.min.css' rel='stylesheet'>

<!-- Custom CSS (if needed) -->
<link type="text/css" rel="stylesheet" href="{{ asset('css/app.css') }}">
</head>

<body>
<nav class="bg-gray-800 p-4">
<div class="container mx-auto flex justify-between items-center">
<a class="text-white hover:bg-gray-700 p-2 rounded" href="{{ route('home') }}">Home</a>

@auth
<div class="flex space-x-4">
<a class="text-white hover:bg-gray-700 p-2 rounded" href="{{ route('profile') }}">{{ auth()->user()->username }}</a>
<form action="{{ route('logout') }}" method="POST" class="inline">
@csrf
<button type="submit" class="text-white hover:bg-gray-700 p-2 rounded">Logout</button>
</form>
</div>
@endauth

@guest
<div class="flex space-x-4">
<a class="text-white hover:bg-gray-700 p-2 rounded" href="{{ route('register') }}">Register</a>
<a class="text-white hover:bg-gray-700 p-2 rounded" href="{{ route('login') }}">Login</a>
</div>
@endguest

<a class="text-white hover:bg-gray-700 p-2 rounded" href="{{ route('leaderboard') }}">Leaderboard</a>
</div>
</nav>

@yield('content')
</body>

</html>
</html>
Loading

0 comments on commit bcbc51c

Please sign in to comment.