I am working on forgot password functionality in my laravel 5.0 application. I am asking user to enter registered email and submit(post method) this form works on jquery ajax post request. After getting email from request i am checking it in db whether it exist or not. if exist i am updating new password, if not sending an error message upto this every this is fine. Now i am trying to send email with new password to the user, it is not working. Password is updating but email not sending.Find my controller code below
public function forgot_pass(Request $request){
$email = $request->input('femail');
$data = ['email' => $email];
$user = Myuser::where($data)->count();
if($user == 0){
return response()->json(['status' => 'Invalid']);
}
else{
$user_details = Myuser::where($data)->get()->first();
$new_pass = $this->generateRandomString();
$md5_pass = md5("EEE".$new_pass);
$status = Myuser::where('email', $email)
->update(['pass' => $md5_pass]);
if($status){
$mail_data = ['name' => $user_details->name, 'new_pass' => $new_pass];
Mail::send('emails.newpassword', $mail_data, function($message)
{
$message->from('us#example.com', 'Laravel');
$message->to($email);
});
return response()->json(['status' => 'Invalid']);
}
}
}
Actually mail is working if i used $message->to('sometest#testmail.com'); instead of $message->to($email);. Below is the error i am getting.
Feeling strange why $email causing error.
You have to pass the $email to the anonymous function
Mail::send('emails.newpassword', $mail_data, function($message) use ($email) {
...
});
Related
i have a code that works perfectly for login for every mobile users,until a user tries to login but he cant here is the login code,
Note, this happens to only this user
public function MobileLogin(Request $request)
{
error_log($request);
$n = $request->get('username');
$p = $request->get('password');
error_log($p);
error_log($n);
error_log('i got the values');
if (Auth::attempt( array(
'UserName' => $request->get('username'),
'password' => $request->get('password')
) )) {
$user = Auth::user();
$id = Auth::id();
error_log($id); // i am able to see this value on the log which means user is authenticated
$n = 'ok';
return Response::json($user); // but i couldn't get this instead
} else {
$n ='Invalid Username or Password Please Try Again'; // i get this
return Response::json($n);
}
}
I am new in php and working on REST API in cakephp3 for my android application.
after setting up php and composer and routing I created login function..
public function login() {
$this->request->allowMethod('post');
$this->loadModel('Users');
$entity = $this->Users->newEntity($this->request->data, ['validate' => 'LoginApi']);
if ($entity->errors()) {
$this->httpStatusCode = 400;
$this->apiResponse['message'] = 'Validation failed.';
foreach ($entity->errors() as $field => $validationMessage) {
$this->apiResponse['error'][$field] = $validationMessage[key($validationMessage)];
}
} else {
$hasher = new DefaultPasswordHasher();
$password = $hasher->hash($entity->password);
$user = $this->Users->find()
->where([
'email' => $entity->email,
'password' => $password
])
->first();
if (empty($user)) {
$this->httpStatusCode = 403;
$this->apiResponse['error'] = 'Invalid email or password.';
return;
}
$payload = ['email' => $user->email, 'name' => $user->name];
$this->apiResponse['token'] = JwtToken::generateToken($payload);
$this->apiResponse['message'] = 'Logged in successfully.';
isset($user);
isset($payload);
}
}
I use 123456 for password and this hasher returns random string every time, but the password which is already saved in database for 123456 is
$2y$10$f7K02jamD7ZeGHLcTkP6Weh6VsthMWHiwqHJmcqbsxuLCKGCQCGCu this.
that is why it gives Invalid password in response.
My question is how to match the exact same string or hashing for request.
thanks in advance.
With reference to this answer
Use this line
password_verify($entity->password, $user->password)
instead of this
$hasher = new DefaultPasswordHasher();
$password = $hasher->hash($entity->password);
you can try this function
public function login()
{
$this->request->allowMethod('post');
$this->loadModel('Users');
$entity = $this->Users->newEntity($this->request->data, ['validate' => 'LoginApi']);
if ($entity->errors()) {
$this->httpStatusCode = 400;
$this->apiResponse['message'] = 'Validation failed.';
foreach ($entity->errors() as $field => $validationMessage) {
$this->apiResponse['error'][$field] = $validationMessage[key($validationMessage)];
}
} else {
$user = $this->Users->find()->where(['email' => $entity->email])->first();
if (count($user)) {
if (password_verify($entity->password, $user->password)) {
$payload = ['email' => $user->email, 'password' => $user->password];
$this->apiResponse['token'] = JwtToken::generateToken($payload);
unset($user->password);
$this->apiResponse['response'] = array($user);
unset($user);
unset($payload);
} else {
$this->httpStatusCode = 403;
$this->apiResponse['error'] = 'Incorrect password';
return;
}
} else {
$this->httpStatusCode = 403;
$this->apiResponse['error'] = 'Email not found';
return;
}
}
}
The general idea would be to hash according to a key you specify.
An advice would be to keep changing the key periodically. You will then need to dehash your save into the clear again using the old key then rehash on new.
I'm not sure if the option is available to you, so you might want to take it with a grain of salt.
Cheers
First of all, CakePHP ships with authentication functionality out of the box, and I'd strongly suggest that you make use of that instead of running your own, given that it sounds as if you're looking for deterministic algorithms, this can very easily backfire.
If you are using CakePHP 3.5+, look into the authentication middleware plugin (currently in RC phase), for earlier CakePHP versions, use the authentication component.
For the sake of completeness, if you were to do this manually, you'd first query the user by its unique identifier (in your case the email address), and then compare the password at PHP level, using the password hashers AbstractPasswordHasher::check() implementation:
$user = $this->Users
->find()
->where([
'email' => $this->request->data('email')
])
->first();
if (!$user ||
$hasher->check($this->request->data('password'), $user->password) !== true
) {
// authentication failed
} else {
// authentication succeeded
}
I want to write a custom authentication on laravel, I want to know should I use default auth or should I write a new?
my auth workflow is:
Step 1- Show email form (in this step we will get just email address)
Step 1-2- check for email existence and if email exists we will go to Step 2 and if not exists I should redirect user to Step 3
Step 2- get the user password (validate password and if everything was OK user will login)
Step 3- show registration form and fill the email with entered user email address (validate form and register user)
What is your solution ?
//Login rules
public function user_login_rules(array $data)
{
$messages = [
'email.required' => 'Please enter your email'
];
$validator = Validator::make($data, [
'email' => 'required'
], $messages);
return $validator;
}
Your post method
public function postSignIn(Request $request)
{
$request_data = $request->all();
$validator = $this->user_login_rules($request_data);
if($validator->fails())
{
return redirect()->back()->withErrors($validator)->withInput();
}
else
{
$email = $request_data['email'];
$user_details = User::where('email', $email)->first();
if(count($user_details) > 0)
{
$credentials = array('email'=> $email ,'password'=> $request_data['password']);
if ($this->auth->attempt($credentials, $request->has('remember')))
{
//Login successful
return redirect()->to('/home');
}
else
{
$error = array('password' => 'Please enter a correct password');
return redirect()->back()->withErrors($error);
}
}
else
{
//Display register page with email
return view('register')->with('email', $email);
}
}
}
I have a function in user controller in laravel that allows users to enter their name and email in a form and send an email to administrator. But when I try to the variable containing them in the MailTo function, it gives error. Here is my code:
public function send_email_contact_us(){
$name = Input::get('name');
$email = Input::get('email');
$message_contact = Input::get('message');
$sender_email = Input::get('email');
$sender_name = Input::get('name');
$validator = Validator::make(
array(
'name' => $name,
'email' => $email
), array(
'name' => 'required',
'email' => 'required',
)
);
if ($validator->fails())
{
$error_messages = $validator->messages()->all();
return Redirect::back()->with('flash_errors',"Message not sent, please try again.");
}
else
{
$data=array("name"=>$name,"email"=>$email,"message_contact"=>$message_contact);
Mail::send('emails.contactus',$data, function($message)
{
$message->from($sender_email, $sender_name); // THIS GIVES ERROR
$message->to("admin#admin.com")->subject('Contact Us');
});
return Redirect::back()->with('flash_success',"Message sent successfully.");
}
}
Any help would be highly appreciated.
change to this
Mail::send('emails.contactus',$data, function($message) use($sender_email,$sender_name)
{
$message->from($sender_email, $sender_name);
$message->to("admin#admin.com")->subject('Contact Us');
});
To use external variables in a closure you have to import the variable into the closure by using the use keyword
I already looking for related issue with this but didn't solved yet.
link 1, link 2, link 3
Auth::attempt() is success
try to register session after Auth::attempt() is success
remember_token field on users table is always null
This is my code:
AuthController:
protected function login(Request $request){
$result = [];
$rules = ['email' => 'required|email', 'password' => 'required|alphaNum|min:3'];
$validator = Validator::make($request->all(), $rules);
if($validator->fails()) {
$result['message'] = 'Login Failed';
}else{
$userdata = ['email' => $request->email, 'password' => $request->password];
if (Auth::attempt($userdata, $request->has('auth_remember'))) {
// dd(Auth::user()); << THIS DATA IS EXIST
// $request->session()->push('user.id', Auth::user()->id);
// $request->session()->push('user.name', Auth::user()->name);
// $request->session()->push('user.email', Auth::user()->email);
// dd($request->session()->all()); << THIS DATA IS EXIST
$result['message'] = 'Login successfull. Redirecting ...';
}else{
$result['message'] = 'User not found';
}
}
echo json_encode($result);
}
I have a middleware Auth when I go to http://.../dashboard, but...
Auth::check() return false
$request->session()->has('user') return false
Auth Middleware:
public function handle($request, Closure $next){
if($this->auth->viaRemember()) return $next($request);
if($this->auth->guest()){
if($request->ajax()){
return response('Unauthorized.', 401);
}else{
return redirect()->guest('login');
}
}
return $next($request);
}
storage/framework/session already set to 777
file session are generated
app timezone already match with server settings and database settings
Any help would be appreciated.
Why are you adding logged user data manually to the session, You can user use Auth::user() to get user data anytime after attempt
Delete this lines:
$request->session()->push('user.id', Auth::user()->id);
$request->session()->push('user.name', Auth::user()->name);
$request->session()->push('user.email', Auth::user()->email);
and verify with dd($request) the auth_remember
I think I resolve this issue.
Laravel authentication are not working when using Ajax. Just follow the documentation from http://laravel.com/docs/5.1/authentication and all should be worked!
But it's strange! Authentication with ajax are worked well in my localhost but no when I upload it to server.