لارافل Auth user

Fmnmt27 • منذ 5 سنوات

السلام عليكم ورحمة الله وبركاته

عندي مشكلة لما بعمل يوزر في الموقع وبعمل لوجن وبعدين دخلت على الموقع من جهاز ثاني بيدخل على صفحتي على طول من غير ما يعمل لوجن او تسجيل وكأنه اليوزر تبعي بيصير public

ممكن احد يفيدني ايش المشكله هذي وليش بتظهر معايا علما انها غير ثابته تظهر احيانا و احيانا لاتظهر ....... وشكرا

ساعد بالإجابة

"إن في قضاء حوائج الناس لذة لا يَعرفها إلا من جربها، فافعل الخير مهما استصغرته فإنك لا تدري أي حسنة تدخلك الجنة."

الإجابات (5)

Ali Majrashi • منذ 5 سنوات

وعليكم السلام ورحمة الله وبركاته

ممكن تحديث السؤال ووضع الكود المسؤل عن تسجيل الدخول الواضح انه يقوم بتسجيل دخول على طول هذي جدا غريبة ممكن فيه خطا في طريقة التعامل مع تسجيل الدخول 

اسهل طريقة لعمل تسجيل دخول وتسجيل عضويات هي باستخدام scafold الافتراضي الي يجي من لارافيل عن طريق Terminal نفذي الامر 

php artisan make:auth

ثم عدلي على ملفات الي داخل controller بمجلد Auth بما يناسبك وايضا على ملفات view داخل مجلد auth غالبا تعديلات طفيفة 

اذا مشروعك على آخر نسخه يدعم ايضا امكانية طلب تفعيل العضو لاميله قبل تسجيل الدخول للمشروع 

كامل المستندات لعملية تسجيل الدخول من هنا 

Authentication

Fmnmt27 • منذ 5 سنوات
<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],

        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],

        'api-admin' => [
            'driver' => 'token',
            'provider' => 'admins',
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],

        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Admin::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],

        'admins' => [
            'provider' => 'admins',
            'table' => 'password_resets',
            'expire' => 15,
        ],

    ],

];
Fmnmt27 • منذ 5 سنوات

session.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Session Driver
    |--------------------------------------------------------------------------
    |
    | This option controls the default session "driver" that will be used on
    | requests. By default, we will use the lightweight native driver but
    | you may specify any of the other wonderful drivers provided here.
    |
    | Supported: "file", "cookie", "database", "apc",
    |            "memcached", "redis", "array"
    |
    */

    'driver' => env('SESSION_DRIVER', 'file'),

    /*
    |--------------------------------------------------------------------------
    | Session Lifetime
    |--------------------------------------------------------------------------
    |
    | Here you may specify the number of minutes that you wish the session
    | to be allowed to remain idle before it expires. If you want them
    | to immediately expire on the browser closing, set that option.
    |
    */

    'lifetime' => env('SESSION_LIFETIME', 120),

    'expire_on_close' => false,

    /*
    |--------------------------------------------------------------------------
    | Session Encryption
    |--------------------------------------------------------------------------
    |
    | This option allows you to easily specify that all of your session data
    | should be encrypted before it is stored. All encryption will be run
    | automatically by Laravel and you can use the Session like normal.
    |
    */

    'encrypt' => false,

    /*
    |--------------------------------------------------------------------------
    | Session File Location
    |--------------------------------------------------------------------------
    |
    | When using the native session driver, we need a location where session
    | files may be stored. A default has been set for you but a different
    | location may be specified. This is only needed for file sessions.
    |
    */

    'files' => storage_path('framework/sessions'),

    /*
    |--------------------------------------------------------------------------
    | Session Database Connection
    |--------------------------------------------------------------------------
    |
    | When using the "database" or "redis" session drivers, you may specify a
    | connection that should be used to manage these sessions. This should
    | correspond to a connection in your database configuration options.
    |
    */

    'connection' => null,

    /*
    |--------------------------------------------------------------------------
    | Session Database Table
    |--------------------------------------------------------------------------
    |
    | When using the "database" session driver, you may specify the table we
    | should use to manage the sessions. Of course, a sensible default is
    | provided for you; however, you are free to change this as needed.
    |
    */

    'table' => 'sessions',

    /*
    |--------------------------------------------------------------------------
    | Session Cache Store
    |--------------------------------------------------------------------------
    |
    | When using the "apc" or "memcached" session drivers, you may specify a
    | cache store that should be used for these sessions. This value must
    | correspond with one of the application's configured cache stores.
    |
    */

    'store' => null,

    /*
    |--------------------------------------------------------------------------
    | Session Sweeping Lottery
    |--------------------------------------------------------------------------
    |
    | Some session drivers must manually sweep their storage location to get
    | rid of old sessions from storage. Here are the chances that it will
    | happen on a given request. By default, the odds are 2 out of 100.
    |
    */

    'lottery' => [2, 100],

    /*
    |--------------------------------------------------------------------------
    | Session Cookie Name
    |--------------------------------------------------------------------------
    |
    | Here you may change the name of the cookie used to identify a session
    | instance by ID. The name specified here will get used every time a
    | new session cookie is created by the framework for every driver.
    |
    */

    'cookie' => env(
        'SESSION_COOKIE',
        str_slug(env('APP_NAME', 'laravel'), '_').'_session'
    ),

    /*
    |--------------------------------------------------------------------------
    | Session Cookie Path
    |--------------------------------------------------------------------------
    |
    | The session cookie path determines the path for which the cookie will
    | be regarded as available. Typically, this will be the root path of
    | your application but you are free to change this when necessary.
    |
    */

    'path' => '/',

    /*
    |--------------------------------------------------------------------------
    | Session Cookie Domain
    |--------------------------------------------------------------------------
    |
    | Here you may change the domain of the cookie used to identify a session
    | in your application. This will determine which domains the cookie is
    | available to in your application. A sensible default has been set.
    |
    */

    'domain' => env('SESSION_DOMAIN', null),

    /*
    |--------------------------------------------------------------------------
    | HTTPS Only Cookies
    |--------------------------------------------------------------------------
    |
    | By setting this option to true, session cookies will only be sent back
    | to the server if the browser has a HTTPS connection. This will keep
    | the cookie from being sent to you if it can not be done securely.
    |
    */

    'secure' => env('SESSION_SECURE_COOKIE', false),

    /*
    |--------------------------------------------------------------------------
    | HTTP Access Only
    |--------------------------------------------------------------------------
    |
    | Setting this value to true will prevent JavaScript from accessing the
    | value of the cookie and the cookie will only be accessible through
    | the HTTP protocol. You are free to modify this option if needed.
    |
    */

    'http_only' => true,

    /*
    |--------------------------------------------------------------------------
    | Same-Site Cookies
    |--------------------------------------------------------------------------
    |
    | This option determines how your cookies behave when cross-site requests
    | take place, and can be used to mitigate CSRF attacks. By default, we
    | do not enable this as other CSRF protection services are in place.
    |
    | Supported: "lax", "strict"
    |
    */

    'same_site' => null,

];

