Controller help and functions - php

I have a general create function that submits a new user to the database - this works fine. Where I am is stuck is the following.
I know that I need the user that is signing up to have clicked the link in the email before the account can login. How do I implement that into my if statement when I run the create function?
I am a bit confused as to how to set my errors if any thing is correct or wrong to do with the activation process I have currently set the messages using $this->form_validation->set_message();. Do I need to use set_flashdata();? and how will echo these into the view?
When I create a new user I have the userActive field set at 0 by default and also the default group is set to users
Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Users extends CI_Controller {
public function index()
{
$data['companyName'] = $this->core_model->companyDetails()->coreCompanyName;
$data['pageTitle'] = "Create User";
$this->load->view('frontend/assets/header', $data);
$this->load->view('frontend/users', $data);
$this->load->view('frontend/assets/footer');
}
public function create(){
//If form validation fails load previous page with errors else do the job and insert data into db
if($this->form_validation->run('createUser') == FALSE)
{
$data['success'] = "";
}else{
$username = $this->input->post('userName');
$password = $this->input->post('userPassword');
$firstname = $this->input->post('userFirstName');
$lastname = $this->input->post('userLastName');
$email = $this->input->post('userEmail');
$passwordHash = $this->encrypt->sha1($password); // Lets encrypt the password why sha1? MD5 is for tossers
$activateCode = $this->_activateCode(10);
// If the data is correct follow through with db insert
if($this->users_model->createUser($username,$passwordHash,$firstname,$lastname,$email,$activateCode))
{
$data['success'] = TRUE;
redirect('frontend/users/create','refresh');
}
}
$data['companyName'] = $this->core_model->companyDetails()->coreCompanyName;
$data['pageTitle'] = "Create User";
$this->load->view('frontend/assets/header', $data);
$this->load->view('frontend/user_create', $data);
$this->load->view('admin/assets/footer');
echo get_class($this);
var_dump(method_exists($this, '_activateCode'));
}
function _userRegEmail($activateCode,$email,$firstname,$lastname){
$data['companyName'] = $this->core_model->companyDetails()->coreCompanyName;
$data['companyEmail'] = $this->core_model->companyDetails()->coreCompanyEmail;
$data['companyContact'] = $this->core_model->companyDetails()->coreContactName;
$data['firstName'] = $firstName;
$data['lastName'] = $lastname;
$data['email'] = $email;
$data['activateCode'] = $activateCode;
$this->email->from($this->core_model->companyDetails()->coreCompanyEmail, $this->core_model->companyDetails()->coreCompanyName);
$this->email->to($email);
$this->email->subject($this->core_model->companyDetails()->coreCompanyName, 'User Registration Confirmation');
$messageContent= $this->load->view('email_templates/userReg','', TRUE);
$this->email->message($messageContent);
//$this->email->send();
}
function usersconfirm(){
$activateCode = $this->uri->segment(3);
if($activateCode == '')
{
$this->form_validation->set_message('userConfirmError', 'Sorry you did not have a correct Activation Code.');
}
$userConfirmed = $this->users_model->confirm_user($activateCode);
if($userConfirmed){
$this->form_validation->set_message('userConfirmed', 'Thanks your account is now active you may login!');
}else{
$this->form_validation->set_message('userRecord', 'I am sorry we do not have any details with that Activation Code');
}
}
function _username_check($username)
{
if($this->users_model->username_taken($username))
{
$this->form_validation->set_message('username_check', 'Sorry the username %s is taken!');
return FALSE;
}else{
return TRUE;
}
}
function _email_check($email)
{
if($this->users_model->email_check($email))
{
$this->form_validation->set_message('email_check','Sorry there is already a user with this %s');
return FALSE;
}else{
return TRUE;
}
}
function _activateCode($length)
{
return random_string('alnum', $length);
}
}
/* End of file users.php */
/* Location: ./application/controllers/users.php */

You can determine if the user has clicked the activation link by checking the database for userActive in your if statement.
You can use flash data, sure. You can retrieve flash data with:
$this->session->flashdata('item'); to echo out to the view.
See http://codeigniter.com/user_guide/libraries/sessions.html > flash data

