Laravel - can't get auth::atempt to work properly - php

$inputs["mail"] = Input::get('mail');
$password = Hash::make(Input::get("password",""));
$user = new User();
$user->password=$password;
$inputs["password"] = $password;
if( Auth::attempt($inputs) )
{
return 'loginOK';
}
else
{
return 'false';
}
i think that $password is different from password of database.
Do I need to try to other way?
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface,
RemindableInterface {
protected $table ='users';
public function getAuthIdentifier(){
return $this->getKey();
}
public function getRememberToken(){
return $this->remember_token;
}
public function getAuthPassword(){
return $this->password;
}
public function setRememberToken($value){
$this->remember_token = $value;
}
public function getRememberTokenName(){
return 'remember_token';
}
public function getReminderEmail() {
return $this->email;
}
}
it is User model.
can't get auth::atempt to work properly
what problem is it?
 
$input = [
'mail' => Input::get('mail'),
'password' => Input::get('password'),
 ];
 if (Auth::attempt($input)) {
echo 'Success';
 } else {
echo 'Failed';
 }
I edited by folower.
I have som trouble.
still i cant get

The problem is that you are passing the Hashed password to the attempt method, that method actually expect the unhashed password and does the hashing itself, so doing:
$inputs["password"] = Input::get('password');
should do the trick.
I'm not sure if your playing around but your code is not properly written and you should consider using the Input object directly.

Two things:
You don't need to hash the password
You don't need to make a user model.
It is enough to do something as follows:
$input = [
'mail' => Input::get('mail'),
'password' => Input::get('password'),
];
if (Auth::attempt($input)) {
echo 'Success';
} else {
echo 'Failed';
}

Related

How to hash a password correctly in Yii2 (Getting "Hash is invalid" error)

I am currently experimenting with Yii2 and I am trying to hash the Password of a newly created user. The I think the hashing gets done well, but when I try to login with the user and his newly hashed password I get the Hash is invalid Error for some reason.
I have checked how to add hashed passwords in yii2 but I can't find a solution working for me.
In my UserController.phpi have the following action:
public function actionCreate()
{
$model = new User();
if ($this->request->isPost) {
if ($model->load($this->request->post()) && $model->save()) {
\Yii::$app->security->generatePasswordHash($model->password);
return $this->redirect(['view', 'id' => $model->iduser]);
}
} else {
$model->loadDefaultValues();
}
return $this->render('create', [
'model' => $model,
]);
}
And in my User.php model I use the following function to validate the password:
public function validatePassword($password) {
if(is_null($this->password)) {
return false;
}
return Yii::$app->getSecurity()->validatePassword($password, $this->password);
}
Anyone can tell me what I am doing wrong? Because I can't see what I am missing here.
You are saving unhashed password with $model->save().
The \Yii::$app->security->generatePasswordHash($model->password) creates password hash and returns it. But you are not using returned hash in any way.
You need to load data into model, set the hashed password in password attribute of model and then save the model:
if ($this->request->isPost) {
if ($model->load($this->request->post())) {
$model->password = \Yii::$app->security->generatePasswordHash($model->password);
if ($model->save()) {
return $this->redirect(['view', 'id' => $model->iduser]);
}
}
}
You can also override load() method to hash password right after data are loaded.
class User extends ActiveRecord implements IdentityInterface
{
public function load($data, $formName = null)
{
$result = parent::load($data, $formName);
//only hash password if it was changed
if ($result && $this->isAttributeChanged('password')) {
$this->password = Yii::$app->security->generatePasswordHash($this->password);
}
return $result;
}
// ... other definitions ...
}

How to store bcrypt data using Make request in laravel

This is how I would make such a function
Controller code
public function store(RegistrationStoreRequest $request){
$user = User::create($request->validated());
Auth::login($user);
return redirect()->home();
}
This is my Request form code
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed'
];
}
You have two options:
Create a value mutator:
public function setPasswordAttribute($value) {
$this->attributes['password'] = Hash::make($value);
}
however you need to ensure you never prehash the password.
Hash in controller
public function store(RegistrationStoreRequest $request){
$user = User::create(array_merge(Arr::except($request->validated(), 'password'), [ 'password' => Hash::make($request->password) ]));
Auth::login($user);
return redirect()->home();
}
The easiest and most clean way is to use a custom cast for password field, first create UserPasswordCast.php class:
<?php
//app/Casts/UserPasswordCast.php
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Support\Facades\Hash;
class UserPasswordCast implements CastsAttributes
{
public function get($model, $key, $value, $attributes)
{
return $value;
}
public function set($model, $key, $value, $attributes)
{
//return hashed value
return Hash::make($value);
}
}
Suggested location:
app/Casts/UserPasswordCast.php
Then update your 'user' model to use this cast, add "$casts" array or update it if existed:
use App\Casts\UserPasswordCast;
...
protected $casts = [
...
'password' => UserPasswordCast::class
];
That's it, you don't have to worry about password again
Just save your user model as it:
public function store(RegistrationStoreRequest $request)
{
$user = User::create($request->validated());
Auth::login($user);
return redirect()->home();
}
For more info please check:
https://laravel.com/docs/8.x/eloquent-mutators#custom-casts
=>create method function add in User.php(Model).
public static function create($user, $request)
{
if (isset($request->name)) {
$user->name = $request->name;
}
if (isset($request->email)) {
$user->email = $request->email;
}
if (isset($request->password)) {
$user->password = bcrypt($request->password);
}
if (isset($request->confirmpassword)) {
$user->confirmpassword = $request->confirmpassword;
}
$user->save();
return $user;
}
=>New user create with validate your all request field.
public function store(RegistrationStoreRequest $request){
$user = User::create(New User,$request);
Auth::login($user);
return redirect()->home();
}
Please try this code it is working.