Alhoqbani: الكود هذا ما يكفي عشان تبان المشكلة. نحتاج الكنترولر والرواتس.

Ali Majrashi: فعلا جميع الاكواد الموجودة هي لملفات الاعدادات ولكن نحتاج الكود المسؤل عن عملية تسجيل الدخول بالضبط غالبا داخل كنترولر او ميدل واير لان ماندري كيف المشروع وترتيب ملفاته واكواده

Fmnmt27 • منذ 5 سنوات

LoginController.php

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
}

RegisterController.php

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

use Mail;
use App\Mail\NewMailRequest;


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 = '/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, [
            'name'           => 'required|string|max:255',
            'email'          => 'required|string|email|max:255|unique:users',
            'mobile'         => 'required|string|min:9|max:15',
            'password'       => 'required|string|min:6|confirmed',
            'organization'   => 'string|max:255|nullable',
            'website'        => 'string|max:255|nullable',
            'account_type'   => 'required',
            'position'       => 'string|max:255|nullable',
            'country'        => 'string|max:255|nullable',
            'city'           => 'string|max:255|nullable',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        if(empty($data['position'])){ $data['position'] = ' ';}
        if(empty($data['country'])){ $data['country'] = ' ';}
        if(empty($data['city'])){ $data['city'] = ' ';}

        /********************/
        $user = User::create([
            'name'          => $data['name'],
            'email'         => $data['email'],
            'mobile'        => $data['mobile'],
            'organization'  => $data['organization'],
            'portal'        => $data['website'],
            'type'          => $data['account_type'],
            'position'      => $data['position'],
            'country'       => $data['country'],
            'city'          => $data['city'],
            'password'      => bcrypt($data['password']),
            'token'         => str_random(25),
        ]);
        //---------------------------------------------------------
        //$user->notify(new VerifyEmail($user));
        if($data['account_type'] == 1){
          $user->sendVerificationEmail();
        }else{
          //$request = array();
          $id_user = \DB::getPdo()->lastInsertId();
          $request = (object)  array(
              'id'            => $id_user,
              'name'          => $data['name'],
              'email'         => $data['email'],
              'mobile'        => $data['mobile'],
              'organization'  => $data['organization'],
              'portal'        => $data['website'],
              'position'      => $data['position'],
              'country'       => $data['country'],
              'city'          => $data['city'],
              'active'        => 0,
              'sender'        => 'ADMIN',
              'e_page'        => 'registration',
              'e_title'       => Config('setting.TITLE_REGISTER_1'),
              'e_message'     => Config('setting.CONTENT_REGISTER_1'),
          );
          Mail::to( Config('setting.MAIN_EMAIL_ADMIN') )->send(new NewMailRequest($request));
        }
        //---------------------------------------------------------

        return $user;
        /********************/




    }
}

AuthAdmin -->LoginController.php

