I am using Socialite for user logins and I would like to set a remember_token to remember the user when they login through Socialite.
Right now I have the following service to create or log the user in:
class SocialAccountService {
public function createOrGetUser(ProviderUser $providerUser) {
$account = SocialAccount::whereProvider('google')
->whereProviderUserId($providerUser->getId())
->first();
if ($account) {
return $account->user;
} else {
$account = new SocialAccount([
'provider_user_id' => $providerUser->getId(),
'provider' => 'google'
]);
$user = User::whereEmail($providerUser->getEmail())->first();
if (!$user) {
$user = User::create([
'email' => $providerUser->getEmail(),
'name' => $providerUser->getName()
]);
}
$account->user()->associate($user);
$account->save();
return $user;
}
}
}
It is called with the following controller:
class AuthController extends Controller {
public function logout() {
Auth::logout();
return redirect('/');
}
public function redirectToGoogle() {
return Socialite::driver('google')->redirect();
}
public function handleGoogleCallback(SocialAccountService $service) {
$user = $service->createOrGetUser(Socialite::driver('google')->user());
auth()->login($user);
return redirect('/');
}
}
The issue is that when the user comes back they are not remembered and automatically logged in. How can I do this with Socialite?
According to the documentation, passing true as the second argument of login() will set the remember token.
// Login and "remember" the given user... Auth::login($user, true);
The Auth facade and auth() helper function access the same object.
Related
This is how I would make such a function
Controller code
public function store(RegistrationStoreRequest $request){
$user = User::create($request->validated());
Auth::login($user);
return redirect()->home();
}
This is my Request form code
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed'
];
}
You have two options:
Create a value mutator:
public function setPasswordAttribute($value) {
$this->attributes['password'] = Hash::make($value);
}
however you need to ensure you never prehash the password.
Hash in controller
public function store(RegistrationStoreRequest $request){
$user = User::create(array_merge(Arr::except($request->validated(), 'password'), [ 'password' => Hash::make($request->password) ]));
Auth::login($user);
return redirect()->home();
}
The easiest and most clean way is to use a custom cast for password field, first create UserPasswordCast.php class:
<?php
//app/Casts/UserPasswordCast.php
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Support\Facades\Hash;
class UserPasswordCast implements CastsAttributes
{
public function get($model, $key, $value, $attributes)
{
return $value;
}
public function set($model, $key, $value, $attributes)
{
//return hashed value
return Hash::make($value);
}
}
Suggested location:
app/Casts/UserPasswordCast.php
Then update your 'user' model to use this cast, add "$casts" array or update it if existed:
use App\Casts\UserPasswordCast;
...
protected $casts = [
...
'password' => UserPasswordCast::class
];
That's it, you don't have to worry about password again
Just save your user model as it:
public function store(RegistrationStoreRequest $request)
{
$user = User::create($request->validated());
Auth::login($user);
return redirect()->home();
}
For more info please check:
https://laravel.com/docs/8.x/eloquent-mutators#custom-casts
=>create method function add in User.php(Model).
public static function create($user, $request)
{
if (isset($request->name)) {
$user->name = $request->name;
}
if (isset($request->email)) {
$user->email = $request->email;
}
if (isset($request->password)) {
$user->password = bcrypt($request->password);
}
if (isset($request->confirmpassword)) {
$user->confirmpassword = $request->confirmpassword;
}
$user->save();
return $user;
}
=>New user create with validate your all request field.
public function store(RegistrationStoreRequest $request){
$user = User::create(New User,$request);
Auth::login($user);
return redirect()->home();
}
Please try this code it is working.
I'm facing login page again and again when try to go to the homepage. I didn't add any middleware to homepage route but still I'm facing this issue.
My Login Controller
protected $redirectTo = '/';
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function redirectToProvider()
{
return Socialite::driver(request()->provider)->redirect();
}
public function handleProviderCallback()
{
$provider = request()->provider;
$providerUser = Socialite::driver($provider)->user();
if($providerUser->getEmail() == null) {
$user = User::where($provider . '_id', $providerUser->getId())->first();
} else {
$user = User::where('email', $providerUser->getEmail())->first();
}
if($user && $user->$provider . '_id' == null) {
dd('test');
$user->update([$provider . '_id' => $providerUser->getId()]);
}
if(!$user) {
$user = User::create([
'email' => $providerUser->getEmail(),
'name' => $providerUser->getName(),
$provider . '_id' => $providerUser->getId(),
]);
}
auth()->login($user, true);
return redirect($this->redirectTo);
// $user->token;
}
public function showLoginForm()
{
session()->put('previousUrl', url()->previous());
return view('auth.login');
}
public function redirectTo()
{
return str_replace(url('/'), '', session()->get('previousUrl', '/'));
}
I don't know the issue is in controller or in routes.
Routes
Route::get('/', 'WelcomePageController#index')->name('welcome');
Auth::routes();
Route::get('/login/{provider}', 'Auth\LoginController#redirectToProvider');
Route::get('/login/{provider}/callback', 'Auth\LoginController#handleProviderCallback');
I can visit the homepage only when I logged in but I want to see it as a guest.
The home route is protected, you can see this in construct method of HomeController. To make it unprotected, try to comment the line in constrct method.
To prevent errors in home view, you have to edit this view too.
I upgraded:
"tymon/jwt-auth": "0.5.*",
from a very old version, and it seems like the API has changed. I managed to fix the login, using:
public function login(Request $request)
{
$credentials = $request->only(['username', 'password']);
$validator = Validator::make($credentials, [
'username' => 'required',
'password' => 'required',
]);
if($validator->fails()) {
throw new ValidationHttpException($validator->errors()->all());
}
if (!$token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
$user = auth()->user();
$user->ip_address = $request->ip();
if ($request->device_token)
$user->device_token = $request->device_token;
$user->save();
$data['token'] = $token;
$data['email'] = $user->email;
return response()->json($data);
}
So my login work, but all API's that required the token - fail now.
Example of API that fail:
class UserController extends Controller
{
public function __construct()
{
// $this->middleware('auth:api', ['except' => ['login']]);
}
public function enterWorld(Request $request)
{
$token = $request->input('token');
$user = JWTAuth::toUser($token);
return $user;
}
Any idea how to convert the token from the request to the user with the new API?
I couldn't find any docs about it.
I tried:
return response()->json(auth()->user());
but in this API it return empty array. only in login it works.
Try the following:
$user = JWTAuth::setRequest($request)->user();
You may also explicitly set the guard when using the following syntax:
// pass the guard in to the auth() helper.
return response()->json(auth('jwt')->user());
Beware with me for a second as I try to lay the background to my issue.
So I having using the python web framework Flask close to a year now and it has a wonderful extension called Flask-Login that helps provide user session management kind of like this in laravel.
Having said all that, there is a certain feature in Flask-Login that provides the functionality that when a user is not logged or signed in and tries to access that a page that requires one to be authenticated for example /create_post, they will be redirected back to the login page with that page encoded in the query string like /login?next=%2Fcreate_post.
Am trying to implement the same feature in a laravel project that am working on so I can redirect the user to the page they probably wanted to go to in the first place or to a different route in case that query string doesn't exist and I cannot seem to find where to put my code to do just that and I don't want to mess with anything in the vendor directory(because of the obvious issues that come with that), and I have tried manipulating the file app/Http/Middleware/RedirectIfAuthenticated.php by doing what is below but with no success.
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/');
}
$previous_url = url()->previous(); // how do I insert this in query string
return $next($request);
}
Will I have to create my own middleware or is there another way of implementing this kind of feature in laravel?
NOTE: I am not using the default laravel authentication system. I have created my own controller SessionsController to handle logins which contains the below code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class SessionsController extends Controller
{
public function __construct()
{
$this->middleware('auth')->except(['create', 'login']);
}
public function create()
{
$data = [
'title' => 'Login',
'body_class' => 'hold-transition login-page',
];
return view('auth.login', $data);
}
public function login(Request $request)
{
$this->validate($request, [
'username' => 'required',
'password' => 'required',
]);
$user = User::checkCredentials($request->username, $request->password);
if (!$user) {
return back()->with([
'class' => 'alert-danger',
'message' => 'Please check your credentials',
]);
}
// set session active flag to true
$user->session_active = true;
$user->save();
auth()->login($user);
return redirect()->route('dashboard');
}
public function destroy()
{
$user = auth()->user();
$user->last_login = date('Y-m-d H:i:s');
$user->session_active = false;
$user->save();
auth()->logout();
return redirect()->route('login')->with([
'class' => 'alert-success',
'message' => 'You logged out successfully',
]);
}
}
Thank you.
I managed to somewhat solve my issue even though I didn't use query strings as I had wanted.
I create a helper function get_previous_url as shown below
/**
* Gets the previous url
*
* #return null|string
*/
function get_previous_url()
{
$host = $_SERVER['HTTP_HOST'];
$previous_url = url()->previous();
// check if previous url is from the same host
if (!str_contains($previous_url, $host)) {
return null;
}
// get the previous url route
list(, $route) = explode($host, $previous_url);
// make sure the route is not the index, login or logout route
if (in_array(substr($route, 1), ['', 'login', 'logout'])) {
$route = '';
}
return $route;
}
And then I called the same function in my SessionsController class in the create method by doing this
public function create()
{
$previous_url = get_previous_url();
if ($previous_url) {
session(['previous_url' => $previous_url]);
}
...
}
And then I changed my login method to
public function login(Request $request)
{
...
$redirect = redirect()->route('dashboard'); // '/'
if (session()->has('previous_url')) {
$redirect = redirect(session()->pull('previous_url'));
}
return $redirect;
}
I have a front-end SPA built on Angular 6 and back-end on Laravel 5.6. I'm trying to make a facebook auth using ngx-social-login on the front-end and a Socialite on the back-end.
That is code in my component
signInWithFacebook(): void {
this.sas.signIn(FacebookLoginProvider.PROVIDER_ID).then(
userData => this.as.fb(userData.authToken).subscribe(x => {
console.log(x);
})
);
}
And this is a service
fb(data): Observable<any> {
return this.http.get(this.API_URL, data);
}
And here is my Laravel routes
$api->version('v1', function ($api) {
$api->get('auth/facebook', 'SocialAuthFacebookController#redirectToProvider');
$api->get('auth/facebook/callback', 'SocialAuthFacebookController#callback');
});
That is a controller
public function redirectToProvider()
{
return Socialite::driver('facebook')->stateless()->redirect();
}
public function callback()
{
$user = Socialite::driver('facebook')->stateless()->user();
$authUser = $this->findOrCreateUser($user, 'facebook');
$token = JWTAuth::fromUser($authUser);
return Response::json(compact('token'));
}
public function findOrCreateUser($user, $provider)
{
$authUser = User::where('provider_id', $user->id)->first();
if ($authUser) {
return $authUser;
}
return User::create([
'name' => $user->name,
'email' => $user->email,
'provider' => $provider,
'provider_id' => $user->id
]);
}
Since I'm using Laravel as an API-only so I suppose that I cannot access redirectToProvider so that I tried to call auth/facebook/callback and pass it an authToken that I get after a login on my SPA. However, it doesn't seem to work.
I'm experiencing the next error
Thanks to Facebook there is so much information so that I don't know what's wrong and what to do with it.
Here's an example that might help:
/**
* Redirect the user to the Facebook authentication page.
*
* #return Response
*/
public function redirectToProvider()
{
return Socialite::driver('facebook')->stateless()->redirect();
}
/**
* Obtain the user information from Facebook.
*
* #return JsonResponse
*/
public function handleProviderCallback()
{
$providerUser = Socialite::driver('facebook')->stateless()->user();
$user = User::query()->firstOrNew(['email' => $providerUser->getEmail()]);
if (!$user->exists) {
$user->name = $providerUser->getName();
$user->save();
}
$token = JWTAuth::fromUser($user);
return new JsonResponse([
'token' => $token
]);
}