megahunt.test/app/Services/UserService.php

56 lines
1.3 KiB
PHP

<?php
namespace App\Services;
use App\Models\User;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
class UserService
{
/**
* Create(register) new user
* @param array $data This is expected to be validated already
* @return User
*/
public function create($data, $autoLogin = true): User
{
if (User::where([ 'email' => $data['email'] ])->count() !== 0) {
throw new HttpResponseException(response()->json('email_taken', 400));
}
$data['password'] = Hash::make($data['password']);
$user = User::create($data);
if ($autoLogin) {
Auth::login($user);
}
return $user;
}
/**
* Login to user
* @param array $data This is expected to be validated already
* @return User
*/
public function login($data): bool
{
if (Auth::attempt($data)) {
request()->session()->regenerate();
return true;
}
return false;
}
public function reset($data)
{
$user = User::where([ 'email' => $data['email'] ])->first();
if ($user === null) {
return;
}
$user->password = Hash::make($data['password']);
$user->save();
}
}