Laravel random to database - php

What i'm try to do: Then user registered on my website he's got a email with confirmation random code.
My controller looks like that:
$activation_code = str_random(40);
/*
* Register user.
*/
$user = Sentry::register([
'username' => Input::get('username'),
'email' => Input::get('email'),
'password' => Input::get('password'),
'language_id' => $language->id,
'activation_code' => $activation_code
]);
$user->slug = Str::slug($user->username);
$user->save();
But then i check databse, the activation_code cell is empty. What i'm doing wrong? Thanks for answers!

I assume you meant the activation column not table, check your fillable array and make sure its in there.
EDIT
Scratch that, it looks like like your auto activating the user, no activation code necessary in that case.

FIXED! Works fine with:
$activationCode = $user->getActivationCode();

Related

Testing Error messages to be shown for user

I'm trying to write a test to assert that my login page displays an error when the user enters an incorrect username or password.
#if ($errors->any())
<p>Looks like you’ve entered the wrong username or password.
<a href="{{route('password.request')}}">
Click here</a> to reset your password“ </p></div>
#endif
The functionality is working fine and I can see the errors on page, but for some reason, I can't get my test to pass.
->assertSessionHasErrors() is working fine, while ->assertSeeText() is not detecting the error messages in text.
`
public function userSeesErrorMessage() {
$user = factory('App\User')->create([
'password' => bcrypt($password = 'test'),
]);
$response = $this->followingRedirects()
->post('/login', [
'email' => $user->email,
'password' => 'incorrectPassword'
]);
$response->assertSeeText('Looks like you’ve entered the wrong username or password. Click here to reset your password');
}`
The response seem to contain the whole document's HTML, except for the part about the errors.
Any help would be much appreciated.
There might be a few reasons why this does does not work. Easiest thing you could do is to set a header for a referer. This way the validation will know where to redirect you back, because currently you're not submitting a form and the redirect is sending you to a page where you might not display the errors:
$response = $this->followingRedirects()
->post(
'/login',
[
'email' => $user->email,
'password' => 'incorrectPassword'
],
['referer' => '/login']
);
Another issue might be that the session errors are lost within the redirects, where you can try following the redirect separately:
$r = $this->post('/login', [
'email' => $user->email,
'password' => 'incorrectPassword'
]);
$r->assertStatus(302);
$r->assertSessionHasErrors('email');
$r = $this->followRedirects($r);
$r->assertSeeText('Looks like you’ve entered the wrong username or password. Click here to reset your password');

How Can I manual pass information to the register controller in Laravel

To create a user without the end-user having to type in the details.
Something akin to
User::classcreate([
'email' => $email,
'password' => $rand_pass,
.....
]);
Thanks for the ideas and feedback in advance :)
The use case is.
The end-user invites another user to use the service by typing in their email and it creates a user with a random password before sending a email to the new user with their created details.
You're almost there with your code. It should look like this:
User::create([
'email' => $email,
'password' => bcrypt($rand_pass),
]);
But if you want to hash the password, you should also send the password to that user through email (which is not very secure). When the users logs in for the first time, you should at least require him to change the password.
You can simply use create() method of your User model:
$userData = [
'email' => 'some#email.com',
'password' => 'somepassword'
];
$newUser = User::create($userData);
You'll also need your password hashed in order for it to work with Laravel's authorization. Add the following to your user model - it will hash password before it's saved to the database:
public function setPasswordAttribute($password)
{
$this->attributes['password'] = Hash::make($password);
}

Get a user by username and password with Laravel

