using get token in php registration - php

Ok when I get it prevents my validation(server side php) from working.
I have commented out the get token and my code works well, is there a reason for this?
code
<?php
require_once 'core/init.php';
if(Input::exists()) {
echo 'i have been run';
it works will i comment this line out //if(Token::check(Input::get('token'))) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'username' => array(
'required' => true,
'min' => 2,
'max' => 20,
'unique' => 'users'
),
'password' => array(
'required' => true,
'min' => 6
),
'password_again' => array(
'required' => true,
'matches' => 'password'
),
'name' => array(
'required' => true,
'min' => 2,
'max' => 50
)
));
if($validation->passed()) {
$user = new User();
$salt = Hash::salt(32);
try {
$user->create(array(
'username' => Input::get('username'),
'password' => Hash::make(Input::get('password'), $salt),
'salt' => $salt,
'name' => Input::get('name'),
'joined' => date('Y-m-d H:i:s'),
'group' => 1
));
Session::flash('home', 'You have been registered and now can log in!');
header('Location: index.php');
} catch(Exception $e) {
die($e->getMessage());
}
} else {
foreach($validation->errors() as $error) {
echo $error, '<br>';
}
}
}
//}
?>
Token.php
<?php
class Token {
public static function generate() {
return Session::put(Config::get('session/token_name'), md5(uniqid()));
}
public static function check($token) {
$tokenName = Config::get('session/token_name');
if(Session::exists($tokenName) && $token === Session::get($tokenName)) {
Session::delete($tokenName);
return true;
}
return false;
}
}
Hash.php
<?php
class Hash {
public static function make($string, $salt = '') {
return hash('sha256', $string . $salt);
}
public static function salt($length) {
return mcrypt_create_iv($length);
}
public static function unique() {
return self::make(uniqid());
}
}

