Create Users for logged in Admin users - laravel-5

I wanted to give option to create users for Admin without using Registration form.
Do I need to change existing methods and forms ? How do I store password with encryption same as in default registration option. what is the best way to do it?
UserController class is already created using
php artisan make:controller PhotoController
class UserController extends Controller {
public function create()
{
$users = User::get();
return view('user.index', compact('users'));
}
public function store()
{
$input = Request::all();
........
}
}

Related

laravel manually authenticate user

I want to manually login a user in laravel 8. The problem is that authentication succeeds, but the authenticated user is not stored in the session(or the session is not updated). I use the method given in de docs.
My loginController has two methods: 1) showing the login form and 2) performing the login
<?php
namespace App\Http\Controllers;
use App\Http\Requests\LoginRequest;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
public function login(){
return view('auth/login');
}
public function validateLogin(LoginRequest $request){
if (Auth::attempt(['email'=>$request->email, 'password'=>$request->password])) {
$request->session()->regenerate();
return redirect()->to('/');
}
return back()->withErrors(['credentials' => 'Deze gegevens zijn niet bekend!']);
}
}
The controller redirects indeed to / , so the user is authenticated but after the redirect the autenticated users is unavailable, so somehow it is not stored in the session.
Does anyone know how to solve this?
I removed the id from the User model as I wanted to use the e-mailadress as the primary key. This violated the Authenticable trait so the session was not updated.
The usermodel needed the following function to replace the id with the email:
public function getKeyName(){
return 'email';
}
The same can be accomplished with:
protected $primaryKey = 'email';
public $incrementing = false;

Laravel override Login controller, login(). How do i retrieve logged in user data if i overwrite the login controller. I tried to get auth() data

I used laravel like 4 years ago. Had to work on a project on laravel and tried using my own authentication methods but mybad forgot there was already inbuilt better security authentication. I understand if my question seem to be basic.
As you can see the commented line "$userID = Auth::user()->userID;" the auth() is null therefore, userID cannot get its id from null. I am unable to get user session data in any other controllers as well.
Any kind of help or suggestions is appreciated.
P.S. i have used the default login and registration inbuilt function only required function like login is override code. I am using laravel v 4.2.3. I tried passing the userid as url parameter but then discarded it as inbuilt session data makes it more secure and easier
the login function of my controller looks like this
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct()
{
$this->middleware('guest')->except('logout');
}
protected function login(Request $request){
$user = new User(); //my model User
$result=$user->login($request); //result has the id of the user
if ($result) {
//$userID = Auth::user()->userID;
return redirect()->route('homepage');
}else{
return redirect()->route('login');
}
}
}
model for user login()
//Auth user then let them login
public function login($request){
$email = $request->input('email');
$password = $request->input('password');
$result=DB::table('users')
->where('email', $email)
->where('password', $password)
->get();
return $result;
}
My Routes.. its default route of "Auth::routes();"
Route::get('/homepage/{userID?}', function($userID = null){
return view('index', ['userID' => $userID]);
})->name('homepage');
Route::get('/evaluate/{userID?}', function ($userID = null) {
return view('evaluate', ['userID' => $userID]);
})->name('evaluate');
I installed a fresh new laravel and tried my code again and somehow it worked. Must have made some errors when trying to override the codes. Thank you

Adding custom where clause to AuthenticatesUser Trait Laravel