YII2 - check user

Okay, so, i am trying to write an API, and for the login function, you send the phone and password and if they match with a record in the database, we send back the user object.
You send phone and password via GET request, and I know what that means security wise, so don't mention that in solution.
Here is code for the API controller
<?php
namespace api\modules\v1\controllers;
use yii\rest\Controller;
use yii\data\SqlDataProvider;
use yii\web\Response;
use yii;
use common\models\User;
class UserController extends ApiController{
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;
public $phone;
public $password;
private $_user = false;
private $password_hash;
public function actionIndex(){
if(isset($_GET['phone']) && isset($_GET['password']))
{
$this->phone = $_GET['phone'];
$this->password = $_GET['password'];
if(!is_null($this->getUser($this->phone)))
{
//if the user is there, we try and validate the password
if (Yii::$app->getSecurity()->validatePassword($this->password, $this->_user->password_hash))
{
echo ("good password");
return $this->_user;
} else
{
echo('bad password');
}
}else
{
return['User Not Found, Please Check Your Credentials And Try Again'];
}
}
else
{
if(!isset($_GET['phone']))
{
return array('Please provide your phone number');
}
if(!isset($_GET['password']))
{
return array('Please provide your password');
}
}
}
public function getUser($phone)
{
if ($this->_user === false) {
$this->_user = User::findOne(['phone' => $phone,'status' => self::STATUS_ACTIVE ]);
}
return $this->_user;
}
}
According to this section of the documentation, the validatePassword() should work, but even when i send the right password, it doesn't work.

Auth::attempt doesn't work [Laravel]

I've looked through all other questions on this...
So I set up a userSeeder which autopopulates my User table:
public function run()
{
$users = [
[
"email" => "email#myemail.co.uk",
"fname" => "Nicola",
"sname" => "Elvin",
"password"=>Hash::make("password")
]
];
foreach ($users as $user)
{
User::create($user);
}
}
My table shows this is stored, and password has been hashed.
In my login function:
$credentials = [
"email" => Input::get("email"),
"password" => Input::get("password")
];
if (Auth::attempt($credentials)) {
return Redirect::route("user/profile");
}else{
echo 'wrong';
}
I did a print_r of $credentials and it correctly displays my email address and password.
Yet it always shows up as wrong. It doesn't ever validate.
USER MODEL
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'user';
protected $hidden = array('password');
public function getAuthIdentifier()
{
return $this->getKey();
}
public function getAuthPassword()
{
return $this->password;
}
public function getReminderEmail()
{
return $this->email;
}
}
I figured it out. Embarrassingly, I had white space at the end of my email address...so it wasn't actually correct as I hadn't trimmed it...
Although the way I figured this out was by seeing the sql query that auth:attempt was running by installing a Laravel 4 profiler

how to remember a user who is login

I have created a sign in form with a remember me checkbox. I want to know how can i allow user to keep sign in when the browser is closed or sign out person when they close the browser. A sample code would be nice thank you.
here is my code
class HomeController extends BaseController {
public function getIndex()
{
if(Auth::check())
{
return Redirect::to('profile');
}
return View::make('index');
}
public function postRegister()
{
//gets array of the register form input values
$value = Input::all();
// create a new instance of the User model
$user = new User;
$validate = $user->userValidate($value);
//checks if the validation for the field fails
if($validate->fails())
{
/* $message = $validation->messages();
return $message; */
return Redirect::back()->withInput()->withErrors($validate);
}
//adds the users input to speicific field in the users table
$user->user_name = $value['username'];
$user->email = $value['email'];
$user->password = Hash::make($value['password']);
//save the inputs to the users table
$user->save();
return 'information has been stored';
}
public function getRegister()
{
$title = 'Register';
return View::make('register')->with('title',$title);
}
public function getSignIn()
{
$title = 'Signup';
return View::make('signup')->with('title',$title);
}
public function postSignIn()
{
//user's information
$credentials = array('email' => Input::get('email'),'password'=>Input::get('password'));
//logs this user in and checked if they are registered already in
if(Auth::attempt($credentials,false))
{
return Redirect::to('profile');
}
return Redirect::back()->withInput();
}
}
You just have to turn it on in your login method:
if (Auth::attempt(array('email' => $email, 'password' => $password), true))
{
// The user will now be logged in and remembered
}
else
{
// Raise a login error
}
This "true" parameter is to remember your user.
Here is the Laravel Auth::attempt() method declaration:
public function attempt(array $credentials = array(), $remember = false, $login = true)
{
...
}
You could set a cookie on the users browser (make sure you tell them if you are) to identify them. But beware that this could be modified by a malicious user.
PHP Cookies Documentation

Categories