How to edit moodle sql to time access - mysql

I'm trying to change my Moodle in 2.6 version.
I want to do something like this: When user is logged in ,He have permission to watch all materials but only when his account is active.
I want to edit sql database to add 1 field 'is_active' and set there datetime stamp.
For Example I have user John Doe , i put in database in field 'is_active' date 25.02.2014 and he can watch all lessons ans stuff till 25.02.2014 after that his account goes unactivate and when he tries to log in he will have information that his account is not active and he has to contact with administrator.
Can you tell me witch Database query change to check that permission when user is trying to log in ? I think that resolution will be to get current date from server and check it with date in database. If system date is lower that database user have access , if date is higher user doesn't have access and he gets info.
If somebody doesn't understand sorry for my english write in comments i will try to describe more.

I would create a user profile field 'is_active', choose datetime and set it to 'Not visible'
site admin -> users -> accounts -> user profile fields
http://docs.moodle.org/26/en/User_profile_fields
Then create a local plugin that uses cron to check the date and sets the user to suspended
In /local/is_active/version.php - http://docs.moodle.org/dev/version.php
defined('MOODLE_INTERNAL') || die();
$plugin->version = 201402301; // Plugin version
$plugin->requires = 2013051402; // Moodle version.
$plugin->component = 'local_is_active'; // Component name
$plugin->cron = 1; // In seconds - how often should this be run?
In /local/is_active/lang/en/local_is_active.php
$string['pluginname'] = 'Is active';
In /local/is_active/lib.php have a cron function local_xxx_cron() that updates the user table to suspended. I haven't tested the SQL but something like this
defined('MOODLE_INTERNAL') || die();
function local_is_active_cron() {
$sql = "UPDATE {user}
SET suspended = :suspended
WHERE EXISTS (SELECT userid
FROM {user_info_field} f
JOIN {user_info_data} d ON d.fieldid = f.id
AND d.data < :now
AND d.userid = mdl_user
WHERE f.shortname = :shortname)";
$params = array('suspended' => 1,
'now' => time(),
'shortname' => 'is_active');
$DB->execute($sql, $params);
}
EDIT : Forgot to add that you will need to go to notifications to install the plugin - site admin -> notifications - then Moodle will automatically call the cron function when cron is run.
You can run cron manually by going to /admin/cron.php
As a site admin you can edit the date via the users profile - go to site admin -> users -> accounts -> browse list of users -> then click the pencil next to a user profile
Or update the date using something like this - the data field needs to be a unix timestamp rather than a string type date
$activedate = strtotime('2014-02-23'); // Timestamp
$fieldid = $DB->get_field('user_info_field', 'id', array('shortname' => 'is_active'));
$params = array('fieldid' => $fieldid, 'userid' => $userid);
if ($DB->record_exists('user_info_data', $params)) {
$DB->set_field('user_info_data', 'data', $activedate, $params);
} else {
$data = new stdClass();
$data->fieldid = $fieldid;
$data->userid = $userid;
$data->data = $activedate;
$data->dataformat = 0;
$DB->insert_record('user_info_data', $data);
}

Related

Magento add a column to sales_flat_quote table and add data

