How to store Auth session - laravel

I'm new in Laravel and firebase and I did the login and password validation by myself, but I would like to use the Route::group(['middleware' => ['auth']]), function to protect unauthorized access to the system, but I don't know how to tell Laravel that the user is already authenticated without using Auth::attempt($credentials).
So how can I set the user is authenticated already, redirect the user to main page passing the login(name of the user) to Auth.
if (Auth::attempt($credentials)) { //I need to replace this line setting the user is logged already
return redirect()->route('home');
}
I tried: Auth()->login($nickname);
But I received:
Argument 1 passed to Illuminate\Auth\SessionGuard::login() must be an instance of Illuminate\Contracts\Auth\Authenticatable, string given

Auth()->login($user);
is the right method, you should pass $user object instead of a string which includes user nickname, for example:
$use = new User();
$user->id = 1;
$user->email = 'eshtiaghi.amin#gmail.com';
$user->name = $nickname;
$user->save();
\Auth::login($user);

Related

JWT laravel: check auth. Cannot check if user is authenticated even i have set the token

I'm trying make a mobile application with vue and i'm using jwt in laravel.
On first login, I can access the auth()->check() then I get false after the app is cancelled. I'm saving the token. I'm saving the token in local storage. How can I get the authenticated user.
controller:
public function JwtAuth(){
if($this->getAuthenticatedUser()){
return $this->JwtUser = $this->getAuthenticatedUser();
}
return [];
}
I want to acheive something like:
if(auth()->user()){
$user = "something";
}else{
$user = '';
}
return $user;
So sometime I will have token and sometime i dont .. how to check?

How to authorize user in laravel

We have auth microservice and an admin panel based on laravel. We login user by calling auth api and returning user id and token. How I could make user as authorized in laravel 5.3? I did not found any information googling.
$request = Request();
$authorize = new Authorize();
$response = $authorize->logIn($request->all());
if ($response->status == 'success') {
$user = new User();
$userResponse = $user->getUser($response->data->id);
Session::put('userId', $response->data->id);
Session::put('userToken', $response->data->token);
Session::put('userData', $userResponse);
if ($request->input('save_login')) {
Cookie::queue(Cookie::make('savedLogin', $request->input('login'), 129600, null, null, false, false));
} else {
Cookie::queue(Cookie::forget('savedLogin'));
}
return redirect('/');
}
You can manually log in the user with either the id or the User Instance.
From the docs:
Authenticate A User Instance
If you need to log an existing user instance into your application,
you may call the login method with the user instance. The given object
must be an implementation of the
Illuminate\Contracts\Auth\Authenticatable contract. Of course, the
App\User model included with Laravel already implements this
interface:
Auth::login($user);
// Login and "remember" the given user...
Auth::login($user, true);
Authenticate A User By ID
To log a user into the application by their ID, you may use the
loginUsingId method. This method accepts the primary key of the user
you wish to authenticate:
Auth::loginUsingId(1);
// Login and "remember" the given user...
Auth::loginUsingId(1, true);

JWT Auth for Laravel

I am trying to authenticate a user from App, and I have written the API in laravel. I want to know what is the difference between JWTAuth::fromUser($user),JWTAuth::toUser($user) and JWTAuth::attempt($user) and any advantages over using it?
JWTAuth::fromUser($user)
If you have user instance already and want to generate token for that user then you use fromUser
$token = JWTAuth::fromUser($user);
JWTAuth::attempt($user)
This function is used to authenticate user from credentials and if authenticate success then it generate token for authenticated user
if (! $token = JWTAuth::attempt($credentials)) {
return Response::json(['error' => 'invalid_credentials'], 401);
}
JWTAuth::toUser($user)
When you want to get user from token then you use toUser method. like this
$user = JWTAuth::toUser($token);
For details you can check it here https://github.com/tymondesigns/jwt-auth/wiki/Creating-Tokens

What is the difference between "login" and "attempt" method in Auth