We have decided to use Laravel for a project as a test run for future frameworks and are really enjoying it. There is one issue we are having though.
We use the trait Illuminate\Foundation\Auth\AuthenticatesUsers which handles user authentication. It works well. However, we have a column in the database called userstatus which could be a 0 or a 1.
How do we inject this where clause into the Illuminate\Foundation\Auth\AuthenticatesUsers trait?
I was thinking maybe something here (in my LoginController):
public function authenticated($request , $user){
//if $user->userstatus != 1 logout and redirect to start page
}
But I dont know how to logout (im looking into that now) .
your logic is right, you should redefine login and authenticated methods within LoginController.
your methods should be like below:
this method should be within your LoginController.php:
class LoginController extends Controller
{
use AuthenticatesUsers {
login as public loginParent;
}
protected function login(Request $request){
$default = '/';
$user = User::where('email', $request->get('email'))->NotActive->first();
if($user){
return redirect()->intended($default);
}
return $this->loginParent($request);
}
protected function authenticated(Request $request, $user)
{
if($user->not_active) {
$this->logout($request);
}
}
}
then we should create ScopeNotActive method within User.php Model as Local Scope:
//User.php
public function ScopeNotActive($query){
return $query->where('userStatus', '!=', 1);
}
and a Mutator to check if the user is not active:
// User.php
public function getNotActiveAttribute(){
return $this->userStatus != 1;
}

Laravel Authentication Reset

I'm having difficulty how do I get the user id based on the token generated by laravel? I'm not very familiar with framewrok can anyone help me?
class ForgotPasswordController extends Controller
{
use SendsPasswordResetEmails;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
}
ResetPasswordController
class ResetPasswordController extends Controller
{
use ResetsPasswords;
protected $redirectTo = '/login';
public function __construct()
{
$this->middleware('guest');
}
protected function guard()
{
return Auth::guard('user');
}
public function broker()
{
return Password::broker('users');
}
public function showResetForm(Request $request, $token = null)
{
var_dump($request->email);
var_dump( $request->token);
return view('auth.passwords.reset')->with(
['token' => $token, 'email' => $request->email]
);
}
}
how to update password? I only have the token received by email?
Check this steps so you can understand better how laravel auth works.
Generate the auth scaffolding with: php artisan make:auth
Run the created migrations:php artisan migrate
Check your route list with php artisan route:list, you can see that routes were created too when you ran make:auth command.
Take note of the controllers and methods the Auth routes are calling.
Go to the routes web.php file. See the Auth::routes();, this generate the default Laravel Auth routes, if you don't need em all, comment or delete this line and add the required Lines.
If you took note of the controllers and methods, you can see what's been called on each route. In this particular case, i think you'd be looking for ResetPasswordController which uses ResetsPasswords from vendor/laravel/framework/src/Illuminate/Foundation/Auth/ResetsPasswords.php there you can see the resets method this is what you'll have to override on your ResetPasswordController.

Access a controller function on Auth::user();

I used the scaffolding tools to generate my authentication code for my laravel project. I created a UserController to make a profile page which works great but when I try to make a function that can be used on Auth::user() i get an error Call to undefined method Illuminate\Database\Query\Builder::admin()
Why isn't the admin function accessible on the Auth::user()? Doesn't that extend my UserController? Or am I mixing it up with the model? Is the the model a good place to check if my user is an admin?
Here is my user controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use App\Http\Requests;
class UserController extends Controller
{
/**
* Create a new user controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* #return View with user data
*/
public function index() {
$user = Auth::user();
return view('users.index', compact('user'));
}
/**
* #return bool
* Returns bool if the user is an admin.
*/
public function admin() {
$user = Auth::user();
$authorized_users = [
'admin#test.com'
];
return array_key_exists($user->email, $authorized_users);
}
}
and I am calling it on a different route controller function
public function index() {
return Auth::user()->admin();
}
I am fairly new to laravel and php so any critique is valuable and wanted!
You could add a function or attribute to you User model, I prefer attributes:
//User.php
class User extends Model{
protected $appends = ['is_admin'];
public function getIsAdminAttribute()
{
$user = Auth::user();
$authorized_users = [
'admin#test.com'
];
return array_key_exists($user->email, $authorized_users);
}
...
}
//Then in your view
Auth::user()->is_admin
No, Auth::user() does not extends any Controller. It represents the instance of the currently logged in/authenticated user. It will allow you retrieve other attributes of the use such as id, name etc Auth::user()->admin(); does not make any sense. Auth::user() has nothing to do with the UserController or any other controller.

Resources