I am coming from a previous enviornment where doing things like modifying queries and adding columns was just a matter of writing the sql and executing it. However, now that I'm working in Magento I want to do things "the Magento way".
Scenario: we use paypal express, and before the controller redirects to paypal, I would really like to add a field (if not there already) in sales_flat_quote, called paypal_status - and set the value = 1 (we'll call it, sent to paypal).
On return I want to update that to either 2 or 3 (returned and pending transaction, or returned and captured transaction).
So there are two things I need to know how to do:
have something like $db->addColumn('paypal_status') where it will only add if not exists, and
write UPDATE sales_flat_quote SET paypal_status = 1 WHERE entity_id =
{whatever}
This will be inside the ...Paypal_Express class.
Open database and fire this SQL: Alter table sales_flat_quote Add paypal_status tinyint(1) NOT NULL DEFAULT 1;
Alternatively, you can write following in your SQL file (located at CompanyName\MyModuleName\sql\companyname_modulename_setup) of your custom module. This file will get executed only one time , that is the first time when the module is installed. At that time your custom column will not be there in database so it will create one.
$installer = $this;
$installer->startSetup();
$installer->run("ALTER TABLE `{$installer->getTable('sales/quote')}` ADD `paypal_status` tinyint(1) NOT NULL DEFAULT 1 COMMENT 'My Custom Paypal Status';");
$installer->endSetup();
Clear all cahces.
To save data :
$myValue = 2;
Mage::getSingleton("checkout/cart")->getQuote()->setPaypalStatus($myValue)->save();
Mage::getSingleton("checkout/cart")->getQuote() will give you current quote.
In your sql file at CompanyName\MyModuleName\sql\companyname_modulename_setup copy the following code in order to create the column.
$installer = $this;
$installer->startSetup();
$installer->getConnection()
->addColumn($installer->getTable('sales/quote'),
'paypal_status',
array(
'type' => Varien_Db_Ddl_Table::TYPE_INTEGER,
'nullable' => true,
'comment' => 'Paypal Status',
)
);
$installer->endSetup();
Logout and login, and flush magento cache in order to add the column to the table.
The Express Checkout controller is in app/code/core/Mage/Paypal/Controller/Express/Abstract.php. If you want to add a field before the controller redirects to paypal you can modify the _initCheckout() method like this:
protected function _initCheckout()
$quote = $this->_getQuote();
if (!$quote->hasItems() || $quote->getHasError()) {
$this->getResponse()->setHeader('HTTP/1.1','403 Forbidden');
Mage::throwException(Mage::helper('paypal')->__('Unable to initialize Express Checkout.'));
}
$quote->setPaymentStatus(1); // Here is your change
$this->_checkout = Mage::getSingleton($this->_checkoutType, array(
'config' => $this->_config,
'quote' => $quote,
));
return $this->_checkout;
}

Using Dancer2::Plugin::DBIC to pull values from database

I have a webapp where a user can log in and see a dashboard with some data. I'm using APIary for mock data and in my Postgres Database each of my users have an ID. These ID's are also used in the APIary JSON file with relevant information.
I'm using REST::Client and JSON to connect so for example the url for the user's dashboard is: "/user/dashboard/12345" (in Apiary)
and in the database there is a user with the ID "12345".
How can I make it so when the user logs in, their ID is used to pull the data that is relevant to them? (/user/dashboard/{id})? Any documentation or advice would be much appreciated!
The docs of Dancer2::Plugin::Auth::Extensible are showing one part of what you need to do already. In short, save the user ID in the session. I took part of code in the doc and added the session.
post '/login' => sub {
my ($success, $realm) = authenticate_user(
params->{username}, params->{password}
);
if ($success) {
# we are saving your user ID to the session here
session logged_in_user => params->{username};
session logged_in_user_realm => $realm;
} else {
# authentication failed
}
};
get '/dashboard' => sub {
my $client = REST::Client->new();
# ... and now we use the user ID from the session to get the
# from the webservice
$client->GET( $apiary . '/user/dashboard/' . session('logged_in_user') );
my $data = $client->responseContent();
# do stuff with $data
};
For those who want to know what I ended up doing:
Dancer2::Plugin::Auth::Extensible has
$user = logged_in_user();
When I printed this it showed me a hash of all the values that user had in the database including the additional ID I had. So I accessed the id with
my $user_id = $user->{user_id};
And appended $user_id to the end of the url!

Change sha1 password mysql and Cakephp log in

I'm very new to CakePHP.
I've recently taken over a project that was built in CakePHP v 1.2.4.8284.
I'm trying to change the password for the login page.
There is only one user stored in a mysql database.
fields - id, username, password(varchar 40), nacl(char(6), firstname, lastname
In phpAdmin, I've tried changing the password while using the SHA1 function, but that doesn't work.
I've even tried creating a new user, but the new user information will not work either.
I've narrowed it down to the usercontroller in the following if statement:
if ($results && $results['User']['password'] == sha1($results['User']['nacl'] . sha1($this->data['User']['password'])))
It looks like the password in the database should have sha1(nacl field) + sha1(password field).
But it is all wrapped in a sha1.
I'm not sure how the encryption is working.
Any help would be appreciated.
Thanks in advance.
Here is the complete login function.
function login()
{
$this->set('error', false);
if ($this->Session->read('user'))
{
$this->redirect('/test-folder/');
} else {
$this->User->set($this->data);
if ($this->data) {
//$results = $this->User->findByUsername($this->data['User']['username']);
$results = $this->User->find('first', array(
'conditions' => array('username' => $this->data['User']['username'])
));
if ($results && $results['User']['password'] == sha1($results['User']['nacl'] . sha1($this->data['User']['password']))) {
$this->Session->write('user', $this->data['User']['username']);
$this->Session->write('admin', $results['User']['group']);
$this->redirect('/test-folder/');
} else {
$this->set('error', true);
}
}
}
}
Get the Security.salt in Config/core.php: 'securitysaltvalue'
Take a password 'yourplainpassword'
UPDATE user SET password = SHA1( CONCAT('securitysaltvalue', 'yourplainpassword')) WHERE id = 123
According to your code, you should be able to generate a new Password with these steps:
1) Generate a Password, for example "test123"
2) Get the id of the user you want to change the password for, for example 123
3) Execute this SQL in your phpMyAdmin (Replace my demo values!!!)
UPDATE user SET password = CONCAT( SHA1(nacl), SHA1("test123")) WHERE id = 123
And please make a complete DB dump on that table before any changes. And better yet, test on some development instance.
The answer from #StefanoDP works, but the table name is 'users', not 'user'. So the command should be:
UPDATE users SET password=SHA1(CONCAT('securitysaltvalue','yourplainpassword')) WHERE id=123;
Don't forget to add the semicolon at the end of the statement.

