Codeigniter Cannot save hashed password to database - mysql

I cannot save hashed password to my 'users' table, but if it's not hashed, the password saved. Can everybody help me?
Controller
public function add()
{
$this->data['title'] = 'add new user';
$this->data['subview'] = 'admin/user/add';
$validate = $this->user->validate;
$this->form_validation->set_rules($validate);
if ($this->form_validation->run() == TRUE){
$this->user->insert(array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'password' => $this->user->hash($this->input->post('password'))
));
$this->session->set_flashdata('message', msg_success('Data Saved'));
redirect('admin/user', 'refresh');
}
$this->load->view('admin/_layout_main', $this->data);
}
my Hash function in user_model
public function hash($string)
{
return hash('md5', $string . config_item('encryption_key'));
}
What's wrong with my code, or is there any other way to do it without any library? or How you do it basically to do this using codeigniter? Thanks
EDIT
this is my insert function from MY_Model
public function insert($data, $skip_validation = FALSE)
{
if ($skip_validation === FALSE)
{
$data = $this->validate($data);
}
if ($data !== FALSE)
{
$data = $this->trigger('before_create', $data);
$this->_database->insert($this->_table, $data);
$insert_id = $this->_database->insert_id();
$this->trigger('after_create', $insert_id);
return $insert_id;
}
else
{
return FALSE;
}
}
Im using Jamie Rumbelow Base Model for my base model, and I have follow his tutorial for insert into database

Related

how can i get value from another CRUD in my json

i have json return values from order crud how can i make it return also value from User Crud by user ID
this is my code now
public function vendorindex(Request $request)
{
$user = Auth::user();
if(isset($user->id)){
$order = Order::where('vendor_id', $user->id)->get();
}else{
$order = null;
}
return response()->json($order);
}
i tried to do this but not work with me to replace another value with the value that i want
public function vendorindex(Request $request)
{
$user = Auth::user();
if(isset($user->id)){
$order = Order::where('vendor_id', $user->id)->get();
foreach($order as $orders){
$mobile = User::where($user->mobile);
$created_at = Order::where($orders->created_at);
$phonenumber = array(
'mobile' => $mobile,
'created_at' => $created_at
);
$orders->created_at = $phonenumber;
}
}else{
$order = null;
}
return response()->json($order);
}

Logout the user from website if they meet the expiry time from database in codeigniter

I am trying to logout the user from website if they meet the expiry time which i have stored in database.
I have create a table called user_sessions where i have stored current userid,logintime(varchar),expirytime(varchar) and i have added one minute extra to the login time in expiry time field so when user logged in these are all values will store in db.
So after user logged in they are redirecting to dashboard so if user doesn't do anything on site up to one minute and if they try to access next page they should logout from site.
If user keep on moving to next pages i need to add one more minute extra time in login time field everytime when they moved to next pages.
I have stored in db like this
Here is my model:
public function sessionStore($data)
{
$this->db->select('*');
$this->db->from('users');
$this->db->where('username', $data['username']);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
$result = $query->result_array();
$recordId = $result[0]['id'];
$status = $result[0]['status'];
$sessionID = random_string('alnum',16);
$currentpass = $result[0]['password'];
if ($status != 1) {
return 4;
}
$checktrue = password_verify($data['password'], $currentpass);
// $checktrue = true;
if ($checktrue) {
$data_log = array(
'userid' => $recordId,
'sessionid' => $sessionID,
'logintime' => time(),
'expirytime' => time()+(60*1)
);
$this->db->insert('user_sessions', $data_log);
return 1;
}
}
}
Here is my controller:
public function login_user() {
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean', 'required');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean', 'required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login_view');
} else {
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$result = $this->Login_model->login($data);
$res = $this->Login_model->sessionStore($data);
if ($result == 1) {
$userData = $this->Login_model->getUserData($data);
$sessionArray = array(
'is_logged' => TRUE,
'user_name' => $data['username'],
'first_name' => $userData['firstname'],
'last_name' => $userData['lastname'],
'userlevel' => $userData['userlevel'],
'organisation_id' => $userData['organisation_id'],
'user_id' => $userData['id'],
'lastip' => $userData['lastip']
);
$this->session->set_userdata($sessionArray);
redirect('dashboard');
} else if ($result == 2) {
$this->session->set_flashdata('message', 'Password seems to be wrong!');
$this->load->view('login_view', $data);
} else if ($result == 4) {
$this->session->set_flashdata('message', 'Username is not active!');
$this->load->view('login_view', $data);
}else {
$this->session->set_flashdata('message', 'Username not found!');
$this->load->view('login_view', $data);
}
}
}
Can anyone help me how to do that.
Thanks in advance.
Please follow the below steps:
Create Common_model.php file \application\models\Common_model.php
Add common_model in autoload.php \application\config\autoload.php
$autoload['model'] = array('common_model');
Write the below code inside Common_model.php.
<?php
class Common_model extends CI_Model {
function __construct()
{
parent::__construct();
$this->checkUserActivity();
}
public function checkUserActivity(){
$this->db->where('expirytime >=',time());
$this->db->where('userid',$this->session->userdata('user_id'));
$result = $this->db->get('user_sessions')->first_row();
/* Check If user active within 1 minute then add 1 minute more*/
if($result){ // Update
$data_log = array(
'expirytime' => time()+(60*1)
);
$this->db->where('userid',$this->session->userdata('user_id'));
$this->db->update('user_sessions', $data_log);
} else {//Logout
$this->activityLogout();
}
//echo $this->db->last_query(); exit;
}
public function activityLogout()
{
$this->session->unset_userdata('user_id'); // single unset
$this->session->sess_destroy(); // Unset all your
redirect('home', 'refresh');
}
}
?>
Hope this helps you!

