When the user created a new account I added it's API token and returned it to the user. But I'm having trouble wanting to return the API token to the user when they view their account information.
GET /account: Returns API Token in response.
This is my code file User.php:
public function index()
{
$users = User::where('id', auth()->user()->id)->get();
return response([
'data' => UserResource::collection($users),
'message' => 'Retrieve successfully'
], 200);
}
// POST
public function store(Request $request)
{
$data = $request->all();
$validator = Validator::make($data, [
'name' => 'required|max:255|string',
'email' => 'required|email|unique:users,email',
'password' => 'required|string',
]);
if ($validator->fails()) {
return response(['error' => $validator->errors(), 'Validation Error'], 400);
}
$users = User::create($data);
$token = $users->createToken('accessToken')->plainTextToken;
return response([
'data' => new UserResource($users),
'api_token' => $token,
'message' => 'Created successfully'
], 201);
}
This is my code file api.php (route):
Route::group(['prefix' => 'v1' ], function () {
// Account
Route::post('/account', [UserController::class, 'store']);
// Protected route
Route::group(['middleware' => ['auth:sanctum']], function () {
// Account
Route::get('/account', [UserController::class, 'index']);
});
});
Use $request->bearerToken() to get bearer token.
public function index()
{
$users = User::where('id', auth()->user()->id)->get();
return response([
'data' => UserResource::collection($users),
'api_token' => $request->bearerToken(),
'message' => 'Retrieve successfully'
], 200);
}
Related
I'm currently developing a mobile apps for my web based system. I'm using laravel as my API .
Currently, I want to do where when User A login, it will only shown User A info.
How can I achieve that ?
This is my AuthController where it generate my tokens.
public function login(Request $request)
{
try {
$validateUser = Validator::make($request->all(),
[
'username' => 'required',
'password' => 'required'
]);
if($validateUser->fails()){
return response()->json([
'status' => false,
'message' => 'validation error',
'errors' => $validateUser->errors()
], 401);
}
$user = UserRegister::where('username', $request->username)->first();
if(!$user || !Hash::check($request['password'], $user->password)) {
return response([
'message' => 'Username & Password does not match'
], 401);
}
return response()->json([
'status' => true,
'message' => 'User Logged In Successfully',
'user' => $user,
'token' => $user->createToken("remember_token")->plainTextToken
], 200);
} catch (\Throwable $th) {
return response()->json([
'status' => false,
'message' => $th->getMessage()
], 500);
}
}
This is my api routes
Route::post('/login', [AuthController::class, 'login']);
// Homepage routes
Route::group(['middleware' => ['auth:sanctum']], function () {
Route::post('/logout', [AuthController::class, 'logout']);
Route::get('/technician', [HomepageController::class, 'technician']);
});
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
and this is my HomepageController where I tried to retrieve user A data only but it does not work.
public function technician()
{
$technician=JobRegister::where('job_assign', auth()->user()->name);
return response()->json($technician);
}
This is my query for web based system.
$query = "SELECT * FROM job_register WHERE job_assign ='{$_SESSION['username']}'"
i want to make user A can only look at their job details that been assign.
do you have any idea how to do it ? your help is much appreciated. thank you.
try this
$username=Auth()->user()->userName //this will return you username of logged in user
$query = "SELECT * FROM job_register WHERE job_assign ='$username'"
don't forget to use auth namespace top of in your controller like this
use Auth;
I want to implement Passport authentication in Laravel. this is the register function:
public function register(Request $request)
{
$credentials = $request->only('name', 'email', 'password');
$rules = [
'name' => 'required|max:100',
'email' => 'required|email|max:120|unique:users',
'password' => 'required',
];
$validator = Validator::make($credentials, $rules);
if($validator->fails()) {
return response()->json(['success'=> false, 'error'=> $validator->errors()]);
}
$user = User::create(['name' => $request->name, 'email' => $request->email, 'password' => bcrypt($request->password)]);
if(Auth::attempt($credentials)){
$user = Auth::guard('api')->user();
$data['id'] = $user->id;
$data['name'] = $user->name;
$data['phone'] = $user->phone;
$data['token'] = $user->createToken('API')->accessToken;
return response()->json([
'success'=> true,
'data'=> $data
]);
}
return response()->json([
'success'=> false,
'data'=> $response
]);
}
and this is my routes:
Route::post('register', 'Api\AuthController#register');
Route::middleware('auth:api')->get('/user', function (Request $request) {
return response()->json($request->user());
});
I want to display the user information in postman, and this is the request header to the url: http://127.0.0.1:8004/api/user:
Accept:application/json
Authorization:Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiOThjYjM0YjkzOWJhMzczMDEwMGI0NmEyNTBhOGEzYTc5MTAyMjI1M2E2OTM0OGY0NGU1YWU4Njg3MzZkYmVlZjNlNzI1MDNiZTRhMjE5NGUiLCJpYXQiOjE1ODQ1NDczMDcsIm5iZiI6MTU4NDU0NzMwNywiZXhwIjoxNjE2MDgzMzA3LCJzdWIiOiI1NyIsInNjb3BlcyI6W119.GcqelFT2d3kKi8fR2vNbgMB1Fe_sQjrd2Mb3cRQLbS20IR_445bcTbcl17yKJrldboFktobeSIHx1GQENIzQbO0RStysmisiKuLk8eoXUvNVJq3t1bpZrjPBiNEGDRPqezq5VEsGhotVgbKRLK1gbVHwvE7mtSuGQTp9nIf6PEsmiJLsGmUJ0GdCmWXXLvJ0dBac1DZ_KauppDs_Lymx9SEXgzTDW60rpYrwHNbbaLfa6wdW3M5tUZM3vMRcKhCgYitvK_DfttKHcWqvEX8_lZT0h5GcQSsori_K8Lj_ynKfjrTfbodUKzT4kDZ8z-RnE4-SgG75LWDeqcpDRhuDmiL0KTIzwtrNFtU0NEo-v0t6dTkAuJCl1ZnTT72sLZoI6rsTPHtNKIDxwN9VrXiTU5pxGEc6ju5e30NQnkjBRjMRsVIcCHR-WohObuWkZOGRq-RP5on3oiLe2VGk0PENXXziMX3D5urpLWK3WR-ZY0Bz3fKitgE8TFaT1cOMSyK6d3zskUEdMjDyLCxbS7vKhmNuAy2moOj7f7DI9yr8XNeyF00WJKw0WJi76XX_Y06O-VtNhqzgeEyu6QM6qRivpBBcj-WkdbSTmveNZlSqAesLm6WD8qWKc9FR-S_41fCc2qLEY_VOotSA8tOYASVKpdsvj2liTbbMH9905HQJe-o
Content-Type:application/json
but the result is always:
{
"message": "Unauthenticated."
}
How could I display user information? thanks in advance
Change
Auth::attempt($credentials)
to
Auth::guard('api')->attempt($credentials)
I made a RegistrationRequest and a LoginRequest and when I register the user I login the user immediatly. But when I try to pass the RegistrationRequest into my LoginRequest I get the following error
Can you not pass requests on to other functions? I did it with normal requests and that worked fine, but I gues the are of the same type.
public function login(LoginRequest $request)
{
$credentials = $request->only('email', 'password');
if ($token = $this->guard()->attempt($credentials))
return $this->respondWithToken($token);
return response()->json(['error' => 'Unauthorized'], 401);
}
public function register(RegistrationRequest $request)
{
$user = User::create([
'user_name' => $request->user_name,
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'email' => $request,
]);
return response()->json([
'success' => true,
'data' => $user,
'meta' => $this->login($request),
], 200);
}
As the title says CreateFreshApiToken doesnt create any cookies. So I cant use it to auth a logged in user for other requests related to the user.
I tried to set a cookie on the response and it works perfectly fine. So this has to do something with CreateFreshApiToken not working.
AuthController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;
class AuthController extends Controller
{
public function signup(Request $request)
{
$request->validate([
'name' => 'required|string',
'email' => 'required|string|email|unique:users',
'password' => 'required|string'
]);
$user = new User([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password)
]);
$user->save();
return response()->json([
'message' => 'Successfully created user!'
], 201);
}
public function signin(Request $request)
{
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string'
]);
$credentials = request(['email', 'password']);
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
$token->save();
return response()->json([
'message' => 'Successfully signed in!'
]);
}
public function signout(Request $request)
{
$request->user()->token()->revoke();
return response()->json([
'message' => 'Successfully signed out!'
]);
}
public function user(Request $request)
{
return response()->json($request->user());
}
public function test()
{
return response()->json([
'message' => 'test'
]);
}
public function test2(Request $request)
{
return response()->json([
'laravel_token' => $request->cookie('laravel_token')
]);
}
}
Kernel.php
protected $middlewareGroups = [
'web' => [
//...
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
'api' => [
'throttle:60,1',
'bindings',
\Barryvdh\Cors\HandleCors::class,
],
];
api.php
Route::group([
'prefix' => 'auth'
], function () {
Route::post('signin', 'AuthController#signin');
Route::post('signup', 'AuthController#signup');
Route::get('test', 'AuthController#test');
Route::get('test2', 'AuthController#test2');
Route::group([
'middleware' => ['auth:api']
], function() {
Route::get('signout', 'AuthController#signout');
Route::get('user', 'AuthController#user');
});
});
And this is my angular code:
test() {
return this.http.get('http://homestead.test/api/auth/test', {withCredentials: true})
.subscribe(response => {
console.log(response);
});
}
test2() {
return this.http.get('http://homestead.test/api/auth/test2', {withCredentials: true})
.subscribe(response => {
console.log(response);
});
}
I've also setup cors with https://github.com/barryvdh/laravel-cors successfully with 'supportsCredentials' enabled. I am also sending a useless GET request to see if any laravel_token is set in the cookie but no success.
CreateFreshApiToken is part of the web middleware group, so in order for it to set cookies you need your login page to be a web route (instead of an api route).
I resolved this part of the problem by replicating CreateFreshApiToken::handler in my login controller:
$response = response()->json([], 200);
// ADDÂ THISÂ LINE:
$response->cookie(\Laravel\Passport\Passport::cookie(),$request->session()->token();
return $response;
I'm using laravel with JWT Auth to connect my laravel project to mobile, this is my api controller at laravel
public function login(Request $request) {
$credentials = $request->only('email', 'password');
try {
// attempt to verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return response()->json(['error' => 'could_not_create_token'], 500);
}
// all good so return the token
$user = Sentry::authenticate($credentials, false);
return response()->json([
'code' => '200',
'message' => 'success',
'last_updated' => $user->updated_at->format("Y-m-d\TH:i:s\Z"),
'data' => [
'id' => $user->id,
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'email' => $user->email,
'username' => $user->username,
'token' => $token
]
]);
}
but how to set the credentials using email or username with this JWT?
If you are using "tymon/jwt-auth" package, then you can just pass the user object to the JWTAuth class and bam!, you can get the JWT token in return which you can use to make user go through the app.
$user = User::where('email', $email)
->orWhere('username', $username)
->first();
$token = null;
if (!$token = JWTAuth::fromUser($get_info)) {
return $this->respondInternalError( 'Can\'t generate the JWT token right now, try again later!', 'object', 400);
}
return response()->json([
'code' => '200',
'message' => 'success',
'last_updated' => $user->updated_at->format("Y-m-d\TH:i:s\Z"),
'data' => [
'id' => $user->id,
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'email' => $user->email,
'username' => $user->username,
'token' => $token
]
]);
You can login using email or using the following format
public function login(Request $request)
{
//validate incoming request
$this->validate($request, [
'email_phone' => 'required|string',
'password' => 'required|string',
]);
try {
$login_type = filter_var( $request->email_phone, FILTER_VALIDATE_EMAIL ) ? 'email' : 'phone';
// return $login_type;
$credentials = [$login_type => $request->email_phone, 'password'=>$request->password];
if (! $token = Auth::attempt($credentials)) {
return response()->json($this->customResponse("failed", "Unauthorized"), 401);
}
return $this->respondWithToken($token);
} catch(JWTException $e) {
return response()->json($this->customResponse("failed", "An error occured, please contact support.", $user), 500);
}
}