Store the login details in session in laravel - laravel

I have a function in controller checklogin() which checks the user details. I want to store into session. So I can get the name of the user and display in blade view
Controller
public function checklogin(Request $request)
{
$req=$request->validate([
'name'=>'required',
'email'=>'required|email',
'password'=>'required|regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[#_!]){8,}/'
]);
$userdata = array(
'name' => $request->input('name') ,
'email'=>$request->input('email'),
'password' => $request->input('password')
);
if (Auth::attempt($userdata))
{
$data = $request->session()->put('user',$userdata['name']);
dd($data) ; //returning null
return redirect('/home');
}
else
{
return back()->with('error', 'Wrong Login Details');
}
}

No need to store logged in user detail in session.You can call auth helper function which will return auth instance.
{{auth()->user()->name}}
if you have both logged in or guest page same then you can do null check
{{ auth()->user()!=null?auth()->user()->name:null }}

Related

Password Protect a Page after login Laravel

After a user registers and logs in, I have an unlisted page/secret page that I need to protect with another password.
I'm trying to get spatie/laravel-littlegatekeeper to help me do this, but running into issues getting it working.
What I'm doing:
littlegatekeeper .config:
<?php
return [
// Login credentials
'username' => env('GATEKEEPER_USERNAME', 'default_username'),
'password' => env('GATEKEEPER_PASSWORD', 'default_password'),
// The key as which the littlegatekeeper session is stored
'sessionKey' => 'littlegatekeeper.loggedin',
// The route to which the middleware redirects if a user isn't authenticated
// 'authRoute' => url('login'),
];
Routes:
Route::get('/secretapage', ['middleware' => 'littlegatekeeper', function () {
return view('dir.secretapage.index');
}]);
Route::get('/secretapage/login', function () {
return view('dir.secretapage.login');
});
Route::post('/secretapage/login/addCredentials', 'SecretController#addCredentials')->name('addCredentials');
SecretController:
After I log in my user. I then try to access the URL /secretpage I get redirected back to the homepage rather the /secretpage/login
public function index(Request $request)
{
$auth = resolve('littlegatekeeper');
if($auth->isAuthenticated())
{
return view('dir.secretpage.index');
}
return view('dir.secretpage.login');
}
///// FOR LOGING IN
public function addCredentials(Request $request)
{
$auth = resolve('littlegatekeeper');
$loginSuccess = $auth->attempt($request->only([
'username',
'password'
]));
if ($loginSuccess) {
return redirect('/secretapage')->with('success', 'Thank You for authorizing. Please proceed.');
}
else{
return back()->with('error', 'You entered the wrong credentials');
}
}
Blade login file:
<form method="POST" action="{{ route('addCredentials') }}">
...
</form>
If I access secretpage/login 1st, I'm able to add the username and password.
Then I can get into /secretpage with no issues....
But I really need to have the users go to /secretpage 1st then if not logged in with the secret username/pass get redirected to /secretpage/login.
I found some help on Laracasts and this ended up working.
Change the authRoute in the littlegatekeeper config file to the following
'authRoute' => '/secretpage/login',

Authorise a user with Laravel Passport when testing RESTful controllers update method

Every time I run the test, I'm getting a 403 response status, what am I doing wrong in here?
I have tried to remove Passport authorization from the test, but then I'm getting a redirect to a login page, 302 status response.
//PostTest:
public function test_can_update_post()
{
//creating a user
$user = factory(User::class)->create();
//creating an author for post
$author = factory(Author::class)->create([
'user_id' => $user->id,
]);
//creating a post
$post = factory(Post::class)->create([
'author_id' => $author->id,
]);
$data = [
'title' => $this->faker->title,
'content' => $this->faker->paragraph,
];
//authorizing user
//I have tried to remove this line, then I'm gettig a redirect to login page 302
$user = Passport::actingAs($user);
$this->actingAs($user)
->patch(route('posts.update', $post->id), $data)
->assertStatus(200);// why I'm getting 403???
}
//API route:
Route::patch('posts/{post}')
->uses('PostController#update')
->middleware('auth:api')
->name('posts.update');
//PostController update method:
public function update(PostUpdateRequest $request, Post $post)
{
$this->authorize('update', $post);
$post->title = $request->input('title');
$post->content = $request->input('content');
$post->save();
return new PostResource($post);
}
//PostPolocy
public function update(User $user, Post $post)
{
return Author::where('user_id', $user->id)->first()->id === $post->author_id;
}
I expect response status 200
I have changed the line in PostPolicy update method to:
if(!$user->author) {
return false;
}
return $user->author->id == $post->author_id;
This worked for me.

