You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
95 lines
2.9 KiB
95 lines
2.9 KiB
<?php |
|
|
|
namespace App\Http\Controllers\Api; |
|
|
|
use App\Models\{User, Role}; |
|
use Illuminate\Http\Request; |
|
use App\Http\Controllers\Controller; |
|
use Illuminate\Support\Facades\{Auth, Validator}; |
|
|
|
class AuthController extends Controller |
|
{ |
|
/** |
|
* Handle the incoming request. |
|
* |
|
* @param \Illuminate\Http\Request $request |
|
* @return \Illuminate\Http\Response |
|
*/ |
|
public function __invoke(Request $request) |
|
{ |
|
$validator = Validator::make($request->all(), [ |
|
'username' => 'required|string', |
|
'password' => 'required|string', |
|
'remember' => '', |
|
'is_mobile' => '' |
|
]); |
|
|
|
if ($validator->fails()) { |
|
return response()->json(['status' => 'error', 'message' => 'You must fill all the fields'], 400); |
|
} |
|
$validated = $validator->safe()->only(['username', 'password']); |
|
|
|
$username = $validated['username']; |
|
$password = $validated['password']; |
|
$remember = $request->remember; |
|
$is_mobile = $request->is_mobile; |
|
|
|
$usernameCheck = false; |
|
$passwordCheck = false; |
|
if (User::query()->where('username', '=', $username)->exists()) : |
|
$usernameCheck = true; |
|
endif; |
|
|
|
if (User::query()->where('password', '=', md5($password))->exists()) : |
|
$passwordCheck = true; |
|
endif; |
|
|
|
if ($usernameCheck & $passwordCheck) { |
|
$user = User::query()->where([ |
|
['username', '=', $username], |
|
['password', '=', md5($password)] |
|
])->first(); |
|
|
|
if ($is_mobile) { |
|
$fcm_token = $request->fcm_token; |
|
|
|
if (!$fcm_token || empty($fcm_token)) : |
|
return response()->json(['status' => 'error', 'message' => 'FCM Token is required'], 400); |
|
endif; |
|
|
|
$hr = User::query()->findOrFail($user['id']); |
|
|
|
if ($hr->exists()) { |
|
$hr->update(["fcm_token" => $fcm_token]); |
|
} |
|
} |
|
|
|
$dataRole = Role::query()->findOrFail($user['role_id']); |
|
|
|
if ($dataRole->exists()) { |
|
$user['role'] = $dataRole; |
|
} |
|
|
|
if (!$token = Auth::login($user)) { |
|
return response()->json(['error' => 'Unauthorized'], 401); |
|
} |
|
|
|
$ttl = 60; |
|
if ($remember) { |
|
$ttl = 10080; |
|
} |
|
|
|
return response()->json([ |
|
'code' => 200, |
|
'data' => array( |
|
'data_user' => $user, |
|
'access_token' => $token, |
|
'token_type' => 'bearer', |
|
'expires_in' => auth()->factory()->getTTL() * $ttl |
|
) |
|
]); |
|
} else { |
|
return response()->json(['code' => 201, 'message' => "username or password doesn't match"], 201); |
|
} |
|
} |
|
}
|
|
|