Login using laravel5.2 - laravel-5

Hi I'm new to laravel and I'm using the laravel5.2 version.
Actually I have this registration form too. But no problem in registration.
My question is that I'm looking for a simple and understandable code in login. I've seen it somewhere while googling but I think that one is not laravel5.2.
I just get the reference code in some examples and test it into my login app. I'm using a repositories on it. I've got some errors. It says
Whoops, looks like something went wrong.
1/1 FatalErrorException in EloquentUserProvider.php line 126: Class '\App\User' not found
I'm not sure why the error says app user not found. Here is my code below
<?php
namespace App\Repositories;
use App\Repositories\Contracts\loginRepositoryInterface;
use Illuminate\Http\Request;
use App\Users;
use DB;
use Session;
use Auth;
class loginRepository implements loginRepositoryInterface{
protected $request;
//Initialize request instance
public function __construct(Request $request){
$this->request = $request;
}
public function loginAuth(){
//validate login
$validator = app('validator')->make($this->request->all(), [
'emailAddress' => 'email|required',
'password' => 'required']);
//if validator fails then return response error
if($validator->fails())
return redirect()->route('get.login')->withErrors($validator)->withInput();
try{
$pwd = $this->request->get('password');
$sha1 = sha1($pwd);
$userdata = array(
'emailAddress' =>$this->request->get('emailAddress'),
'password' =>$sha1
);
if(Auth::attempt($userdata)){
return redirect()->intended('get.dashboard');
}else{
return redirect()->route('get.login')->withErrors($validator)->withInput();
}
}catch(\Exception $e){
return redirect()->route('get.login')->withErrors(["error"=>"Could not add details! Please try again."])->withInput();
}
}
//postCreate
public function postCreate($screen){
switch($screen){
case 'auth':
return $this->loginAuth();
break;
}
}
//getLoginView
public function getCreate(){
return view('login');
}
}
In method public function loginAuth()
My routes
//postLogin
Route::post('/login/{screen}', [
'as' => 'post.login.auth',
'uses' => 'loginController#postCreate'
]);
//getLoginView
Route::get('/login', [
'as' => 'get.login',
'uses' => 'loginController#getCreate'
]);
Can some one help me on this?
Thanks.

Make sure you have the \App\User model in app/User.php from the looks of the code you posted above, you seem to have \App\Users not \App\User

Related

How make Route::resource with page and filter options?