How To Get Auth ID form user table and grab it for store to other table on database

I want to get Auth ID from user who has logged in and then use the Auth ID to store on other table
User_detail Controller
this is my store function
$data = new ModelUser();
$user= new user();
$data->fill(Auth::user());
$data->id_user = Auth::get('id');
$data->jenis_kelamin = $request->jenis_kelamin;
$data->no_tlp = $request->no_tlp;
$data->jurusan = $request->jurusan;
$data->wilayah = $request->wilayah;
$data->save();
return redirect()->route('surveylist');
and this is function Login
public function LoginPost(Request $request)
{
$email = $request->email;
$password = $request->password;
$data = user::where('email',$email)->first();
if($data) //check email apakah ada atau tidak
{
if(Hash::check($password,$data->password))
{
Session::put('id',$data->id);
Session::put('full_name',$data->full_name);
Session::put('email',$data->email);
Session::put('login',TRUE);
return redirect('userdt');
}
else
{
return redirect('index')->with('alert','Password atau Email yang anda masukan salah !!! ' );
}
}
}
this is the routes files
Route::get('/index','UserController#show')->name('surevey.index');
Route::get('/logout','UserController#Logout')->name('user.logout');
Route::post('/registerpost','UserController#RegisterPost')->name('user.register');
Route::post('/loginpost','UserController#LoginPost')->name('user.login');
//reward routes
Route::get('/reward','RewardController#index')->name('reward.list');
//profile
Route::put('/editprofile/edit/{id}','UserController#edit')->name('profile.edit');
Route::post('/editprofile/update','UserController#update')->name('profile.update');
Route::get('/userdt',['middleware'=>'auth','uses'=>'UserController#userdetail'])->name('userdt.show');
Route::post('/userdt/store','UserController#store')->name('userdt.store');
//Survei
Route::get('/createsurvey','SurveyController#show')->name('survey.create');
Route::get('/surveylist','SurveyController#index')->name('survey.list');
Auth::routes();
ModelUser
protected $fillable = [
'id_user',
'jenis_kelamin',
'no_tlp',
'jurusan',
'wilayah'
];
protected $table ='user_detail';
public function user()
{
return $this->belongsTo(user::class);
}
and I get error like this
Argument 1 passed to Illuminate\Database\Eloquent\Model::fill() must
be of the type array, null given, called in
E:\Laravel\surevey\app\Http\Controllers\UserController.php on line 110
You don't need to use $data->fill(Auth::user()); as you have only single user_id field need to set.
Also you can get the current logged in user's id using. \Auth::user()->id
So your code would be as follow:
$data = new ModelUser();
$data->id_user = \Auth::user()->id;
$data->jenis_kelamin = $request->jenis_kelamin;
$data->no_tlp = $request->no_tlp;
$data->jurusan = $request->jurusan;
$data->wilayah = $request->wilayah;
$data->save();
return redirect()->route('surveylist');
Note: Make sure you have included auth middleware with your route.
Like:
Route::get('profile', ['middleware' => 'auth', function() {
// Only authenticated users may enter...
}]);
And you have followed the authuntication process carefully.
https://laravel.com/docs/5.2/authentication
Edited:
Your loging should be changed as:
public function LoginPost(Request $request)
{
$email = $request->email;
$password = $request->password;
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// Authentication passed...
return redirect()->intended('userdt');
}
return redirect('index')->with('alert','Password atau Email yang anda masukan salah !!! ' );
}
If your reverse one-to-one relationship in the User Model looks like this:
public function detail()
{
return $this->hasOne(ModelUser::class);
}
And you are sure a user is logged in, you could simply do this
$data = Auth::user()->detail()->save($request->all());
return redirect()->route('surveylist');
Laravel's ORM takes care of the rest.
should be Auth::id() or Auth::user()->id but seems like your Auth::user() is returning a null.make sure you sessions, routes are set up properly.
use Auth::attempt()to login user

