Laravel: Security For ADMIN and USER - php

I have a two different login forms for user and admin. What I want is the user should only login in their own form otherwise it should be an error, and just the same for the admin form.
I only have 1 table for both user and admin in my database. They only differ in user_type which is obviously "admin" and "user"
What I am doing is when the user tried to login in admin login form it shows an info that says 'sorry, you are not an admin in this site'. But that means that the user is still logged in.
What I want is when the tries to login in admin form I don't want it to access the system at all.
Here my code so far:
public function validateLoginResort(Request $requests){
$username = $requests->username;
$password = $requests->password;
$attempt = Auth::attempt([
'email' => $requests->username,
'password' => $requests->password,
]);
if(Auth::check()){
if(Auth::user()->type_user == 'admin'){
return redirect('home');
}
else{
Auth::logout();
return redirect('login');
}
}else{
return "Invalid input";
}
}
I tried using Auth::logout if the user is not an admin but I dont think it is safe and right at all.
I think there is still a better way to do this, can you guys give a suggestion on how to implement this correctly? Thank you

You could check user type first, and then login user if he/she is admin.
Suppose your user table name is "users" and corresponding eloquent model is "User", then you could do this:
$user = User::where('email', $request->get('email'))->first();
if (!$user || !\Hash::check($request['password'], $user->password)) {
return 'Invalid user credential';
}
if ($user->type_user !== 'admin') {
return 'Only admin allowed';
}
\Auth::login($user); // This is the key point.
return redirect('home');

You're struggling in creating custom code in laravel how the thing works. I suggest you use the laravel package located here: https://github.com/spatie/laravel-permission it allows you to manage user permissions and roles in a database
Thanks,

Related

Laravel 5.4 detach row

When i want change password user and user table got relationship i made detch, next i can change password but how use attach to add again thats same role what user got?
Route::post('profil/changepassword', function() {
$User = User::find(Auth::user()->id);
//$User->roles()->$rola;
$User->roles()->detach();
if(Hash::check(Input::get('passwordold'), $User['password']) && Input::get('password') == Input::get('password_confirmation')){
$User->password = bcrypt(Input::get('password'));
$User->save();
$User->roles()->attach(1);
return back()->with('success','Hasło zostało zmienione');
}
else{
return back()->with('error','Hasło nie zostało zmienione');
}
});
I made something like that and when user change password it will get role User. When Moderator change password thats same get User role not moderator like got befor. So i ask how i can figure it becouse i will use detach in other funcion and i really dont know how make it.

Laravel Socialite log out and database storing

I am trying to set up Socialite in Laravel for facebook logging. I got user logged in , but now I have a problem storing the details in the database.
Also I would like to know how to notice my app that User is logged in? For normal loggin I used native AuthController and everything goes smooth.
Now if user try to log in again, then Laravel automatically redirect it to the url without logging, with appended code like this ?code=AQBCM-KbFqB-VJepSJ-45nFURnsvPPdpdqOu...
So how can I logout the user completely and how can I store the details for the next logging??
This is what I am using but it is not working:
public function getSocialAuth($provider=null)
{
if(!config("services.$provider")) abort('404'); //just to handle providers that doesn't exist
return $this->socialite->with($provider)->redirect();
}
public function getSocialAuthCallback($provider=null)
{
if($user = $this->socialite->with($provider)->user()){
dd($user);
/* This is also not working:
$user1 = new User;
$user1->facebook_id = $user->getId();
$user1->email=$user->email();
$user1->fullname=$user->name();
$user1->provider="facebook";
$user1->save();*/
// not working:
User::create([
'facebook_id' => $user->getId(), 'email' => $user->email(),
'fullname' => $user->name()
]);
}else{
return 'something went wrong';
}
}

Cakephp 3.x way to check if a user exists in the database

