I'm using Larave 4.2, and everything works just fine. If I enter the correct credentials I will be taken to the correct URL (the one with auth filter). But the problem I'm currently experiencing is when one of the fields entered is incorrect and the user submits it will show a white screen.
I'm expecting of course that the user will be redirected back to login page with Input and display the error.
I've checked the filters, and quite sure it is still what came with Laravel and didn't change anything.
My routes
<?php
Route::get('login', function()
{
// just a shortcut to redirec to /login into /cms/login : prevents redirect LOOP
return Redirect::route('cms.login');
});
Route::group(array('prefix' => 'cms'), function()
{
Route::get('/', function()
{
if (Auth::guest())
{
return Redirect::route('cms.login');
}
else
{
return Redirect::route('cms.home');
}
});
Route::get('login', array(
'as' => 'cms.login',
'uses' => 'CMSController#login'
));
Route::post('login', array(
'as' => 'cms.postLogin',
'uses' => 'CMSController#userLogin'
));
Route::get('logout', array(
'as' => 'cms.logout',
'uses' => 'CMSController#userLogout'
));
Route::group(array('before' => 'auth'), function()
{
Route::get('home', array(
'as' => 'cms.home',
'uses' => 'CMSController#home'
));
Route::get('my-account', array(
'as' => 'cms.myaccount',
'uses' => 'AccountsController#myAccount'
));
Route::get('my-account/edit', array(
'as' => 'cms.edit-myaccount',
'uses' => 'AccountsController#editMyAccount'
));
Route::resource('accounts', 'AccountsController');
Route::resource('products', 'ProductsController');
Route::resource('news', 'NewsController');
Route::resource('settings', 'SettingsController');
Route::resource('homepage-sliders', 'HomepageSlidersController');
Route::resource('testimonials', 'TestimonialsController');
Route::resource('effects', 'EffectsController');
});
});
User model
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* Fillable array
*
*/
protected $fillable = array('email', 'password', 'username', 'position', 'mobile');
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
/**
* Sets the Validation Rules when Logging In
*
* #var array
*/
public static $loginRules = array(
'email' => 'required|email',
'password' => 'required|alpha_dash|min:6'
);
/**
* Sets the Validation Rules creating a User
*
* #var array
*/
public static $rules = array(
'email' => 'required|email|unique:users',
'username' => 'required|min:2|unique:users',
'position' => 'required|',
'mobile-number' => 'required|numeric|digits:11',
'password' => 'required|alpha_dash|min:6|confirmed',
'password_confirmation' => 'required|alpha_dash|min:6'
);
/**
* Sets the Validation Rules updating a User
*
* #var array
*/
public static $updateRules = array(
'username' => 'required|min:2',
'password' => 'required|alpha_dash|min:6|confirmed',
'password_confirmation' => 'required|alpha_dash|min:6'
);
/**
* Defines many-to-many relationship with Module
*
*/
public function permissions()
{
return $this->belongsToMany('Module', 'permissions')->withPivot('add','edit', 'view','delete');
}
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
/**
* Gets the Remember Token
*
* #return string $this->remember_token
*/
public function getRememberToken()
{
return $this->remember_token;
}
/**
* Set the Remember Token
*
* #param string $value
*/
public function setRememberToken($value)
{
$this->remember_token = $value;
}
/**
* Get the Remember Token name
*
* #return string 'remember_token'
*/
public function getRememberTokenName()
{
return 'remember_token';
}
/**
* Get the password and Hash it before saving to the database.
*
* #param string $value
*/
public function setPasswordAttribute($value)
{
$this->attributes['password'] = Hash::make($value);
}
/**
* Checks if Guest User input invalid credentials
*
* #param array $credentials
* #return object $validation
*/
public static function loginIsInvalid($credentials)
{
$validation = Validator::make($credentials, self::$loginRules);
if ($validation->fails())
{
return $validation;
}
}
My CMSController
<?php
class CMSController extends BaseController {
/**
* Display the login page.
* GET /cms
*
* #return Response
*/
public function login()
{
return View::make('cms.login');
}
/**
* Accepts the post request for login
* of user in CMS
*
*/
public function userLogin()
{
$user_credentials['email'] = Input::get('email');
$user_credentials['password'] = Input::get('password');
//sets the remember_me variable
if (Input::has('remember'))
{
$remember_me = true;
}
else
{
$remember_me = false;
}
if ($errors = User::loginIsInvalid($user_credentials))
{
return Redirect::route('cms.login')->withInput()->withErrors($errors);
}
if (Auth::attempt(array(
'email' => $user_credentials['email'],
'password' => $user_credentials['password']), $remember_me))
{
return Redirect::route('cms.home');
}
}
/**
* Accepts the post request for logout
* of user in CMS
*
*/
public function userLogout()
{
Session::clear();
Auth::logout();
return Redirect::route('cms.login');
}
/**
* Directs user to home page
*
*/
public function home()
{
return View::make('cms.home');
}
}
Currently in your code there is nothing after Auth::attempt() - so if the Auth fails - it has no where to go.
Just add a return after the Auth::attempt() to make it work
if (Auth::attempt(array(
'email' => $user_credentials['email'],
'password' => $user_credentials['password']), $remember_me))
{
return Redirect::route('cms.home');
}
return Redirect::route('cms.login')->withInput()->withErrors($errors);
Related
This is the test function
public function testCreateSuccess(){
$user=['first_name'=>"heba",'last_name'=>"chakaron",'email'=>"hebachakaron#gmail.com",'password'=> "123456"];
$userReturned=['first_name'=>"heba",'last_name'=>"chakaron",'email'=>"hebachakaron#gmail.com",'password'=> Hash::make('123456')];
$userRequest = UserRegisterRequest::create("http://127.0.0.1:8000/api/users/", 'POST',[
'first_name'=>"heba",
'last_name'=>"chakaron",
'email'=>"hebachakaron#gmail.com",
'password'=>'123456',
'password_confirmation'=>'123456'
]);
/**
* #var UserService|\Mockery\MockInterface|\Mockery\LegacyMockInterface
*/
$mock=Mockery::mock(UserService::class);
$mock->shouldReceive('create')->with($user)
->once()
->andReturn($userReturned);
$this->userController=new UserController($mock);
$this->app->instance('App\Services\UserService', $mock);
$created=$this->userController->create($userRequest);
$this->assertSame($created['password'],$userReturned['password']);
}
This is the controller
class UserController extends Controller
{
//
public function __construct(UserService $userService)
{
$this->userService = $userService;
}
public function create(UserRegisterRequest $request)
{
$data = $this->userService->create($request->validated());
return HTTPResponse::ok($data);
}
}
This is the UserRegisterRequest
class UserRegisterRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
];
}
}
When I run this testCreateSuccess it return There was 1 error:
Tests\Unit\UserTest::testCreateSuccess
Error: Call to a member function validated() on null
and the error is on the line $created=$this->userController->create($userRequest)
I use Laravel.
I use the same field for username and email. Additionally the user has to choose, if the input is an username or an email.
If the type is email, i like to add the email validation. If it's username, there is no email validation needed.
I tried to create a custom rule with the if function. But how can i then validate the email?
class StoreUserRequest extends FormRequest
{
public function rules()
{
return [
'first_name' => 'required',
'last_name' => 'required',
'password' => 'required',
'email' => ['required', new ValidateEmailRule()]
];
}
public function authorize()
{
return true;
}
}
class ValidateEmailRule implements Rule
{
/**
* Create a new rule instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
if (request()->is_email) {
//validate email ---here i need help to get the right code---
}
return true;
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
return 'The validation error message.';
}
}
Can't you just use 'email' => 'required_if:is_email:1?
EDIT:
$rules = [
'first_name' => 'required',
'last_name' => 'required',
'password' => 'required',
];
if ($this->is_email) {
$rules['email'] = 'email';
}
return $rules;
i want to redirect to a previously accessed page right before accessing the registration page after a user has successfully registered themselves. I edited the registration controller as below although i get the following exception View [http:..127.0.0.1:8000.prices] not found. I cross checked my routes and everything is fine. Here is my register controller.
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'fname' => ['required', 'string', 'max:255'],
'lname' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'phonenumber' => ['required', 'string', 'min:10', 'max:10'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'fname' => $data['fname'],
'lname' => $data['lname'],
'email' => $data['email'],
'phonenumber' => $data['phonenumber'],
'password' => Hash::make($data['password']),
]);
}
/**
* Show the application's registration form.
*
* #return \Illuminate\Http\Response
*/
public function showRegistrationForm()
{
if(session('link')) {
$myPath = session('link');
$registerPath = url('/register');
$previous = url()->previous();
if($previous = $registerPath) {
session(['link' => $myPath]);
}else{
session(['link' => $previous]);
}
}else{
session(['link' => url()->previous()]);
}
return view('auth.register');
}
protected function redirectTo()
{
if(session('link')){
return view(session('link'));
}
return view('/');
}
}
I think the issue is most likely to be with the function:
protected function redirectTo()
{
if(session('link')){
return view(session('link'));
}
return view('/');
}
I tried replacing return view(session('link')); with return url()->previous(); but there was no luck. I am using laravel 7.
The issue was actually with adding view. Instead of return view(session('link')); use return (session('link')); Same applies to the return outside the if statement.
try to use redirect back
return Redirect::back();
do not forget to import redirect in controller
use Redirect;
i have some problem...
here is my code..
i can't get what i swrong with my code.....
here is the error
here is my user class
this is the full DashboardController
/**
* '/home' calls this route
*
* #param none
* #return view dashboard
*/
public function index()
{
$this->permission();
$data = [
'pagetitle' => 'Dashboard',
'permission' => Session()->get('permission'),
'name' => Auth::user()->name,
];
return view('dashboard',$data);
}
/**
* Checks if session has permission in it if not they adds to it
*
* #param null
* #return null
*/
private function permission()
{
if (!Session()->has('permission')) {
$permission = User::find(Auth::user()->id)->details;
$permission_arr = [
'department' => $permission->permission_department,
'asset' => $permission->permission_asset,
'users' => $permission->permission_users,
];
Session()->put('permission', $permission_arr);
}
}
}
i have no idea how solve it..
any help would be great..
You get this kind of problem for you are getting only access of details column From your User table . Remove the details from $permission = User::find(Auth::user()->id);
private function permission(){
if (!Session()->has('permission')){
$permission = User::find(Auth::user()->id);
$permission_arr = [
'department' => $permission->permission_department,
'asset' => $permission->permission_asset,
'users' => $permission->permission_users,
];
Session()->put('permission', $permission_arr);
}
}
Note I have only remove the details object from your permission variable
I want to implement a backend user management but how can i set up a hased password for a user?
my controller:
public function store(Request $request)
{
$this->validate($request, ['email' => 'required', 'name' => 'required', 'password' => 'required', 'surname' => 'required', ]);
$user = new User($request->all());
$user->password=bcrypt($request);
$user->save();
return redirect('dash/users');
}
view
<div class="form-group {{ $errors->has('password') ? 'has-error' : ''}}">
{!! Form::label('password', trans('users.password'), ['class' => 'col-sm-3 control-label']) !!}
<div class="col-sm-6">
{!! Form::text('password', null, ['class' => 'form-control', 'required' => 'required']) !!}
{!! $errors->first('password', '<p class="help-block">:message</p>') !!}
</div>
</div>
fixed now, the function work and my new user are stored in database, but when i try to login with them the loginform say me "nothing record found"
why?
You need to pass the password text to bcrypt instead of whole $request
$user->password=bcrypt('yourpasswordtext');
<?php
namespace App\Http\Controllers\Dash;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Auth;
use App\User;
use App\Report;
use App\Category;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Session;
class UsersController extends Controller
{
/**
* Display a listing of the resource.
*
* #return void
*/
public function index()
{
$users = User::paginate(15);
return view('dash.users.index', compact('users'));
}
/**
* Show the form for creating a new resource.
*
* #return void
*/
public function create()
{
return view('dash.users.create');
}
/**
* Store a newly created resource in storage.
*
* #return void
*/
public function store(Request $request)
{
$this->validate($request, ['email' => 'required', 'name' => 'required', 'password' => 'required', 'surname' => 'required', ]);
$user = new User($request->all());
$user->password = bcrypt($request);
$user->save();
return redirect('dash/users');
}
/**
* Display the specified resource.
*
* #param int $id
*
* #return void
*/
public function show($id)
{
$user = User::findOrFail($id);
return view('dash.users.show', compact('user'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
*
* #return void
*/
public function edit($id)
{
$user = User::findOrFail($id);
return view('dash.users.edit', compact('user'));
}
/**
* Update the specified resource in storage.
*
* #param int $id
*
* #return void
*/
public function update($id, Request $request)
{
$this->validate($request, ['email' => 'required', 'name' => 'required', 'password' => 'required', 'surname' => 'required', ]);
$user = User::findOrFail($id);
$user->update($request->all());
Session::flash('flash_message', 'User updated!');
return redirect('dash/users');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
*
* #return void
*/
public function destroy($id)
{
User::destroy($id);
Session::flash('flash_message', 'User deleted!');
return redirect('dash/users');
}
}
update, this is controller
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
/* ruote for Admin */
Route::group(['middleware' => ['web']], function () {
Route::resource('dash/reports', 'Dash\\ReportsController');
});
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('dash/categories', 'Dash\\CategoriesController');
});
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('dash/roles', 'Dash\\RolesController');
});
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('dash/permissions', 'Dash\\PermissionsController');
});
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('dash/users', 'Dash\\UsersController');
});
/* another routes */
Route::auth();
Route::get('/provola', 'HomeController#autorizzazione');
Route::get('/home', 'HomeController#index');
Route::get('/', function () {return view('welcome');});
/* injection for user roles
Route::get('/start', 'HomeController#inject');
*/
my routes
For Laravel 5.6+
Password should be hashed using Hash::make($password)