i want to do hash password and check that with database ( password_hash )
How can I do it????
$username = $auth['username'];
my password is
$password = $auth['password'];
i want hash that :
$find = \dektrium\user\models\User::findOne(['username' => $username, 'password_hash' => $password]);
You could generate the $hash using
$hash = Yii::$app->getSecurity()->generatePasswordHash($password);
$find = \dektrium\user\models\User::findOne(['username' => $username,
'password_hash' => $hash]);
Th code belowe is from dektrium/yii2-user/helpers/password.php ( the code for hash function ..of dektrium adn as you see the extensions use the generatePasswordHash and a cost
public static function hash($password)
{
return \Yii::$app->security->generatePasswordHash($password,
\Yii::$app->getModule('user')->cost);
}
default cost = 8
I know quite late to answer this, but for those who are still looking.. I recently encountered this issue and after lots of testing below code worked for me:
$behaviors['authenticator'] = [
'class' => HttpBasicAuth::className(),
'auth' => function ($username, $password) {
$user = \dektrium\user\models\User::findOne(['username' => $username]);
if ($user->validate($password)) {
return $user;
}
return null;
}
];
Related
I have tried this code to get current running mysql process for this db and current user but the problem is when another api is called with large runtime query this previouse api block this request.
public function getDBProcess_p(Request $request)
{
$db = env('DB_DATABASE') ?? '';
$username = env('DB_USERNAME') ?? '';
$password = env('DB_PASSWORD') ?? '';
$data = DB::table('INFORMATION_SCHEMA.PROCESSLIST')
->where(
[
'DB' => $db,
'USER' => $username,
'COMMAND' => 'Execute',
]
)
->paginate(10);
$data = [
'paginator' => getFormattedPaginatedArray($data),
'data' => $data->items(),
];
return $this->set_response($data, 200,'success', ['Process list']);
}
when I'm trying to update user I got this error
this error point out at $user->first_name = $request->input('first_name');
update method
public function update($id, Request $request){
$this->validate($request, array(
'first_name' => 'string|max:255',
'last_name' => 'string|max:255',
'email' => "string|email|max:255|unique:users,email,$id",
'password' => "sometimes|nullable |string|min:8,$id",
'avatar' => 'image|mimes:jpg,jpeg,gif,png,svg|max:2048',
));
$password = bcrypt(request('password'));
$user = User::where('email',$request['email'])->first();
$user->first_name = $request->input('first_name');
$user->last_name = $request->input('last_name');
if(!empty($request->password))
{
$user->password = $password;
}
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300, 300)->save( public_path('/images/avatars/' . $filename ) );
$user->avatar = $filename;
}
$user->roles()->detach();
if ($request['user']) {
$user->roles()->attach(Role::where('name','User')->first());
}
if ($request['editor']) {
$user->roles()->attach(Role::where('name','Editor')->first());
}
if ($request['admin']) {
$user->roles()->attach(Role::where('name','Admin')->first());
}
$user->save();
return redirect('admin/users')->with('success', 'user is successfully saved');
}
Your assignment $user is null because there is no record with the email you are providing.
Use findOrFail($request['email']) so that you throw a ModelNotFoundException in this scenario.
OR
$user = User::where('email',$request['email'])->first();
if(!is_null($user) { // check not null of $user here
$user->first_name = $request->input('first_name');
$user->last_name = $request->input('last_name');
}
References:
https://laravel.com/docs/5.7/eloquent#retrieving-single-models
https://laracasts.com/discuss/channels/laravel/errorexception-in-profilecontrollerphp-line-98-creating-default-object-from-empty-value
You should use FindOrFail method instead
so instead of using this line:
$user = User::where('email',$request['email'])->first();
use this:
$user = User::findOrFail($id);
so FindOrFail will get the user by id and if it does not exist it will fail and show 404 Not found.
I'm looking for a way to execute a little bit of JSON from my Symfony (2.6 btw) controller, moreover than an other action (post data into database)
In fact, there is an register page with a controller which put data into database and then, redirect user to another page. But i need that my controller execute too a little bit of JSON to use Mailchimp API.
I've found a lot of docs about how to render JSON response, but, it seems to me that it's not what i want to be.
There is my controller
public function registerAction(Request $request)
{
/** #var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
$formFactory = $this->get('fos_user.registration.form.factory');
/** #var $userManager \FOS\UserBundle\Model\UserManagerInterface */
$userManager = $this->get('fos_user.user_manager');
/** #var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
$dispatcher = $this->get('event_dispatcher');
$user = $userManager->createUser();
$user->setEnabled(true);
$event = new GetResponseUserEvent($user, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);
if (null !== $event->getResponse()) {
return $event->getResponse();
}
$form = $formFactory->createForm();
$form->setData($user);
$form->handleRequest($request);
if ($form->isValid()) {
// Gestion du type d'utilisateur et ajout du role
$user_type = $form->get('user_profile')->get('type')->getData();
$new_role = $this->roles[$user_type];
$event = new FormEvent($form, $request);
$user = $event->getForm()->getData();
$user->addRole($new_role);
$user->getUserProfile()->setEmail($user->getEmail());
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);
$userManager->updateUser($user);
if (null === $response = $event->getResponse()) {
$url = $this->generateUrl('fos_user_registration_confirmed');
$response = new RedirectResponse($url);
}
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
return $response;
}
return $this->render('FOSUserBundle:Registration:register.html.twig', array(
'form' => $form->createView(),
));
}
There is my JSON request
{
"email_address": "$email",
"status": "subscribed",
"merge_fields": {
"FNAME": "$name",
"LNAME": "$lastname",
"DATE": "$date"
}
}
So, how can i do to execute this JSON with this controller ?
Thank you in advance for your help (and sorry for my excellent english)
You probably want to create the JSON from an array rather than try to pass variables. Try:
$data = [
'email_address' => $email,
'status' => 'subscribed',
'merge_fields' => [
'FNAME' => $name,
'LNAME' => $lastname,
'DATE' => $date,
],
];
$json = json_encode($data);
Then I'm assuming this data gets sent to MailChimp in a POST request? If so, you could use Guzzle to send the data to MailChimp:
First add the guzzle dependency in composer by running:
composer require guzzlehttp/guzzle
Then send the data:
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'https://MAILCHIMP_URL', ['body' => $data]);
To send JSON instead of raw data, do the following:
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'https://MAILCHIMP_URL', ['json' => $data]);
Depending on the response status, you can then handle the logic afterwards.
You can achieve this also using JsonResponse (Symfony\Component\HttpFoundation\JsonResponse)
use Symfony\Component\HttpFoundation\JsonResponse;
...
// if you know the data to send when creating the response
$data = [
'email_address' => $email,
'status' => 'subscribed',
'merge_fields' => [
'FNAME' => $name,
'LNAME' => $lastname,
'DATE' => $date,
]
];
$response = new JsonResponse($data);
return $response;
More details here https://symfony.com/doc/current/components/http_foundation.html
I used phpass to hash my password on Insert as follows
public function addAdmin(){
$this->load->library('phpass');
$this->load->database();
$psw = 'admin1234';
$hashed = $this->phpass->hash($psw);
$now = date("Y-m-d H:i:s");
$data = array(
'userid' => 'admin_user' ,
'userfname' => 'Admin' ,
'userlname' => 'Admin',
'userdname' => 'Admin' ,
'useraddress' => '20/72,Vidarshana Mawatha, Galawilawatta, Homagama' ,
'usercountry' => 'Sri Lanka',
'usercontactno' => '0112-892199' ,
'userlastlog' => $now ,
'userpassword' => $hashed ,
'userpermission' => '1',
'useremail' => 'dilukshanmahendra#gmail.com'
);
$this->db->insert('ecom-user', $data);
echo "Successfully Added!";
}
But when I input the same userid & password (Correct UserID and Password) at the Login where it validate by matching them with the stored ones, it returns '0' for the following where I expcted '1'
public function validateLogin($userid,$userpass){
$this->load->library('phpass');
$this->load->database();
$hashed = $this->phpass->hash($userpass);
$this->db->select('*');
$this->db->from('ecom-user');
$this->db->where('userid', $userid);
$this->db->where('userpassword', $hashed);
$result = $this->db->get();
echo $this->db->last_query();
echo '<br/>'.$result->num_rows();
}
Please some one help me to solve this
Better have a look here
, meanwhile, trim all input fields you've got for login and registering new users!
I want to perform a custom query in zf2. Now I have a Album controller and AlbumTable. Inside AlbumTable, I want to perform an join operation. But I am unable to do this.Please give me some suggation.
below my code:
namespace WebApp\Table;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Sql;
new Zend\Db\Adapter\Adapter;
class UserTable
{
protected $tableGateway;
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function searchUser($search)
{
$search = "mehedi";
$adapter = new Adapter();
$sql = new Sql($adapter);
$select = $sql->select();
$select->from('foo');
$select->join('profiles', 'user.user_id = profiles.ownerId', array('name'));
$select->where(array('id' => 2));
$statement = $sql->prepareStatementForSqlObject($select);
$results = $statement->execute();
return $results;
}
}
The issue is you are trying to instantiate your Adapter with no parameters, when it requires at least a driver :
$adapter = new Adapter(); // Bad
$adapter = new Adapter($driver); // ..
You should use the ServiceManager to get your Adapter, did you start with the Skeleton Application?
It should have already been injected into the TableGateway for you..
$adapter = $this->getAdapter();
An example of instantiating an Adapter:
$config = $serviceLocator->get('Config');
$adapter = new Adapter($config['db']);
where you specify your setup inside your config, local.php will do:
return array(
/**
* Database Config
*/
'db' => array(
'driver' => 'pdo',
'dsn' => 'mysql:dbname=dbname;host=localhost',
'username' => 'root',
'password' => 'password',
),
I got some solution of this problem with helping all of here.
$adapter = $this->tableGateway->getAdapter();
/* $adapter variable is used to fetch Adapter
configuration from serivce manager. */
$sql = new Sql($adapter);
$select = $sql->select();
$select->from('foo');
$select->join('profile', 'foo.skillId = profile.id', array('name'));
$statement = $sql->prepareStatementForSqlObject($select);
$results = $statement->execute();
/* if you want you can see your
desired output in here. */
foreach ($results as $person) {
echo "<pre>";
print_r($person);
}
return $results;
It's because the join method expects an array for the join table. Also I personally would prefix the tables in the query, something like this:-
$search = "mehedi";
$adapter = new Adapter();
$sql = new Sql($adapter);
$select = $sql->select();
// PREFIXED THE foo table f
$select->from(array('f' =>'foo'));
// PREFIXED THE profiles table p
$select->join(array('p' => 'profiles'), 'user.user_id = profiles.ownerId', array('name'));
$select->where(array('id' => 2));
$statement = $sql->prepareStatementForSqlObject($select);
$results = $statement->execute();
return $results;