hi i create a project in hmvc architecture with creolab module in laravel 4 here
let say i divided my project into 3 module like example there
--module--
auth
shop
content
the scenario here user must login in auth modul first
after that they be able to access 2 module left (Shop & content)
when i try to auth protecting route in module shop or content like this example
Authenticating Group */
Route::group(array('before' => 'auth'), function() {
Route::get('shop', array(
'as' => 'shop',
'uses' => 'App\Modules\Shop\Controllers\ShopController#getShop'
));
});
i can't access it although i already success login in modul Auth
i already confirm it i success login with return string like this
i think the problem is here
in my module account, my accountController contain script like this
public function postLogin() {
$validator = Validator::make(Input::all(), array(
'username' => 'required',
'password' => 'required'
));
if($validator->fails()) {
return Redirect::route('login.post')
->withErrors($validator);
} else {
$auth = Auth::attempt(array(
'username' => Input::get('username'),
'password' => Input::get('password')
));
if($auth) {
return "login success";
// return Redirect::intended('shop');
}
else {
return Redirect::route('login')
->with('global', 'Email or Password Not Match');
}
}
}
when i return simple string (disable redirect) i got login successin screen that indicate i already success login, but when i active redirect to another module, i got push back to login page
i check auth state with this simple script in login page like this
#if (Auth::check())
{{ login }}
#else
{{ "not login "}}
#endif
and got not login text
can someone help me?
#update
public function postLogin() {
$validator = Validator::make(Input::all(), array(
'username' => 'required',
'password' => 'required'
));
if($validator->fails()) {
return Redirect::route('login.post')
->withErrors($validator);
} else {
$auth = Auth::attempt(array(
'username' => Input::get('username'),
'password' => Input::get('password')
));
if($auth) {
return Redirect::intended('shop');
}
else {
return Redirect::route('login')
->with('global', 'Email or Password Not Match');
}
}
}
#2nd Update
route in shop module
<?php
/* Authenticating Group */
Route::group(array('before' => 'auth'), function() {
Route::get('shop', array(
'as' => 'shop',
'uses' => 'App\Modules\Shop\Controllers\ShopController#getShop'
));
Route::post('shop', array(
'as' => 'shop.post',
'uses' => 'App\Modules\Shop\Controllers\ShopController#postShop'
));
Route::post('shop-delete', array(
'as' => 'shop.delete',
'uses' => 'App\Modules\Shop\Controllers\ShopController#postShopDelete'
));
});
#update my authentication filters.php
/*
|--------------------------------------------------------------------------
| Authentication Filters
|--------------------------------------------------------------------------
|
| The following filters are used to verify that the user of the current
| session is logged into this application. The "basic" filter easily
| integrates HTTP Basic authentication for quick, simple checking.
|
*/
Route::filter('auth', function()
{
if (Auth::guest())
{
if (Request::ajax())
{
return Response::make('Unauthorized', 401);
}
else
{
return Redirect::guest('login');
}
}
});
Try this if it works.
if(Auth::attempt(['usernae' => Input::get('username'), 'password' => Input::get('password')]))
{
return 'login success';
}else{
return 'login failed';
}
Related
I'm creating a login function in Laravel 5.4 and I want to show error message in the view when the password is incorrect. Also I have a custom message for account approval so it makes things a bit difficult for me. Meanwhile I put those messages together but is not very user-friendly. How can I separate them?
This is my controller:
public function login(Request $request)
{
// validate the form data
$this->validate($request, [
'email' => 'required|email|exists:users,email',
'password' => 'required|min:6'
]);
// attempt to log
if (Auth::attempt(['approve' => '1', 'email' => $request->email, 'password' => $request->password ], $request->remember)) {
// if successful -> redirect forward
return redirect()->intended(route('user.overview'));
}
// if unsuccessful -> redirect back
return redirect()->back()->withInput($request->only('email', 'remember'))->withErrors([
'approve' => 'Wrong password or this account not approved yet.',
]);
}
As result i want to replace Wrong password or this account not approved yet with two separate messages:
If password is wrong to show: Password is wrong
If account not approved show: This account not approved yet
You can pass custom error messages for each validation rule, you can do this:
public function login(Request $request)
{
//Error messages
$messages = [
"email.required" => "Email is required",
"email.email" => "Email is not valid",
"email.exists" => "Email doesn't exists",
"password.required" => "Password is required",
"password.min" => "Password must be at least 6 characters"
];
// validate the form data
$validator = Validator::make($request->all(), [
'email' => 'required|email|exists:users,email',
'password' => 'required|min:6'
], $messages);
if ($validator->fails()) {
return back()->withErrors($validator)->withInput();
} else {
// attempt to log
if (Auth::attempt(['approve' => '1', 'email' => $request->email, 'password' => $request->password ], $request->remember)) {
// if successful -> redirect forward
return redirect()->intended(route('user.overview'));
}
// if unsuccessful -> redirect back
return redirect()->back()->withInput($request->only('email', 'remember'))->withErrors([
'approve' => 'Wrong password or this account not approved yet.',
]);
}
}
Before this, you have to include Validator class:
use Illuminate\Support\Facades\Validator;
Without writing a new custom login method we can easily handle a custom wrong password message with the Auth default login process.
Open LoginController from the location: app/Http/Controllers/Auth/
Include the Request class if not exit on top of the controller
use Illuminate\Http\Request;
Finally add below line of codes at the very bottom of your LoginController to process the response error with custom message
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
protected function sendFailedLoginResponse(Request $request)
{
$errors = [$this->username() => trans('auth.failed')];
// Load user from database
$user = \App\User::where($this->username(), $request->{$this->username()})->first();
if ($user && !\Hash::check($request->password, $user->password)) {
$errors = ['password' => 'Wrong password'];
}
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}
You can use like this:
return Redirect::back()->withInput(Input::all());
If you're using Form Request Validation, this is exactly how Laravel will redirect you back with errors and the given input.
Excerpt from \Illuminate\Foundation\Validation\ValidatesRequests:
return redirect()->to($this->getRedirectUrl())
->withInput($request->input())
->withErrors($errors, $this->errorBag());
Controller:
public function login(Request $request)
{
// validate the form data
$this->validate($request, [
'email' => 'required|email|exists:users,email',
'password' => 'required|min:6'
]);
// attempt to log
if (Auth::attempt(['approve' => '1', 'email' => $request->email, 'password' => $request->password ], $request->remember)) {
// if successful -> redirect forward
return redirect()->intended(route('user.overview'));
}
// if unsuccessful -> redirect back
return Redirect::back()
->withInput()
->withErrors(
[
'password' => 'Wrong Password',
],
[
'approve' => 'Account not approved',
],
);
}
In my app I have two types of users - admin and teacher. In my AuthController I have this :
public function getLogin() {
return view('auth.login');
}
public function postLogin(\Illuminate\Http\Request $request) {
if(Auth::attempt([
'username' => $request->input('username'),
'password' => $request->input('password'),
'type' => 'admin'
])) {
return redirect ('admin');
}
if(Auth::attempt([
'username' => $request->input('username'),
'password' => $request->input('password'),
'type' => 'teacher'
])) {
return redirect ('educator/account');
}
return redirect('login')->with('message', [
'type' => 'danger',
'message' => 'Грешно потребителско име или парола!'
]);
}
public function getLogout() {
Auth::logout();
return redirect('login');
}
But when I'm logged in as a user with type teacher if i go to http://localhost/school_system/public/admin I automatically go to the admin panel without asking for username and password. I want if I want to go to the admin panel from the teacher account this to happen with asking for username and password, how can I make this?
My routes:
Route::group(['middleware' => ['auth']
], function () {
Route::group([
'prefix' => 'admin',
'namespace' => 'Admin'
], function () {
Route::controller('student', 'StudentsController');
Route::controller('profile', 'ProfilesController');
Route::controller('class', 'ClassesController');
Route::controller('subjects', 'SubjectsController');
Route::controller('teacher', 'TeachersController');
Route::controller('marktype', 'MarkTypeController');
Route::controller('rules', 'RuleController');
Route::get('{slug?}', 'PageController#getView');
});
});
Route::group(['middleware' => ['auth']
], function () {
Route::group([
'prefix' => 'educator',
'namespace' => 'Educator'
], function () {
Route::controller('account', 'AccountController');
Route::get('{slug?}', 'EducatorController#getView');
});
});
Thanks ^^
You can create an "adminmiddleware" : php artisan make:middleware AdminMiddleware
Example of code you can use
if ($request->user()->type != 'admin')
{
return redirect('home');
}
and in the route:
Route::group(['middleware' => ['admin']...
Finished ;)
I tried to create a login, after I tried successfully identified,
return "Success Login";
but when I replace with
return Redirect::to('dashboard');
always returned to Login page
can you help me ? what's wrong with my code...
here is my code :
route.php
Route::get('login',array('as' => 'login', 'uses' => 'AuthController#getLogin'))->before('guest');
Route::post('login',array('uses' => 'AuthController#postLogin'))->before('csrf');
Route::group(array('before' => 'auth'), function(){
Route::get('dashboard', array('as' => 'panel', 'uses' => 'DashboardController#view_dashboard'));
});
AuthController.php
class AuthController extends Controller {
public function getLogin(){
return View::make('users.login');
}
public function postLogin(){
$rules = array('username' => 'required', 'password' => 'required');
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()){
return Redirect::route('login')->withErrors($validator);
}
$auth = Auth::attempt(array(
'username' => Input::get('username'),
'password' => Input::get('password')
), false);
if(!$auth){
return Redirect::route('login')->withErrors(array(
'Maaf anda bukan sebagai admin..'
));
}
//return "Success";
return Redirect::to('dashboard');
}
}
DashboardController.php
class DashboardController extends Controller {
public function view_dashboard(){
return View::make('dashboard.view_home_admin');
}
}
view_home_admin.blade.php
<h1>Welcome <small>{{ ucwords(Auth::user()->username) }}</small></h1>
I'm getting this TokenMismatchException with Laravel 4.2.
TokenMismatchException will show up when I trying to post request.
For example Login Page.
If I submit that form TokenMismatchException will show up.
Is there any way I can validate all post request submitted ?
Here's the error :
Route::filter('csrf', function()
{
if (Session::token() != Input::get('_token'))
{
throw new Illuminate\Session\TokenMismatchException;
}
});
Here's my code :
route.php
Route::get('login',array('as' => 'login', 'uses' => 'AuthController#getLogin'))->before('guest');
Route::post('login',array('uses' => 'AuthController#postLogin'))->before('csrf');
Route::group(array('before' => 'auth'), function(){
Route::get('dashboard', array('as' => 'panel', 'uses' => 'DashboardController#view_dashboard'));
});
AuthController.php
class AuthController extends Controller {
public function getLogin(){
return View::make('users.login');
}
public function postLogin(){
$rules = array('username' => 'required', 'password' => 'required');
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()){
return Redirect::route('login')->withErrors($validator);
}
$auth = Auth::attempt(array(
'username' => Input::get('username'),
'password' => Input::get('password')
), false);
if(!$auth){
return Redirect::route('login')->withErrors(array(
'Maaf anda bukan sebagai admin..'
));
}
//return "Success";
return Redirect::to('dashboard');
}
}
DashboardController.php
class DashboardController extends Controller {
public function view_dashboard(){
return View::make('dashboard.view_home_admin');
}
}
seems like you don't have hidden csrf field in your form.
try to add this in your form
{{ Form::token() }}
In my L4 App i use subdomains for my routing to different stuff.
accounts.domain.com = where alle the Authentication stuff happens
dashboard.domain.com = The main frontpage for authenticated users
community.domain.com = Community stuff for authenticated users.
If someone visits community.domain.com/forum and is not autenticated he should be send to accounts.domain.com, login and then get redirected back to the Forum.
But now i have 2 problems.
1 and major problem: afer the login the user is only autenticated for the domain: accounts.domain.com
for all other domains he gets redirected to the login.
If a user is autenticated and trys to access dashboard.domain.com he gets redirected to the login page.
and the 2. problem is the redirect after the login.
Atm i just have a static redirect after the login, doesn't matter where the user was coming from. How can i change it so he get redirected back to the page he tried to visited as unauthenticated user before?
My routes file:
Route::get('login', function()
{
return Redirect::action('AccountsController#getLogin');
});
Route::group(array('domain' => 'accounts.domain.com'), function()
{
Route::get('/', function()
{
return Redirect::action('AccountsController#getLogin');
});
Route::get('users/sing_in', array('as' => 'login', 'uses' => 'AccountsController#getLogin'));
Route::post('users/sing_in', array('as' => 'login', 'uses' => 'AccountsController#doLogin'));
Route::get('users/sing_out', array('as' => 'logout', 'uses' => 'AccountsController#doLogout'));
Route::group(array('before' => 'auth'), function() {
Route::get('users/profile', array('as' => 'profile', 'uses' => 'AccountsController#getProfile'));
});
});
Route::group(array('domain' => 'dashboard.domain.com'), function()
{
Route::group(array('before' => 'auth'), function() {
Route::get('/', array('as' => 'dashhome', 'uses' => 'DashboardController#getIndex')); //If someone tries to access this, he get redirected to the login page, even if he just authenticated himself
});
});
And my Login Controller:
public function getLogin()
{
if (Auth::check()) {
return Redirect::action('AccountsController#getProfile');
} else {
return View::make('login.index');
}
}
public function doLogin()
{
$rules = array(
'email' => 'required|email',
'password' => 'required|min:3'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::route('login')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
$userdata = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
if (Auth::attempt($userdata)) {
return Redirect::action('AccountsController#getProfile');
} else {
return Redirect::route('login')->withErros('Wrong E-mail address or Password');
}
}
}
public function doLogout()
{
Auth::logout(); // log the user out of our application
return Redirect::route('login'); // redirect the user to the login screen
}
Thanks for any help.
Set the domain in app/config/session.php to .domain.com, so a session gets shared between subdomains.
To redirect the user, you can return Redirect::back() or Redirect::route(<wherever the user should land>).