CodeIgniter custom encrypt function - codeigniter

In my previous project i was created a custom encryption function to login. How can i use it in CI. here is my code
function sha_password($username,$password){
$username = strtoupper($username);
$password = strtoupper($password);
return SHA1($username.':'.$password);
}
and i was called like that to get encrypted password
$password = strtoupper(sha_password($username,$password));
how can i do it to work in CI? :?

you can place it in various places:
a model - if you have a model for a user, $user->getEncryptedPassword();
a library - in my project i have libuser that has the encryption function, so i call it by $this->libuser->encrypt_password();
a controller (MY_Controller for example) - create a function and call it by $this->encrypt_user_password(..)
just drop it in some of the files that will always be loaded, in config or something
if you don't plan on changing it, just do $encpass = sha1(strtoupper($username.':'.$password)); although i wouldn't go there.
options 1 and 2 are most recommended

Related

Laravel - OutputStyle from jobs

I'm running into issues with allowing a Laravel job to interact with the console output.
At the moment I am passing in the OutputStyle from a Command to the Job constructor and assigning it.
I have seen the InteractsWithIO trait but if I use that by itself without assigning the OutputStyle from the command then it says it is null.
Call to a member function title() on null
I have also tried setting $this->output from the container using
$this->output = resolve(OutputStyle::class);
This fails with a
Target [Symfony\Component\Console\Input\InputInterface] is not instantiable while building [Illuminate\Console\OutputStyle].
I've also ran into issues with PHPUnit tests that run through this job. The output from the class is displayed in the test output.
.......................Processing element 1 for "Section"
.......
What's the best way to handle outputting to the console within Laravel that also works with PHPUnit?
Putting the following code in a Service Provider works:
$this->app->bind('console.output', function () {
return new OutputStyle(
new StringInput(''),
new StreamOutput(fopen('php://stdout', 'w'))
);
});
I am then able to say, in my Job,
$this->output = resolve('console.output');
Which gives access to all the methods such as title, section, and table.

Testing multiple databases in Laravel with phpunit

In my application I have tests that use Sqlite and seeding to cover my functionality. So my phpunit env value is set to:
<env name="DB_DEFAULT" value="sqlite" />
However, I'd also like a small subset of my tests to look at my current db data. So within 1 test file, connect to my MySQL connection.
The reason for this is I want to check if we have images for all the records in one of my tables, so the test needs to access the latest data, dummy data would not help in this case.
I presumed I could just connect using the following:
$pdo = DB::connection('mysql')->getPdo();
However, the test only connects if I specify "sqlite" here, which is the name of my sqlite connection.
The testing I want to do is not based on a Model, so I don't want to have a solution built into my Model file, I'd like to switch database just in this 1 test file if possible.
How do I configure a small number of tests to use a different database connection, the existing MySQL connection?
So, the reason why I could not connect was because there were no DB_ values in my .env.testing file. The mysql connection was then using the Laravel config defaults so the connection did not error.
.env.testing
DB_DEFAULT=mysql
DB_HOST=database
DB_NAME=my_database_name
DB_USER=root
DB_PASS=root
Adding the lines above got everything working and now my test file can access the current local database.
public function __construct()
{
$this->imgPath = dirname(__FILE__, 3) . '/public/images/';
}
public function testImages()
{
$items = DB::connection('mysql')
->select(DB::raw('SELECT image_filename FROM items')
);
foreach ($items as $item) {
$this->assertFileExists($this->imgPath . $item->image_filename . '.jpg');
}
}

AX2012 - Pre-Processed RecId parameter not found