I'm learning Laravel 5.4 and customizing and making my original Auth functionalities.
The below is my "authenticate" method.
public function authenticate(Request $request)
{
$remember_me = (Input::has('remember')) ? true : false;
Auth::guard('web');
$this->validateLogin($request);
$credentials = array(
'username' => trim($request->input('username')),
'password' => trim($request->input('password'))
);
if(Auth::attempt($credentials, $remember_me)){
$user = Auth::guard('web')->user();
Auth::guard('web')->login($user, $remember_me);
return redirect()->route('mypage');
}
return redirect()->back();
}
I have a question about the part of $remember_me argument about both attempt and login methods noted above.
What is the difference between them?
When I saw the documentation, it said similar to, if you want to make "remember me" token, you can set the second boolean argument about both of them.
attempt($credentials, $remember_me) will attempt to log the user in if the login credentials are correct. If they are not, then the user is not logged in. This method returns a boolean so you can check success.
login($user_id, $remember_me) will log the user in, without checking any credentials.
The remember me specifys if the user login should persist across browser sessions without needing to re-auth.
In your example I see your calling login(...) within your attempt(...). This shouldn't be needed. You can remove the login(...) line.
Example:
if(Auth::attempt($credentials, $remember_me)){
return redirect()->route('mypage');
}

Cartalyst Sentry and registration user

It is possible to create user from Admin panel, by administrator without password? I imagine follow procedure:
Administrator create user without password
User get email with instruction for entering password and activation account
User can register with email and his password
I don't think so. That's why when I create my users I generate a random password.
$user->password = str_shuffle("Random_Password"); // generate random initial password
I have done this before by hacking the 'forgotten password' functionality of Laravel (rather that reinventing the wheel). I can't say how well this fits into Sentry but it was pretty trivial to do it in plain old Laravel:
Create user with blank password
Add an entry into the password reminders table (manually, don't use Auth::remind or whatever it is as it'll send an email, but do use the code from the class to generate the token)
Send welcome email to user with link to /user/confirm (or whatever, the point is that it doesn't have to be /user/forgotten-password) and hook that route up in the normal way for forgotten password with an added check for $user->password == '' if you wanna make sure only unconfirmed people can go to that page (not that it really matters).
You may also wish to extend the timeout on the forgotten passwords or, as I did (proper hacky I know), when the user's in the /user/confirm version of the forgotten password functionality, just refresh the timeout in the table before passing through to Laravel's auth system for checking.
Our code is something like this:
On register:
// however you register the user:
$user = new User;
$user->email = Input::get('email');
$user->password = '';
$user->save();
// create a reminder entry for the user
$reminderRepo = App::make('auth.reminder.repository');
$reminderRepo->create($user);
Mail::send(
'emails.registered',
[
'token' => $reminder->token,
],
function ($message) use ($user) {
$message->to($user->email)->setSubject(Lang::get('account.email.registered.subject', ['name' => $user->name]));
}
);
Now the confirm link:
class AccountController extends Controller
{
public function confirm($token)
{
$reminder = DB::table('password_reminders')->whereToken($token)->first();
if (! $reminder) {
App::abort(404);
}
// reset reminder date to now to keep it fresh
DB::table('password_reminders')->whereToken($token)->update(['created_at' => Carbon\Carbon::now()]);
// send token to view but also email so they don't have to type it in (with password reminders it's is a good thing to make users type it, but with confirm account it feels weird)
return View::make('account.confirm-account')->withToken($token)->withEmail($reminder->email);
}
public function postConfirm($token)
{
$credentials = Input::only('email', 'password', 'password_confirmation', 'token');
$response = Password::reset($credentials, function ($user, $password) {
$user->password = $password;
$user->save();
});
switch ($response) {
case Password::INVALID_PASSWORD:
case Password::INVALID_TOKEN:
case Password::INVALID_USER:
return Redirect::back()->withInput()->with('message-error', Lang::get($response));
case Password::PASSWORD_RESET:
Auth::login(User::whereEmail(Input::get('email'))->first());
return Redirect::route('account.home')->with('message-info', Lang::get('messages.confirm_account.succeeded'));
}
}

Resources