Reputation: 2029
I am build API endpoints using Laravel 5.8 and handling API authentication using Passport. So here's the simple logic of the React app that will be consuming the API
I have set up the endpoints like this
Route::post('register', 'BaseController@register');
Route::post('login', 'BaseController@login);
BaseController looks like this right now
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'firstname' => 'required',
'lastname' => 'required',
'username' => 'required|email',
'password' => 'required'
]);
if ($validator->fails()) {
return response()->json(['Error', $validator->errors()], 401);
}
$user = User::create([
'firstname' => $request->firstname,
'lastname' => $request->lastname,
'username' => $request->username,
'password' => bcrypt($request->password)
]);
$success['token'] = $user->createToken('Pramopro')->accessToken;
return response()->json(['success' => $success, 'message' => 'You have successfully registered'], 200);
}
public function login() {
if (Auth::attempt(['username' => request('username'), 'password' => request('password')])) {
$user = Auth::user();
$success['token'] = $user->createToken('Pramopro')->accessToken;
return response()->json(['success' => $success, 'message' => 'You have succesfully signed in.'], 200);
}
else
{
return response()->json(['error' => 'Unauthorised'], 401);
}
}
Both API endpoints work fine when tested on Postman.
Following the logic, what would be the best way to set up an API endpoint that will display the authenticated user info?
Upvotes: 0
Views: 312
Reputation: 515
For login: I suggest that you don't need to send a message back to frontend or devices. Just send the token like the following:
{
"api_token": "kdlksjdflksjdlfkjsdlkfjslkdfjskjflksdjflskdjflskdjlfksjfd"
}
You can show a success message if the status is 200 or if the value for api_token is true.
As for register: you just send a message saying success or whatever. If the status is 200 then it's understood that the user is registered.
Upvotes: 1