Laravel Socialite Google login only with one domain

I have a Google+ login on my app with Laravel Socialite. When the login is done I have a callback to connect the user (I create her in database if necessary).
But I want to restrain the connection to only the company (email like "example#company.com", so only the email with "company.com").
Can I do it with Laravel Socialite ? I can make the verification manually in my callback but if Socialite can do it, it's better.
Thank you
My callback :
public function handleProviderCallback($provider){
$user = Socialite::driver($provider)->user();
if ($user) {
$local_user = User::whereEmail($user->getEmail())->first();
// If we don't have a user create a new user
if (!$local_user) {
$fragment = explode(' ', $user->getName());
$local_user = User::create([
'first_name' => isset($fragment[0]) ? $fragment[0] : '',
'last_name' => isset($fragment[1]) ? $fragment[1] : '',
'email' => $user->getEmail(),
'last_seen' => Carbon::now(),
'password' => ''
]);
$local_user->roles()->attach(Role::whereName('User')->first());
}
auth()->login($local_user);
}
return redirect($this->redirectTo);
}
You have a step by step guide for domain restriction.
In controller you need to specifiy these actions:
public function handleProviderCallback()
{
try {
$user = Socialite::driver('google')->user();
} catch (\Exception $e) {
return redirect('/login');
}
// only allow people with #company.com to login
if(explode("#", $user->email)[1] !== 'company.com'){
return redirect()->to('/');
}
// check if they're an existing user
$existingUser = User::where('email', $user->email)->first();
if($existingUser){
// log them in
auth()->login($existingUser, true);
} else {
// create a new user
$newUser = new User;
$newUser->name = $user->name;
$newUser->email = $user->email;
$newUser->google_id = $user->id;
$newUser->avatar = $user->avatar;
$newUser->avatar_original = $user->avatar_original;
$newUser->save();
auth()->login($newUser, true);
}
return redirect()->to('/home');
}
No, you can’t do it in Socialite itself because Socialite is just a mechanism of retrieving tokens from OAuth-compliant servers.
If you only want to accept users with a particular email suffix, then that’s business logic so something you should handle in your callback:
public function handleProviderCallback()
{
$user = Socialite::driver('google')->user();
if (Str::endsWith($user->getEmail(), '#example.com')) {
// Look up user and authenticate them
}
abort(400, 'User does not belong to organization');
}

Return user info in Sentry2

I want to return the users info to my view when a user logs in but I keep getting an error message that says "Undefined variable: user"
Here is my controller code:
public function postLogin()
{
$credentials = array(
'email' => \Input::get('email'),
'password' => \Input::get('password')
);
try
{
$user = \Sentry::authenticate($credentials, false);
if ($user);
{
$user = \Sentry::getUser();
\Notification::succes('Succesvol ingelogd als,'. $user->name);
return \Redirect::back()-with($user);
}
}
catch(\Exception $e)
{
\Notification::error($e->getMessage());
return \Redirect::back();
}
}
and in my view I try to use the $user variable but then I get the error.
When you do:
Redirect::back()->with('user',$user);
In your new request you must get the user from the Session:
$user = Session::get('user');
and pass it to your view:
return View::make('view')->with('user', $user);
Because Laravel doesn't create global variables as it does when you:
return View::make('view')->with('variableName', $value);

Resources