Laravel 4 how can I get the original password? - laravel-4

I use the Hash::make to deal with the password when it write into database.
But now I have a problem,How I get the original password?
I mean not hashed password.
Because I have a page want to show the password to the user himself.
Should I have another database field to record the original password?
Or there has a simple Laravel way?

Just to expand on what Doon says, which as Mike points out is definitely correct - never save plain text passwords - always provide a reset option only for lost/forgotten passwords.
Laravel luckily can help you out here with its RemindableInterface, which you can implement in your User class/model, eg.
class User extends Eloquent implements RemindableInterface {
public function getReminderEmail()
{
return $this->email;
}
}
so no need to start from scratch on this - details about usage here - http://four.laravel.com/docs/security#password-reminders-and-reset
Glen

Related

How can I obtain password hash from ParseUser?

I am currently in the process of migrating all user accounts of my parse-server backend to a 3rd-party SSO provider. The provider allows me to import users with pre-hashed passwords, allowing me to do the transition without needing the users to sign-in to finish the migration process.
I have been having issues trying to obtain the hashed password from the ParseUser object. I can see it in the MongoDB (the _hashed_password field), however I have been unable to extract the password field from the queried object.
I obtain the ParseUser object via the following query (simplified, removed async/await)
const query = new Parse.Query(Parse.User)
query.find({useMasterKey: true}).then(users => {
users.forEach(user => {
// obtain password here + do migration
})
});
I have attempted to get the password via
user.getPassword()
user.get("password")
user.get("_hashed_password")
query.select(["_hashed_password", "password"]).find({useMasterKey: true}).then(...)
The getPassword() function does not exist, but I wanted to try it anyway. the get("password") and get("_hashed_password) returns undefined.
The query.select(...) returns the entire user (except the password), even though I thought it would return either the password or an empty object.
My question is: How can I programatically get the hashed password of a user on the parse platform?
Currently for debugging purposes I am developing this migration as a cloud function. Once I have it working I was planning to move it as a job. I believe this should have no effect on the way the code works, but am leaving this note here just in case anyway.
Thanks in advance for your help.
Thanks to Davi Macêdo, I figured it out.
One has to use aggregate query, however the field _hashed_password gets filtered out by Parse even in aggregate queries, so we need to compute additional field based on the _hashed_password. The following code works:
new Parse.Query(Parse.User).aggregate({
"project": {
"myPassword": "$_hashed_password"
}
})

Laravel Unknown formatter "prefix" error after 4.1.26 update whilst re-seeding

After following the steps for the 4.1.26 upgrade on Laravel, when I try to re-migrate and re-seed the database, I am presented with Laravel Unknown formatter "prefix" error.
I add the nullable string to the User's migration file and the three functions to the User's model.
$table->string('remember_token', 100)->nullable();
and
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return 'remember_token';
}
Looking at PHP Artisan, it rolls back the migrations, migrates them all, it's when it moves onto the seeding of the database.
I know it's the update as when I go back to a previous version, it's all working correct.
Upgrading To 4.1.26 From <= 4.1.25
Laravel 4.1.26 introduces security improvements for "remember me" cookies. Before this update, if a remember cookie was hijacked by another malicious user, the cookie would remain valid for a long period of time, even after the true owner of the account reset their password, logged out, etc.
This change requires the addition of a new remember_token column to your users (or equivalent) database table. After this change, a fresh token will be assigned to the user each time they login to your application. The token will also be refreshed when the user logs out of the application. The implications of this change are: if a "remember me" cookie is hijacked, simply logging out of the application will invalidate the cookie.
http://laravel.com/docs/upgrade#upgrade-4.1.26
https://laracasts.com/lessons/laravel-updating-to-4-1-26
The error turns out was from the seeding of the users table. For some obscure reason, the faker data, was trying to reference a prefix instead of a title.

Using the Hash::make method to update all entries in table

Since I'm porting an app to Laravel and it's using the Auth Class, I need to change all the passwords in my users table to bycrypt (using Hash::make()).
The thing is that I want to use the usernames as default password (so when the migration is done, my user "Mario" will have a Password of "Mario") — I wanna do this with all the entries of the database via a Migration, but I can't seem to make it, since I don't know how to get the value of the select, hash it, then use it in the update.
Is there any way to do this without using loops? (i.e without making one query per user)
EDIT: Yes, this is impossible to do without loops. I realized that. And #Adrenaxus has the right answer.
Why don't you do something like this:
foreach(User::all() as $user){
$user->password = Hash::make($user->username);
$user->save();
}

How to login with 3 parameters in asp.net mvc