php/mysql:what's the idea to active/inactive a code from being executed

i have a php code to show online users,my question is that how to make an option(yes,no) in the admin panel to control the appearance of enabling or disabling the code
just i want to know the idea for making something like that?what are the fields required?what are the queries to do that?
or an article discuss the process of activate or in activate some code from being executed according the state of selected option(y,n)
and a practical snippet for that.......
session_start();
$session=session_id();
$time=time();
$time_check=$time-600; //SET TIME 10 Minute
$host="localhost"; // Host name
$username="advphp_advphp"; // Mysql username
$password="112233"; // Mysql password
$db_name="advphp_download"; // Database name
$tbl_name="user_online"; // Table name
// Connect to server and select databse
mysql_connect("$host", "$username", "$password")or die("cannot connect to server");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name WHERE session='$session'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count=="0"){
$sql1="INSERT INTO $tbl_name(session, time)VALUES('$session', '$time')";
$result1=mysql_query($sql1);
}
else {
"$sql2=UPDATE $tbl_name SET time='$time' WHERE session = '$session'";
$result2=mysql_query($sql2);
}
$sql3="SELECT * FROM $tbl_name";
$result3=mysql_query($sql3);
$count_user_online=mysql_num_rows($result3);
echo "المتواجدون الان : "; echo $count_user_online + 30;
// if over 10 minute, delete session
$sql4="DELETE FROM $tbl_name WHERE time<$time_check";
$result4=mysql_query($sql4);
mysql_close();
You can think of the list of online users as a module that you can configure from a back end.
Keep a XML file with the list of all the modules and their statuses (enabled/disabled) and allow the user to disable/enable the module from the back end by setting the right value for the module name in the XML file.
When you need to check the module you can either load the XML file and check the status or just keep a session variable with the statuses of the modules and decide according to that variable weather to show it or not.
For each user add an extra field called privilege which stores if user has admin, special privilege
Write a php page like admin.php
if the logged in user has admin privilege then include the admin.php page in their homepage or else do not include the admin.php
admin,php will contain the additional features for an admin user
query
select username, status from tableName
where loginName='$user' and password='$password';
then in code
if(row['status'] == 'admin')
{
include_once('admin.php');
}

Retrieve session data Codeigniter

I'm working on a messaging system and want the user's userid to be posted to the database along with the message. Right now, the message is posting to the database, but with a user ID of 0.
How can I get the user ID from the session data to post to the database along with the message? Sidenote: I'm using Tank Auth for authentication. (From the mysql side, user_id in the message table is a foreign key referencing id in the users table).
Controller
function index() {
if ($this->input->post('submit')) {
$id = $this->input->post('user_id');
$message = $this->input->post('message');
$this->load->model('message_model');
$this->message_model->addPost($id, $message);
}
}
Model
function addMessage($id, $message) {
$data = array(
'user_id' => $id,
'message' => $message
);
$this->db->insert('message', $data);
}
For tank_auth, get the user_id using the following, and then assign that to your sessions
$user_id = $this->tank_auth->get_user_id();
Taken directly from CI's documentation:
Retrieving Session Data
Any piece of information from the session array is available using the
following function:
$this->session->userdata('item');
Where item is the array index
corresponding to the item you wish to fetch. For example, to fetch the
session ID you will do this:
$session_id = $this->session->userdata('session_id');
Note: The
function returns FALSE (boolean) if the item you are trying to access
does not exist.
So, if you have a piece of session data named user_id, you would access it like this:
$user_id = $this->session->userdata('user_id');