I want to change my password which is been hashed while saving.
How can i change the password?
'password' => Hash::make($data->password).
My Controller
$request->validate([
'oldpass' => 'required',
'password' => 'required|alphaNum|min:6',
'password_confirmation' => 'required|same:newpass',
]);
$id = $request->id;
$users = Auth::user()->whereId($id)->get();
foreach ($users as $user) {
if ($oldpass == $user->password) {
$user->update([
'password' => Hash::make($request->newpass)
]);
return view('\balance');
} else {
return 'error';
}
}
You should use Hash::check($old_password, $hashed_password), something like this:
public function passwordChange(Request $request, User $user_name) {
// find the loggedin user
$user = User::find(Auth::user()->id);
// validate rules
$validator = Validator::make($request->all(), [
'old_password' => 'required|min:6',
'password' => 'required_with:password_confirmation|required|min:6',
'password_confirmation' => 'confirmed|required|min:6',
]);
// what to do if validator fails
if ($validator->fails()) {
return redirect($user->user_name . '/settings')->withErrors($validator)->withInput();
} else {
$old_password = $request->input('old_password');
$new_password = $request->input('password');
$hashed_password = Auth::user()->password;
// checking the old pass with new one
if (Hash::check($old_password, $hashed_password)) {
$user->update([
'password'=> Hash::make($new_password)
]);
return redirect($user->user_name . '/settings')->with('success', 'Your Password updated.');
} else {
return redirect($user->user_name . '/settings')->with('success', 'Your Old password is wrong!');
}
}
}
Please also notice 'password' => 'required_with:password_confirmation and 'password_confirmation' => 'required|same:newpass' on validator. Hope it helps.
Related
The problem is that it does not generate the TOKEN, throwing the following error
TypeError: Lcobucci\JWT\Token\Builder::relatedTo(): Argument #1 ($subject) must be of type string, null given
When I make the request through the post verb, it performs all the previous validation but when it comes to generating the token, the error occurs.
`
public function login(Request $request)
{
$credentials = $request->only('usuario', 'password');
$validator = Validator::make($request->all(), [
'usuario' => 'required',
'password' => 'required'
]);
if ($validator->fails()) {
return response()->json([
'message' => $validator->errors(),
'token' => null
], 404);
}
$user = usuarios::where('usuario', $request->usuario)->first();
if (!$user) {
return response()->json([
'message' => 'Usuario no registrado.',
'token' => null
], 401);
}
$isValid = Hash::check($request->password, $user->password);
if (!$isValid) {
return response()->json([
'message' => 'ContraseƱa incorrecta.'
]);
}
$token = JWTAuth::fromUser($user);
return response()->json([
'message' => 'Usuario logueado correctamente',
'token' => $token
]);
}
`
And my code mode is this
`
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
//AƱadimos la clase JWTSubject
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;
class usuarios extends Model implements JWTSubject
{
use HasFactory, HasApiTokens, Notifiable;
protected $table = 'usuarios';
protected $fillable = [
'tipo_usuario',
'acceso_pv',
'nombre',
'usuario',
'password',
];
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
public $timestamps = false;
}
`
I have two controller
the first one has a register method:
public function register(Request $request)
{
$generalTrait = new GeneralTrait;
$user = new User;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->type = $request->type;
$user->save();
return $generalTrait->returnData('user',$user);
}
and the second also has register method:
public function register(Request $request)
{
$generalTrait = new GeneralTrait;
$user = (new UserAuthController)->register($request);
$admin = Admin::create([
'admin_name' => $request->admin_name,
//'user_id' => $response->user->user_id,
'user_id' => $user_id
]);
//Admin created, return success response
return $generalTrait->returnSuccessMessage('Admin created successfully');
}
when I try to get data from (JsonResponse) $user I find this error:
ErrorException: Undefined property: Illuminate\Http\JsonResponse::$user
returnDate method in GeneralTrait return:
public function returnData($key, $value, $msg = ""){
return response()->json([
'status' => true,
'errNum' => "5000",
'msg' => $msg,
$key => $value
]);
}
I find same Error when I try to get the status from the $response
How can I fix it?
I fix it by replacing returnData with:
public function returnData($key, $value, $msg = ""){
return [
'status' => true,
'errNum' => "5000",
'msg' => $msg,
$key => $value
];}
so to get user_id from user I said:
'user_id' => ($response["user"])->user_id
I wish I knew what my mistake was, and how I could have fixed it some other way
In BroadcastServiceProvider.php I've got data when user joins the channel and I would like to store it to DB. I am wondering how to override this storeUser() function to make it work (I've used this function before but it was in other circumstances).
public function storeUser() {
UserInfo::create([
'ip' => Request::ip(),
'name' => Auth::user()->name
]);
}
BroadcastServiceProvider.php
Broadcast::channel('chat', function ($user) {
$ip = Request::ip();
if (auth()->check()) {
return [
'id' => $user->id,
'ip' => $ip,
'name' => $user->name
];
}
});
Update the UserInfo model to have the storeUser method.
class UserInfo
{
public static function storeUser() {
UserInfo::create([
'ip' => Request::ip(),
'name' => Auth::user()->name
]);
}
Then you can call it in the broadcaster
Broadcast::channel('chat', function ($user) {
$ip = Request::ip();
if (auth()->check()) {
UserInfo::storeUser();
return [
'id' => $user->id,
'ip' => $ip,
'name' => $user->name
];
}
});
You can also call it in the same way UserInfo::storeUser(); in the users controller where ever you need it.
I have a working project that i want to extend with authentication. I followed the Simple Authentication and Authorization Tutorial here.
Logging in works and i can print the Username etc. But the access control is not working. The Method isAuthorized is simply not working. What am i missing here?
Edit - I receive the below error;
"You are not authorized to access that location."
Part of my AppController:
public $components = array('Flash', 'RequestHandler', 'Cookie', 'Session', 'Auth' => array(
'loginRedirect' => array(
'controller' => 'status',
'action' => 'index'
),
'logoutRedirect' => array(
'controller' => 'user',
'action' => 'login'
),
'authenticate' => array(
'Form' => array(
'passwordHasher' => 'Blowfish'
),
),
'authorize' => array('Controller')
));
public function isAuthorized($user)
{
if (isset($user['role']) && $user['role'] === 'admin') return true;
return false;
}
Part of my taskController:
public function isAuthorized($user)
{
debug($user); die();
if ($this->action === 'index') return true;
if (in_array($this->action, array('edit', 'delete')))
{
$postId = (int) $this->request->params['pass'][0];
if ($this->Post->isOwnedBy($postId, $user['id'])) return true;
}
return parent::isAuthorized($user);
}
Part of UsersController:
public function login()
{
if ($this->request->is('post'))
{
if ($this->Auth->login())
{
return $this->redirect($this->Auth->redirectUrl()); // This is being called after login so it seems to work!
}
$this->Flash->error(__('Invalid username or password, try again'));
}
}
What i'm doing wrong?
<?php
public function login() {
$user_name = time();
User::create(array(
'name' => $user_name,
'email' => $user_name.'#test.com',
'password' => Hash::make('123123'),
));
$user = array(
'email' => $user_name.'#test.com',
'password' => '123123',
);
$m = User::where('email' , '=', $user_name.'#test.com')->first();
dd([
'Auth::attempt($user)',
Auth::attempt($user),
'Auth::check()',
Auth::check(),
'Hash::check($m->password, \'123123\')',
Hash::check($m->password, '123123')
]);
}
Result:
array(6) {
[0]=>
string(20) "Auth::attempt($user)"
[1]=>
bool(false)
[2]=>
string(13) "Auth::check()"
[3]=>
bool(false)
[4]=>
string(38) "Hash::check($user->password, '123123')"
[5]=>
bool(false)
}
Not sure what information should I add.
app/config/auth.php
'driver' => 'eloquent',
'model' => 'User',
'table' => 'users',
app/config/app.php
'key' => 'DMmiPAxSYz4O2jG44S92OcdPZN7ZsGGs',
'cipher' => MCRYPT_RIJNDAEL_256,
models/User.php
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* Validation rules
*/
public static $rules = array(
'name' => 'required',
'email' => 'email|required|unique',
'password' => 'min:6',
);
/**
* Validation rules
*/
public static $messages = array(
'name.required' => 'The name field is required',
'email.email' => 'The email field must contain properly formatted email.',
'email.required' => 'The email field is required',
'password.required' => 'The password field is required',
'password.min:6' => 'The password must be minimum 6 characters long',
);
protected $table = 'users';
protected $hidden = array('password', 'remember_token');
protected $guarded = array('id');
public function setPasswordAttribute($value) {
if ($value) {
$this->attributes['password'] = Hash::make($value);
}
}
}
Well here's some checks that you can do
Have you setup config/auth.php with driver, model and table?
Have you filled the fillable array of the User's model?
Have you change the key inside config/app.php ?
Also try to dd($m) in order to see what you got from that query.
I found what is wrong.
This part of code hash password for first time:
User::create(array(
'name' => $user_name,
'email' => $user_name.'#test.com',
'password' => Hash::make('123123'), // <---- first time
));
And this mutator in User model does hashing for second time before put password to database:
public function setPasswordAttribute($value) {
if ($value) {
$this->attributes['password'] = Hash::make($value); // <---- second time
}
}
So I just changed first block to this:
User::create(array(
'name' => $user_name,
'email' => $user_name.'#test.com',
'password' => '123123', // <---- no hashing here
));