game-village-politics-backend/app/Http/Controllers/AuthController.php

66 lines
2.8 KiB
PHP
Raw Normal View History

<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
/** Issues the bearer token the WS client sends when it subscribes. Everything else is WS. */
class AuthController extends Controller
{
/** 3 to 24 characters: letters, digits, and spaces, dots, dashes or underscores inside. */
public const NAME = '/^[\p{L}\p{N}][\p{L}\p{N} ._\-]{1,22}[\p{L}\p{N}]$/u';
/**
* A new account. Every refusal names the field and a code the client translates, so
* the form can mark the right field.
*/
public function register(Request $request): JsonResponse
{
$name = trim((string) $request->input('name'));
$email = mb_strtolower(trim((string) $request->input('email')));
$password = (string) $request->input('password');
$refusal = match (true) {
! preg_match(self::NAME, $name) || str_contains($name, ' ') => ['name', 'name_invalid', 'Names are 3 to 24 letters, digits, spaces, dots, dashes or underscores.'],
User::whereRaw('LOWER(name) = ?', [mb_strtolower($name)])->exists() => ['name', 'name_taken', 'That name is taken.'],
! filter_var($email, FILTER_VALIDATE_EMAIL) || mb_strlen($email) > 255 => ['email', 'email_invalid', 'That is not an email address.'],
User::where('email', $email)->exists() => ['email', 'email_taken', 'This email is already registered.'],
mb_strlen($password) < 8 || mb_strlen($password) > 255 => ['password', 'password_short', 'Passwords are at least 8 characters.'],
! $request->boolean('terms') => ['terms', 'terms_required', 'Accept the terms to play.'],
default => null,
};
if ($refusal) {
return $this->refuse($refusal[1], $refusal[2], $refusal[0]);
}
return $this->issue(User::create(['name' => $name, 'email' => $email, 'password' => $password, 'terms_accepted_at' => now()]));
}
public function login(Request $request): JsonResponse
{
$email = mb_strtolower(trim((string) $request->input('email')));
$user = User::where('email', $email)->first();
if (! $user || ! Hash::check((string) $request->input('password'), $user->password)) {
return $this->refuse('invalid_credentials', 'Wrong email or password.');
}
return $this->issue($user);
}
private function issue(User $user): JsonResponse
{
return response()->json([
'token' => $user->createToken('game')->plainTextToken,
'user' => $user->only('id', 'name', 'email'),
]);
}
private function refuse(string $code, string $message, ?string $field = null): JsonResponse
{
return response()->json(['code' => $code, 'message' => $message, 'field' => $field], 422);
}
}