Related

I can't store data to session when with redirect

I can't store data to session storage when I redirect to user, how can I fix this ? if add a view instead redirect, it works.. but below codes doesn't work..
public function makeLogin(){
$model = new User();
$user = $model->read()->where("username","=",post("username"))->first();
if(password_verify(post("password"),$user['password'])){
$_SESSION['auth']['user'] = $user['name'];
$_SESSION['auth']['username'] = $user['username'];
$_SESSION['auth']['user_role'] = $user['user_role'];
return redirect('redirect-core');
} else {
session("message","wrong username or password");
session("message_type","danger");
return redirect(ref_url());
}
}
session() helper
function session($name = null,$message=null){
if (is_null($name) && is_null($message)){
return new \Core\Session();
} else {
$_SESSION[$name] = $message;
}
}
redirect() helper
function redirect($url){
if (substr($url,0,4)==="http"){
header("Location:".$url,true,303);
} else {
header("Location:".APP_URL."/".$url);
}
}

How to pass data from model to controller (CodeIgniter, session help)

First sorry for my english( it is not my main language ).
I am new in CodeIgniter3 and i like it.
Lets say this is my model:
function login($uname, $upassword)
{
$this->db->where('uname', $uname);
$this->db->where('upassword', $upassword);
$query = $this->db->get('zamestnanci');
foreach ($query->result() as $row) {
$data['zamestnanec'] = $row->tpred_zamestnanci." ".$row->meno_zamestnanci. " ".$row->priezvisko_zamestnanci." ".$row->tza_zamestnanci;;
}
return ($data);
}
And this is my controller:
//Funkcia na prihlásenie používatela
function loginUser()
{
//Načítať model
$this->load->model('user_model');
$uname = $this->input->post('uname');
$upassword = $this->input->post('upassword');
$meno = $this->user_model->login($uname, $upassword);
//Ak sa meno a heslo zhoduje
if ($this->user_model->login($uname, $upassword))
{
$this->session->set_userdata('user', $meno);
$data['user'] = $this->session->userdata('user');
redirect('/otk/', $data);
}
else
{
redirect('/user/');
}
}
I want to ask you how to pass/display data from model to session. To $this->session->userdata('user').
Can you explain me the correct process off passing data from model to controller and from model to session. (like if you were trying to explain to a man who is thinking slowly).
I do not want links to documentation, just one or few persons who can explain it on example.
you can pass information from model to controller in two ways.
By using session
first fetch information using query and return that array to controller.
it is good if you return data to controller first then in controller
set up the session by using that returned array.
As in this example.
Model
function login($uname, $upassword)
{
$this->db->select("*");
$tthis->db->from("table_name")
$this->db->where('uname', $uname);
$this->db->where('upassword', $upassword);
$query = $this->db->get('zamestnanci');
// you can user result_array() to get all information in array form.
$this->result = $query->result_array();
return $this->result;
}
In Controller
//Funkcia na prihlásenie používatela
function loginUser()
{
//Načítať model
$this->load->model('user_model');
$uname = $this->input->post('uname');
$upassword = $this->input->post('upassword');
$meno = $this->user_model->login($uname, $upassword);
//Ak sa meno a heslo zhoduje
if ($this->user_model->login($uname, $upassword))
{
$this->session->set_userdata('user', $meno); // here you are setting up the session.
$data['user'] = $this->session->userdata('user');
redirect('/otk/', $data);
}
else
{
redirect('/user/');
}
}
Hope this will help you :
get all the user information (in array) from the model whatever you want :
In controller :
First way :
$uname = $this->input->post('uname');
$upassword = $this->input->post('upassword');
$lname = $this->input->post('lname');//example
$session_arr['uname'] = $uname;
$session_arr['fullname'] = $fname.' '.$lname; // example
$this->session->set_userdata($session_arr);
Second way :
$user = $this->user_model->login($uname, $upassword);
if ($user != false)
{
// Valid user
// $validate containing user details too. to check add this next line
// print_r($validate);die;
$this->session->set_userdata($user);
redirect('/otk/');
}
for more : https://codeigniter.com/user_guide/libraries/sessions.html#initializing-a-session
$user = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($user);
Just pass the model to controller whether data is correct or not. no need a big loop there in the model
In Model
function login($uname, $upassword)
{
$this->db->where('uname', $uname);
$this->db->where('upassword', $upassword);
$query = $this->db->get('zamestnanci');
$result = $query->result_array();
$count = count($result); # get how many data passed
if ($count == 1) {
return $result;
}
else
{
return false;
}
}
In Controller
function loginUser()
$this->load->model('user_model');
$uname = $this->input->post('uname');
$upassword = $this->input->post('upassword');
//$meno = $this->user_model->login($uname, $upassword);
//Ak sa meno a heslo zhoduje
$validate = $this->user_model->login($uname, $upassword);
if ($validate != false)
{
# Valid user
# $validate conating user details too. to check add this next line print_r($validate);die;
$this->session->set_userdata('user', $uname);
redirect('/otk/');
}
else
{
# Invalid User
redirect('/user/');
}
}
And in otk function just call session value user

