Laravel Authentication and routing with socialite - laravel

Somebody please help me. I am trying to implement Socialite Authentication, everything works fine but routes under Auth is not working.They are redirect back to login page.What is problem with my Auth or Routes. My Route and Controller files are below
Route::group(['middleware' => ['web']], function () {
Route::get('facebook',array(
'as' => 'facebook',
'uses' =>'FacebookController#redirectToProvider'
));
Route::get('Callback', 'FacebookController#handleProviderCallback');
});
Route::group(['middleware' => ['web','auth']], function () {
Route::get('play', function () {
return view('landing');
});
Route::get('go', function () {
return view('landing');
});
});
Controller
public function handleProviderCallback()
{
try
{
$user = Socialize::with('facebook')->user();
}
catch (Exception $e)
{
return Redirect::to('login');
}
$authUser = $this->findOrCreateUser($user);
Auth::login($authUser, true);
$user = Auth::user();
return Redirect::to('play');
}
private function findOrCreateUser($facebookUser)
{
if ($authUser = User::where('id', $facebookUser->getId())->first())
{
return $authUser;
}
return User::create([
'id' => $facebookUser->getId(),
'name' => $facebookUser->getName(),
'email' => $facebookUser->getEmail(),
'gender' => $facebookUser->user['gender'],
'avatar' => $facebookUser->getAvatar(),
'avatar_original' => $facebookUser->avatar_original,
'verified' => $facebookUser->user['verified']
]);
}

Related

how to retrieve user info using laravel auth sanctum API

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;

GET /account: Returns API Token on response

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);
}

Laravel validation weird behavior

i'm validating a form with this:
public function update(UpdateExamenRequest $examenRequest, UpdateResultadoRequest $resultadoRequest)
{
$examenRequest->validated();
$resultadoRequest->validated();
This are the rules in UpdateExamenRequest
public function rules()
{
$this->redirect = url()->previous();
return [
'Paciente_id' => 'required|string|max:10',
'Examen_id' => 'required|string|max:10',
'Nombre' => 'required|string|max:50',
'Descripcion' => 'nullable|string',
];
}
public function messages()
{
return [
'Paciente_id.required' => __('Paciente_id.required'),
'Examen_id.required' => __('Examen_id.required'),
'Nombre.required' => __('Nombre.required'),
'Nombre.string' => __('Nombre.string'),
'Nombre.max' => __('Nombre.max'),
'Descripcion.string' => __('Descripcion.string'),
];
}
My routes:
Route::get('/', function () {
return view('auth.login');
})->middleware('guest');;
Route::get('/welcome', function () {
return view('welcome');
})->name('welcome');
Route::get('/dashboard', function () {
return view('dashboard');
})->middleware(['auth'])->name('dashboard');
require __DIR__ . '/auth.php';
Route::resource('pacientes', PacientesController::class)->middleware('auth');
Route::resource('examenes', ExamenesController::class)->middleware('auth');
Route::resource('resultados', ResultadoController::class)->middleware('auth');
i'm having a situation, and i've really don't know whats happening. The validation sends me to the show view, that i haven't created yet, there is a video: https://youtu.be/S-PtTdUH13Y

Why is not redirected to home after login?

auth()->attempt($credentials, true) is working but its redirecting to /login however! I didn't do anything like that in middleware for example. Can anyone knows what is going on? Thanks
LoginController
public function login(Request $request)
{
$this->validateLogin($request);
$credentials = $request->only('email', 'password');
if (auth()->attempt($credentials, true)) {
// return 'it works';
return redirect()->to('/');
}
return redirect()->back()->withErrors([
'msg' => trans('labels.others.credentials_not_valid')
]);
}
Routes
Route::group(['middleware' => 'auth'], function () {
Route::get('/', ['as' => 'home', 'uses' => 'HomeController#index']);
});

CreateFreshApiToken doesn't create the laravel_token cookie

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;

Resources