birzha-legalizasia/app/Http/Controllers/AuthController.php

69 lines
1.9 KiB
PHP
Raw Normal View History

2022-06-24 11:56:01 +00:00
<?php
namespace App\Http\Controllers;
use App\Models\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
//controller where all auth process for client happens
class AuthController extends Controller
{
//Login - POST (function to login client from API using Sanctum)
public function login(Request $request){
$validatedData = request()->validate([
'email' => 'required',
'password' => 'required|min:6'
]);
// get user object
$client = Client::where('email', request()->email)->first();
// do the passwords match?
if (!Hash::check(request()->password, $client->password)) {
// no they don't
return response()->json(['error' => 'Unauthorized'], 401);
}
Auth::login($client);
// get new token
$tokenResult = $client->createToken('auth_token');
// return token in json response
return response()->json(['success' => ['token' => $tokenResult]], 200);
}
//Register - POST (function to register client from API using Sanctum)
public function register(Request $request){
$validatedData = request()->validate([
'email' => 'required',
'password' => 'required|min:6',
'firstname' => 'required',
'lastname' => 'required',
]);
$data = $request->all();
// hashing client's passord
$data['password'] = Hash::make($data['password']);
// set client's status to false (Admin will set the client's status from Admin Panel)
$data['status'] = false;
$client = Client::create($data);
Auth::login($client);
// get new token
$tokenResult = $client->createToken('auth_token');
// return token in json response
return response()->json(['success' => ['token' => $tokenResult]], 200);
}
}