Yii2 - encrypt password for db connection - yii2

How to encrypt the database password ?
return [
'class' => 'yii\db\Connection',
'dsn' => 'pgsql:host=localhost;port=5432;dbname=database',
'username' => 'user',
'password' => 'abcPassword',
'charset' => 'utf8',
];

Yii2 comes with user module in advanced setup. See how it store user passwords in encrypted way.
You can use setPassword() method in User Model to get hashed passwords.
public function setPassword($password)
{
$this->password_hash = Yii::$app->security->generatePasswordHash($password);
}
and call this method before saving model data.
public function signup()
{
if ($this->validate()) {
$user = new User();
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
if ($user->save()) {
return $user;
}
}
return null;
}
Also look at the Yii2 doc for passwords =>http://www.yiiframework.com/doc-2.0/guide-security-passwords.html and
authentication.=> http://www.yiiframework.com/doc-2.0/guide-security-authentication.html

Try Via This way.. I didn't tasted it.. but might be helpful to you.
$database = 'mydb';
$username = 'abc';
$password = '1234';
$config['components'] = [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=192.168.*.*;dbname=' . $database,
'username' => $username,
'password' => md5($password); // Try this
'password' => Yii::$app->security->generatePasswordHash($password); // Or Else try this
'charset' => 'utf8',
]
return config;

Related

MySQL doesn't update properly

I am trying to update status for users. code works fine .but it can't update in DB
controller.php
public function update_customer(Request $request)
{
$sid = 1;
$setting['setting'] = Settings::editGeneral($sid);
$site_max_image_size = $setting['setting']->site_max_image_size;
$name = $request->input('name');
$username = $request->input('username');
$email = $request->input('email');
$user_type = $request->input('user_type');
$status =$request->input('status');
$data = array('name' => $name, 'username' => $username, 'email' => $email, 'user_type' => $user_type, 'password' => $pass, 'earnings' => $earnings, 'user_photo' => $user_image,'status'=>$status, 'updated_at' => date('Y-m-d H:i:s'));
Members::updateData($token, $data);
return redirect($page_url)->with('success', 'Update successfully.');
}
}
model.php
public static function updateData($token,$data){
DB::table('users')
->where('user_token', $token)
->update($data);
}
how to solve it??
You can use Model class instead of DB Facade. Like below:
User.php
protected $fillable = [
'name' , 'username' , 'email' , 'user_type' , 'password' , 'earnings' , 'user_photo' ,'status', 'updated_at'
];
public static function updateData($token,$data)
{
User::where('user_token', $token)
->update($data);
}

is it possible to create an email only authentication from existing email-password structure in Laravel

I am trying to create email only authentication. Instead of having a login, I want a situation where I will only have signup and once the email is entered, a bearer token is created.
I have the signup function and login function which worked when I had password initiated but I have removed the password but I tried to move the "create token" to signup. It gives error that token is undefined.
Signup function
public function signup(Request $request)
{
$request->validate([
'email' => 'required|string|email|unique:users'
]);
$user = new User([
'email' => $request->email
]);
$user->save();
return response()->json([
'message' => 'Successfully created user!'
], 201);
}
Login function
public function login(Request $request)
{
$request->validate([
'email' => 'required|string|email'
]);
$credentials = request(['email', '=']);
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if ($request->remember_me)
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString()
]);
}
It is really simple, you have already done most of the work needed to be done here. You don't need the login function rather you need to copy the token part of the function as illustrated below
public function signup(Request $request)
{
$request->validate([
'email' => 'required|string|email|unique:users'
]);
$user = new User([
'email' => $request->email
]);
$user->save();
Auth::login($user);
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if ($request->remember_me)
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
return response()->json([
'message' => 'Successfully created user!',
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString()
], 201);
}

Yii2-user Dektrium - how to hash password

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;
}
];

Could not send email: unknown Cake\Network\Exception\SocketException in cakephp3

