I've made a login function in which I render a template after checking the login and password. This's the form that i've made inside a template.
<form action="{{ path("login") }}" method="post" id="formulaire_connexion">
<label class="control-label">Email
<input type="text" name="email" id="email" placeholder="your#email.com" onclick="this.select()"/>
</label>
<label class="control-label">Password</br>
<input type="password" name="password" id="password" placeholder="*********" onclick="this.select()"/>
</label>
<input type="checkbox" id="remember_me" name="remember_me"><label for="remember_me">Remember me </label></br>
<button type="submit" id="connexion" name="connexion">Connexion</button>
</form>
And this's the logging check method :
public function loginAction(Request $request)
{
$mail = $request->get('email');
$pass = $request->get('password');
$oauth = new OAuth($mail, $pass);
$baseUrl = "http://api.localhost/v1/";
$connexion = "{$baseUrl}login/".$mail."/".$pass;
$oauth->fetch($connexion, $_REQUEST, OAUTH_HTTP_METHOD_GET);
$reponseInformations = json_decode($oauth->getLastResponse(), true);
if (!$reponseInformations) {
$data['erreur'] = "Bad credentials";
return $this->render('EspacePointDeVenteBundle:Authentication:authentication.html.twig', array(
'erreur' => $data,
));
}else{
return $this->render('EspacePointDeVenteBundle:Home:index.html.twig', array(
'reseau' => $reseau,
'identifiant' => $key,
'key' => $identifiant,
));
}
}
After a wrong login connexion I render the same login template, but the routing is changed to /login instead of havig /index per example. What I need to know how to keep the same routing even if we called a foreign method.
Related
This is a question I have seen asked before but I have been unable to find an answer for the newer version of Codeigniter.
Controller
<?php
namespace App\Controllers;
class SendEmail extends BaseController
{
public function index($validation = NULL){
// Load form helper
helper('form');
// Instantiate session
$session = \Config\Services::session();
// Set css, javascript, and flashdata
$data = [
'css' => array('contact.css'),
'js' => array('contact.js'),
'validation' => $validation,
'success' => $session->get('success')
];
// Show views
echo view('templates/header', $data);
echo view('contact', $data);
echo view('templates/footer', $data);
}
public function sendEmail(){
// Instantiate request
$request = $this->request;
// Captcha API
$captchaUser = $request->getPost('g-recaptcha-response');
// Captcha Key loaded from a file left out of the repo
$captchaConfig = config('Config\\Credentials');
$captchaKey = $captchaConfig->captchaKey;
$captchaOptions = [
'secret' => $captchaKey,
'response' => $captchaUser
];
$client = \Config\Services::curlrequest();
$captchaResponse = $client->request('POST', 'https://www.google.com/recaptcha/api/siteverify', ['form_params' => $captchaOptions]);
$captchaObj = json_decode($captchaResponse->getBody());
// Load validation library
$validation = \Config\Services::validation();
// Set validation rules
$validation->setRules([
'name' => 'required|alpha_dash|alpha_space',
'email' => 'required|valid_email',
'subject' => 'required|alpha_numeric_punct',
'message' => 'required|alpha_numeric_punct'
]);
// Validate inputs
if (!$this->validate($validation->getRules())){
// Run index function to show the contact page again
$this->index($this->validator);
}
// Validate captcha
elseif(!$validation->check($captchaObj->success, 'required')){
$validation->setError('captcha','Did not pass captcha. Please try again.');
$this->index($validation->getErrors());
}
else{
// Set variables to input
$name = $request->getPost('name');
$email = $request->getPost('email');
$subject = $request->getPost('subject');
$message = $request->getPost('message');
// Load email class
$emailC = \Config\Services::email();
// Set email settings
$emailC->setFrom('bensirpent07#benkuhman.com', $name);
$emailC->setReplyTo($email);
$emailC->setTo('benkuhman#gmail.com');
$emailC->setSubject($subject);
$emailC->setMessage($message);
// Testing section
echo '<br>'.$name.'<br>'.$email.'<br>'.$subject.'<br>'.$message;
/* Temporarily disabled for testing purposes
// Send email
if($emailC->send(false)){
// Redirect
return redirect()->to(base_url().'/contact')->with('success', true);
}else{
// Display error
throw new \CodeIgniter\Database\Exceptions\DatabaseException();
};
*/
}
}
}
Contact View
<div class="container">
<div class="row">
<div class="col">
<div class="alert alert-success align-center" id="message-alert" <?php if($success){echo 'style="display:block"';} ?>>Message successfully sent!</div>
</div>
</div>
<div class="row justify-content-center">
<div class="col-md-6">
<?php echo form_open('send_email', ['id'=>'contactForm'])?>
<div class="form-group">
<label for="name">Name</label>
<input name="name" type="text" class="form-control" id="name" aria-describedby="name" placeholder="Name" required>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('name')){echo $validation->getError('name');}?></p>
</div>
<div class="form-group">
<label for="email">E-Mail</label>
<input name="email" type="email" class="form-control" id="email" aria-describedby="email" placeholder="E-mail" required>
<small id="emailHelp" class="form-text">I'll never share your email with anyone else.</small>
<?php //echo $validation->email;?>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('email')){echo $validation->getError('email');}?></p>
</div>
<div class="form-group">
<label for="subject">Subject</label>
<input name="subject" type="text" class="form-control" id="subject" placeholder="Subject" required>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('subject')){echo $validation->getError('subject');}?></p>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea name="message" rows="5" class="form-control" id="message" placeholder="Type your message here." required></textarea>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('message')){echo $validation->getError('message');}?></p>
</div>
<button id="submitButton" type="submit" class="btn btn-primary g-recaptcha" data-sitekey="6Ldf07AZAAAAAAflQCaJcWgGFCWevCswpIrm0mJN" data-callback='onSubmit' data-action='submit'>Submit</button>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('captcha')){echo $validation->getError('captcha');}?></p>
<?php echo form_close()?>
</div>
</div>
</div>
<script>
function onSubmit(token) {
document.getElementById("contactForm").submit();
}
</script>
<script src="https://www.google.com/recaptcha/api.js"></script>
From my understanding of the way validation used to work in CodeIgniter, is that when you loaded your view after a form validation it would update the values with what was previously entered. This does not seem to be the case for CodeIgniter 4. I've also tried directly loading the views rather than calling the index function on validation fail. Still would not fill in the form values.
Now I could just pass these values to the index function via $data array. Which is the fix I'm going to use for now. This is more so a sanity check to see if there is something basic I'm missing or if I'm incorrectly using the validation format for CodeIgniter 4.
in CI4 you can use old() function to preserve the input value upon form validation:
View file:
<input type="tel" name="phone" value="<?= old('phone'); ?>">
In Controller you must use withInput() in the redirect() code:
$validation = \Config\Services::validation();
$request = \Config\Services::request();
// your input validation rules
$validation->setRules(...)
if($request->getMethod() == "post" && ! $validation->withRequest($request)->run()) {
return redirect()->back()->withInput()->with('error', $this->validation->getErrors());
} else {
// form validation success
}
I am trying to reset the password but I am getting the error message "Trying to get property of non-object".
I have also attached the screen shot of my error please have a look at it.
My Controller for resetting the password:
class ResetPasswordController extends Controller
{
protected $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function showResetForm(Request $request, $token = null)
{
return view('auth.passwords.reset')->with(
['token' => $token, 'email' => $request->email]
);
}
public function reset(Request $request)
{
try {
$password = $this->user->where('id', Auth::user()->id)->value('password');
if(Hash::check($request->input('current_password'),$password)) {
$this->user->where('id', Auth::user()->id)->update(['password' => bcrypt($request->input('new_password'))]);
$token = $request->header('Authorization');
JWT::invalidate($token);
Auth::logout();
return response(['status' => true, 'message' => 'Password changed successfully'], 200);
} else {
return response(['status' => false, 'message' => 'The Current Password is invalid.'], 200);
}
} catch (\Exception $ex) {
return response(['status' => false, 'message' => $ex->getMessage()], 500);
}
}
}
My Routes configuration:
\Illuminate\Support\Facades\Auth::routes();
Route::get('password/reset/{token}', 'Auth\ResetPasswordController#showResetForm');
Route::post('password/reset', 'Auth\ResetPasswordController#reset')->name('password.request');
My View template:
<form action="{{ route('password.request') }}" method="post">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label for="login-form-email">Current Password</label>
<input type="password" class="form-control" name="current_password" id="login-form-password" tabindex="2" placeholder="Current Password" tabindex="4">
</div>
<div class="form-group">
<label for="login-form-password">New password</label>
<input type="password" class="form-control" name="new_password" id="login-form-password" tabindex="2" placeholder="New Password" tabindex="4">
</div><!-- /.form-group -->
<div class="form-group">
<label for="login-form-password-retype">Confirm new password</label>
<input type="password" class="form-control" name="new_password_confirmation" id="login-form-password-retype" tabindex="3" placeholder="Confirm password">
</div><!-- /.form-group -->
<div class="form-group">
<input type="submit" class="btn btn-primary pull-right" name="reset-confirm" id="reset-confirm" tabindex="4" value="Reset Password">
</div>
</form>
How can I find a solution based on this code and error message?
User doesn't need to be a member
Your first problem is here:
public function __construct(User $user)
You're injecting a user, without it knowing what user to use, unless this is coming from middleware. So the constructor shouldn't take a user, nor do you need to protected member. If you really want it as a protected member you could do the following:
public function __construct()
{
$this->user = Auth::user();
}
But since you have Auth::user(), you don't need it as a member.
where on a Model is Static
You have
$this->user->where('id', Auth::user()->id)->value('password')
Model's where function is a static function you shouldn't call it on an individual object. Instead you shoud call it using the scoping operator (::). Most versions of PHP should error out at that point. The correct way to get the current user's password hash from the database is:
$hash = Auth::user()->password;
If you had an id, you could:
$hash = User::where('id','=',$userId)->get()->password;
If you kept the user as a member (against the recommendation) but did it as in the above section of this answer, you could:
$hash = $this->user->password
Why?
Lastly, the Auth module from Laravel in modern versions already takes care of this for you in app\Http\Controllers\Auth. Why are reinventing the wheel?
I need to check the password given by the user in an input and check it. If it's right I'll update the password with new password, if the password is wrong I want to give the user an alert in laravel 5.4.
controller:
public function edit(Request $request){
$user = new User;
$user = $user->find(1);
$oldpassword = $request->input('oldpassword');
$newpassword = $request->input('newpassword');
//if condition
/*if (user()->id == $oldpassword){
$updatesucess = 1;
}else {
$updatesucess = 0;
}*/
$user->update(['password' => $newpassword]);
return back();
}
view:
#section('content')
<div class="form">
<div class="logo-area">
<img src="images/logo.png">
</div>
<form method="POST" action="/edit">
{{ csrf_field() }}
<input type="password" name="oldpassword" placeholder="old Password" required>
<input type="password" name="newpassword" placeholder="new Password" required>
<input type="submit" value="Save changes">
</form>
Use check method of Hash facade (documentation)
In your controller file add Hash facade:
use Illuminate\Support\Facades\Hash;
Add password check and in case of mismatch handle redirect with an error
$user = User::find(1);
$oldpassword = $request->input('oldpassword');
if (Hash::check($oldpassword, $user->password)) {
// redirect back with error
}
Update user password using Hash::make
$newpassword = $request->input('newpassword');
$user->update(['password' => Hash::make($newpassword)]);
For Laravel versions>8 this is the best solution.
'old_password' => 'required|current_password'
You can also specify the api
'old_password' => 'required|current_password:web'
I have some problem with Auth::attempt. When i write good Login with bad password attempt login into website anyway with wrong user. Why it dont work ?
Method:
public function postLogin(LoginRequest $request) {
if (Auth::attempt(["name" => $request["name"], "password" => $request["password"]])) {
return Redirect::route("home");
} else {
return Redirect::route("home");
}
}
LoginRequest
class LoginRequest extends Request {
public function rules() {
return [
"name" => "required|exists:users",
"password" => "required",
];
}
public function messages(){
return [
"name.required" => "Login is empty.",
"password.required" => "Password is empty.",
"name.exists" => "User not found.",
];
}
}
I know i redirect to same view, but view have 2 options for auth and !auth, but I see auth page when I login with good login and bad password, other options works. What did I wrong ?
Regards
edit:
view
<form action={{ route("login") }} method="post">
<input class="form-control" type="text" name="name" /><br />
<input class="form-control" type="password" name="password" /><br />
<input class="form-control" type="hidden" name="_token" value="{{ csrf_token() }}" /><br />
Remember me! <input class="form-control" type="checkbox" name="remember_me" value=""/><br />
<input class="btn btn-primary" type="submit" value="Zaloguj" />
</form>
the password column is named "password" ? and is hashed?
you can see the doc for more information.
https://laravel.com/docs/5.2/authentication#authenticating-users
I am trying to get the login to work in Kohana, but so far it fails to log the user in.
I have been successfully able to create new users, so I have all the tables set up.
My view for the login page is as follows,
<td style="vertical-align:top">
<div id="log_in">
<form class="pure-form pure-form-stacked" action="/kohana-blog/index.php/signup/login" method="post">
<fieldset>
<legend>Log In</legend>
<label for="username">Username</label>
<input id="username" name="username" type="text" placeholder="nonamedude" required>
<label for="password">Password</label>
<input id="password" name="password" type="password" placeholder="Password" required>
<label for="remember" class="pure-checkbox"></label>
<input id="remember" type="checkbox"> Remember me
<br>
<button type="submit" class="pure-button notice">Log In</button>
</fieldset>
</form>
</div>
</td>
My controller is as follows
$this->template->content = View::factory('signup/home')
->bind('message', $message);
if (HTTP_Request::POST == $this->request->method())
{
$remember = array_key_exists('remember', $this->request->post()) ? (bool) $this->request->post('remember') : FALSE;
$remember = FALSE;
$user = Auth::instance()->login($this->request->post('username'), $this->request->post('password'), $remember);
if ($user)
{
Request::current()->redirect('signup/home');
}
else
{
$message = "login failed";
}
}
I can't figure out why it doesn't authenticate the user.
My auth.php is as follows:
'driver' => 'orm',
'hash_method' => 'sha256',
'hash_key' => 'somerandomstring',
'lifetime' => 1209600,
'session_type' => Session::$default,
'session_key' => 'auth_user',
Additionally, the roles_users table have the correct values and the users table has the data from the form.
Is there a way to debug this to find the source of the issue?
First of all make sure your user has login role assigned in roles_users table.
By default you won't be able to login if you don't have this role.
Btw. it's cleaner to write:
$post = $this->request->post();
$user = Auth::instance()->login($post['email'], $post['password'], isset($post, 'remember'));