I've got a C5 site wherein I need to programmatically create user accounts. What I've done is use the register method of the UserInfo class, which seems to work. Problem is none of the users created this way are able to log in, the C5 login page just returns "Invalid email address or password."
I've checked and they are showing up in the users table. I've tried copying the password hash for a user who can log in, but the programmatically created user still can't log in. I've also asked another dev I know and after looking at the code says it's practically identical to how he's done this in the past. At this point I'm a bit stumped on how to move forward with troubleshooting this.
If it makes a difference the site is set to use email addresses instead of usernames for login.
//name = guy incognito \ both passed in
//email = 1234#5678.com \ via POST
function getRandomString($length) {
$seed = chr(mt_rand(97 ,122)).substr(md5(time( )), 1);
$rand = "";
for($y = 0; $y <= $length; $y++) {
$rand .= substr($seed, rand(0, strlen($seed)), 1);
}
return $rand;
}
$pswd = getRandomString(8);
$userData['uName'] = md5($name . rand(1, 1000) . date('Y-m-d H:i:s'));
$userData['uEmail'] = $email;
$userData['uPassword'] = $pswd;
$userData['uPasswordConfirm'] = $pswd;
$ui = UserInfo::register($userData);
Here's a screen capture of the entry created in the user table:
http://i.stack.imgur.com/N1ebw.png (unfortunately I lack the reputation to post images directly)
Edit - 19/09/2014
Having worked on this a little further I've traced the problem down into the checkPassword function of the 3rd party phpass library C5 is using. The hash it's generating when it checks during login is different than the hash generated at the time of account creation.
account creation hash = $2a$12$6UZ//BGdH6sO2AhfykvyHOLfzR2ADOuQVnzcFu6P9FckbJ56Y40WW
login attempt hash = $2a$12$6UZ//BGdH6sO2AhfykvyHOoxM727vGVnxo.3VsFYwDjKUM13SJqtO
After looking at concrete/core/dashboard/users/add.php I noticed they were registering users in a slightly different manner. Here they aren't passing a password confirmation, are specifying a default language, and most noticeably not calling UserInfo::Register but instead UserInfo::Add.
After updating my code to reflect how it was being done there things work. For the record:
$uName = md5($_POST['repName'] . rand(1, 1000) . date('Y-m-d H:i:s'));
$data = array('uName' => $uName, 'uPassword' => $authCode, 'uEmail' => $_POST['repEmail'], 'uDefaultLanguage' => 'En');
$ui = UserInfo::add($data);
Related
We use LDAP (Samba) for authentication and now I want to make user able to change their password. I'm using this script:
$username = $request->request->get('username');
$oldpasswd = $request->request->get('oldpasswd');
$newpasswd = $request->request->get('newpasswd');
$userPassword = mb_convert_encoding('"'.$newpasswd.'"', 'utf-16le');
$ldapPasswd = $this->getParameter('LDAP_PASSWD');
$ldap->bind("CN=LDAPADMIN,CN=Users,DC=DOMAIN,DC=net", $ldapPasswd);
$query = $ldap->query('CN=users,DC=DOMAIN,DC=net', "(&(objectclass=person)(sAMAccountName=$username))");
$result = $query->execute()->toArray();
$entry = $result[0];
$newEntry = new Entry($entry->getDn(), [
'unicodePwd' => [$userPassword],
]);
$ldap->getEntryManager()->update($newEntry);
It is working ok but with this, all security settings are not valid: Don't repeat password, password length > 6 characters etc etc... And, the script uses an Adminstrator account to change password.Is there any other way to update the user password using user account for that and validating password security configs?
Based on your code, it seems you're using Symfony and you have an Active Directory server.
Your code is doing a "password reset", which is something an administrator would do if a user forgets their password. It requires administrative rights and does not require knowing the previous password, and thus it does not enforce previous history.
What you want to do is a "password change". The documentation for unicodePwd explains how to do this:
If the Modify request contains a delete operation containing a value Vdel for unicodePwd followed by an add operation containing a value Vadd for unicodePwd, the server considers the request to be a request to change the password. The server decodes Vadd and Vdel using the password decoding procedure documented later in this section. Vdel is the old password, while Vadd is the new password.
In LDAP, this is called a "batch request", which contains both a delete instruction and an add instruction, all in the same single request to the server. The Symfony documentation includes a section on how to do Batch Updating. In your case, it should look something like this:
$username = $request->request->get('username');
$oldpasswd = $request->request->get('oldpasswd');
$newpasswd = $request->request->get('newpasswd');
$oldUserPassword = mb_convert_encoding('"'.$oldpasswd.'"', 'utf-16le');
$userPassword = mb_convert_encoding('"'.$newpasswd.'"', 'utf-16le');
$ldapPasswd = $this->getParameter('LDAP_PASSWD');
$ldap->bind("CN=LDAPADMIN,CN=Users,DC=DOMAIN,DC=net", $ldapPasswd);
$query = $ldap->query('CN=users,DC=DOMAIN,DC=net', "(&(objectclass=person)(sAMAccountName=$username))");
$result = $query->execute()->toArray();
$entry = $result[0];
$entryManager->applyOperations($entry->getDn(), [
new UpdateOperation(LDAP_MODIFY_BATCH_REMOVE, 'unicodePwd', $oldUserPassword),
new UpdateOperation(LDAP_MODIFY_BATCH_ADD, 'unicodePwd', $userPassword),
]);
Notice that you have to encode the old password the same way you encoded the new password.
Good evening, I tell you my problem. I have an application developed in PHP with Codeigniter running on a web hosting in Wiroos. Everything was working correctly, but as time passed, the application had more users who accessed simultaneously (obviously) and the following problem began to occur.
When user A logs in from location A, a session A is generated. If at the same time user B from location B accesses the application, user A's session is automatically loaded into its location B ... as it can Is this possible?
I show you the code of my application to see if you can help me
Login Controller
public function index($estadoLogin = 0){
if($this->session->userdata('estado_sesion'))
{
redirect(base_url()."panel");
}
$data['estadoLogin'] = $estadoLogin;
$data['title'] = "Iniciar Sesión - LandingApp";
$data['bodyClass'] = "external-page sb-l-c sb-r-c";
$this->load->view('templates/header',$data);
$this->load->view('login/loginbox', $data);
}//End method index
Login Method
public function ingresar(){
$correo = $this->security->xss_clean(strip_tags($this->input->post('correo')));
$pass = md5($this->security->xss_clean(strip_tags($this->input->post('password'))));
$Usuarios = new Usuario_Model();
$result = $Usuarios->login($correo, $pass);
if(count($result)>0){
foreach($result as $u){
$this->session->unset_userdata('id');
$this->session->unset_userdata('mail');
$this->session->unset_userdata('nombre');
$this->session->unset_userdata('activo');
$this->session->unset_userdata('logo_empresa');
$this->session->unset_userdata('nombre_empresa');
$this->session->unset_userdata('id_empresa');
$this->session->unset_userdata('nivel');
$this->session->unset_userdata('estado_sesion');
$this->session->set_userdata('id', $u->id);
$this->session->set_userdata('mail', $u->mail);
$this->session->set_userdata('nombre', $u->nombre);
$this->session->set_userdata('activo', $u->activo);
$this->session->set_userdata('nivel', $u->nivel);
$this->session->set_userdata('nombre_empresa', $u->nombre_empresa);
$this->session->set_userdata('id_empresa', $u->id_empresa);
$this->session->set_userdata('logo_empresa', $u->logo_empresa);
$this->session->set_userdata('avatar_user', $u->avatar_user);
$this->session->set_userdata('estado_sesion', TRUE);
redirect(base_url()."panel");
}//End foreach
}else{
$this->session->set_flashdata('mensaje', 'El usuario o password es incorrecto');
redirect(base_url()."login/index/1");
//$this->index(1);
}//End if
Panel Controller
public function index(){
$id = $this->session->userdata('id');
$id_empresa = $this->session->userdata('id_empresa');
$data_session['title'] = "Panel General";
$data_session['opcionMenu'] = "panel";
$data_session['bodyClass'] = "dashboard-page";
$data_session = $this->session_data_lib->set_data_session($data_session); //cargo las variables de sesion
if ($data_session['nivel']==1 || $data_session['nivel']==2){
$data_counters = $this->counters_lib->get_admin_counters(); //cargo las variables de contadores
}else{
$data_counters = $this->counters_lib->get_user_counters(); //cargo las variables de contadores
}
$this->load->view('templates/header', $data_session);
$this->load->view('templates/menu_top', $data_session);
$this->load->view('templates/menu_left', $data_counters);
if ($data_session['nivel']==0) {
$this->load->view('panel/panel_user',$data_counters);
}else{
$this->load->view('panel/panel_admin',$data_counters);
}
$this->load->view('templates/footer',$data_counters);
}//End method index
Session_Data_lib > set_data_session
public function set_data_session($data_session){
$data_lib_session['title'] = $data_session['title'];
$data_lib_session['opcionMenu'] = $data_session['opcionMenu'];
$data_lib_session['bodyClass'] = $data_session['bodyClass'];
$data_lib_session['nombre'] = $this->CI->session->userdata('nombre');
$data_lib_session['userid'] = $this->CI->session->userdata('id');
$data_lib_session['nivel'] = $this->CI->session->userdata('nivel');
$data_lib_session['avatar_user'] = $this->CI->session->userdata('avatar_user');
$data_lib_session['logo_empresa'] = $this->CI->session->userdata('logo_empresa');
$data_lib_session['nombre_empresa'] = $this->CI->session->userdata('nombre_empresa');
$data_lib_session['id_empresa'] = $this->CI->session->userdata('id_empresa');
$data_lib_session['arr_css'] = array("absolute_admin/assets/fonts/iconsweets/iconsweets.css");
$data_lib_session['lastSegs'] = $this->CI->panel_model->get10LastSeg($this->CI->session->userdata('id_empresa'));
return $data_lib_session;
}//End method set_data_session
I tried to migrate Codeigniter to version 3.0, and even make the following configuration in application / config / config.php
$config['sess_driver'] = 'database';
$config['sess_cookie_name'] = 'ci_sessions';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = 'ci_sessions';
$config['sess_match_ip'] = TRUE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
I do not know what else to try, I have the feeling that it can be a server configuration, but I still had no response from the support other than this:
Our servers have a micro-cache layer managed by nginx that may have
caused this behavior, now I deactivated it for your domain. Could you
please try it again?
Obviously the problem persists. I do not understand how it can be that two different users from different locations can access the session of the other at the time that both are consulting the server. I hope you can help me, thanks!
As I said in the comments you should update your passwords to use PHP's hash_password instead of md5
I can't say this is your issue, but you should verify that you do not have duplicate data in your users table. This code
public function ingresar(){
$correo = $this->security->xss_clean(strip_tags($this->input->post('correo')));
$pass = md5($this->security->xss_clean(strip_tags($this->input->post('password'))));
Specifically
$this->input->post('correo')
CI can return FALSE if the data is not set in the $_POST so if there is a problem you're are not checking if you are using FALSE for either one or both the password and the email. You should be checking like this, for example
public function ingresar(){
if(!$this->input->post('correo'))
//throw an error - stop execution, etc.
if(!$this->input->post('password'))
//throw an error - stop execution, etc.
/* ...continue on if both inputs are valid ... */
If you do not have unique fields set in your Database, you could have dozens of duplicate users with the same password and email. Both set to false
I can't tell this without knowing what constraints you have set on your DB fields for the user table. But, if you don't have the proper constraints then it may be possible to have multiple users with a password of false and an email of false ( at least according to your login code ) which would pass into your database lookup and pull multiple results.
The only way to know for sure is to look in PhpMyAdmin, at your user table, and see if you have duplicate passwords and emails in there.
Also in line with multiple users, you are not restricting login to 1 account only. Consider this part of your code.
public function ingresar(){
/* ..... */
if(count($result)>0){ //should expect only one user returned.
foreach($result as $u){
A loop here implies we are expecting one or more return records. This should throw an error if more then 1 user is returned. Emails should be unique and we should never have 2 or more users returned when looking up a user by his email. ( again without seeing the implementation of your User Model I can only guess ). But you should be explicitly checking like this:
public function ingresar(){
/* ..... */
if(count($result)==1){
//log user in
}else if(count($result)>1){
//this should never happen but it is, so you should pay attention here
}else{
//user not found or wrong password.
}
Something that could happen with the loop you have there, is that the session data will be overwritten until the last duplicate record. So everyone with a 'bad' account gets logged in as the last record pulled by the bad email data.
All in all I would say there are a lot of "holes" in your code that could allow this to happen under the right conditions. Most of this is "Guesses" based of what I can see an the loose constraints you have in place for login. The login is the gateway to your application and should be buttoned down much tighter then this.
PS. I used google translate, so I hope I read everything correctly.
Thanks for your replies. Problem was is micro-cache layer managed by NGINX. My hosting support disabled that and all works fine!
I have problems setting password for exiting user in Ion Auth, Version: 2.5.2, Codeigniter : 3.1.0-dev
In application/config/ion_auth.php I have by default :
$config['hash_method'] = 'bcrypt'; // sha1 or bcrypt, bcrypt is STRONGLY recommended
$config['default_rounds'] = 8; // This does not apply if random_rounds is set to true
$config['random_rounds'] = FALSE;
$config['min_rounds'] = 5;
$config['max_rounds'] = 9;
$config['salt_prefix'] = '$2y$';
$config['default_group'] = 'Members'; // Default group, use name
$config['admin_group'] = 'Admin'; // Default administrators group, use name
$config['identity'] = 'email'; // A database column which is used to login with
$config['min_password_length'] = 6; // Minimum Required Length of Password
$config['max_password_length'] = 20; // Maximum Allowed Length of Password
$config['email_activation'] = FALSE; // Email Activation for registration
$config['manual_activation'] = FALSE; // Manual Activation for registration
$config['remember_users'] = TRUE; // Allow users to be remembered and enable auto-login
//$config['user_expire'] = 986500; // How long to remember the user (seconds). Set to zero for no expiration
$config['user_expire'] = 0; // How long to remember the user (seconds). Set to zero for no expiration
$config['user_extend_on_login'] = TRUE; // Extend the users cookies every time they auto-login
$config['track_login_attempts'] = FALSE; // Track the number of failed login attempts for each user or ip.
$config['track_login_ip_address'] = TRUE; // Track login attempts by IP Address, if FALSE will track based on identity. (Default: TRUE)
$config['maximum_login_attempts'] = 3; // The maximum number of failed login attempts.
$config['lockout_time'] = 600; // The number of seconds to lockout an account due to exceeded attempts
$config['forgot_password_expiration'] = 0; // The number of milliseconds after which a forgot password request will expire. If
In my control I run :
$OkResult = $this->ion_auth_model->reset_password($lUserOperator['email'], $GeneratePassword) ;
AppUtils::deb($OkResult, '$OkResult::');
where $GeneratePassword is string like 'JKC3vmci', $lUserOperator['email'] is valid email of active user, value of returned value OkResult = 1
looking into db for updated user I see password value like '$2y$08$vyeSO30G4eQL3efuYbNii.VAlayDrAslKQNMDkdLYegggcsLWsQbe' and salt field is empty string(not NULL). But I can not login to system, but I login under usual login ok. What can be the reason of problem?
Also revieing code of ion_auth I see in reset_password function triggering events like post_change_password, post_change_password...
Could you please give ref to examples of using of this events?
In my control I run :
$OkResult = $this->ion_auth_model->reset_password(...
Why are you calling the ion_auth_model directly?
This is unnecessary and likely the cause of your troubles since you're bypassing much of Ion Auth's critical logic.
As per the developer's documentation:
NOTE: Methods available in the model are called through the controller using PHP5 magic. You should never use ion_auth_model->method() in your applications.
The developer has already provided many relevant functions you can use anywhere in your project. To update any user's account including resetting their password, you would use the update() class...
$id = 12; // <- Existing user's ID
$data = array(
'password' => '123456789', // <- NEW password
);
$this->ion_auth->update($id, $data); // <- Update the user's account
update() returns true if the update was successful and false if not.
If you don't know the user's id, then you simply do a standard database query on the "users" table to retrieve their id based on email address.
Could you please give ref to examples of using of this events?
See documenation: benedmunds.com/ion_auth
I have built a lot of internal applications at my company. And my programming is on the the database/app level. Most of my applications have been using the same login/authentication class for years. However, said company wants everything going through their SSO authentication application. They have sent me their SSO application URL, the fields names they are passing, my sites actionURL, and my appKey.
All of my applications are on the same domain. I understand that I can set cookies to work on entire domain and have that set. Right now I am a bit stuck because I wrote some very simple test code. It is taking users to the SSO server and authenticating and sending the back over to my actionURL which is just my root of my domain.
So I am trying to request a URL that is behind my code, it shows that I need to be authenticated, passes me to the SSO app, and then I get passed back to my actionURL. What do I need on my actionURL to allow me to navigate through my apps.
Current code:
session_start();
if ($_POST && isset($_POST['digest']))
{
$digest = $_POST["digest"];
// set the session variables ...
$_SESSION['username'] = $_POST["firstname"]." ".$_POST["lastname"];
$_SESSION['firstname'] = $_POST["firstname"];
$_SESSION['lastname'] = $_POST["lastname"];
$_SESSION['email'] = $_POST["email"];
$_SESSION['uid'] = $_POST["uid"];
// Needed for key
$uid = $_POST["uid"];
$time = $_POST["time"];
// Read the property file with the key and URL so this won't go into the main code ...
// this sets $appKey and $safeurl
require_once("safe_login_properties.php");
$mykey = "".$uid.$time.$appKey;
$mydigest = md5($mykey);
if ($debugthis) // enable this for some debugging
{
$fp = fopen("DebugInfo.txt", "a");
fprintf($fp, "%s\n", date("H:i:s"));
foreach($_POST as $p => $v)
{
fprintf($fp, "POST: %s: %s\n", $p, $v);
}
foreach($_SESSION as $p => $v)
{
fprintf($fp, "SESSION: %s: %s\n", $p, $v);
}
fprintf($fp, "mykey: %s (uid: %s, time %s, key %s)\n", $mykey, $uid, $time, $appKey);
fprintf($fp, "posted digest: %s\n", $digest);
fprintf($fp, "mydigest: %s\n", $mydigest);
if ($digest == $mydigest)
fprintf($fp, "Digest match\n");
else
fprintf($fp, "***** digest does not match\n");
fclose($fp);
}
if ($digest != $mydigest)
{
die("Invalid login - expected digest does not match");
}
}
if (!isset($_SESSION['username']) || empty($_SESSION['username']))
{
// Read the property file with the key and URL so this won't go into the main code ...
// this sets $appKey and $safeurl
require_once("safe_login.php");
header("Location: ".$safeurl);
}
Additional info - All of my applications are mysql and php based. So I need to bring my mysql piece into it. I need something that says yes you are authorized, your username was passed over, and now we will look you up in the mysql database and use your corresponding row for rights/access. Does that make sense? Trying to write that part right now.
In your case, there has to be a mapping between the users in your MySQL db and the SSO server. A simple one would be an email address. A better one would be a GUID - globally unique ID. Whetever it is, the SSO server should pass a unique ID identifying the user when it calls your actionURL ( in SSO terms... your callback url).
Once you get the unique ID, retrieve the user from your MySQL DB using that ID. If he exists, log him in.
Normally, the SSO server will create a cookie which your applications can see. This should indicate if your user is logged in or not ( so you don't have to keep going back to the Server to authenticate a user).
HTH
I'm working on my CMS and I want it to log activities by users and other admins.
For example: when new user registers or admin makes a new news post -> update last activity.
I want to know what is the best and easiest way.
Create a table in your database to
log your user activity.
Define the various activity types
that can happen in your App.
Create a common function that logs
any activity to that table.
Call that function from anywhere
you perform log-worthy activities in
your app.
You can then write a reporting tool that gives your admins access to those logged activities, you can filter by user, time and activity types.
In my log-framework, I specially mark activities which could be seen as malicious actions and assign them different numeric threat-values. If the sum of a user's thread-value reaches a certain threshold I log-out the user.
Ideally if you write an Application, you write your infrastructure code like logging at the very beginning and then use it in all your business logic code later.
Edit for cleanup:
Over time you may collect lots of records in that table. Depending on your requirements you could do different things.
Delete any entries older than x days (maybe a year)
Delete any entries of certain types older than x days, but keep entries of other types for longer, or forever.
Move entries older than a certain threshold into an archive log table. This keeps your main table small but allows you to access older log data if you really have to. I have a checkbox Use archive on my review logs page.
Basic Answer
Instead of doing this yourself, from scratch, check out how some existing systems do it, and if their license allows, use their design and code (make sure you document what code you've used and add a copyright notice to your CMS somewhere).
Possibly Helpful Example
I'm not sure about PHP CMS's which do this, but I know Django's admin app does. Django is implemented in Python, but it should be fairly straightforward to port this code over to PHP. Even if the code isn't a straight port, the design could be ported.
The file which contains the logging is in the admin module in models.py.
Some key aspects:
The data model for the logging table:
class LogEntry(models.Model):
action_time = models.DateTimeField(_('action time'), auto_now=True)
user = models.ForeignKey(User)
content_type = models.ForeignKey(ContentType, blank=True, null=True)
object_id = models.TextField(_('object id'), blank=True, null=True)
object_repr = models.CharField(_('object repr'), max_length=200)
action_flag = models.PositiveSmallIntegerField(_('action flag'))
change_message = models.TextField(_('change message'), blank=True)
objects = LogEntryManager()
And the LogEntryManager, which saves the actual log entries:
class LogEntryManager(models.Manager):
def log_action(self, user_id, content_type_id, object_id, object_repr, action_flag, change_message=''):
e = self.model(None, None, user_id, content_type_id, smart_unicode(object_id), object_repr[:200], action_flag, change_message)
e.save()
I use two tables for activities, one that gives each activity an id, and another one that just logs the user id, activity id, and a timestamp. I do this because an int takes up less space than a string, so why log the same strings over and over? The second one isn't really necessary, you just just as easily keep the action codes in a text file for your own reference, but the db just seems like a easier place to remember.
In the past I've used a function to handle the actual logging actions, but the next time I do it I'm going to be using the Observer pattern. It appears to be a lot more flexible, and I've already had to edit out logging function calls from older code I have that wasn't going to log anything. I much prefer reusing code with no editing required.
Its very simple to do with PHP/JAVA FUNCTION JQUERY and its AJAX data posting method...
Before posting the solution -- Lets read these two lines
Why and What we want to record ?
--- As we know only to record transaction with in the database --not all the clicks and checks -- but yes its possible with this solution....
Here is the solution step by step: -
1. create a DB Table -- to record these things
a) Page Name.
b) logged in user name
c) session details (To record all the sessions).
d) POST/GET data details (To record all the post/get data for the
page)
e) Record Created Date.
or any other thing that you want to record.
2. Create a Jquery function or PHP function -- which will be auto triggered with every page.
3. This function will collect all the session of that page,user logged in details and what data passed to that page.
Apart from this - you can also record -- from which page this new page is called -- Its pretty simple and best way to implement loggs recording features even in already running old software's :)
If you want all the Code i mentioned above to use -- Search it over the NET the mechanism i have defined just you need FUNCTION CODE -- AUTO execute function code -- simple
PHP AND MYSQL
Create a Table to save the logs
CREATE TABLE `test_loq` (
id int(11) PRIMARY KEY AUTO_INCREMENT,
page varchar(255) NOT NULL,
username varchar(255) NOT NULL,
log_time datetime DEFAULT CURRENT_TIMESTAMP,
log_action longtext NOT NULL,
log_name varchar(255) NOT NULL,
user_id int(11) NOT NULL,
ip int(11) NOT NULL
)
explain :
log_action is the kind of action made here you can write a lot of information about the action that has been made.
page is the page that the action was made of, the name of the php file
log_name is the name of the action that was done
username is the name of the user that hade made this action
user_id is the id of the user that made this action
ip is the ip adress of the user
2. Create a Class
class log
{
CONST ENVIRONMENT = 'developemnt';
private $id;
protected $log_action;
protected $username;
protected $page;
protected $ip;
protected $log_name;
private $user_id;
public function __construct(string $log_action, string $username, string $log_name)
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
if(!empty($_SESSION['id'])){
$id = $_SESSION['id'];
} else {
$id = 0;
}
$this->log_action = $log_action;
$this->username = $username;
$this->log_name = $log_name;
$this->user_id = $id;
$this->page = basename($_SERVER['PHP_SELF']);
$this->ip = $ip;
}
public function createAction()
{
global $conn;
if(!$conn) {
echo mysqli_error($conn); die;
}
$sql = "INSERT INTO test_log (`log_action`,`username`,`log_name`,`page`,`user_id`,`ip`) values ('".$this->log_action."','".$this->username."','".$this->log_name."','".$this->page."','".$this->user_id."','".$this->ip."')" ;
$sql_query = mysqli_query($conn,$sql);
if(!$sql_query){
echo mysqli_error($conn); die;
}
if(ENVIRONMENT == 'development'){
$_SESSION['msg'] = 'A new log was created ' . $this->log_name;
}
} }
explain:
ENVIRONMENT can be development or production , if it's in development it will show flash messages about the log that has been made
3.Log An Action!
example: log action for login attempts
Create a php file logincheck.php
<?php
session_start();
include("include/configurationadmin.php");
//include_once('../include/classes/config.inc.php');
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$sql = mysqli_query($conn,"select * from ".$sufix."admin where username='".$username."'") ;
// HERE HOW TO LOG ACTION
$log = new log("Logging in attempt from $username" , $username ,'Login Attempt' );
$log->createAction();
//SIMPLE AND COOL RIGHT?
if(mysqli_num_rows($sql) > 0)
{
$rows = mysqli_fetch_assoc($sql);
if(md5($password) == $rows['password']) {
$_SESSION['id'] = $rows['id'];
$_SESSION['username'] = $rows['username'];
$_SESSION['usertype'] = $rows['type'];
mysqli_query($conn,"update ".$sufix."admin set lastlogin='".date('Y-m-d')."' where id = '".$rows['id']."' and username='".$rows['username']."'") ;
$domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;
setcookie('rrdssrdda', $rows['id'], time()+120, '/', $domain, false);
header("Location: http://localhost/test/admin-new/dashboard");
exit();
} else {
$_SESSION['message']="<div class='alert alert-danger' role='alert'>Invalid userid/password!</div>";
header("Location: http://localhost/test/admin-new/");
exit();
}
} else {
$_SESSION['message']="<div class='alert alert-danger' role='alert'>Invalid userid/password!</div>";
header("Location: http://localhost/test/admin-new/");
exit();
} ?>
Happy Coding!