Alif
Alif

Reputation: 93

Auth::attempt value always false

I have some problem when I want to make login, I got an issue for my Auth::attempt always false value, Is am I got something wrong in my code?

Controller :

public function register(Request $register)
{
    $validator = Validator::make($register->all(), [
        'name' => 'required',
        'email' => 'required|email',
        'password' => 'required',
    ]);
    if ($validator->fails()) {
        return response()->json(['error' => $validator->errors()], 401);
    } else {
        $name = $register->input('name');
        $email = $register->input('email');
        $pwd = $register->input('password');
        $c_pwd = $register->input('c_password');

        // Crypting password & c_password to md5
        $md5_pwd = md5($pwd);
        $md5_c_pwd = md5($c_pwd);

        // Salt password & c_password 
        $password = crypt($md5_pwd, "asd");
        $c_password = crypt($md5_c_pwd, "asd");

        $data = new User();

        if ($password == $c_password) {
            $user = User::create([
                'name' => $name,
                'email' => $email,
                'password' => $password,
            ]);
            $success['token'] = $user->createToken('SSOApp')->accessToken;
            return response()->json([
                'success' => true,
                'token' => $success,
                'user' => $user
            ]);
        } else {
            return response()->json(['error' => "Password doesn't match"], 401);
        }
    }
}

public function login()
{
    $email = request('email');
    $pwd = request('password');
    $md5 = md5($pwd);
    $password = crypt($md5, "asd");
    if (Auth::attempt(['email' => $email, 'password' => $password])) {
        $user = Auth::user();
        $success['token'] = $user->createToken('SSOApp')->accessToken;
        return response()->json([
            'success' => true,
            'token' => $success,
            'user' => $user
        ]);
    } else {
        return response()->json([
            'success' => false,
            'message' => 'Invalid Email or Password',
        ], 401);
    }
}

Upvotes: 1

Views: 1339

Answers (5)

AH.Pooladvand
AH.Pooladvand

Reputation: 2059

Instead of using md5 or crypt use \Hash::make() it is much secure
I refactored your code and it does the same thing
You only need to rename your c_password to password_confirmation
Source
Below code does the same thing that your code do

public function register(Request $register)
{
    $this->validate($register, [
        'name' => 'required',
        'email' => 'required|email',
        'password' => 'required|confirmed',
    ]);

    $user = User::create([
        'name' => $register->input('name'),
        'email' => $register->input('email'),
        'password' => $register->input('password'),
    ]);
    $success['token'] = $user->createToken('SSOApp')->accessToken;

    return response()->json([
        'success' => true,
        'token' => $success,
        'user' => $user,
    ]);
}

public function login(Request $request)
{
    $request->merge(['password' => \Hash::make($request->input('password'))]);

    if (Auth::attempt($request->only(['email', 'password']))) {
        $user = Auth::user();
        $success['token'] = $user->createToken('SSOApp')->accessToken;

        return response()->json([
            'success' => true,
            'token' => $success,
            'user' => $user,
        ]);
    }

    return response()->json([
        'success' => false,
        'message' => 'Invalid Email or Password',
    ], 401);
}

when you hashing password using crypt it has a key to unlock it that's why there is a decrypt but when you use Hash::make() it doesn't have a key to break or unlock it, it will check it's algorithm to see if given password is matching the algorithm that already exists in the database that's why crypt is not safe and Hash::make is much much more safe

Upvotes: 1

Kenneth Sunday
Kenneth Sunday

Reputation: 895

Laravel Auth uses the bcrypt hashing when saving password via model you may use either of the 2 method

$account->password = bcrypt("YOUR_PASSWORD"); or $account->password = Hash::make("YOUR_PASSWORD");

Then if you're dealing with the auth attempt function, just simply call the method like this

if($account = Auth::attemp(['email' => "[email protected]",  'password' => "YOUR_PASSWORD"])){
    //success login, do your extra job here
}else{
    //invalid credentials here
}

Upvotes: 1

Foued MOUSSI
Foued MOUSSI

Reputation: 4813

I assume you messed up with Laravel Default Password Hashing System

public function register(Request $register)
{
    $validator = Validator::make($register->all(), [
        'name' => 'required',
        'email' => 'required|email',
        'password' => 'required',
        'c_password' => 'required|same:password',
    ]);
    if ($validator->fails()) {
        return response()->json(['error' => $validator->errors()], 401);
    } else {
        $name = $register->input('name');
        $email = $register->input('email');
        $pwd = $register->input('password');
        $c_pwd = $register->input('c_password');


        // $data = new User();

        $user = User::create([
                'name' => $name,
                'email' => $email,
                'password' => bcrypt($password . 'salt'),
        ]);

        $success['token'] = $user->createToken('SSOApp')->accessToken;
        return response()->json([
                'success' => true,
                'token' => $success,
                'user' => $user
        ]);

    }
}

public function login()
{
    $email = request('email');
    $pwd = request('password');

    if (Auth::attempt(['email' => $email, 'password' => $password . 'salt'])) {
        $user = Auth::user();
        $success['token'] = $user->createToken('SSOApp')->accessToken;
        return response()->json([
            'success' => true,
            'token' => $success,
            'user' => $user
        ]);
    } else {
        return response()->json([
            'success' => false,
            'message' => 'Invalid Email or Password',
        ], 401);
    }
}

Upvotes: 1

Andy Song
Andy Song

Reputation: 4684

your problem is that laravel by default hashes the password. so when you do Auth::attempt it's going to hash the password you provided. And the result is what you get, it will always false.

Instead, you need to Other Authentication Methods.

Auth::login($user);

// Login and "remember" the given user...
Auth::login($user, true);

Above is the easiest way to fix your code.

It's recommended to hash your password rather than encrypting the password.

Hashing password in laravel is also

Hash::make($password);

And then you can use Auth::attempt to log in your user.

Upvotes: 1

Japs
Japs

Reputation: 1052

Try this code. I don't know what happened to your code about the password you tried to encrypt it in attempt.

public function login(LoginRequest $request) {
      if(!Auth::attempt([
        'email' => $request->email,
        'password' => $request->password,
        'active' => true
      ])) {
        return response()->json('Email or Password is incorrect', 500);
      }

      $this->user = Auth::user()->load('roles');
      return $this->createUserAccessTokenResponse();
    }

protected function createUserAccessTokenResponse() {
      return response()->json([
        'status' => 'success',
        'data' => [
          'token' => $this->user->createToken($this->user->name)->accessToken,
          'user' => $this->user
        ],
      ], 200);
    }

Upvotes: 1

Related Questions