ravinder sharma
ravinder sharma

Reputation: 11

laravel 7 authentication not working with jenssegers-mongodb

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Model\Company;
use App\Model\User;
use Crypt;
use Hash;
use Illuminate\Support\Facades\Auth;


class LoginController extends Controller
{
    public function login(Request $request) {
        $email = $request->input('email');
        $password = $request->input('password');

        $user = User::where('email', $email)->first();
        if ($user) {
            if (! $user->is_verified) {
                return response()->json(['success' => false,'message' => 'User not verified.']);
            }
            if (Auth::attempt(['email' => $email, 'password' => $password])) {
                return response()->json(['success' => true,'message' => 'Logged in successfully.']);
            }
            return response()->json(['success' => false,'message' => 'User not found.']);

        } else {
            return response()->json(['success' => false,'message' => 'User not found.']);
        }
    }
}
<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

use Illuminate\Notifications\Notifiable;
use Jenssegers\Mongodb\Auth\User as Authenticatable;

class User extends Authenticatable 
{
    use Notifiable;

    protected $primaryKey = '_id';

    protected $connection = 'mongodb';
    protected $collection = 'users';
    
    protected $fillable = [
        'name', 'email','password','user_type', 'company_id' , 'is_verified', 'is_active','created_at'
    ];

    public function getAuthIdentifierName(){

    }
    public function getAuthIdentifier(){

    }
    public function getAuthPassword(){

    }
    public function getRememberToken(){

    }
    public function setRememberToken($value){

    }
    public function getRememberTokenName(){
        
    }
}
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Model\Company;
use App\Model\User;
use Illuminate\Support\Facades\Hash;
use Auth;
use Mail;
use Crypt;

class RegisterController extends Controller
{
    public function userSignup(Request $request) {

        $name = $request->input('name');
        $email = $request->input('email');
        $password = Hash::make($request->input('password'));

        $user = User::where('email', $email)->first();
        if ($user) {
            return response()->json(['success' => false,'message' => 'User already exists.']);
        } else {
            $this->userSignUpProcess($name, $email, $password);
            return response()->json(['success' => true,'message' => 'User signed up successfully.Verify email to login']);
        }
    }

    private function userSignUpProcess($name, $email, $password, $company_id=0){
        $user = User::create([
            'name' =>$name,
            'email' => $email,
            'password' => $password,
            'company_id' => $company_id,
            'is_verified' => false,
            'is_active' => true
        ]);
        $hash_user_id = Crypt::encryptString($user->_id);
        Mail::send('mails.verify-account', ['hash_user_id' => $user->_id], function ($mail) use ($user) {
            $mail->from('[email protected]', config('app.name'));
            $mail->to($user->email)->subject('Verify Your account');
        });
    }
}

Auth::attempt(['email' => $email, 'password' => $password]) returning false. Hash::check($password, $user->password); This is returning true. Using laravel 7 auth is not working with MongoDB. For MongoDB I am using jenssegers/mongodb 4.0.0-alpha.1. But now I'm facing error when I'm creating login authentication in Laravel controller.

Any one Please help.

Upvotes: 1

Views: 1338

Answers (2)

linh dinhvan
linh dinhvan

Reputation: 61

I encountered a similar error, at login then redirest, Auth::user() returned null.

I discovered the culprit is the data type of created_at, updated_at which is string. The solution is to convert the string data type to mongoDB date

Upvotes: 0

Hitesh Vaghani
Hitesh Vaghani

Reputation: 194

app/Models/User.php

<?php

namespace App\Models;

use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
use Illuminate\Auth\Authenticatable as AuthenticatableTrait;
use Illuminate\Contracts\Auth\Authenticatable;

class User extends Eloquent implements Authenticatable
{
    use AuthenticatableTrait;

    protected $connection = 'mongodb';
    protected $collection = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token'
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime'
    ];
}

config/database.php

<?php

return [

    'default' => env('DB_CONNECTION', 'mongodb'),

    'connections' => [

        ********************************

        'mongodb' => [
            'driver' => 'mongodb',
            'dsn' => env('DB_URI', 'mongodb+srv://username:[email protected]/myFirstDatabase?retryWrites=true&w=majority'),
            'database' => 'my_management',
        ],

    ],

    ********************************
];

app/Http/Controllers/Auth/LoginController.php

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
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 = RouteServiceProvider::HOME;

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

app/Http/Controllers/Auth/RegisterController.php

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

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, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\Models\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'api_token' => Str::random(80),
        ]);
    }
}

After you have changed User.php and database.php.

The RegisterController.php and LoginController.php files are as it is, provided by laravel.

I don't think there will be any other files that you have to change.

You can access MongoDB Databases using NoSQLBooster for MongoDB and MongoDBCompass.

Upvotes: 0

Related Questions