Okay I have been to almost all threads but I couldn't find the answer what I want.
Controller: RegistersController
namespace App\Controller;
use App\Controller\AppController;
use Cake\Auth\DefaultPasswordHasher;
use Cake\Event\Event;
use Cake\Mailer\Email;
use Cake\Routing\Router;
class RegistersController extends AppController
{
public function add()
{
$this->loadModel('Tbusers');
$tbusers = $this->Tbusers->newEntity();
if ($this->request->is('post'))
{
$tbusers = $this->Tbusers->patchEntity($tbusers, $this->request->data);
if ($this->Tbusers->save($tbusers)) {
$this->Flash->success(__('Yayie! You have been registered.'));
$baseurl = Router::url('/', true);
$email = base64_encode($this->request->data['email']);
$first_name = $this->request->data['fname'];
$last_name = $this->request->data['lname'];
$username = $first_name.' '.$last_name;
//$confirmation_link = $baseurl.'users/confirm/'.$email;
$email = new Email();
$email->template('email')
->subject('Student Portal - Signup')
->emailFormat('html')
->to($this->request->data['email'])
//->viewVars(['confirmation_link' => $confirmation_link,'username'=>$username])
->viewVars(['username'=>$username])
->from('dotnetdev555#gmail.com')
->send();
if ($email->send())
{
// Success
echo "mail sent";
}
else
{
echo "Mail not sent";
// Failure
}
return $this->redirect(['action' => 'add']);
}
}
Inside Template->Email->html I have file called
email.ctp
Hello <?php echo $username; ?>,<br/>
Thanks,<br/>
Jaymin Sejpal Founder at Student Portal
app.php
'EmailTransport' => [
'default' => [
'className' => 'Mail',
// The following keys are used in SMTP transports
'host' => 'smtp.elasticemail.com',
'port' => 2525,
'timeout' => 30,
'username' => 'dotnetdev555#gmail.com',
'password' => 'secret',
'client' => null,
'tls' => null,
'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),
],
],
I don't know what I am missing to it. I am refferring this
http://book.cakephp.org/3.0/en/core-libraries/email.html for now.
The email host that you are using might be using smtp protocol , so in your app.php . Try editing you className parameter to 'Smtp'
'EmailTransport' => [
'default' => [
'className' => 'Smtp',
// The following keys are used in SMTP transports
'host' => 'smtp.elasticemail.com',
'port' => 2525,
'timeout' => 30,
'username' => 'dotnetdev555#gmail.com',
'password' => 'secret',
'client' => null,
'tls' => null,
'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),
],
],

How to generate SqlDataProvider for 2 db connection

I have a 2 DB connection, db and db2. I want to get all data from table claim in db2 connection. Below is my sql and it did not read from db2 connection. How to solved this?
$sql = "SELECT * FROM claim where provider_id = xx ";
$sql_count = "SELECT COUNT FROM ( $sql ) AS count ";
$totalCount = Yii::$app->db2->createCommand($sql_count)->queryScalar();
$dataProvider = new SqlDataProvider([
'sql' => $sql,
'totalCount' => $totalCount,
'sort' =>false,
'pagination' => [
'pageSize' => 10,
],
]);
return $dataProvider;
First you need to configure your databases like below:
return [
'components' => [
'db1' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=db1name', //maybe other dbms such as psql,...
'username' => 'db1username',
'password' => 'db1password',
],
'db2' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=db2name', //maybe other dbms such as psql,...
'username' => 'db2username',
'password' => 'db2password',
],
],
];
Then you can simply :
//to get from db1
Yii::$app->db1->createCommand((new \yii\db\Query)->select('*')->from('tbl_name'))->queryAll()
//to get from db2
Yii::$app->db2->createCommand((new \yii\db\Query)->select('*')->from('tbl_name'))->queryAll()
If you are using an active record model, in your model you can define:
public function getDb() {
return Yii::$app->db1;
}
//Or db2
public function getDb() {
return Yii::$app->db2;
}
Then:
if you have set db1 in getDb() method, result will be fetched from db1 and so on.
ModelName::find()->select('*')->all();