After installing the tymon/jwt
package and assigning a token to each user, does the following code, which is related to displaying user information using the token, automatically identify the request and user through the token or not?
auth()->user()
The reason for this question is that I use the following code to generate a token:
$token = auth()->login($user);
And I want to know if Laravel creates a session for this login or not. Therefore, if it does not create a session, it should automatically identify and display user information by reading the information sent by the token on the server side. This issue has confused me a bit.
The codes I have written to implement this scenario are as follows:
class AuthController extends Controller
{
protected ?JWTSubject $user = null;
public function __construct()
{
$this->middleware('auth:api', ['except' => ['signup', 'login', 'refresh_token']]);
}
public function signup(Request $request): JsonResponse
{
$validator = Validator::make($request->all(), [
'username' => 'required',
'password' => 'required',
'member_type' => 'required'
]);
if ($validator->fails()) {
return response()->json(
[
'status' => false,
'errors' => $validator->errors()
],
Response::HTTP_BAD_REQUEST
);
}
$credentials = [
'username' => $request['username'],
'password' => $request['password'],
];
$message = 'user logged successful';
$user = User::whereUsername($request->username)->first();
if ($user) {
if (!Auth::attempt($credentials)) {
return response()->json(
[
'message' => 'Username or Password is not correct',
], Response::HTTP_UNAUTHORIZED
);
}
} else {
$user = new User();
$user->username = $request->username;
$user->password = bcrypt($request->password);
$user->save();
$profile = new Profile();
$profile->member_type = $request->get('member_type');
$user->profile()->save($profile);
$profile->activation_code()->save($activation_code);
$response = Response::HTTP_CREATED;
$message = 'user created successful';
}
$token = auth()->login($user);
return $this->respondWithToken($token, $message, $response ?? Response::HTTP_OK);
}
public function who_am_i(Request $request): JsonResponse
{
//dd(auth()->user());
return response()->json(User::with(
[
'profile.address',
'profile.payment_method',
]
)->whereId(JWTAuth::parseToken()->authenticate()->id)->first());
}
public function refresh_token(): JsonResponse
{
return $this->respondWithToken(auth()->refresh(), 'new token for user created successful', $response ?? Response::HTTP_OK, false);
}
protected function respondWithToken($token, $message = '', $status = Response::HTTP_OK, $attach_user_info = true): JsonResponse
{
$data = [
'message' => $message,
'access_token' => $token,
];
$user = User::with(
[
'profile.address',
'profile.payment_method',
]
)->whereId(auth()->user()->id)->first();
if ($attach_user_info) {
$data = array_merge($data, [
'user'=>$user
]);
}
return response()->json($data, $status);
}
}