<?php
namespace App\Http\Controllers\AuthAdmin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */
    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/index';
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest:admin')->except(['logout']);
    }
    /**
     * Show the application's login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showLoginForm()
    {
        return view('authAdmin.login');
    }
    /**
     * Handle a login request to the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $this->validate($request, [
            'email' => 'required|email',
            'password' => 'required|min:6'
        ]);
        $credential = [
            'email' => $request->email,
            'password' => $request->password
        ];
        // Attempt to log the user in
        if (Auth::guard('admin')->attempt($credential, $request->member)){
            // If login succesful, then redirect to their intended location
            return redirect()->intended(route('admin.home'));
        }
        // If Unsuccessful, then redirect back to the login with the form data
        return redirect()->back()
                         ->withErrors(['Please confirm your email and password'])
                         ->withInput($request->only('email', 'remember'));
        //return redirect()->back()->withInput($request->only('email', 'remember'));
    }

    public function logout(Request $request)
    {

        Auth::guard('admin')->logout();
//        $request->session()->invalidate();
        return redirect('/admin/login');
    }

}

AuthAdmin-->RegisterController.php

<?php
namespace App\Http\Controllers\AuthAdmin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */
    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/index';
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest:admin')->except(['logout']);
    }
    /**
     * Show the application's login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showLoginForm()
    {
        return view('authAdmin.login');
    }
    /**
     * Handle a login request to the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $this->validate($request, [
            'email' => 'required|email',
            'password' => 'required|min:6'
        ]);
        $credential = [
            'email' => $request->email,
            'password' => $request->password
        ];
        // Attempt to log the user in
        if (Auth::guard('admin')->attempt($credential, $request->member)){
            // If login succesful, then redirect to their intended location
            return redirect()->intended(route('admin.home'));
        }
        // If Unsuccessful, then redirect back to the login with the form data
        return redirect()->back()
                         ->withErrors(['Please confirm your email and password'])
                         ->withInput($request->only('email', 'remember'));
        //return redirect()->back()->withInput($request->only('email', 'remember'));
    }

    public function logout(Request $request)
    {

        Auth::guard('admin')->logout();
//        $request->session()->invalidate();
        return redirect('/admin/login');
    }

}

هذي الاكواد اللي في Controller Auth and AuthAdmin

MiddleWare -->RedirectIfAuthentication.php

<?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)
    {
        switch ($guard){
            case 'admin':
                if (Auth::guard($guard)->check()) {
                    return redirect()->route('admin.home');
                }
                break;
            default:
                if (Auth::guard($guard)->check()) {
                    return redirect()->route('home');
                }
                break;
        }
        return $next($request);
    }
}

iهذا الكود اللي في الMiddleWare

Alhoqbani: وش الصفحة اللي تنفتح لاي شخص؟ هل عليها ميدلوير ؟

Fmnmt27: لما بعمل لوجن بيوزري واحد دخل على الموقع في نفس الصفحة بيظهر له اليوزر تبعي وكأنه هو عامل لوجن بيوزري MiddelWare --&gt;RedirecIfAuthentication.php &lt;?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) { switch ($guard){ case 'admin': if (Auth::guard($guard)-&gt;check()) { return redirect()-&gt;route('admin.home'); } break; default: if (Auth::guard($guard)-&gt;check()) { return redirect()-&gt;route('home'); } break; } return $next($request); } }

Fmnmt27: اضفت الكود اللي في الميدلوير في التعليق السابق

Ali Majrashi: هل من الممكن رفع المشروع على github او على bitbucket ووضع الرابط لرؤية جميع الملفات ومحاولة معرفة السبب

Fmnmt27: للأسف المشروع خاص جدا ... لكن انا قمت بحذف ملفات السيشن والتوكن واختفت المشكله حاليا مدري هل ستظهر ثانية ام لا علما انها تظهر احيانا واحيانا لا

Fmnmt27: للأسف المشروع خاص جدا ... لكن انا قمت بحذف ملفات السيشن والتوكن واختفت المشكله حاليا مدري هل ستظهر ثانية ام لا علما انها تظهر احيانا واحيانا لا

Ali Majrashi: غريبه جدا المشكلة لان ممكن يكون شي بالكود حافظ بيانات الدخول ولاتتغير حتى باختلاف الاجهزة اذا رجعت ياريت تكون على الاقل نعرف الكود الي فعلا سببها عشان نقدر نساعد بحلها

Fmnmt27 • منذ 5 سنوات

مارجعت بس ظهرت مشكلة أخري وهي عند تعديل اي شي في الادمن مثل محتوى صفحة معينه وعمل حفظ يظهر الخطأ الآتي 

ErrorException (E_NOTICE)

unserialize(): Error at offset 0 of 40 bytes

/uploads/2018/November/jin8urrpf0moVNweexyiBbIDyWmefbBYgsho9N3Y.png

لايوجد لديك حساب في عالم البرمجة؟

تحب تنضم لعالم البرمجة؟ وتنشئ عالمك الخاص، تنشر المقالات، الدورات، تشارك المبرمجين وتساعد الآخرين، اشترك الآن بخطوات يسيرة !