It looks like you're using Laravel. If that's the case, there's already a CSRF filter that I think is accomplishing what you're trying to do.
See: /app/filters.php
Route::filter('csrf', function()
{
if (Session::token() != Input::get('_token') {
throw new Illuminate\Session\TokenMismatchException;
}
});
You can enforce this filter on a route like this:
Route::post('register', array('before' => 'csrf', function( ) {
return 'You gave a valid CSRF token!';
}));
See also: http://laravel.com/docs/html#csrf-protection

Related

CodeIgniter 4 redirect()->to() not working on IE

I am getting error from IE when I redirect to "dashboard" controller after settings session values in "login" function ( return redirect()->to(base_url('dashboard'));). I have this working on Chrome, Firefox, Edge, and Opera.
I am using public $sessionDriver = 'CodeIgniter\Session\Handlers\DatabaseHandler'; for session storage. this works well with other borwsers.
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use App\Models\UserModel;
class User extends BaseController
{
public function login()
{
$data = [];
if ($this->request->getMethod() == 'post') {
$rules = [
'email' => 'required|min_length[6]|max_length[50]|valid_email',
'password' => 'required|min_length[8]|max_length[255]|validateUser[email,password]',
];
$errors = [
'password' => [
'validateUser' => "Email or Password don't match",
],
];
if (!$this->validate($rules, $errors)) {
return view('login', [
"validation" => $this->validator,
]);
} else {
$model = new UserModel();
$user = $model->where('email', $this->request->getVar('email'))
->first();
// Stroing session values
$this->setUserSession($user);
// Redirecting to dashboard after login
return redirect()->to(base_url('dashboard'));
}
}
return view('login');
}
private function setUserSession($user)
{
$data = [
'id' => $user['id'],
'name' => $user['name'],
'phone_no' => $user['phone_no'],
'email' => $user['email'],
'isLoggedIn' => true,
];
session()->set($data);
return true;
}
public function register()
{
$data = [];
if ($this->request->getMethod() == 'post') {
//let's do the validation here
$rules = [
'name' => 'required|min_length[3]|max_length[20]',
'phone_no' => 'required|min_length[9]|max_length[20]',
'email' => 'required|min_length[6]|max_length[50]|valid_email|is_unique[tbl_users.email]',
'password' => 'required|min_length[8]|max_length[255]',
'password_confirm' => 'matches[password]',
];
if (!$this->validate($rules)) {
return view('register', [
"validation" => $this->validator,
]);
} else {
$model = new UserModel();
$newData = [
'name' => $this->request->getVar('name'),
'phone_no' => $this->request->getVar('phone_no'),
'email' => $this->request->getVar('email'),
'password' => $this->request->getVar('password'),
];
$model->save($newData);
$session = session();
$session->setFlashdata('success', 'Successful Registration');
return redirect()->to(base_url('login'));
}
}
return view('register');
}
public function profile()
{
$data = [];
$model = new UserModel();
$data['user'] = $model->where('id', session()->get('id'))->first();
return view('profile', $data);
}
public function logout()
{
session()->destroy();
return redirect()->to('login');
}
}
CodeIgniter4 has its "user agent class" this should help you to be able to validate if you are using IE, I share the documentation and I hope it helps you.
You can validate using that class and redirect with another method.
https://codeigniter.com/user_guide/libraries/user_agent.html

remember me checkbox in login using cookie in codeignitor

i want to save email and password on clicking remember me checkbox and cookie should get set on remember me.login is working fine. kindly help me with my code in codeignitor here is my controller code:
public function loginaction()
{
$email=$this->input->post('email');
$password=$this->input->post('password');
$where = array('email'=>$email,'password'=>$password);
$tbname='login';
$query = $this->Insert_Model->viewdata($tbname,$where);
if(empty($query))
{
$data['msg']="Invalid email or password";
$this->load->view('login',$data);
}
else
{
redirect('dashboardv1');
}
}
below is cookie code which i implemented:
function set()
{
$cookie= array(
'name' => 'chkremember',
'value' => 'test',
'expire' => '300',
'secure' => TRUE
);
$this->input->set_cookie($cookie);
}
function get()
{
echo $this->input->cookie('chkremember',true);
}
firstly you have to include cookie helper as I mention in the comment section
After that in your controller
public function loginaction()
{
$this->load->helper('cookie');
$email=$this->input->post('email');
$password=$this->input->post('password');
$where = array('email'=>$email,'password'=>$password);
$tbname='login';
$query = $this->Insert_Model->viewdata($tbname,$where);
if(empty($query))
{
$data['msg']="Invalid email or password";
$this->load->view('login',$data);
}
else
{
//first you have to delete old cookie and create new one
delete_cookie("email");
delete_cookie("password");
if ($this->input->post('remember') == 'true') {
$userName = array(
'name' => 'email',
'value' => YOUREMAIL,
'expire' => '86500',
'prefix' => '',
'secure' => FALSE
);
$this->input->set_cookie($userName);
$password = array(
'name' => 'password',
'value' => YOURPASSWORD,
'expire' => '86500',
'prefix' => '',
'secure' => FALSE
);
$this->input->set_cookie($password);
}
redirect('dashboardv1');
}
}
Get the cookie you can use below code
<?php echo get_cookie('email'); ?>
<?php echo get_cookie('password'); ?>

Why the sql query to update password in not running in a php script of a webpage?

I am creating a website which have two database table of client and freelancer. Now i have to integrate everything, like profile credentials, password, images etc.
initially the application have two different files(in two different folders) that handels. The change in passwords and other profile credentials such as name, username and email of freelancer and client.
So to integrate everything into single file, i am executing all the sql queries of freelancer table in the client one. All the profile credentials get updated successfully, but not the password. I dont understand why?
This is Client/profile.php file
$client = new Client();
$freelancer = new Freelancer();
//Check if Client is logged in
if (!$client->isLoggedIn() && !$freelancer->isLoggedIn()) {
Redirect::to('../index.php');
}
//Get Instructor's Data
$query = DB::getInstance()->get("client", "*", ["clientid" => $client->data()->clientid]);
if ($query->count()) {
foreach ($query->results() as $row) {
$nid = $row->id;
$name = $row->name;
$username = $row->username;
$email = $row->email;
$bgimage = $row->bgimage;
$phone = $row->phone;
}
}
//Edit Profile Data
if (isset($_POST['profile'])) {
if (Input::exists()) {
if (Token::check(Input::get('token'))) {
$errorHandler = new ErrorHandler;
$validator = new Validator($errorHandler);
$validation = $validator->check($_POST, [
'username' => [
'required' => true,
'maxlength' => 20,
'minlength' => 2
],
'name' => [
'required' => true,
'maxlength' => 100,
'minlength' => 2
],
'email' => [
'required' => true,
'maxlength' => 255,
'email' => true,
],
'phone' => [
'required' => false,
'maxlength' => 10,
'minlength' => 10
]
]);
if (!$validation->fails()) {
$client->update([
'name' => Input::get('name'),
'username' => Input::get('username'),
'email' => Input::get('email'),
'phone' => Input::get('phone')
], [
'clientid' => $client->data()->clientid
]);
if (count($client) > 0) {
$noError = true;
}
else {
$hasError = true;
}
$freelancer->update([
'name' => Input::get('name'),
'username' => Input::get('username'),
'email' => Input::get('email'),
'phone' => Input::get('phone')
], [
'freelancerid' => $freelancer->data()->freelancerid
]);
if (count($freelancer) > 0) {
$noError = true;
} else {
$hasError = true;
}
}
else {
$error = '';
foreach ($validation->errors()->all() as $err) {
$str = implode(" ", $err);
$error .= '
<div class="alert alert-danger fade in">
×
<strong>Error!</strong> ' . $str . '
</div>
';
}
}
}
}
}
/*Edit Password Data*/
if (isset($_POST['register'])) {
if (Input::exists()) {
if (Token::check(Input::get('token'))) {
$errorHandler = new ErrorHandler;
$validator = new Validator($errorHandler);
$validation = $validator->check($_POST, [
'password_current' => [
'required' => true,
'maxlength' => 300
],
'password_new' => [
'required' => true,
'minlength' => 6
],
'password_new_again' => [
'required' => true,
'match' => 'password_new'
]
]);
if (!$validation->fails()) { //working fine
if ( (Hash::make(Input::get('password_current'), $client->data()->salt) !== $client->data()->password) && (Hash::make(Input::get('password_current'), $freelancer->data()->salt) !== $freelancer->data()->password) ){
$hasError = true;
}
else {
$salt = Hash::salt(32);
$changed_password = Hash::make(Input::get('password_new'), $salt);
$client->update([
'password' => $changed_password,
'salt' => $salt
], [
'clientid' => $client->data()->clientid
]);
$noError = true;
}
if (!$validation->fails()) { //not working
if (Hash::make(Input::get('password_current'), $freelancer->data()->salt) !== $freelancer->data()->password) {
$hasError = true;
}
else {
$salt = Hash::salt(32);
$freelancer->update([
'password' => Hash::make(Input::get('password_new'), $salt),
'salt' => $salt
],[
'freelancerid' => $freelancer->data()->freelancerid
]);
$noError = true;
}
}
else {
$error = '';
foreach ($validation->errors()->all() as $err) {
$str = implode(" ", $err);
$error .= '
<div class="alert alert-danger fade in">
×
<strong>Error!</strong> ' . $str . '
</div>
';
}
}
}
}
}
This is Freelancer/profile.php file code to change password
if(isset($_POST['register'])){
if (Input::exists()) {
if (Token::check(Input::get('token'))) {
$errorHandler = new ErrorHandler;
$validator = new Validator($errorHandler);
$validation = $validator->check($_POST, [
'password_current' => [
'required' => true,
'maxlength' => 300
],
'password_new' => [
'required' => true,
'minlength' => 6
],
'password_new_again' => [
'required' => true,
'match' => 'password_new'
]
]);
if (!$validation->fails()) {
if (Hash::make(Input::get('password_current'), $freelancer->data()->salt) !== $freelancer->data()->password) {
$hasError = true;
}
else {
$salt = Hash::salt(32);
$freelancer->update([
'password' => Hash::make(Input::get('password_new'), $salt),
'salt' => $salt
],[
'freelancerid' => $freelancer->data()->freelancerid
]);
$noError = true;
}
}
else {
$error = '';
foreach ($validation->errors()->all() as $err) {
$str = implode(" ",$err);
$error .= '
<div class="alert alert-danger fade in">
×
<strong>Error!</strong> '.$str.'
</div>
';
}
}
}
}
}
My question is if the query to change username, email and phone number is working fine, why the password change for freelancer is not working?
The hash function algorithm can give two encrypted strings for a same inputed string so when i am calling the function two times for the client and the freelancer, two different strings and getting stored in the data base.

PHP form validation passes even though there is error

I am trying to develop a form validation system. But the problem is even though there is no data given by users as required the validation passes. Can't figure out where the problem is.
This is my form validation class
class Validation
{
private $_passed = false,
$_errors = array(),
$_db = null;
public function __construct() {
$this->_db = DB::getInstance();
}
public function check($source, $items= array()) {
foreach ($items as $item => $rules) {
foreach ($rules as $rule => $rule_value) {
$value = $source[$item];
if ($rule === 'required' && empty($value)) {
$this->addError("{$item} is required");
} else {
}
}
}
if (empty($this->_errors)) {
$this->_passed = true;
}
return $this;
}
private function addError($error) {
$this->errors[] = $error;
}
public function errors() {
return $this->_errors;
}
public function passed() {
return $this->_passed;
}
}
And this is the form page containing Html form.
require_once 'core/init.php';
if (Input::exists()) {
$validate = new Validation();
$validation = $validate->check($_POST, array(
'username' => array(
'required' => true,
'min' => 2,
'max' => 20,
'unique' => 'users'
),
'password' => array(
'required' => true,
'matches' => 'password'
),
'password_again' => array(
'required' => true,
'min' => 6
),
'name' => array(
'required' => true,
'min' => 2,
'max' => 60
),
));
if ($validation->passed()) {
//register new user
echo "passed"; //this passes even though users provides no data
} else {
print_r($validation->errors());
}
}
So, all i get is echo passed on the screen even though user provide no data at all. It should throw the errors instead. Please help. Thanks
addError writes in $this->errors, while the other methods use $this->_errors. (with underscore). The _errors array will remain empty, so _passed will be set to true in this statement:
if (empty($this->_errors)) {
$this->_passed = true;
}

Codeigniter Login session Unknown Error

Good Day Fellows .
I have a problem in my CMS login , When i Click the login button, The login page refreshes and comes again.
Session library is defined. Session encryption key is set.
Login Controller Code is :
<?php
class User extends Admin_Controller {
public function __construct(){
parent::__construct();
}
public function login(){
$dashboard = 'admin/dashboard';
$this->user_m->loggedin() == FALSE || redirect($dashboard);
$rules = $this->user_m->rules;
$this->form_validation->set_rules($rules);
if ($this->form_validation->run() == TRUE) {
// We can login and redirect
if ($this->user_m->login() == TRUE) {
redirect($dashboard);
}
else {
$this->session->set_flashdata('error', 'That email/password combination does not exist');
redirect('admin/user/login', 'refresh');
}
}
$this->data['subview'] = 'admin/user/login';
$this->load->view('admin/_layout_modal', $this->data);
}
public function logout(){
$this->user_m->logout();
redirect('admin/user/login');
}
}
Login Model code is :
<?php
class User_M extends MY_Model
{
protected $_table_name = 'users';
protected $_order_by = 'name';
public $rules = array(
'email' => array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email|xss_clean'
),
'password' => array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required'
)
);
function __construct ()
{
parent::__construct();
}
public function login ()
{
$user = $this->get_by(array(
'email' => $this->input->post('email'),
'password' => $this->hash($this->input->post('password')),
), TRUE);
if (count($user)) {
// Log in user
$data = array(
'name' => $user->name,
'email' => $user->email,
'id' => $user->id,
'loggedin' => TRUE,
);
$this->session->set_userdata($data);
}
}
public function logout ()
{
$this->session->sess_destroy();
}
public function loggedin ()
{
return (bool) $this->session->userdata('loggedin');
}
public function hash ($string)
{
return hash('sha512', $string . config_item('encryption_key'));
}
}
I suggest better to put login view in else condition ,
public function login(){
$dashboard = 'admin/dashboard';
$this->user_m->loggedin() == FALSE || redirect($dashboard);
$rules = $this->user_m->rules;
$this->form_validation->set_rules($rules);
if($this->input->post()) { //check if request if post
if ($this->form_validation->run() == TRUE) {
// We can login and redirect
if ($this->user_m->login() == TRUE) {
redirect($dashboard);
}
else {
$this->session->set_flashdata('error', 'That email/password combination does not exist');
redirect('admin/user/login', 'refresh');
}
}
} else { //defult login page
$this->data['subview'] = 'admin/user/login';
$this->load->view('admin/_layout_modal', $this->data);
} }
If you still faces the problem , please manually debug and check where it getting stuck!

Categories