I made a custom report in AX2012, to replace the WHS Shipping pick list. The custom report is RDP based. I have no trouble running it directly (with the parameters dialog), but when I try to use the controller (WHSPickListShippingController), I get an error saying "Pre-Processed RecId not found. Cannot process report. Indicates a development error."
The error is because in the class SrsReportProviderQueryBuilder (setArgs method), the map variable reportProviderParameters is empty. I have no idea why that is. The code in my Data provider runs okay. Here is my code for running the report :
WHSWorkId id = 'LAM-000052';
WHSPickListShippingController controller;
Args args;
WHSShipmentTable whsShipmentTable;
WHSWorkTable whsWorkTable;
clWHSPickListShippingContract contract; //My custom RDP Contract
whsShipmentTable = WHSShipmentTable::find(whsWorkTable.ShipmentId);
args = new Args(ssrsReportStr(WHSPickListShipping, Report));
args.record(whsShipmentTable);
args.parm(whsShipmentTable.LoadId);
contract = new clWHSPickListShippingContract();
controller = new WHSPickListShippingController();
controller.parmReportName(ssrsReportStr(WHSPickListShipping, Report));
controller.parmShowDialog(false);
controller.parmLoadFromSysLastValue(false);
controller.parmReportContract().parmRdpContract(contract);
controller.parmReportContract().parmRdpName(classStr(clWHSPickListShippingDP));
controller.parmReportContract().parmRdlContract().parmLanguageId(CompanyInfo::languageId());
controller.parmArgs(args);
controller.startOperation();
I don't know if I'm clear enough... But I've been looking for a fix for hours without success, so I thought I'd ask here. Is there a reason why this variable (which comes from the method parameter AifQueryBuilderArgs) would be empty?
I'm thinking your issue is with these lines (try removing):
controller.parmReportContract().parmRdpContract(contract);
controller.parmReportContract().parmRdpName(classStr(clWHSPickListShippingDP));
controller.parmReportContract().parmRdlContract().parmLanguageId(CompanyInfo::languageId());
The style I'd expect to see with your contract would be like this:
controller = new WHSPickListShippingController();
contract = controller.getDataContractObject();
contract.parmWhatever('ParametersHere');
controller.parmArgs(args);
And for the DataProvider clWHSPickListShippingDP, usually if a report is using a DataProvider, you don't manually set it, but the DP extends SRSReportDataProviderBase and has an attribute SRSReportParameterAttribute(...) decorating the class declaration in this style:
[SRSReportParameterAttribute(classstr(MyCustomContract))]
class MyCustomDP extends SRSReportDataProviderBase
{
// Vars
}
You are using controller.parmReportContract().parmRdpContract(contract); wrong, as this is more for run-time modifications. It's typically used for accessing the contract for preRunModifyContract overloads.
Build your CrossReference in a development environment then right click on \Classes\SrsReportDataContract\parmRdpContract and click Add-Ins>Cross-reference>Used By to see how that is generally used.
Ok, so now I feel very stupid for spending so much time on that error, when it's such a tiny thing...
The erronous line is that one :
controller.parmReportName(ssrsReportStr(WHSPickListShipping, Report));
Because WHSPickListShipping is the name of the AX report, but I renamed my custom report clWHSPickListShipping. What confused me was that my DataProvider class was executing as wanted.

What is the safest way to store a password using Code Igniter?