I need to do some extra checks on a user, I would like to get the user by username and password.
Firstly:
Is there a built in function that gets a user by username and password without authenticating them?
Secondly:
If the above is no, then how do I correctly hash the password, because if I use Hash::make( $password ) and then compare to the database, it is not the same... You would usually use Hash::check but I need to actually get the user by username and password.
In Laravel 5.2
You can use Auth::once($credentials) to validate credentials and thereafter Auth::getUser(); to get the user.
$credentials = Request::only('username', 'password');
if(!Auth::once($credentials)) {
// Invalid user credentials; throw Exception.
}
$user = Auth::getUser();
First:
If you want to check if user data to authentication is correct you can use:
if (Auth::validate($credentials))
{
//
}
But if you want to get user from database with user and password, you can use:
$user = User::whereName($username)->wherePassword(Hash::make($password))->first();
Second
To store password in database you should use Hash::make($password) as you showed and it works without any problems. Using Auth::validate should solve the issue.
Yes, there is a built in function you should use. I recommend you to read the docs. But here's a good example, it's pretty self-evident:
$input = array(
'username' => Input::get('username'),
'password' => Input::get('password'),
);
$remember = (boolean)Input::get('remember'); //'Remember me' checkbox
if (Auth::attempt($input, $remember)) {
return Redirect::intended('dashboard')->with("success", "You're logged in!"); //Redirect the user to the page intended to go to, with the dashboard page as default
}
Registering a user looks something like this:
$input = array(
'username' => Input::get('username'),
'email' => Input::get('email'),
'password' => Hash::make(Input::get('password')) //Encrypt password
);
$user = User::create($input);
I also recommend you to read about input validation. I hope this helps, good luck.
Edit: I didn't read the "without authenticating them" part. You should use Auth::validate($input) as Marcin already explained.
Laravel 5.7
To check a users credentials without logging them in, I had to do this:
$user = User::whereEmail($request->email)->first();
$user = password_verify($request->password, optional($user)->getAuthPassword()) ? $user : false;
Laravel auth validation makes use of https://www.php.net/manual/en/function.password-verify.php

input the data from url Laravel

I need to get the value from link and then add them to DB.
I am working with another developer who created an api as a bridge because he does not know Laravel. Here is the api http://laravel.io/bin/614Xv I am currently passing string valued data like so http://laravel.io/bin/wYry0 and passing the parameters $user, $name, $password through the route.
Here is my route
Route::get('/profile/activated/{user?}/{pass?}/{email?}', array(
'as' => 'invited-user-account-created-get',
'uses' => 'ProfileController#getCreateInvitedUser'
));
Here is my function:
public function getCreateInvitedUser($user=null, $password=null, $email=null) {
$user = Input::get('username', 'abcd');
$pass = Input::get('password', '1234');
$email = Input::get('email', 'asas#gam.com');
//insert $user array in database users table
$user = User::create(array(
'username' => $user,
'password' => $pass,
'email' => $email
));
}
The other developer is wanting me to set the input to the variables I get from the url link/profile/activated/user/pass/email
Maybe I am tired but I am not understanding what he wants me to do and how to grab the variables from the url. The whole reason in doing this is to instantly store the invited guest info in the database when they click the activation link so they do not have to sign up for an account later.
Your route has a problem
Use this instead
Route::get('/profile/activated/{user}/{pass}/{email}', array(
'as' => 'invited-user-account-created-get',
'uses' => 'ProfileController#getCreateInvitedUser'
));
But his idea is totally messed up! Passing password values through a URL, Who does that even?
You sound enlightened, please advise him to try a different approach in whatever thing he's trying to achieve.

What happens if Drupal's user_save() fails?

I'm on Drupal 5.x and I'm trying to add new users to the site using a script that calls drupal_bootstrap(). After generating the username, email, password, and role array, I create the new user like so:
$newuser = array( 'name' => $username, 'mail' => $email, 'status' => 1, 'pass' => $password, 'roles' => $roles);
$user = user_save('', $newuser);
I know that with this code I can test the $user object returned by user_save(), but how do I test if the user was created and inserted correctly? Do I have to query the database to test if the user was created successfully?
In drupal 5 it's not easy to see it it fails like in drupal 6. But since it returns a fresh user object from the db, you can inspect it to see if the data was saved properly. So if you try to insert a user and it failed, it will return FALSE.

Categories