I want to create a simple check if a user exists in my database just after he is logged on (LDAP Authentication). If he doesn't exist, a record should be created in the db.
Is there any standard CakePHP 3.x -way of doing such things?
Or I can just create a function in my "users" Controller which checks if a user exists in the db and call it in the end of login() function (if user session has been successfully created)?
public function login(){
if ($this->request->is('post')){
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
$this->createStudent($user);
return $this->redirect($this->Auth->redirectUrl());
}
// user is not identified
$this->Flash->error('Your username or password is not correct');
}
}
public function createStudent($user){
$studExists = $this->Students->find('isExists', ['uid' => $user['uid']]);
if (!$studExists) {
$student = $this->Students->newEntity();
$data = ['id' => $user['uid']];
$student = $this->Students->patchEntity($student, $data);
if ($this->Students->save($student)) {
$this->Flash->success(__('It is your first logon. You have been added to our database!'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('You could not be saved in our database. Please, try again.'));
}
}
}
Thank you in advance.
What you have shown works but a better way would using an event from your LDAP authenticate class to notify that a new user record needs to be created in your app. Your table's createStudent() can be set as a listener callback for that event. Also your LDAP authenticate class should also only return info if a matching record is found in your datbase table, which I don't think is the case currently.
You can refer to this HybridAuthAuthenticate which does similar. The readme of the plugin shows how to setup listener for the event.

CakePHP 3 refresh session data

I have a page where i can modify user details (username,first name,avatar...).
I have an element in my navbar with informations about the currently logged in user. The thing is I can't figure out how to refresh the session immediately after data is modified.
in UsersController:
public function edit($id = null)
{
if (!$id) {
throw new NotFoundException(__('Invalid user'));
}
$user = $this->Users->get($id);
if ($this->request->is(['post', 'put'])) {
$this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
//REFRESH SESSION ????\\
$this->request->session()->write('Auth.User', $user);
//\\
$this->Flash->success(__('User has been updated.'));
return $this->redirect(['action' => 'edit/' . $id]);
}
$this->Flash->error(__('Unable to update User details.'));
}
$this->set(compact('user'));
}
Just update it the same way as you're setting it when loggin in, ie using AuthComponent::setUser().
Also you may want to do that only in case the user that has been edited, is actually the user that is currently logged in. And you want to set the data in the same format as the Auth component does, that is (for now), as an array, and, for security purposes, without the password.
A simple example that assumes a single column primary key named id, and a password column named password
if ($this->Auth->user('id') === $user->id) {
$data = $user->toArray();
unset($data['password']);
$this->Auth->setUser($data);
}
See also
Cookbook > Controllers > Components > Authentication > Identifying Users and Logging Them In
Cookbook > Controllers > Components > Authentication > Manually Logging Users In

How to Check whether the user logged in and Redirect Accordingly

Here is my Route :
Route::get('/', 'HomeController#home');
Route::post('login', 'LoginController#Login');
Route::get('vehicle', 'VehicleController#VehicleLayout');
So far all pages can be accessed by any users.
And I started using auth::user So
if (Auth::attempt($LoginData))
{
return Redirect::intended('dashboard');
}
else
{
return Redirect::to('')->with('Message', 'UserName or Password Invalid');
}
I am checking in the Login screen.
But from my above code. The page vehicle can be accessed from any where. And there i am getting the logged in user's details by {{ Auth::user()->FirstName}}
And when i try to access the vehicle page, If the user didn't logged in it simply throws the error
Trying to get property of non-object (View: C:\xampp\htdocs\mti\app\views\layouts\dashboardlayout.blade.php) (View: C:\xampp\htdocs\mti\app\views\layouts\dashboardlayout.blade.php)
Is there any way to check whether the user has logged in and Redirect the user to login page with errors in laravel way.
<?php
if (Auth::guest())
{
return Redirect::to('logout')->with('Message', 'You Must Logged In to Access this page.');
}
?>
Is the above given a good process or is there any laravel way to do this.
You can and should use filters for this. There's even a built in auth filter (you can find it inside app/filters.php)
It works very well in combination with route groups. Here's an example:
Route::group(array('before' => 'auth'), function(){
Route::get('vehicle', 'VehicleController#VehicleLayout');
Route::get('foo', 'FooController#BarAction');
});
In laravel it's simple to do what you are asking.
There is a function to check values from login form, and then check if the user exists in database.
if (Auth::attempt(array( 'email' => $email, 'password' => $password ) ) )
{
return Redirect::to( 'your route' ); // route for loged users
}else
{
return Redirect::to('/home')->withMessage('Wrong username/pass')
}
On the home page you can display error message like this {{ If(Session::has('message') {{ $message}} }}
If you have that user in database, the function will redirect you to page where loged user go, and then you can type Auth::user()->username, and you will be able to acces any data of that user.
**To check if the user is loged, just type
if(Auth::check){
then do something
}else{
do something else
}**

Categories