I have an application where one username can belong to many companies. Thus to distinguish them, i need to use the both username and password as unique pair to login.
I'm using ASP.NET MVC and i struggle to understand where the Login occurs.
Actually i can see where it validates the user but i don't find where it retrieves the user.
So where the
Select user where username=xx and password=xx occurs ?
Asked differently : i did not find wher User is set ? I see User.Identity.Name it in the code, but i don't see :
User=Select....
Thanks
John
John, as you are using MVC. You wont be seeing any queries in the code aside from the LINQ syntax. Im guessing what you are trying to do is a many to many relationship between the User table and the Company table. (one user has multiple companys and 1 company has multiple users)
Pretty much database wise this would mean you need an extra table with both primairy keys of Company and Users.
To get back to your question. ASP.net MVC has its own membership provider. You can choose to either use the default one with its own tables or overwrite it and create ur own custom membership provider (with the ability to use ur own user table)
The default one pretty much should contain most of the basic attributes. (password reset, password salt, email,..)
http://www.asp.net/web-forms/tutorials/security/membership/creating-the-membership-schema-in-sql-server-cs
skip to the step: Installing the Application Services to generate the tables
However guessing you already have a database with your very own user table. you should overwrite the custom membership class.
Simply this would mean you make a new class that inherits from the abstract class "MembershipProvider"
public class MyMembershipProvider : MembershipProvider
{
}
After that you have to let asp know that you will be overwriting the default membershipprovider with yours in web.config:
<membership defaultProvider="MyMembershipProvider">
<providers>
<clear />
<add name="MyMembershipProvider"
applicationName="MyApp"
Description="My Membership Provider"
passwordFormat="Clear"
connectionStringName="MyMembershipConnection"
type="MyApp.MyMembershipProvider" />
</providers>
</membership>
Some methods in the membership provider requires you to return or use an object of MembershipUser. Everything of how to implement this is right here:
http://msdn.microsoft.com/en-us/library/system.web.security.membershipuser.aspx
This is not a necessary step but its recommended.
Good luck john :)
If theres any confusion in the explanation, dont hesitate to ask
Short Answer:
The code you're describing happens behind the scenes in the LogOn action of the Account Controller:
MembershipService.ValidateUser(model.UserName, model.Password)
Which returns true for a valid user. The user is then "signed in" with the next line in the code:
FormsService.SignIn(model.UserName, model.RememberMe)
(You can see both of those functions defined in the AccountModels file under the Models folder)
If you want to also check company id while authenticating the user then you'll need to write your own auth method to replace ValidateUser. Ths will depend on what you're using for your store (SQL?)
But, as a broader point, best practices you should not allow the same user name for different users. It's just a bad idea and will lead to trouble.
UPDATE:
If I were recommending how to do this, I would suggest you user the UserProfile aspect of ASP.NET Membership. It is designed to capture and store additional user variables (such as company) while still using the nicely built and secure Membership that they've written for you. Read up on it, but below is my CreateUser function in the app I'm currently working on. Note how I use the Profile to store first and last name as well as a flag that the user needs their password reset.
Again, this would preempt the ability to have multiple users with the same username, but I really think you ought to avoid that.
[HttpPost]
public ActionResult CreateUser(string username, string email, string first, string last, string role)
{
string password;
MembershipUser user;
//Generate a random password
password = Auth.CreateRandomPassword(6);
try
{
//Create the user
user = Membership.CreateUser(username, password, email);
//Add the user to the chosen role
Roles.AddUserToRole(username, role);
//Create the user profile
UserProfile profile = UserProfile.GetUserProfile(username);
profile.FirstName = first;
profile.LastName = last;
profile.ForcePasswordReset = true;
profile.Save();
EmailNewUser(username, email, password);
}
catch (Exception ex)
{
HttpContext.Response.StatusCode = 500;
HttpContext.Response.StatusDescription = ex.Message;
HttpContext.Response.Clear();
}
return PartialView("UserTable", Auth.Users());
}

Set Admin User's Password Hash Directly

I have an existing admin_user that I'm basically migrating to an additional admin_user record, and I want to set the password hash for the new record with the value from the old record.
Because _beforeSave hooks setPassword() and encrypts it, it doesn't seem possible.
Was in the process of writing this question, when I figured out how to solve it, so I'll go ahead and post my own answer here, in case it helps anyone else.
Looks like you need to overload the Mage_Admin_Model_User class to do this. Since you'll probably be loading the class directly and calling the method to set the password, you probably won't need to worry about rewrites or event observing.
Here's how I did it:
class Me_Mymodule_Model_Admin_User extends Mage_Admin_Model_user
{
protected function _beforeSave()
{
parent::_beforeSave();
if ($this->getPasswordHash()) {
$this->setData('password', $this->getPasswordHash());
}
}
}
And then, to change it, do the following. In my case, I did this within a custom migration script that I wrote.
// This just sets the "password_hash" data on the model which has no function other
// than to be converted to the "password" value in the _beforeSave() above.
$adminUser = Mage::getModel('mymodule/admin_user')->load($id);
$adminUser->setPasswordHash('insert password hash here')->save();
The setPasswordHash() and getPasswordHash() methods are regular Magento magic getters / setters, so they don't need to be defined anywhere.
UPDATE: Don't downvote for answering own question, it's encouraged.

Resources