what could make session that was set in login page but lost when redirect?

I have a problem with my script. I have been using this same script for months. Lat week I got a message from my client that cannot access their
dashboard anymore. I check it was showing too much redirect problem. I
quickly made attempt to solve this programming but all availed. I found out
that the session actually set on the Login page because I echo it out
without redirecting, but whenever I redirect to member dashboard the session
variable will be undefined. I have gone through other people similar problem
on this forum but none were able to proffer solution to my problem. Because
this same script has been working for months. Please take a look at the code
and help me out.
This is Login page. Login.php The session actually set because when display LoginId when I echo echo it out. but lost when redirecting to another page. though It was working for more four months before this unexpected problem
<?php
require("includes/config.php");
require_once(ROOT_PATH . "main/class.member.php");
$auth_member = new MEMBER();
if($auth_member->is_loggedin() != ""){
$auth_member->redirect(BASE_URL.'member');
}
if(isset($_POST['loginMemBtn'])){
$userLoginID = strip_tags($_POST['userID']);
$password = strip_tags($_POST['password']);
if($auth_member->memberLogin($userLoginID, $password)){
$auth_member->redirect(BASE_URL.'member');
}
else{
$error[] = "Inccorrect Login Details!";
}
}
?>
class.member.php
This is the class that holds all the member details and where the session
was set. It contain MemberLogin Function
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once(ROOT_PATH.'includes/dbconnect.php');
// Class
class MEMBER{
private $connect;
public function __construct(){
$database = new Database();
$db = $database->dbConnection();
$this->connect = $db;
}
public function lastInsertId(){
return $this->connect->lastInsertId();
}
public function runQuery($sql){
$stmt = $this->connect->prepare($sql);
return $stmt;
}
public function memberLogin($userLoginID, $password){
try {
$stmt = $this->connect->prepare("SELECT * FROM members
WHERE status='Active'
AND (email=:email OR phone=:phone OR username=:email)
");
$stmt->execute(array(':email'=>$userLoginID, ':phone'=>$userLoginID));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0) {
if(password_verify($password, $userRow['password'])) {
$_SESSION['member_session'] = $userRow['login_id'];
return true;
}else{
return false;
}
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
public function is_allowuser(){
if(isset($_SESSION['member_session'])) {
return true;
}
}
public function redirect($url){
header("Location: $url");
}
public function doMememberLogout(){
session_destroy();
unset($_SESSION['member_session']);
return true;
}
}
?>
session.php this file that check whether session is set or not and it
include i to all other script
<?php
$session = new MEMBER();
if(!$session->is_allowuser()){
$session->redirect(BASE_URL.'login');
exit();
}else{
$auth_member = new MEMBER();
$loginID = $_SESSION['member_session'];
$stmt = $auth_member->runQuery("SELECT * FROM members WHERE
login_id=:loginID");
$stmt->execute(array(":loginID"=>$loginID));
$userInfo = $stmt->fetch(PDO::FETCH_ASSOC);
if($userInfo['status'] != 'Active'){
unset($_SESSION['member_session']);
}
}
?>
This is dashboard.php this is the page that member redirect to from Login
Page
<?php
require("../includes/config.php");
require_once(ROOT_PATH . "main/class.member.php");
require_once(ROOT_PATH . "main/session.php");
//echo $_SESSION['member_session'];
?>
public function redirect($url){
header("Location: $url");
exit;
}
Use exit after header call in redirect method of class.member.php file

PHP Login based on "role" of user

My code uses a Login Class to authenticate. I need to have a variable based on the user's login information (role) that will direct admin users to a separate page.
Here I tried to set a $role variable inside my login class:
private function getUserRole($role)
{
if ($this->databaseConnection()) {
$query_user = $this->db_connection->prepare('SELECT role FROM users WHERE user_name = :user_name');
$query_user->bindValue(':role', $role, PDO::PARAM_STR);
$query_user->execute();
return $query_user->fetchObject();
} else {
return false;
}
}
Here on my index.php page I am trying to direct the login traffic:
require_once('classes/Login.php');
$login = new Login();
if ($login->isUserLoggedIn() == true and $login->getUserRole() == 'admin'){
include("views/logged_in.html");
} else {
include("views/not_logged_in.php");
}
I am new to using a login class and I am working with my existing code so any help or advise would be greatly appreciated.
You need to pass user_name instead of role
private function getUserRole($user_name)
{
if ($this->databaseConnection()) {
$query_user = $this->db_connection->prepare('SELECT role FROM users WHERE user_name = :user_name');
$query_user->bindValue(':user_name', $user_name, PDO::PARAM_STR);
$query_user->execute();
return $query_user->fetchObject();
} else {
return false;
}
}
index.php
require_once('classes/Login.php');
$login = new Login();
if ($login->isUserLoggedIn() == true and $login->getUserRole($user_name) == 'admin') {
include("views/logged_in.html");
} else {
include("views/not_logged_in.php");
}

Result returns 0 on password hash validation

I'm in the process of learning how to use the CI framework and am currently working on a user login form. Haven't created a user registration yet, so I'm manually adding credentials into the database. Since I'm testing everything locally, I decided to give crypt a try with no salt which is probably not the best method. I'm using form validation and a callback to check the form data against the information in the database.
here is a snippet from the users controller:
function password_check($password) {
$username = $this->input->post('username', TRUE);
$password = Modules::run('security/create_hash', $password);
$this->load->model('mdl_users');
$result = $this->mdl_users->password_check($username, $password);
if ($result == FALSE) {
//$this->form_validation->set_message('password_check', 'Please login using the correct credentials!');
//return FALSE;
echo $password;
echo '<br/><br/>';
echo $result;
echo '<br/><br/>';
}
else {
return TRUE;
}
}
I echoed the password and the result for testing and password is showing as hashed.
Here is the password_check method:
function password_check($username, $password) {
$table = $this->get_table();
$this->db->where('username', $username);
$this->db->where('password', $password);
$query=$this->db->get($table);
$num_rows = $query->num_rows();
return $num_rows;
if ($num_rows>0) {
return TRUE;
} else {
return FALSE;
}
}
I'm sure the reason this isn't working is because the password in the DB is being treated as a literal string and not as hashed, but I'm not sure as to how I can compare it as a hash.
You could do something like this: get the user from the model and then check the saved value from the password with the hashed value from the user. If you would use md5 it would look a bit like this.
controller
$this->load->model('user_model');
public function login() {
$name = $this->input->post('name');
$password = $this->input->post('password');
$user = $this->user_model->get_user_through_name($name);
if($user['password'] == md5($password)) {
//logged in
} else {
//wrong password
}
}
model
public function get_user_through_name($name) {
$query = $this->db->get_where('Users', array(
'username' => $name
));
return $query->row_array();
}

Categories