|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Http\Controllers\Api; |
| 4 | + |
| 5 | +use App\Data\Models\User; |
| 6 | +use App\Exceptions\Auth\InvalidCredentialsException; |
| 7 | +use Illuminate\Http\Request; |
| 8 | +use Tymon\JWTAuth\JWTAuth; |
| 9 | + |
| 10 | +class AuthController extends Controller |
| 11 | +{ |
| 12 | + public function register(Request $request) |
| 13 | + { |
| 14 | + $this->validate($request, [ |
| 15 | + 'name' => 'required|max:255', |
| 16 | + 'email' => 'required|email|max:255|unique:users', |
| 17 | + 'password' => 'required|min:6', |
| 18 | + ]); |
| 19 | + |
| 20 | + $user = User::create( |
| 21 | + [ |
| 22 | + 'email' => $request->email, |
| 23 | + 'name' => $request->name, |
| 24 | + 'password' => bcrypt($request->password) |
| 25 | + ]); |
| 26 | + return $user; |
| 27 | + } |
| 28 | + |
| 29 | + public function login(Request $request) |
| 30 | + { |
| 31 | + //Retrieve user based on the credentials provided |
| 32 | + $user = $this->authenticateUser($request); |
| 33 | + //Generate a token for the user and return it |
| 34 | + $token = app(JWTAuth::class)->fromUser($user); |
| 35 | + return ['token' => $token]; |
| 36 | + } |
| 37 | + |
| 38 | + |
| 39 | + private function authenticateUser($request) |
| 40 | + { |
| 41 | + //Validate request data |
| 42 | + $this->validate($request, [ |
| 43 | + 'email' => 'required|email', |
| 44 | + 'password' => 'required', |
| 45 | + ]); |
| 46 | + |
| 47 | + //Check if a user with this credentials exist, throw error if not |
| 48 | + if (!\Auth::guard()->attempt($request->only('email', 'password'))) { |
| 49 | + throw new InvalidCredentialsException('Invalid email/password combination'); |
| 50 | + } |
| 51 | + |
| 52 | + //Retrieve the user details and return |
| 53 | + return User::where('email', $request->email)->first(); |
| 54 | + } |
| 55 | +} |
0 commit comments