In Laravel 5.8 making backend rest api app with resource defined in routes/api.php, as
Route::group(['middleware' => 'jwt.auth', 'prefix' => 'adminarea', 'as' => 'adminarea.'], function ($router) {
...
Route::resource('skills', 'API\Admin\SkillController');
now on clients part for listing of skills I need to add current_page and filter_name.
Can it be done with Route::resource definition ?
Actually when we making the resource controller in laravel then it created the method index
create,
store,
show,
edit,
update,
destroy.
method and routes of these respectively but when you are going to define the new method and for access this method then you need to create new route for this.
otherwise it is not possible with the resource route in laravel.
public function abc(Request $request)
{
dd($request->all());
}
route for this
route::post('/abc','ABCController#abc')->name('abc');
you can check the route by this command
php artisan route:list or
php artisan r:l
hope you understand.
After some search I found a decision in defining in routes one more post route:
Route::group(['middleware' => 'jwt.auth', 'prefix' => 'adminarea', 'as' => 'adminarea.'], function ($router) {
Route::post('skills-filter', 'API\Admin\SkillController#filter');
Route::resource('skills', 'API\Admin\SkillController');
...
and in app/Http/Controllers/API/Admin/SkillController.php :
<?php
namespace App\Http\Controllers\API\Admin;
use Auth;
use DB;
use Validator;
use App\User;
use App\Http\Resources\Admin\Skill as SkillResource;
class SkillController extends Controller
{
private $requestData;
private $page;
private $filter_name;
private $order_by;
private $order_direction;
public function __construct()
{
$this->middleware('jwt.auth', ['except' => []]);
$request = request();
$this->requestData = $request->all();
}
public function filter()
{
if ( ! $this->checkUsersGroups([ACCESS_ROLE_ADMIN])) {
return response()->json(['error' => 'Unauthorized'], 401);
}
$backend_items_per_page = Settings::getValue('backend_items_per_page');
$this->page = !empty($this->requestData['page']) ? $this->requestData['page'] : '';
$this->filter_name = !empty($this->requestData['filter_name']) ? $this->requestData['filter_name'] : '';
$this->order_by = !empty($this->requestData['order_by']) ? $this->requestData['order_by'] : 'name';
$this->order_direction = !empty($this->requestData['order_direction']) ? $this->requestData['order_direction'] : 'asc';
$this->index();
$skills = Skill
::getByName($this->filter_name)
->orderBy($this->order_by, $this->order_direction)
->paginate($backend_items_per_page);
return SkillResource::collection($skills);
} // public function filter()
public function index()
{
if ( ! $this->checkUsersGroups([ACCESS_ROLE_ADMIN])) {
return response()->json(['error' => 'Unauthorized'], 401);
}
$backend_items_per_page = Settings::getValue('backend_items_per_page');
$skills = Skill::paginate($backend_items_per_page);
return SkillResource::collection($skills);
}
As that is adminarea some filter actions can have more 1 filter...
Just interested to know which other decisions are possible here?

How to remove Laravel Auth Hashing (to replace it by mysql hashing)?

I added registration, and I don't want to using laravels hash but mysql Hash (because I want existing users to still be able to connect).
So i do it step by step and for now I just try to register and then login without any hashing. The credentials are correct in my table but I get
"message":"The given data was invalid.","errors":{"email":["These credentials do not match our records."]}
I tried setting it in LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
public function username()
{
return 'email';
}
public function password()
{
return 'email';
}
public function setPasswordAttribute($password){
$this->attributes['password'] = $password;
}
public function Login(Request $request)
{
if(Auth::attempt(['email' => $request->email, 'pwd' => $request->password, 'password' => $request->password])){
$user = Auth::user();
$username = $user->nom;
return response()->json([
'status' => 'success',
'user' => $username,
]);
} else {
return response()->json([
'status' => 'error',
'user' => 'Unauthorized Access'
]);
}
}
}
I guess I should overwrite another function, but can't find out which one.
Could you please give me some help?
Altough what you're trying to achieve is considered unsecure, to remove Laravel's hashing for password, you need to add this to your User model :
public function setPasswordAttribute($password){
$this->attributes['password'] = $password;
}
and not in your controller, and be sure to remove the brcypt() methods in your RegisterController
To add your MySQL own hashing methods, update your controller to insert a RAW query while creating a user upon registration

laravel UserRequest $request error

laravel5.2,I create a UserRequest.php under Requests directory,but in controller,public function add(UserRequest $request) show error,but use public function add(Request $request) is normal.
UserRequest
namespace App\Http\Requests;
use App\Http\Requests\Request;
class UserRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'user_sn' => 'required|unique',
'user_name' => 'required',
'email' => 'required|unique',
'password' => 'required',
];
}
}
UserController
namespace App\Http\Controllers;
use App\Http\Requests\UserRequest;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
class UserController extends Controller
{
public function add(UserRequest $request)
{
if ($request->get('dosubmit')) {
$validator = Validator::make($request->all(), $request
->rules(), $request->messages());
if ($validator->fails()) {
return redirect('user/add')->withErrors($validator)
->withInput();
}
}
$corporation_list = DB::table('corporation')->get();
$department_list = DB::table('department')->get();
return view('user.add', ['corporation_list' => $corporation_list, 'department_list' => $department_list]);
}
}
Route
Route::group(['middleware'],function (){
Route::any('user/add',['as'=>'user.add','uses'=>'UserController#add']);
});
There are usually 2 reasons you could be having this issue.
You've not added the use statement for the UserRequest.
At the top of your controller (above the class) add:
use App\Http\Requests\UserRequest
assuming that is the correct namespace.
You may need to run composer dump-autoload to make sure the class has been added to the autoloader.
Edit
Firstly, replace the add() method with the following methods:
public function create()
{
$corporation_list = DB::table('corporation')->get();
$department_list = DB::table('department')->get();
return view('user.add', compact('corporation_list', 'department_list'));
}
public function store(UserRequest $request)
{
// If you get to this point the validation will have passed
// Process the request
}
Then change your routes from:
Route::any('user/add',['as'=>'user.add','uses'=>'UserControl‌​ler#add'])
to:
Route::get('user/add', ['as' => 'user.add', 'uses' => 'UserControl‌​ler#create']);
Route::post('user/add', ['as' => 'user.store', 'uses' => 'UserControl‌​ler#store']);
Obviously, feel free to change the as in the Routes to whatever, they should unique though.
Lastly, I would suggest looking at Resource Controllers which is a RESTful approach.
The problem is that you have not identified UserController that you are using UserRequest file
use App\Http\Requests\UserRequest
It will solve the problem

How to check user status while login in Laravel 5?

I have used Laravel Authentication (Quickstart). But I need to check the status of the user (approved/pending). If not approved, then an error will be shown in the login page. I need to know in which file I have to make the change and what is the change. Currently I am working on Laravel 5.3.
You can create a Laravel Middleware check the link for additional info
php artisan make:middleware CheckStatus
modify your middleware to get
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class CheckStatus
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
//If the status is not approved redirect to login
if(Auth::check() && Auth::user()->status_field != 'approved'){
Auth::logout();
return redirect('/login')->with('erro_login', 'Your error text');
}
return $response;
}
}
then add your middleware to your Kernel.php
'checkstatus' => \App\Http\Middleware\CheckStatus::class,
and finally add the middleware to your route
Route::post('/login', [
'uses' => 'Auth\AuthController#login',
'middleware' => 'checkstatus',
]);
I hope it helps
I found a simple solution for this. Artisan create App\Http\Controllers\Auth\LoginController, in this default controller just add this code if you have some conditions to login, for example I have a field state, you posibbly have status, email_status or other.
// Custom code for Auth process
protected function credentials( Request $request )
{
$credentials = $request->only($this->username(), 'password');
$credentials['state'] = 1;
return $credentials;
}
upper answer saves me
if (Auth::attempt(['email'=>$input['email'],'password'=>$input['password'], 'user_status'=>1 ]))
this will check the status
Just Add following method in my LoginController works like charm
protected function authenticated(Request $request, $user)
{
if ($user->yourFirldName != "Active") {
Auth::logout();
return redirect('/login')->with('error', 'Looks Like Your status is InActive');
}
}
I don't agree with upper answer, which will lead to your application performance is very low, and also don't recommend to modify the Laravel's source code.
So you can rewrite getCredentials function to your app\Http\Controllers\Auth\AuthController.php file like this:
<?php
//app\Http\Controllers\Auth\AuthController.php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Http\Request;
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
//you need add this function
protected function getCredentials(Request $request)
{
$data = $request->only($this->loginUsername(), 'password');
$data['is_approved'] = 1;
return $data;
}
}
then you can use Laravel Authentication (Quickstart) directly.
Hope this will help.
The pinned answer is the best approach.
Just a note: if you are using Laravel 5.8+ you need use:
//Default Auth routes
Auth::routes();
//Override and add middleware
Route::post('/login', [
'uses' => 'Auth\LoginController#login',
'middleware' => 'checkstatus',
]);
Follow the steps...
First add a column in your user table (suppose is_approved)
In App/Http/Controllers/Auth/LoginController file
public function authenticate()
{
if (Auth::attempt(['email' => $email, 'password' => $password, 'is_approved'=>1])) {
// Authentication passed...
return redirect()->intended('dashboard');
}
}
Hope this will help
Auth/LoginController
Though it is a long time from the question created date. You can go this way.
Go to Auth/LoginController and add this line.
protected function credentials(Request $request)
{
return [
'email' => $request->email,
'password' => $request->password,
'status' => 1,
];
}
For this to work you have to have a column named 'status' in users table. 1 is for active and 0/2 is for inactive user.
Hope this will work for you.
public function login(Request $request){
if ($request->isMethod('post')) {
$data= $request->all();
$roles=[
'email' => 'required|email|max:255',
'password' => 'required',
];
$customessage=[
'email.required' =>'Email is required',
'email.email' => 'Email is not vaild',
'password.required' => 'Password is required',
];
$this->validate($request,$roles,$customessage);
if(Auth::guard('admin')->attempt(['email'=>$data['email'],'password'=>$data['password'],'status'=>1])) {
return redirect('admin/dashboard');
} else {
Session::flash('error_message','You are not Active by Admin');
return redirect()->back();
}
}
return view('admin.admin_login');
}

