<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class GuestController extends Controller
{
public function authorization(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required',
]);
if ($validator->fails()) {
return response()->json([
'success' => false,
'message' => $validator->errors()->first(),
], 422);
}
$user = User::where('email', $request->email)->first();
if (!$user || !Hash::check($request->password, $user->password)) {
return response()->json([
'success' => false,
'message' => 'Login failed',
], 401);
}
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json([
'success' => true,
'message' => 'Success',
'token' => $token,
]);
}
public function registration(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email|unique:users',
'password' => 'required|min:8|regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/',
'first_name' => 'required',
'last_name' => 'required',
]);
if ($validator->fails()) {
return response()->json([
'success' => false,
'message' => $validator->errors()->first(),
], 422);
}
$user = User::create([
'email' => $request->email,
'password' => Hash::make($request->password),
'first_name' => $request->first_name,
'last_name' => $request->last_name,
]);
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json([
'success' => true,
'message' => 'Success',
'token' => $token,
]);
}
}