How to login right after registration in Laravel? - laravel

I am trying to register a new user into my system, and right after make the login automatically. How can I call another function in the same Controller and pass $request variables to it?
I did the var_dump, login function is getting data, the login is being made, but it's not redirecting to index (line 28)
public function login(Request $request)
{
//var_dump($request->only('email', 'password'));
$credentials = [
'email' => $request->email,
'password' => $request->password,
];
if(Auth::attempt($credentials)) {
return redirect()->route('movie.index');
}
return redirect()->route('login')->with([
'error' => 'danger',
'msg' => 'Error message',
]);
}
public function register(Request $request)
{
$newUser = new User;
$newUser->name = $request->name;
$newUser->email = $request->email;
$newUser->password = Hash::make($request->password);
$newUser->save();
$this->login($request);
}

Right way is
Auth::login($newUser);
Then redirect to your page after login.

Related

Laravel Auth::attempt ans Hash::check not working

I try make rest API with Laravel 8 + Sanctum. And my database is MySql Maria DB.
I create LoginController and make function call login. When i try my API, it's always return Unauthorized. I pretty sure my USERNAME and PASSWORD is correct.
This is my LoginController
public function store(Request $request) {
$user = User::create(
[
"USERNAME" => $request->username,
"PASSWORD" => Hash::make($request->password),
"ADM_MST_SITE_ID" => 0,
]
);
$token = $user->createToken('apiToken')->plainTextToken;
$res = [
'user' => $user,
'token' => $token
];
return response($res, 201);
}
public function login(Request $request)
{
$data = $request->validate([
'username' => 'required|string',
'password' => 'required|string'
]);
$user = User::where('username', $data['username'])->first();
$credentials = request(['username', 'password']);
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$token = $user->createToken('apiToken')->plainTextToken;
$res = [
'user' => $user,
'token' => $token
];
return response($res, 201);
}
Model
////
protected $table = 'adm_mst_user';
protected $guarded = ['ID'];
public function getAuthPassword()
{
return $this->PASSWORD;
}
////
The store function is work well, the new data are inserted to my database. But, when i login with username and password, it's not working.
I try 2 different auth check, using Auth::attempt and Hash::check.
I don't know where the error coming from. It's always return Unauthorized.
$user = User::where('username', $data['username'])->first();
$this->guard()->login($user);
and make a guard function in same controller
protected function guard()
{
return Auth::guard();
}
import use Illuminate\Support\Facades\Auth; in top
include
use Illuminate\Support\Facades\Hash;
You need to make it with email not with username
$credentials = request(['email', 'password']);
OR, modify your attempt code
if(!Auth::attempt(['username' => $credentials['username'], 'password' => $credentials['password']))
this code worked with sanctum
use App\Models\User;
use Illuminate\Support\Facades\Hash;
function login($candidate)
{
$user = User::where('username', $candidate['username'])->first();
if (!$user || !Hash::check($candidate['password'], $user->password)) {
return [
'message' => 'These credentials do not match our records.'
];
}
$token = $user->createToken('my-token')->plainTextToken;
return [
'user' => $user,
'token' => $token
];
}

Verify Token is Token Laravel Passport

I was recently updating from laravel's sanctum to passport; and there is this one test that bothers me a lot.
In sanctum there is this method under the PersonalAccessToken model that finds the token and returns the token if it exists.
I don't seem to find anything like that in the docs or online.
I'm validating the test by asserting that $user->tokens is not empty... yet I wish to validate that the token I'm returning from my login controller is indeed a token; not just the creation;
Thnx in advance...
Login Test
public function user_can_login()
{
//$this->withoutExceptionHandling();
$user = User::factory()->create();
$url = route('api.v1.auth.login', [
'email' => $user->email,
'password' => 'password'
]);
$res = $this->jsonApi()
->post($url)
->assertStatus(200);
$token = $res->json(['access_token']);
$this->assertNotEmpty($user->tokens);
}
Login method in authcontroller
public function login(Request $request)
{
$request->validate([
'email' => 'required|email',
'password' => 'required',
]);
$credentials = $request->only(['email', 'password']);
if (Auth::attempt($credentials)) {
$user = Auth::user();
$access_token = $user->createToken('laravel-api.local')->accessToken;
return response()->json(['access_token' => $access_token], 200);
} else {
return response()->json(['error' => 'Unauthorized'], 401);
}
}
pues:dont know why im writing the code, but just for ref of what i'm doing
https://laracasts.com/discuss/channels/testing/how-do-i-create-a-route-while-testing
solution is quite simple... you'll find it here... I had an issue when I tried that before hand and it seems to be with the use of the Route::name('name') method and the route('name') function threw a server error. but if you call the path directly it should work...
any who... authController and login method stay the same but the test changes to...
public function setUp(): void
{
parent::setUp();
Route::middleware('auth:api')
->get('/test-route', function (Request $request) {
return $request->user();
});
$clientRepository = new ClientRepository();
$client = $clientRepository->createPersonalAccessClient(
null,
'Personal Access Client Test',
'/'
);
DB::table('oauth_personal_access_clients')->insert([
'client_id' => $client->id,
'created_at' => date('Y-m-d'),
'updated_at' => date('Y-m-d'),
]);
}
/** #test */
public function user_can_login_with_correct_credentials()
{
//$this->withoutExceptionHandling();
$user = User::factory()->create();
$url = route('api.v1.auth.login', [
'email' => $user->email,
'password' => 'password',
'device_name' => $user->name . ' test Device'
]);
$res = $this->jsonApi()
->post($url)
->assertStatus(200);
$token = $res->json(['access_token']);
$this->jsonApi()
->withHeader('Authorization', 'Bearer ' . $token)
->get('/test-route')
->assertStatus(200);
}

How to redirect the user back to intended route after social login?

This is my code in LoginController:
public function handleProviderCallback($provider)
{
$socialUser = Socialite::driver($provider)->stateless()->user();
$user = User::where('email', $socialUser->getEmail())->first();
if (!$user) {
$user = User::create([
'name' => $socialUser->getName(),
'email' => $socialUser->getEmail(),
'password' => Hash::make('12345678'),
'social_id' => $socialUser->getId(),
]);
}
Auth::login($user, true);
return redirect()->intended($this->redirectPath());
}
When performing normal login, it redirects to intended. But, in case of social login, it doesn't. What could be the cause?
I had a similar problem. You have to store the path you want to redirect in a session and then redirect the the path intended. I am also using the Socialite. Here is how I solved it.
public function redirect($provider)
{
session()->put('intended_url', url()->previous());
return Socialite::driver($provider)->redirect();
}
public function callback(Request $request, $provider){
$intendedUrl = session('intended_url');
if (!$request->has('code') || $request->has('denied')) {
return redirect('/');
}
$userSocial = Socialite::driver($provider)->stateless()->user();
$users = User::where(['email' => $userSocial->getEmail()])->first();
if($users){
Auth::login($users);
return redirect()->intended($intendedUrl);
}else{
$user = User::create([
'name' => $userSocial->getName(),
'email' => $userSocial->getEmail(),
'provider_id' => $userSocial->getId(),
'provider' => $provider,
]);
Auth::login($user);
return redirect()->intended($intendedUrl);
}
}
Before the redirect I store the previous route and then I use it. So no matter from which URL the user signs in, it will be redirected to the same page.
Check your url()->previous() in my case I actually needed the current url. So I used session()->put('intended_url', url()->full()); in the controller I hit and after lgoin redirect to this url as in the example.
Also you need to use Session::forget('intended_url'); afeter assigning it to variable.

Can't login with the correct credentials of a user created from admin panel

I created a UserController where admin can create a user with special privileges, asides from the Laravel Automatic register page, the issue is user creation works fine via the UserController but I can't sign in with the details I used when creating the account. Would appreciate any help I can find on here.
public function create()
{
//
$privileges = privilege::all();
$courses = course::all();
return view('tutor.create')->with('privileges', $privileges)->with('courses',$courses);
}
public function store(Request $request)
{
//
$this->validate($request,[
'name' => 'required',
'email' => 'required',
'password' => 'required',
]);
$users = new User;
$users->name = $request->input('name');
$users->email = $request->input('email');
$users->password = \Hash::make($request['password']);
$users->privilege_id = $request->input('privilege_id');
$users->save();
$course = $request->get('course');
$users->courses()->attach($course);
return redirect('/tutor')->with('success','User created');
}

Auto login after register in laravel 5.7

I want when I finished register it redirects me to the dashboard page (Auto login after the register).
this is the user register code :
public function store(Request $request)
{
$this->validator($request->all())->validate();
$apprenant = Apprenant::create([
'nom' => $request['nom'],
'prenom' => $request['prenom'],
'email' => $request['email'],
'niveau' => $request['niveau'],
'password' => Hash::make($request['password']),
]);
return redirect('/apprenant/dashboard');
}
But when I finished registring it redirects me to the login page
Hi if you are create a guard then run this code for after register login
Auth::guard(guard_name)->loginUsingId($id);
// example
public function register(Request $req)
{
$user = new User; // define here your model
$user->name = $req->name;
$user->email = $req->email;
$user->password = Hash::make($req->password);
if($user->save()){
Auth::guard(guard_name)->loginUsingId($user->id);
}
}
// logout overite
public function logout()
{
Auth::guard('guard_name')->logout();
return redirect("login_path");
}
When creating a new user, create() method, should return a new model object.
Use Auth::loginUsingId($apprenant->id); before redirecting to dashboard:
public function store(Request $request)
{
$this->validator($request->all())->validate();
$apprenant = Apprenant::create([
'nom' => $request['nom'],
'prenom' => $request['prenom'],
'email' => $request['email'],
'niveau' => $request['niveau'],
'password' => Hash::make($request['password']),
]);
Auth::loginUsingId($apprenant->id);
return redirect('/apprenant/dashboard');
}
source
https://laravel.com/docs/5.7/authentication#other-authentication-methods
Write this line before redirecting to the dashboard:
\Auth::login($apprenant);
or just,
auth()->login($apprenant);
That means, you code will look like:
public function store(Request $request)
{
$this->validator($request->all())->validate();
$apprenant = Apprenant::create([
'nom' => $request['nom'],
'prenom' => $request['prenom'],
'email' => $request['email'],
'niveau' => $request['niveau'],
'password' => Hash::make($request['password']),
]);
//login the user
\Auth::login($apprenant);
return redirect('/apprenant/dashboard');
}

Resources