What does "Method [show] does not exist" mean?

I'm new to Laravel 4 and trying to figure out why I'm getting an error saying that Method [show] does not exist.
I do not have a method named "show" and can only imagine that this is an internal, Laravel method but I do not know how to affect this or what could have done this. Any thoughts or help on this would be incredibly appreciated as I have been stuck on this for two days now and cannot figure out what I am doing wrong.
View:
<li>Sign in</li>
Route:
/*Sign In (GET)*/
Route::get('/account/sign-in', array(
'as' => 'account-sign-in',
'uses' => 'AccountController#getSignIn'
));
AccountController:
class AccountController extends BaseController {
public function getSignIn(){
return View::make('user.signIn');
}
public function postSignIn(){
$validator = Validator::make(Input::all(), array( 'email' => 'required|email', 'password' => 'required' ) );
if($validator->fails()){ /*Redirect to the sign in page*/
return Redirect::route('account-sign-in') ->withErrors($validator) ->withInput();
}
else { /*Attempt user sign in*/
$remember = (Input::has('remember')) ? true : false;
$auth = Auth::attempt(array( 'email' => Input::get('email'), 'password' => Input::get('password'), 'active' => 1 ), $remember);
if($auth){
/*Redirect to the intended page*/ return Redirect::intended('/');
}
else {
return Redirect::route('account-sign-in')->with('global', 'Email/password wrong, or account not activated.');
}
}
return Redirect::route('account-sign-in') ->with('global', 'There was a problem signing you in.');
}
}
What does “Method [show] does not exist” mean?
Code provided in your question doesn't shows anything about show() method, anyways. According to to your comments you didn't extend the BaseController but all your controlers should extend the BaseController and the BaseController should extend the Controller so this is how your BaseController should look like (By default):
class BaseController extends Controller {
/**
* Setup the layout used by the controller.
*
* #return void
*/
protected function setupLayout()
{
if ( ! is_null($this->layout))
{
$this->layout = View::make($this->layout);
}
}
}
Your controller should extend it like this:
class AccountController extends BaseController {
// Define all of your methods
// including show() if you are using it
}
It sounds like you just have a typo on the first line of your AccountController
It probably says class AccountController extends BasesController {
BasesController should be BaseController
I had this problem. I had previously listed a (now deprecated) resource that was causing a collision in the routes.php file.
Route::resource('scheduler', 'SchedulerController');
Route::get('scheduler/notices', 'SchedulerController#notices');

Resources