63 lines
1.8 KiB
PHP
63 lines
1.8 KiB
PHP
|
<?php
|
||
|
namespace App\Http\Controllers\API;
|
||
|
|
||
|
use App\Http\Controllers\Controller;
|
||
|
use Illuminate\Http\Request;
|
||
|
use Illuminate\Support\Facades\Hash;
|
||
|
use Auth;
|
||
|
use Validator;
|
||
|
use App\Models\User;
|
||
|
use App\Http\Resources\UserResource;
|
||
|
|
||
|
class AuthController extends Controller
|
||
|
{
|
||
|
public function register(Request $request)
|
||
|
{
|
||
|
$validator = Validator::make($request->all(),[
|
||
|
'name' => 'required|string|max:255',
|
||
|
'email' => 'required|string|email|max:255|unique:users',
|
||
|
'password' => 'required|string|min:8'
|
||
|
]);
|
||
|
|
||
|
if($validator->fails()){
|
||
|
return response()->json($validator->errors());
|
||
|
}
|
||
|
|
||
|
$user = User::create([
|
||
|
'name' => $request->name,
|
||
|
'email' => $request->email,
|
||
|
'password' => Hash::make($request->password)
|
||
|
]);
|
||
|
|
||
|
$token = $user->createToken('auth_token')->plainTextToken;
|
||
|
|
||
|
return response()
|
||
|
->json(['data' => $user,'access_token' => $token, 'token_type' => 'Bearer', ]);
|
||
|
}
|
||
|
|
||
|
public function login(Request $request)
|
||
|
{
|
||
|
if (!Auth::attempt($request->only('username', 'password')))
|
||
|
{
|
||
|
return response()
|
||
|
->json(['message' => 'Unauthorized'], 401);
|
||
|
}
|
||
|
|
||
|
$user = User::where('username', $request['username'])->firstOrFail();
|
||
|
|
||
|
$token = $user->createToken('auth_token')->plainTextToken;
|
||
|
|
||
|
return response()
|
||
|
->json(['message' => 'Hi '.$user->name.', welcome to home','access_token' => $token, 'token_type' => 'Bearer', ]);
|
||
|
}
|
||
|
|
||
|
// method for user logout and delete token
|
||
|
public function logout()
|
||
|
{
|
||
|
auth()->user()->tokens()->delete();
|
||
|
|
||
|
return [
|
||
|
'message' => 'You have successfully logged out and the token was successfully deleted'
|
||
|
];
|
||
|
}
|
||
|
}
|