A
A
AlpineMilk2018-08-24 23:06:28
Laravel
AlpineMilk, 2018-08-24 23:06:28

How to make a separate login form using laravel?

I have two login forms. One for the admin in the admin panel, the other for entering the chat for ordinary users.
When I log in through the chat form, I can also go to the admin panel, please tell me how to solve this problem? here is my controller
code

class LoginController extends Controller
{
    use AuthenticatesUsers;

    protected $redirectTo = '/chat';

    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }

    public function showLoginForm()
    {
        return view('chat.chat_login');
    }

    public function logout(){
        Auth::logout();
        return redirect('/chat/login');
    }

    public function login(Request $request)
    {
        if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
            return redirect(route('chat'));
        }
    }

    protected function guard()
    {
        return Auth::guard('chatLogin');
    }
}

Middleware
class ChatLogin
{
    public function handle($request, Closure $next,$guard = 'chatLogin')
    {
        if (!Auth::guard($guard)->check()) {
            return redirect('/chat/login');
        }
        return $next($request);
    }
}

guards and providers
'guards' => [
     'chatLogin' =>[
            'driver' => 'session',
            'provider' => 'chatLogin',
        ],
    ],

'providers' => [
        'chatLogin' => [
            'driver' => 'eloquent',
            'model' => App\Models\ChatUser::class,
        ],
    ],

like everything
PS If something needs to be added, then write

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kairat Ubukulov, 2018-08-25
@ubukulov

It is better to make 2 controllers. One for the admin and one for users.
Here is the code:

<?php
namespace App\Http\Controllers\Admin;
use App\Admin;
use Validator;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Http\Request;
class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */
    use AuthenticatesAndRegistersUsers, ThrottlesLogins;
    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/admin/dashboard';
    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }
    /**
     * 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, [
            'username' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
        ]);
    }
    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return Admin::create([
            //'name' => $data['name'],
            //'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
    public function showLogin(){
        return view('admin/login');
    }
    public function authenticate(Request $request){
        if (Auth::guard('admin')->attempt(['username' => $request->get('username'), 'password' => $request->get('password')])) {
            return redirect()->intended('admin/dashboard');
        }else{
            return redirect()->back()->with('message', 'Логин или пароль не правильный');
        }
    }
    protected function guard(){
        return Auth::guard('admin');
    }
    protected function username(){
        return 'username';
    }
    public function logout(){
        Auth::guard('admin')->logout();
        return redirect()->route('home');
    }
}

Вот контроллер для пользователей:

<?php
namespace App\Http\Controllers\Usr;
use App\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Validator;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Http\Request;
use Cookie;
use App\Card;
class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */
    use AuthenticatesAndRegistersUsers, ThrottlesLogins;
    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/user/account';
    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
    }
    /**
     * 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, [
            'username' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
        ]);
    }
    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return User::create([
            //'name' => $data['name'],
            //'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
    public function showLogin(){
        return view('user/login');
    }
    public function authenticate(Request $request){
        if (Auth::attempt(['mphone' => $request->get('username'), 'password' => $request->get('password')])) {
            $this->checkPartnerAuth();
//            if(Cookie::has('store')){
////                return redirect(Cookie::get('cert'));
//                return redirect('/cart');
//            }
            if(isset($_SESSION['REQUEST_URI'])){
                return redirect('/store'.$_SESSION['REQUEST_URI']);
            }
            return redirect()->intended('user/account');
        }else{
            return redirect()->back()->with('message', 'Логин или пароль не правильный');
        }
    }
    protected function username(){
        return 'mphone';
    }
    # проверка
    public function checkPartnerAuth(){
        if(Auth::guard('partner')->check()){
            Auth::guard('partner')->logout();
        }
    }
    # форма сброса пароля пользователя
    public function showResetForm(){
        return view('user/password-reset');
    }
    # сброс пароля
    public function reset(Request $request){
        $phone = $request->get('username');
        $password = generateCode(4);
        $hash_password = Hash::make($password);
        sendSms($phone,"Vash noviy parol: $password");
        $result = DB::update("UPDATE users SET password='$hash_password' WHERE mphone='$phone'");
        if($result){
            return redirect()->back()->with('message', 'Пароль успешно сброшен. Новый пароль отправлено на ваш номер.');
        }
    }
    # форма регистрации нового пользователя
    public function showRegisterForm(){
        return view('user/user-register');
    }
    
    # регистрация нового пользователя
    public function register(Request $request){
        $password = generateCode(4);
        $hash_password = Hash::make($password);
        $phone = $request->get('username');
        $balance = __encode('0', env('KEY'));
        $data = [
            'firstname' => $request->get('firstname'), 'lastname' => $request->get('lastname'),
            'email' => $request->get('email'), 'mphone' => $phone, 'fm' => $balance,
            'referral' => $request->get('id_referral'), 'password' => $hash_password
        ];
        if(User::check_user_by_phone($phone)){
            $lastInsertId = User::create($data)->id;
            if($lastInsertId){
                Auth::loginUsingId($lastInsertId, true);
                Card::setCard($lastInsertId);
                sendSms($phone, "Vashy dannye: Login: $phone, parol: $password");
                return redirect('user/account');
            }
        }else{
            return redirect()->back()->with('message', 'Пользователь с таким номер уже зарегистрирован');
        }
    }
}

Ниже посредники.

Посредник для админку.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfNotAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Auth::guard('admin')->check()) {
            return redirect('/admin/dashboard');
        }
        return $next($request);
    }
}

Посредник для пользователей:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {
            return redirect('/');
        }
        return $next($request);
    }
}

More or less like this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question