yii 2.0 get logged in user's Session ID

Am new to Yii, this is the login function (path /basic/controllers/siteController.php), once the users is logged in it will render the login template.
After a user is logged in,
How to get the SESSION ID and store to DB. ?
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
}
return $this->render('login', [
'model' => $model,
]);
}
And the model code (path /models/LoginForm.php)
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
}
return false;
}
$session = Yii::$app->session->getId();
Will grab the Id. There is a good article on sessions here http://www.bsourcecode.com/yiiframework2/session-handling-in-yii-framework-2-0/
And to save something like:
$model->session = $session;
$model->save();

codeIgniter how can i create session into login controller

How can I create login session name? I tried but it didn't work for me.
Here is my code:
loginModel
public function login($name, $pass){
$this->db->select("username", "password");
$this->db->from("users");
$this->db->where("username", $name);
$this->db->where("password", $pass);
$query = $this->db->get();
$ret = $query->row();
if($query->num_rows() == 1){
return true;
}
else {
return false ;
}
}
loginControler;
public function checkLogin(){
$this->form_validation->set_rules("username", "Username", "required");
$this->form_validation->set_rules("password", "Password", "required");
if($this->form_validation->run() == false){
$this->load->view("login");
}
else {
redirect("SiteCont/index");
}
}
public function verifyUser(){
$name = $this->input->post("username");
$pass = $this->input->post("password");
$this->load->model("loginModel");
if($this->loginModel->login($name, $pass)){
return true;
}
else {
$this->form_validation->set_message("verifyUser", "geçersiz kullanıcı adı veya porala");
return false;
}
Only I need something ;
if($this->session->userdata('name')){
//show dashboard
}
else {
//show login
}
in the login page.
loginModel
public function login($name, $pass){
$this->db->select("username", "password");
$this->db->from("users");
$this->db->where("username", $name);
$this->db->where("password", $pass);
$query = $this->db->get();
$ret = $query->row();
if($query->num_rows() == 1){
//set the session data (you can add more values to array according to your needs)
$data = array(
'user_id' => $ret->user_id, //change your actual user id field
);
$this->session->set_userdata($data);
//set the session data
return true;
}
else {
return false ;
}
}
To check
if($this->session->userdata('user_id')){
//redirect to dashboard
}
else{
//redirect to login
}
This will work properly. Change name of variables according to your needs.

No form errors shown in JsonResponse - Symfony

I have a registration form with fields that are validated in User entity class. The validation works fine, however I can't return JsonResponse with form error messages in it.
My registration form controller method looks like this:
/**
* #Route("/register", name="register")
*/
public function registerAction(Request $request)
{
$user = new User();
$form = $this->createForm(RegistrationType::class, $user);
$form->handleRequest($request);
$errors = "";
if ($form->isSubmitted())
{
if ($form->isValid())
{
$password = $this->get('security.password_encoder')
->encodePassword($user, $user->getPlainPassword());
$user->setPassword($password);
$user->setIsActive(1);
$user->setLastname('none');
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
return new JsonResponse(
array(
'message' => 'Success! User registered!',
), 200);
}
else
{
$errors = ($this->get('validator')->validate($form));
return new JsonResponse(
array(
'message' => 'Not registered',
'errors' => $errors,
), 400);
}
}
return $this->render(
'ImmoBundle::Security/register.html.twig',
array('form' => $form->createView(), 'errors' => $errors)
);
}
I get the following json response when I submit the registration form with invalid data:
{"message":"Not registered","errors":{}}
Actually I'm expecting that "errors":{} will contain some error fields, but it doesn't. Does anyone know what the problem here is?
UPD:
My RegistrationType looks like this:
class RegistrationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('firstname', TextType::class)
->add('email', EmailType::class)
->add('plainPassword', RepeatedType::class, array(
'type' => PasswordType::class,
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Repeat password'),
'invalid_message' => "Passwords don't match!",
))
->add('register', SubmitType::class, array('label' => 'Register'));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'ImmoBundle\Entity\User',
'csrf_protection' => true,
'csrf_field_name' => '_token',
'csrf_token_id' => 'authenticate',
));
}
}
UPD2: Found the solution. I needed to do this iteration and then call for getMessage():
$allErrors = ($this->get('validator')->validate($form));
foreach ($allErrors as $error)
{
$errors[] = $error->getMessage();
}
Form validated when you call $form->handleRequest($request);
To get form errors use getErrors method
$errors = $form->getErrors(true); // $errors will be Iterator
to convert errors object to messages array you can use code from this response - Handle form errors in controller and pass it to twig
This is exapmle how i'm process errors in one of my projects
$response = $this->get('http.response_formatter');
if (!$form->isValid()) {
$errors = $form->getErrors(true);
foreach ($errors as $error) {
$response->addError($error->getMessage(), Response::HTTP_BAD_REQUEST);
}
return $response->jsonResponse(Response::HTTP_BAD_REQUEST);
}
It's worked for me.
And also this can help you - Symfony2 : How to get form validation errors after binding the request to the form
You must set error_bubbling to true in your form type by explicitly setting the option for each and every field.