I am using Code Igniter for my current project.
As of now, I am using MD5 for password hashing, but I have read at a lot of places, that it is not a good practice to do so.
What should I go with?
Using a salt
Or should I use bcrypt
Also, if bcrypt is recommended, then how to use it with Code Igniter?
EDIT
I have put these files in application/libraries
PasswordHash.php
c/Makefile
c/crypt_private.c
In my controller, I am using this code -
$params = array(
'phpass_hash_strength' => 8,
'phpass_hash_portable' => FALSE
);
$this->load->library('PasswordHash', $params);
$password = $this->passwordhash->HashPassword($pwd);
I am getting these errors -
A PHP Error was encountered
Severity: Notice
Message: Uninitialized string offset: 3
Filename: libraries/PasswordHash.php
Line Number: 116
A PHP Error was encountered
Severity: Warning
Message: strpos() [function.strpos]: Empty delimiter
Filename: libraries/PasswordHash.php
Line Number: 116
Update
Removed PasswordHash.php, using SimpleLoginSecure now.
Use bcrypt. This discussion came up here in the comments to my answer. You can use a library such as phppass to really simplify the password encryption.
On the matter of salt. Use it! Otherwise somebody can simply go to this site and download the rainbow tables that will cover the large majority of passwords the average users chooses. Especially with all the security leaks in the last few months, now is not the time to be saying you won't use something as simple to implement as random salt.
UPDATE
To use PHPPass with CI, download and extract the files from the phppass website, linked above. Put the PasswordHash.php file into your CI application/libraries directory.
In your code, you then load the library via: $this->load->library('PasswordHash',array(8, FALSE));
Hashing passwords is then as simple as $this->PasswordHash->HashPassword($password);
To later check if a password is correct, it is as simple as:
$password = $_POST['password'];
$actualPassword = /*Get the hashed password from your db*/;
$check = $this->PasswordHash->CheckPassword($password, $actualPassword);
I've taken this demo from http://dev.myunv.com/articles/secure-passwords-with-phpass/ which gives you a lot more informations. I've modified that tutorial slightly to utilize CI's loader which is why you don't need the include or new statements.
why use md5() when it is just as easy to use sha1() ?
Also salting the passwords is always a good idea as it effectively removes the threat of a Rainbow Table attack
In my experience a salted SHA1 hash is pleanty secure for 99% of web application situations.
Code Igniter has changed since the time this question was asked. But for the benefit of some who may not have come across the extensive documentation of CI or haven't seen this before, CI has an encryption class which provides a two-way data encryption using the Mcrypt library of PHP.
After initializing the class using:
$this->load->library('encrypt');
You can encrypt as follows:
$msg = 'My secret message';
$encrypted_string = $this->encrypt->encode($msg);
and decrypt as follows:
$encrypted_string = 'APANtByIGI1BpVXZTJgcsAG8GZl8pdwwa84';
$plaintext_string = $this->encrypt->decode($encrypted_string);
CI also has a non-decodable 1-way hashing:
$hash = $this->encrypt->sha1('Some string');
For more information see:
http://www.codeigniter.com/user_guide/libraries/encryption.html

Run Doctrine 2 CLI Tools Tasks from a script run from the browser

A little background information: I am working on integrating Doctrine into a CodeIgniter application. I have it working, but I would like to be able to run the Doctrine command line (CLI) tasks from the browser, i.e. not from the command line script.
The reason I desire this is because I will be running Doctrine and CodeIgniter on a shared hosting package where I will not have command line access.
This seems like a very basic feature, but is not readily available with Doctrine 2.
My last-ditch effort will be going into the command line tool and figuring out how the tasks are being executed then duplicating that code in a CodeIgniter controller.
If there is any simpler way to do this, please let me know.
Thanks!
Unanswered duplicate posted a while back.
For the following
$doctrine = \Zend_Registry::get('doctrine');
$em = $doctrine->getEntityManager();
$tool = new \Doctrine\ORM\Tools\SchemaTool($em);
Get the SQL to update the current schema:
$sqlArray = $tool->getUpdateSchemaSql($em->getMetadataFactory()->getAllMetadata());
Update the schema with the current metadata
$res = $tool->updateSchema($em->getMetadataFactory()->getAllMetadata());
Create the schema.
$res = $tool->createSchema($em->getMetadataFactory()->getAllMetadata());
This belongs in an install script. Just create and verify the db connection
$conn = $doctrine->getConnection();
$sql = "SELECT * FROM users";
try {
$stmt = $conn->query($sql); // Simple (too simple?)
die('Already installed');
} catch (Exception $e) {
// Table not found, continue
}
Then create your schema.
You probably don't want to try to run the command-line tools without a command-line.
However, you can do it yourself in scripts pretty simply. For instance, if you wanted to do things that orm:schema-tool:* does, you'd start here

Resources