I am getting error on saving the edited data. Actually User clicked on the edit button User is redirected to edit data page at the end (after) editing the data when user wants to save the edited data cakephp gives error sql integrity violation code 1062. The code for edit is default code generated by the cake bake. the code is
public function edit($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
$this->request->data = $this->User->find('first', $options);
}
}
i also tried savefield instead of save but that is adding new user with all null fields.
You should set the id property on the user before you save it:
$this->User->id = $id;
Or make sure that in your $this->request->data;, the id of the object your are editing is present, $this->request->data['User']['id']; in this particular case, the absence of the user id on the request data is causing the problem.
Related
I've trying to create login code in REST Server and while I use POSTMAN to check it, the output always show HTTP_BAD_REQUEST(Login Failed). The code is ignoring security.
I use REST from https://github.com/chriskacerguis/codeigniter-restserver
This is My Controller
public function index_post(){
$data_memb = array(
'id_member'=>$this->post('id_member'),
'password'=>$this->post('password')
);
$result = $this->Member_model_api->loginMember($data_memb);
if ($result == TRUE) {
$this->response([
'status' => true,
'message' => 'Login Successfull'
], REST_Controller::HTTP_OK);
} else {
$this->response([
'status' => false,
'message' => 'Login Failed'
], REST_Controller::HTTP_BAD_REQUEST);
}
}
}
This is My Model
public function loginMember($data_memb)
{
$sql = 'SELECT * FROM member WHERE id_member = ?';
$binds = array($data_memb['id_member']);
$query = $this->db->query($sql, $binds);
if ($query->num_rows()>0) {
$rw_password = $query->result();
if (password_verify($data_memb['password'],
$rw_password[0]->password)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
I expect the output is HTTP_OK(Login Successfull), or if you have more reference code, please tell me. Thanks for your help.
Since you are using POST method, you should use form-data while sending request.
I assume there may be some re-formatting issue on the server-side which might be preventing your login functionality to get verified.
Try printing both variables on the server-side and view the output.
var_dump($data_memb)
Nothing needs to send urlencoded in POST request.
Try changing the request type and see, this will work.
I have been attempting to implement an OpenID log-in with Yii2 today, and for the most part it has worked. Below is code from my controller, with the action 'Register' running through, and outputting the user->identity->username, but when I, say, redirect this action back to any page on the site, the logged in user is essentially forgotten. I can return to my Register action and have the user logged in.
Help would be appreciated. Thank you.
public function actionRegister()
{
require ('../views/site/steamauth/userInfo.php');
$localId = $_SESSION['steam_steamid'];
$foundUser = User::findOne(['steamid' => $localId]);
if(isset($foundUser))
{
Yii::$app->user->login($foundUser);
var_dump($foundUser);
echo Yii::$app->user->identity->username;
} elseif(!isset($foundUser)) {
$db = new User();
$db->steamid = $_SESSION['steam_steamid'];
$db->username = $_SESSION['steam_personaname'];
$db->visstate = $_SESSION['steam_communityvisibilitystate'];
$db->profile = $_SESSION['steam_profileurl'];
$db->avs = $_SESSION['steam_avatar'];
$db->avm = $_SESSION['steam_avatarmedium'];
$db->avf = $_SESSION['steam_avatarfull'];
$db->persstate = $_SESSION['steam_personastate'];
$db->save();
$foundUser = User::findOne(['steamid' => $localId]);
Yii::$app->user->login($foundUser);
return $this->goHome();
}
}
/**
Ah. After scouring Stackoverflow I found it.
The standard model function findIdentity
return isset(self::$usrs[$id]) ? new static(self::$usrs[$id]) : null;
must be change to reflect the new table of
return User::findOne($id);
What I'm pretending to do is to include the LDAP for internal users in a Guard Authentication System configured by ddbb.
I already have build my Guard Authentication System and works really nice thanks to https://knpuniversity.com/screencast/symfony-security.
But I need also to try to log in previously via LDAP mode. More precisely, the functionality must be like this:
The user try to log in on the Guard System Authentication configured with a database from MySQL and:
1- Check if exist the user in the table User from MySQL. If exist, we go to step 2. If not exist return false to the authentication with the error message.
2-Check if the user exist in the LDAP mode. If exist go to the step 3. If not exist go to the step 4.
3-Try to log in via LDAP with the username and password. If the authentication is ok, it's logged in. If can't match the password via LDAP, return false to the authentication with the error message.
4-After checking the LDAP option, we will just try to log in via Guard Authentication System. If the authentication it's ok, the user is logged in. If can't match the password via Guard with the MySQL users table, return false to the authentication with the error message.
In the LoginFormAuthenticator file I finally could manage this behavior I want as shows the next code.
<?php
namespace AppBundle\Security;
use ...
use Zend\Ldap\Ldap;
use Zend\Ldap\Exception\LdapException;
class LoginFormAuthenticator extends AbstractFormLoginAuthenticator
{
use TargetPathTrait;
private $em;
private $router;
private $passwordEncoder;
private $csrfTokenManager;
public function __construct(...
}
public function getCredentials(Request $request)
{
...
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$username = $credentials['username'];
$ldapPassword = $credentials['password'];
$ldaphost = 'ldap.example.com'; // your ldap servers
$baseDn = 'dc=example,dc=es';
$options = [
'host' => $ldaphost,
'username' => $username,
'password' => $ldapPassword,
'bindRequiresDn' => false,
'accountDomainName' => 'example.es',
'baseDn' => $baseDn,
];
$userInterface = $this->em->getRepository('AppBundle:User')
->findOneBy(['email' => $username]);
$ldap = new Ldap($options);
try {
$ldap->bind();
$userInterface->setIsAuthenticationLDAP(true);
} catch (LdapException $zle){
$userInterface->setIsAuthenticationLDAP(false);
}
return $userInterface;
}
public function checkCredentials($credentials, UserInterface $user)
{
$password = $credentials['password'];
if($user->isAuthenticationLDAP()){
$user->setLoginAttempts(0);
$this->em->persist($user);
$this->em->flush();
return true;
} else {
if($this->passwordEncoder->isPasswordValid($user, $password)) {
$user->setLoginAttempts(0);
$this->em->persist($user);
$this->em->flush();
return true;
} else {
if($user->getLoginAttempts() == '0') $user->setFirstLoginAttempt(new \DateTime('now'));
$user->setLoginAttempts($user->getLoginAttempts() + 1);
if($user->getLoginAttempts() >= 5) {
$user->setLockedDateTime(new \DateTime('now'));
$user->setLoginAttempts(0);
}
$this->em->persist($user);
$this->em->flush();
}
}
return false;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
....
}
protected function getLoginUrl()
{
return $this->router->generate('fos_user_security_login');
}
}
I hope anyone can enjoy this answer.
I am working on my collage project i.e. Employee Management. I have Employee table in sql(crud is also generated from gii). only Admin is having rights to create Employee (there is no Signup).
My Problem: when I am creating employee then I am not able to save data in user table also, please help me to save data in both Employee and user table.
Thanks in advance
Update:
Below is the code:
public function actionCreate() {
$model1=new Employee;
$model2=new User;
if(isset($_POST['Employee']) && isset($_POST['User']))
{
$model1->attributes=$_POST['Emoloyee'];
$model2->attributes=$_POST['User'];
$model1->save();
$model2->save();
echo 'data is saved in both tables';
}
$this->render('create',array('model1'=>$model1,model2'=>$model2));
}
could be you have some validation problem
try check this way
......
$model1->attributes=$_POST['Emoloyee'];
$model2->attributes=$_POST['User'];
if ($model1->validate() && $model2->validate() ) {
$model1->save();
$model2->save();
} else {
$errors1 = $model1->errors;
$errors2 = $model2->errors;
var_dump($errors1);
var_dump($errors2);
exit();
}
then just for debug try using
$model1->attributes=$_POST['Emoloyee'];
$model2->attributes=$_POST['User'];
$model1->save(false);
$model2->save(false);
and check in db if the value are saved ..
You can try this example,
public function actionCreate()
{
$model = new Employee();
$user = new User();
if ($model->load(Yii::$app->request->post()) && $user->load(Yii::$app->request->post())) {
if($model->save() && $user->save()) {
Yii::$app->session->setFlash('success', 'Record saved successfully.');
} else {
//var_dump($model->getErrors());
//var_dump($user->getErrors());
Yii::$app->session->setFlash('error', 'Record not saved.');
}
return $this->redirect(['index']);
} else {
var_dump($model->getErrors());
var_dump($user->getErrors());
die();
}
return $this->render('create', [
'model' => $model,
'user' => $user,
]);
}
Follow the instruction given in below link . This should work
how to insert data to 2 tables i.e Employee and User(migrated) from single form(Employee Create) and controller in yii2
I am new to CodeIgniter, and am trying to write code to log in after registering using a username and password in registration form using a PHPMyAdmin database. I am not getting anything when I try to log in, and it doesn't display an error or any message.
public function login() {
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password' , 'Password');
if($this->form_validation->run() == TRUE){
//check user in database
$this->db->select('username' , 'password');
$this->db->from('user_register');
$this->db->where(array('username' => $username, 'password' => $password));
$query = $this->db->get();
$user = $query->row();
if($user->email){
$this->session->set_flashdata("Successful login");
$_SESSION['user_logged'] = TRUE;
$_SESSION['username'] = $user->username;
} else {
$this->session->set_flashdata("Error No such record found");
}
}
// load view and showing login form
$this->load->view('login');
}
First, you should read the documentation, looks like you skip that part, but it's very important!
Let's code a little bit and fix the bugs!
User data
Well, users will enter their data and we will check, if evertyhing is correct, we can redirect user to the protected page. You call for variables (see Query:) but you I'm not seeing on your code. You should put like that, before your query job
$username = $this->input->post("username");
$password = $this->input->post("password");
Now, you will be able to use the where to get the user data. =)
Query:
If read about OOP with PHP, you know that when you pass parameters to a method, each parameter have their own "action". In case of the select method, you should keep the data you want to select, on the same quote, because you the way you do, it's like you passing multiple parameters to the method.
$this->db->select('username, password');
$this->db->from('user_register');
$this->db->where(array('username' => $username, 'password' => $password));
First, to decide if the record exist or not, I prefer this way:
if($query->num_rows() > 0) {
$user_data = $query->row();
// We should verify if the user entered the password that correspond to the account.
// If not, we tell them that the password is incorrect.
if($password != $user_data->password) {
$this->session->set_flashdata("error", "Wrong password!");
return redirect(site_url());
}
// You can use the CI built in methods to work with sessions
$this->session->set_userdata(array(
'username' => $user_data->username,
));
$this->session->set_flashdata("success", "You are logged in!");
return redirect(site_url());
} else {
$this->session->set_flashdata("Error: No such record found");
redirect(site_url());
}
Flash data
Yeah, we use flashdata to show a message for the user. But, you should pass an item and the value of this item. Like that:
$this->session->set_flashdata('success', 'Successfully logged in!");
And, to retrieve the data on your views, you can do like...
<?php
$success = $this->session->flashdata("success");
$error = $this->session->flashdata("error");
if(!empty($success)) {
echo $success;
}
if(!empty($success)) {
echo $error;
}
?>
Recommendations
Sessions: https://codeigniter.com/userguide3/libraries/sessions.html
Database: https://www.codeigniter.com/userguide3/database/query_builder.html
Also, I recommed you, to take a minute on YouTube, to understand CodeIgniter.
If I forgot something, let me know! =)
Great Suggestion by webmasterdro's Answer.
I would like to extend it a little bit.
Looking at your code it looks like you have added the query to the controller.
And as a suggestion, if you are using an MVC framework then try to follow some basic MVC flow. because if you are not following that then it will be useless to use a framework.
User Controller to handle the post data and validations.
Use model to do the database query.
Use __construct for loading the common model or libraries.
Do not save plane password use md5 or other encryption technique.
Store User detail to the session which you can use further in after login.
Codeigniter has a great user guide. Try to follow that.
So, your code Should be your like this below.
Controller:
public function __construct() {
parent::__construct();
// Load model
$this->load->model('login_database');
}
public function your_controller_function_name() {
// Check validation for user input in SignUp form
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login_form_view');
} else {
$username = $this->input->post("username");
$password = $this->input->post("password");
$result = $this->login_database->registration_insert($username, $password);
//You can do this also if($result != FALSE)
if (!empty($result)) {
// You can set other data to the session also form here
$session_data = array(
'username' => $result['user_name']
);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
// You can set flash data here
$this->load->view('your_view');
} else {
$data = array(
'error_message' => 'Invalid Username or Password'
);
$this->load->view('your_login_form_view', $data);
}
}
}
Model:
// Read data using username and password
public function login($username, $password) {
$this->db->select('username');
$this->db->from('user_register');
$this->db->where(array('username' => $username, 'password' => $password));
$query = $this->db->get();
$user_data = $query->row_array();
if ($query->num_rows() == 1) {
return user_data;
} else {
return false;
}
}
I have not added detail related to flash data because the previous answer has explained it properly.