diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..b5a64d0 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,13 @@ +root = true + +[*] +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +indent_style = tab +indent_size = 4 + +[*.{json,yml,xml}] +indent_style = space +indent_size = 2 diff --git a/.gitignore b/.gitignore index 4e79763..ee791be 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,2 @@ -# Created by .gitignore support plugin (hsz.mobi) -.idea/ +node_modules +_book \ No newline at end of file diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..5ac3c40 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,39 @@ +language: php + +notifications: + email: false + +php: + - '5.5' + - '5.6' + - '7.0' + +services: + - mysql + +env: + global: + - CI_HOME=`pwd` + matrix: + - CODEIGNITER_VERSION="3.1.2" + +before_install: + - mkdir ${CI_HOME}/testing_base && mv !(testing_base) ${CI_HOME}/testing_base + - composer require satooshi/php-coveralls:dev-master + - curl -o CI-${CODEIGNITER_VERSION}.zip https://codeload.github.com/bcit-ci/CodeIgniter/zip/${CODEIGNITER_VERSION} + - unzip -qq CI-${CODEIGNITER_VERSION}.zip + - rm -f CI-${CODEIGNITER_VERSION}.zip + - cd CodeIgniter-${CODEIGNITER_VERSION} + - composer require "kenjis/ci-phpunit-test:dev-master" + - php vendor/kenjis/ci-phpunit-test/install.php -s + - rm -f application/tests/controllers/Welcome_test.php + - cp -R ${CI_HOME}/testing_base/* ${CI_HOME}/CodeIgniter-${CODEIGNITER_VERSION}/application/ + - ls -R ${CI_HOME}/CodeIgniter-${CODEIGNITER_VERSION}/application/tests/models + - cd ${CI_HOME}/CodeIgniter-${CODEIGNITER_VERSION}/application/tests + +before_script: + - mysql -e 'create database aauth_test;' + +script: + - phpunit --coverage-clover ${CI_HOME}/CodeIgniter-${CODEIGNITER_VERSION}/application/build/logs/clover.xml + - cd ${CI_HOME}/CodeIgniter-${CODEIGNITER_VERSION}/application/ && travis_retry bash <(curl -s https://codecov.io/bash) diff --git a/README.md b/README.md index cc6e333..9aa104d 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,11 @@ -[![Stories in Ready](https://badge.waffle.io/emreakay/CodeIgniter-Aauth.png?label=ready&title=Ready)](https://waffle.io/emreakay/CodeIgniter-Aauth) +[![Travis-CI](https://img.shields.io/travis/REJack/CodeIgniter-Aauth/v3-dev.svg?style=flat-square)](https://travis-ci.org/REJack/CodeIgniter-Aauth) +[![Codecov](https://img.shields.io/codecov/c/github/REJack/CodeIgniter-Aauth/v3-dev.svg?style=flat-square)](https://codecov.io/gh/REJack/CodeIgniter-Aauth)

*** -Aauth is a User Authorization Library for CodeIgniter 2.x and 3.x, which aims to make easy some essential jobs such as login, permissions and access operations. Despite its ease of use, it has also very advanced features like private messages, groupping, access management, and public access. +Aauth is a User Authorization Library for CodeIgniter 3.x, which aims to make easy some essential jobs such as login, permissions and access operations. Despite its ease of use, it has also very advanced features like private messages, groupping, access management, and public access. **This is Quick Start page. You can also take a look at the [detailed Documentation Wiki](https://github.com/emreakay/CodeIgniter-Aauth/wiki/_pages) to learn about other great Features** diff --git a/application/config/aauth.php b/application/config/aauth.php deleted file mode 100644 index 1bcaf2a..0000000 --- a/application/config/aauth.php +++ /dev/null @@ -1,151 +0,0 @@ - FALSE, - - 'admin_group' => 'admin', - 'default_group' => 'default', - 'public_group' => 'public', - - 'db_profile' => 'default', - - 'users' => 'aauth_users', - 'groups' => 'aauth_groups', - 'group_to_group' => 'aauth_group_to_group', - 'user_to_group' => 'aauth_user_to_group', - 'perms' => 'aauth_perms', - 'perm_to_group' => 'aauth_perm_to_group', - 'perm_to_user' => 'aauth_perm_to_user', - 'pms' => 'aauth_pms', - 'user_variables' => 'aauth_user_variables', - 'login_attempts' => 'aauth_login_attempts', - - 'remember' => ' +3 days', - - 'max' => 13, - 'min' => 5, - - 'additional_valid_chars' => array(), - - 'ddos_protection' => true, - - 'recaptcha_active' => false, - 'recaptcha_login_attempts' => 4, - 'recaptcha_siteKey' => '', - 'recaptcha_secret' => '', - - 'totp_active' => false, - 'totp_only_on_ip_change' => false, - 'totp_reset_over_reset_password' => false, - 'totp_two_step_login_active' => false, - 'totp_two_step_login_redirect' => '/account/twofactor_verification/', - - 'max_login_attempt' => 10, - 'max_login_attempt_time_period' => "5 minutes", - 'remove_successful_attempts' => true, - - 'login_with_name' => false, - - 'email' => 'admin@admin.com', - 'name' => 'Emre Akay', - 'email_config' => false, - - 'verification' => false, - 'verification_link' => '/account/verification/', - 'reset_password_link' => '/account/reset_password/', - - 'hash' => 'sha256', - 'use_password_hash' => false, - 'password_hash_algo' => PASSWORD_DEFAULT, - 'password_hash_options' => array(), - - 'pm_encryption' => false, - 'pm_cleanup_max_age' => "3 months", -); - -$config['aauth'] = $config_aauth['default']; - -/* End of file aauth.php */ -/* Location: ./application/config/aauth.php */ \ No newline at end of file diff --git a/application/controllers/example.php b/application/controllers/example.php deleted file mode 100644 index e4a462b..0000000 --- a/application/controllers/example.php +++ /dev/null @@ -1,376 +0,0 @@ -load->library("Aauth"); - } - - public function index() { - - if ($this->aauth->login('aa@a.com', '12345')) - echo 'tmm'; - else - echo 'hyr'; - //echo date("Y-m-d H:i:s"); - - $this->aauth->print_errors(); - } - - function debug(){ - - echo "
";
-
-        print_r(
-        //$this->aauth->is_admin()
-        //$this->aauth->get_user()
-        //$this->aauth->control_group("Mod")
-        //$this->aauth->control_perm(1)
-        //$this->aauth->list_groups()
-        //$this->aauth->list_users()
-        //$this->aauth->is_allowed(1)
-        //$this->aauth->is_admin()
-        //$this->aauth->create_perm("deneme",'defff')
-        //$this->aauth->update_perm(3,'dess','asd')
-        //$this->aauth->allow(1,1)
-        //$this->aauth->add_member(1,1)
-        //$this->aauth->deny(1,1)
-        //$this->aauth->mail()
-        //$this->aauth->create_user('seass@asds.com','asdasdsdsdasd','asd')
-        //$this->aauth->verify_user(11, 'MLUguBbXpd9Eeu5B')
-        //$this->aauth->remind_password('seass@asds.com')
-        //$this->aauth->reset_password(11,'0ghUM3oIC95p7uMa')
-        //$this->aauth->is_allowed(1)
-        //$this->aauth->control(1)
-        //$this->aauth->send_pm(1,2,'asd')
-        //$this->session->flashdata('d')
-        //$this->aauth->add_member(1,1)
-        //$this->aauth->create_user('asd@asd.co','d')
-        //$this->aauth->send_pm(1,2,'asd','sad')
-        //$this->aauth->list_pms(1,0,3,1)
-        //$this->aauth->get_pm(6, false)
-        //$this->aauth->delete_pm(6)
-        //$this->aauth->set_as_read_pm(13)
-        //$this->aauth->create_group('aa')
-         $this->aauth->create_perm('asdda')
-         //''
-
-        );
-
-        echo '
---- error ---
'; - echo $this->aauth->get_errors(); - - echo '
---- info ---
'; - echo $this->aauth->get_infos(); - - echo "
"; - } - - function flash(){ - $d['a'] = 'asd'; - $d['3'] = 'asdasd'; - - $this->session->set_flashdata('d', $d); - - $d['4'] = 'tttt'; - - $this->session->set_flashdata('d', $d); - } - - - function settings() { - - //echo $this->aauth->_get_login_attempts(4); - //echo $this->aauth->get_user_id('emre@emreakay.com'); - //$this->aauth->_increase_login_attempts('emre@emreakay.com'); - //$this->aauth->_reset_login_attempts(1); - } - - public function login_fast(){ - $this->aauth->login_fast(1); - } - - public function is_loggedin() { - - if ($this->aauth->is_loggedin()) - echo 'girdin'; - - print_r( $this->aauth->get_user() ); - } - - public function logout() { - - $this->aauth->logout(); - } - - public function is_member() { - - if ($this->aauth->is_member('deneme',9)) - echo 'uye'; - } - - public function is_admin() { - - if ($this->aauth->is_member('Admin')) - echo 'adminovic'; - } - - function get_user_groups(){ - //print_r( $this->aauth->get_user_groups()); - - foreach($this->aauth->get_user_groups() as $a){ - - echo $a->id . " " . $a->name . "
"; - } - } - - public function get_group_name() { - - echo $this->aauth->get_group_name(1); - } - - public function get_group_id() { - - echo $this->aauth->get_group_id("Admin"); - } - - public function list_users() { - echo '
';
-        print_r($this->aauth->list_users());
-        echo '
'; - } - - public function list_groups() { - echo '
';
-        print_r($this->aauth->list_groups());
-        echo '
'; - } - - public function check_email() { - - if ($this->aauth->check_email("aa@a.com")) - echo 'uygun '; - else - echo 'alindi '; - - $this->aauth->print_errors(); - } - - public function get_user() { - print_r($this->aauth->get_user()); - } - - function create_user() { - - $a = $this->aauth->create_user("admin@admin.com", "12345", "Admin"); - - if ($a) - echo "tmm "; - else - echo "hyr "; - - - print_r($this->aauth->get_user($a)); - - $this->aauth->print_errors(); - } - - public function is_banned() { - print_r($this->aauth->is_banned(6)); - } - - function ban_user() { - - $a = $this->aauth->ban_user(6); - - print_r($a); - } - - function delete_user() { - - $a = $this->aauth->delete_user(7); - - print_r($a); - } - - function unban_user() { - - $a = $this->aauth->unban_user(6); - - print_r($a); - } - - function update_user() { - $a = $this->aauth->update_user(6, "a@a.com", "12345", "tested"); - - print_r($a); - } - - function update_activity() { - $a = $this->aauth->update_activity(); - - print_r($a); - } - - function update_login_attempt() { - $a = $this->aauth->update_login_attempts("a@a.com"); - - print_r($a); - } - - function create_group() { - - $a = $this->aauth->create_group("deneme"); - } - - function delete_group() { - - $a = $this->aauth->delete_group("deneme"); - } - - function update_group() { - - $a = $this->aauth->update_group("deneme", "zxxx"); - } - - function add_member() { - - $a = $this->aauth->add_member(8, "deneme"); - } - - function fire_member() { - - $a = $this->aauth->fire_member(8, "deneme"); - } - - - function create_perm() { - - $a = $this->aauth->create_perm("deneme","def"); - } - - - function update_perm() { - - $a = $this->aauth->update_perm("deneme","deneme","xxx"); - } - - function delete_perm() { - - $a = $this->aauth->update_perm("deneme","deneme","xxx"); - } - - function allow_user() { - - $a = $this->aauth->allow_user(9,"deneme"); - } - - - function deny_user() { - - $a = $this->aauth->deny_user(9,"deneme"); - } - - function allow_group() { - - $a = $this->aauth->allow_group("deneme","deneme"); - } - - function deny_group() { - - $a = $this->aauth->deny_group("deneme","deneme"); - } - - function list_perms() { - - $a = $this->aauth->list_perms(); - print_r($a); - } - - function get_perm_id() { - - $a = $this->aauth->get_perm_id("deneme"); - print_r($a); - } - - - function send_pm() { - - $a = $this->aauth->send_pm(1,8,'s',"w"); - $this->aauth->print_errors(); - } - - function list_pms(){ - - print_r( $this->aauth->list_pms() ); - } - - function get_pm(){ - - print_r( $this->aauth->get_pm(39,false)); - } - - function delete_pm(){ - - $this->aauth->delete_pm(41); - } - - - function count_unread_pms(){ - - echo $this->aauth->count_unread_pms(8); - } - - function error(){ - - $this->aauth->error("asd"); - $this->aauth->error("xasd"); - $this->aauth->keep_errors(); - $this->aauth->print_errors(); - - } - - function keep_errors(){ - - $this->aauth->print_errors(); - //$this->aauth->keep_errors(); - } - - function set_user_var(){ - $this->aauth->set_user_var("emre","akasy"); - } - - function unset_user_var(){ - $this->aauth->unset_user_var("emre"); - } - - function get_user_var(){ - echo $this->aauth->get_user_var("emre"); - } - - function set_system_var(){ - $this->aauth->set_system_var("emre","akay"); - } - - function unset_system_var(){ - $this->aauth->unset_system_var("emre"); - } - - function get_system_var(){ - echo $this->aauth->get_system_var("emre"); - } - -}//end - -/* End of file welcome.php */ diff --git a/application/helpers/googleauthenticator_helper.php b/application/helpers/googleauthenticator_helper.php deleted file mode 100644 index 7424d0b..0000000 --- a/application/helpers/googleauthenticator_helper.php +++ /dev/null @@ -1,208 +0,0 @@ -_getBase32LookupTable(); - unset($validChars[32]); - - $secret = ''; - for ($i = 0; $i < $secretLength; $i++) { - $secret .= $validChars[array_rand($validChars)]; - } - return $secret; - } - - /** - * Calculate the code, with given secret and point in time - * - * @param string $secret - * @param int|null $timeSlice - * @return string - */ - public function getCode($secret, $timeSlice = null) - { - if ($timeSlice === null) { - $timeSlice = floor(time() / 30); - } - - $secretkey = $this->_base32Decode($secret); - - // Pack time into binary string - $time = chr(0).chr(0).chr(0).chr(0).pack('N*', $timeSlice); - // Hash it with users secret key - $hm = hash_hmac('SHA1', $time, $secretkey, true); - // Use last nipple of result as index/offset - $offset = ord(substr($hm, -1)) & 0x0F; - // grab 4 bytes of the result - $hashpart = substr($hm, $offset, 4); - - // Unpak binary value - $value = unpack('N', $hashpart); - $value = $value[1]; - // Only 32 bits - $value = $value & 0x7FFFFFFF; - - $modulo = pow(10, $this->_codeLength); - return str_pad($value % $modulo, $this->_codeLength, '0', STR_PAD_LEFT); - } - - /** - * Get QR-Code URL for image, from google charts - * - * @param string $name - * @param string $secret - * @param string $title - * @return string - */ - public function getQRCodeGoogleUrl($name, $secret, $title = null) { - $urlencoded = urlencode('otpauth://totp/'.$name.'?secret='.$secret.''); - if(isset($title)) { - $urlencoded .= urlencode('&issuer='.urlencode($title)); - } - return 'https://chart.googleapis.com/chart?chs=200x200&chld=M|0&cht=qr&chl='.$urlencoded.''; - } - - /** - * Check if the code is correct. This will accept codes starting from $discrepancy*30sec ago to $discrepancy*30sec from now - * - * @param string $secret - * @param string $code - * @param int $discrepancy This is the allowed time drift in 30 second units (8 means 4 minutes before or after) - * @param int|null $currentTimeSlice time slice if we want use other that time() - * @return bool - */ - public function verifyCode($secret, $code, $discrepancy = 1, $currentTimeSlice = null) - { - if ($currentTimeSlice === null) { - $currentTimeSlice = floor(time() / 30); - } - - for ($i = -$discrepancy; $i <= $discrepancy; $i++) { - $calculatedCode = $this->getCode($secret, $currentTimeSlice + $i); - if ($calculatedCode == $code ) { - return true; - } - } - - return false; - } - - /** - * Set the code length, should be >=6 - * - * @param int $length - * @return PHPGangsta_GoogleAuthenticator - */ - public function setCodeLength($length) - { - $this->_codeLength = $length; - return $this; - } - - /** - * Helper class to decode base32 - * - * @param $secret - * @return bool|string - */ - protected function _base32Decode($secret) - { - if (empty($secret)) return ''; - - $base32chars = $this->_getBase32LookupTable(); - $base32charsFlipped = array_flip($base32chars); - - $paddingCharCount = substr_count($secret, $base32chars[32]); - $allowedValues = array(6, 4, 3, 1, 0); - if (!in_array($paddingCharCount, $allowedValues)) return false; - for ($i = 0; $i < 4; $i++){ - if ($paddingCharCount == $allowedValues[$i] && - substr($secret, -($allowedValues[$i])) != str_repeat($base32chars[32], $allowedValues[$i])) return false; - } - $secret = str_replace('=','', $secret); - $secret = str_split($secret); - $binaryString = ""; - for ($i = 0; $i < count($secret); $i = $i+8) { - $x = ""; - if (!in_array($secret[$i], $base32chars)) return false; - for ($j = 0; $j < 8; $j++) { - $x .= str_pad(base_convert(@$base32charsFlipped[@$secret[$i + $j]], 10, 2), 5, '0', STR_PAD_LEFT); - } - $eightBits = str_split($x, 8); - for ($z = 0; $z < count($eightBits); $z++) { - $binaryString .= ( ($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48 ) ? $y:""; - } - } - return $binaryString; - } - - /** - * Helper class to encode base32 - * - * @param string $secret - * @param bool $padding - * @return string - */ - protected function _base32Encode($secret, $padding = true) - { - if (empty($secret)) return ''; - - $base32chars = $this->_getBase32LookupTable(); - - $secret = str_split($secret); - $binaryString = ""; - for ($i = 0; $i < count($secret); $i++) { - $binaryString .= str_pad(base_convert(ord($secret[$i]), 10, 2), 8, '0', STR_PAD_LEFT); - } - $fiveBitBinaryArray = str_split($binaryString, 5); - $base32 = ""; - $i = 0; - while ($i < count($fiveBitBinaryArray)) { - $base32 .= $base32chars[base_convert(str_pad($fiveBitBinaryArray[$i], 5, '0'), 2, 10)]; - $i++; - } - if ($padding && ($x = strlen($binaryString) % 40) != 0) { - if ($x == 8) $base32 .= str_repeat($base32chars[32], 6); - elseif ($x == 16) $base32 .= str_repeat($base32chars[32], 4); - elseif ($x == 24) $base32 .= str_repeat($base32chars[32], 3); - elseif ($x == 32) $base32 .= $base32chars[32]; - } - return $base32; - } - - /** - * Get array with all 32 characters for decoding from/encoding to base32 - * - * @return array - */ - protected function _getBase32LookupTable() - { - return array( - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', // 7 - 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 15 - 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 23 - 'Y', 'Z', '2', '3', '4', '5', '6', '7', // 31 - '=' // padding char - ); - } -} diff --git a/application/helpers/recaptchalib_helper.php b/application/helpers/recaptchalib_helper.php deleted file mode 100644 index 35d19c7..0000000 --- a/application/helpers/recaptchalib_helper.php +++ /dev/null @@ -1,140 +0,0 @@ -" . self::$_signupUrl . ""); - } - $this->_secret=$secret; - } - - /** - * Encodes the given data into a query string format. - * - * @param array $data array of string elements to be encoded. - * - * @return string - encoded request. - */ - private function _encodeQS($data) - { - $req = ""; - foreach ($data as $key => $value) { - $req .= $key . '=' . urlencode(stripslashes($value)) . '&'; - } - - // Cut the last '&' - $req=substr($req, 0, strlen($req)-1); - return $req; - } - - /** - * Submits an HTTP GET to a reCAPTCHA server. - * - * @param string $path url path to recaptcha server. - * @param array $data array of parameters to be sent. - * - * @return array response - */ - private function _submitHTTPGet($path, $data) - { - $req = $this->_encodeQS($data); - $response = file_get_contents($path . $req); - return $response; - } - - /** - * Calls the reCAPTCHA siteverify API to verify whether the user passes - * CAPTCHA test. - * - * @param string $remoteIp IP address of end user. - * @param string $response response string from recaptcha verification. - * - * @return ReCaptchaResponse - */ - public function verifyResponse($remoteIp, $response) - { - // Discard empty solution submissions - if ($response == null || strlen($response) == 0) { - $recaptchaResponse = new ReCaptchaResponse(); - $recaptchaResponse->success = false; - $recaptchaResponse->errorCodes = 'missing-input'; - return $recaptchaResponse; - } - - $getResponse = $this->_submitHttpGet( - self::$_siteVerifyUrl, - array ( - 'secret' => $this->_secret, - 'remoteip' => $remoteIp, - 'v' => self::$_version, - 'response' => $response - ) - ); - $answers = json_decode($getResponse, true); - $recaptchaResponse = new ReCaptchaResponse(); - - if (trim($answers['success']) == true) { - $recaptchaResponse->success = true; - } else { - $recaptchaResponse->success = false; - $recaptchaResponse->errorCodes = $answers['error-codes']; - } - - return $recaptchaResponse; - } -} - -?> diff --git a/application/language/french/aauth_lang.php b/application/language/french/aauth_lang.php deleted file mode 100644 index 31e7257..0000000 --- a/application/language/french/aauth_lang.php +++ /dev/null @@ -1,56 +0,0 @@ - - * @contributor Jacob Tomlinson - * @contributor Tim Swagger (Renowne, LLC) - * @contributor Raphael Jackstadt - * - * @copyright 2014-2016 Emre Akay - * - * @version 2.5.12 - * - * @license LGPL - * @license http://opensource.org/licenses/LGPL-3.0 Lesser GNU Public License - * - * The latest version of Aauth can be obtained from: - * https://github.com/emreakay/CodeIgniter-Aauth - * - * @todo separate (on some level) the unvalidated users from the "banned" users - */ -class Aauth { - - /** - * The CodeIgniter object variable - * @access public - * @var object - */ - public $CI; - - /** - * Variable for loading the config array into - * @access public - * @var array - */ - public $config_vars; - - /** - * Array to store error messages - * @access public - * @var array - */ - public $errors = array(); - - /** - * Array to store info messages - * @access public - * @var array - */ - public $infos = array(); - - /** - * Local temporary storage for current flash errors - * - * Used to update current flash data list since flash data is only available on the next page refresh - * @access public - * var array - */ - public $flash_errors = array(); - - /** - * Local temporary storage for current flash infos - * - * Used to update current flash data list since flash data is only available on the next page refresh - * @access public - * var array - */ - public $flash_infos = array(); - - /** - * The CodeIgniter object variable - * @access public - * @var object - */ - public $aauth_db; - - ######################## - # Base Functions - ######################## - - /** - * Constructor - */ - public function __construct() { - - // get main CI object - $this->CI = & get_instance(); - - // Dependancies - if(CI_VERSION >= 2.2){ - $this->CI->load->library('driver'); - } - $this->CI->load->library('session'); - $this->CI->lang->load('aauth'); - - // config/aauth.php - $this->CI->config->load('aauth'); - $this->config_vars = $this->CI->config->item('aauth'); - - $this->aauth_db = $this->CI->load->database($this->config_vars['db_profile'], TRUE); - - // load error and info messages from flashdata (but don't store back in flashdata) - $this->errors = $this->CI->session->flashdata('errors') ?: array(); - $this->infos = $this->CI->session->flashdata('infos') ?: array(); - } - - - ######################## - # Login Functions - ######################## - - //tested - /** - * Login user - * Check provided details against the database. Add items to error array on fail, create session if success - * @param string $email - * @param string $pass - * @param bool $remember - * @return bool Indicates successful login. - */ - public function login($identifier, $pass, $remember = FALSE, $totp_code = NULL) { - - // Remove cookies first - $cookie = array( - 'name' => 'user', - 'value' => '', - 'expire' => -3600, - 'path' => '/', - ); - $this->CI->input->set_cookie($cookie); - if ($this->config_vars['ddos_protection'] && ! $this->update_login_attempts()) { - - $this->error($this->CI->lang->line('aauth_error_login_attempts_exceeded')); - return FALSE; - } - if($this->config_vars['ddos_protection'] && $this->config_vars['recaptcha_active'] && $this->get_login_attempts() > $this->config_vars['recaptcha_login_attempts']){ - $this->CI->load->helper('recaptchalib'); - $reCaptcha = new ReCaptcha( $this->config_vars['recaptcha_secret']); - $resp = $reCaptcha->verifyResponse( $this->CI->input->server("REMOTE_ADDR"), $this->CI->input->post("g-recaptcha-response") ); - - if( ! $resp->success){ - $this->error($this->CI->lang->line('aauth_error_recaptcha_not_correct')); - return FALSE; - } - } - if( $this->config_vars['login_with_name'] == TRUE){ - - if( !$identifier OR strlen($pass) < $this->config_vars['min'] OR strlen($pass) > $this->config_vars['max'] ) - { - $this->error($this->CI->lang->line('aauth_error_login_failed_name')); - return FALSE; - } - $db_identifier = 'username'; - }else{ - $this->CI->load->helper('email'); - if( !valid_email($identifier) OR strlen($pass) < $this->config_vars['min'] OR strlen($pass) > $this->config_vars['max'] ) - { - $this->error($this->CI->lang->line('aauth_error_login_failed_email')); - return FALSE; - } - $db_identifier = 'email'; - } - - // if user is not verified - $query = null; - $query = $this->aauth_db->where($db_identifier, $identifier); - $query = $this->aauth_db->where('banned', 1); - $query = $this->aauth_db->where('verification_code !=', ''); - $query = $this->aauth_db->get($this->config_vars['users']); - - if ($query->num_rows() > 0) { - $this->error($this->CI->lang->line('aauth_error_account_not_verified')); - return FALSE; - } - - // to find user id, create sessions and cookies - $query = $this->aauth_db->where($db_identifier, $identifier); - $query = $this->aauth_db->get($this->config_vars['users']); - - if($query->num_rows() == 0){ - $this->error($this->CI->lang->line('aauth_error_no_user')); - return FALSE; - } - if($this->config_vars['totp_active'] == TRUE AND $this->config_vars['totp_only_on_ip_change'] == FALSE AND $this->config_vars['totp_two_step_login_active'] == FALSE){ - if($this->config_vars['totp_two_step_login_active'] == TRUE){ - $this->CI->session->set_userdata('totp_required', true); - } - - $query = null; - $query = $this->aauth_db->where($db_identifier, $identifier); - $query = $this->aauth_db->get($this->config_vars['users']); - $totp_secret = $query->row()->totp_secret; - if ($query->num_rows() > 0 AND !$totp_code) { - $this->error($this->CI->lang->line('aauth_error_totp_code_required')); - return FALSE; - }else { - if(!empty($totp_secret)){ - $this->CI->load->helper('googleauthenticator'); - $ga = new PHPGangsta_GoogleAuthenticator(); - $checkResult = $ga->verifyCode($totp_secret, $totp_code, 0); - if (!$checkResult) { - $this->error($this->CI->lang->line('aauth_error_totp_code_invalid')); - return FALSE; - } - } - } - } - - if($this->config_vars['totp_active'] == TRUE AND $this->config_vars['totp_only_on_ip_change'] == TRUE){ - $query = null; - $query = $this->aauth_db->where($db_identifier, $identifier); - $query = $this->aauth_db->get($this->config_vars['users']); - $totp_secret = $query->row()->totp_secret; - $ip_address = $query->row()->ip_address; - $current_ip_address = $this->CI->input->ip_address(); - - if ($query->num_rows() > 0 AND !$totp_code) { - if($ip_address != $current_ip_address ){ - if($this->config_vars['totp_two_step_login_active'] == FALSE){ - $this->error($this->CI->lang->line('aauth_error_totp_code_required')); - return FALSE; - } else if($this->config_vars['totp_two_step_login_active'] == TRUE){ - $this->CI->session->set_userdata('totp_required', true); - } - } - }else { - if(!empty($totp_secret)){ - if($ip_address != $current_ip_address ){ - $this->CI->load->helper('googleauthenticator'); - $ga = new PHPGangsta_GoogleAuthenticator(); - $checkResult = $ga->verifyCode($totp_secret, $totp_code, 0); - if (!$checkResult) { - $this->error($this->CI->lang->line('aauth_error_totp_code_invalid')); - return FALSE; - } - } - } - } - } - - $query = null; - $query = $this->aauth_db->where($db_identifier, $identifier); - $query = $this->aauth_db->where('banned', 0); - - $query = $this->aauth_db->get($this->config_vars['users']); - - $row = $query->row(); - - // if email and pass matches and not banned - $password = ($this->config_vars['use_password_hash'] ? $pass : $this->hash_password($pass, $row->id)); - - if ( $query->num_rows() != 0 && $this->verify_password($password, $row->pass) ) { - - // If email and pass matches - // create session - $data = array( - 'id' => $row->id, - 'username' => $row->username, - 'email' => $row->email, - 'loggedin' => TRUE - ); - - $this->CI->session->set_userdata($data); - - if ( $remember ){ - $this->CI->load->helper('string'); - $expire = $this->config_vars['remember']; - $today = date("Y-m-d"); - $remember_date = date("Y-m-d", strtotime($today . $expire) ); - $random_string = random_string('alnum', 16); - $this->update_remember($row->id, $random_string, $remember_date ); - $cookie = array( - 'name' => 'user', - 'value' => $row->id . "-" . $random_string, - 'expire' => 99*999*999, - 'path' => '/', - ); - $this->CI->input->set_cookie($cookie); - } - - // update last login - $this->update_last_login($row->id); - $this->update_activity(); - - if($this->config_vars['remove_successful_attempts'] == TRUE){ - $this->reset_login_attempts(); - } - - return TRUE; - } - // if not matches - else { - - $this->error($this->CI->lang->line('aauth_error_login_failed_all')); - return FALSE; - } - } - - //tested - /** - * Check user login - * Checks if user logged in, also checks remember. - * @return bool - */ - public function is_loggedin() { - - if ( $this->CI->session->userdata('loggedin') ){ - return TRUE; - } else { - if( ! $this->CI->input->cookie('user', TRUE) ){ - return FALSE; - } else { - $cookie = explode('-', $this->CI->input->cookie('user', TRUE)); - if(!is_numeric( $cookie[0] ) OR strlen($cookie[1]) < 13 ){return FALSE;} - else{ - $query = $this->aauth_db->where('id', $cookie[0]); - $query = $this->aauth_db->where('remember_exp', $cookie[1]); - $query = $this->aauth_db->get($this->config_vars['users']); - - $row = $query->row(); - - if ($query->num_rows() < 1) { - $this->update_remember($cookie[0]); - return FALSE; - }else{ - - if(strtotime($row->remember_time) > strtotime("now") ){ - $this->login_fast($cookie[0]); - return TRUE; - } - // if time is expired - else { - return FALSE; - } - } - } - } - } - return FALSE; - } - - /** - * Controls if a logged or public user has permission - * - * If user does not have permission to access page, it stops script and gives - * error message, unless 'no_permission' value is set in config. If 'no_permission' is - * set in config it redirects user to the set url and passes the 'no_access' error message. - * It also updates last activity every time function called. - * - * @param bool $perm_par If not given just control user logged in or not - */ - public function control( $perm_par = FALSE ){ - - $this->CI->load->helper('url'); - - if($this->CI->session->userdata('totp_required')){ - $this->error($this->CI->lang->line('aauth_error_totp_verification_required')); - redirect($this->config_vars['totp_two_step_login_redirect']); - } - - $perm_id = $this->get_perm_id($perm_par); - $this->update_activity(); - if($perm_par == FALSE){ - if($this->is_loggedin()){ - return TRUE; - }else if(!$this->is_loggedin()){ - $this->error($this->CI->lang->line('aauth_error_no_access')); - if($this->config_vars['no_permission'] !== FALSE){ - redirect($this->config_vars['no_permission']); - } - } - - }else if ( ! $this->is_allowed($perm_id) OR ! $this->is_group_allowed($perm_id) ){ - if( $this->config_vars['no_permission'] ) { - $this->error($this->CI->lang->line('aauth_error_no_access')); - if($this->config_vars['no_permission'] !== FALSE){ - redirect($this->config_vars['no_permission']); - } - } - else { - echo $this->CI->lang->line('aauth_error_no_access'); - die(); - } - } - } - - //tested - /** - * Logout user - * Destroys the CodeIgniter session and remove cookies to log out user. - * @return bool If session destroy successful - */ - public function logout() { - - $cookie = array( - 'name' => 'user', - 'value' => '', - 'expire' => -3600, - 'path' => '/', - ); - $this->CI->input->set_cookie($cookie); - - return $this->CI->session->sess_destroy(); - } - - //tested - /** - * Fast login - * Login with just a user id - * @param int $user_id User id to log in - * @return bool TRUE if login successful. - */ - public function login_fast($user_id){ - - $query = $this->aauth_db->where('id', $user_id); - $query = $this->aauth_db->where('banned', 0); - $query = $this->aauth_db->get($this->config_vars['users']); - - $row = $query->row(); - - if ($query->num_rows() > 0) { - - // if id matches - // create session - $data = array( - 'id' => $row->id, - 'username' => $row->username, - 'email' => $row->email, - 'loggedin' => TRUE - ); - - $this->CI->session->set_userdata($data); - return TRUE; - } - return FALSE; - } - - /** - * Reset last login attempts - * Removes a Login Attempt - * @return bool Reset fails/succeeds - */ - public function reset_login_attempts() { - $ip_address = $this->CI->input->ip_address(); - $this->aauth_db->where( - array( - 'ip_address'=>$ip_address, - 'timestamp >='=>date("Y-m-d H:i:s", strtotime("-".$this->config_vars['max_login_attempt_time_period'])) - ) - ); - return $this->aauth_db->delete($this->config_vars['login_attempts']); - } - - /** - * Remind password - * Emails user with link to reset password - * @param string $email Email for account to remind - * @return bool Remind fails/succeeds - */ - public function remind_password($email){ - - $query = $this->aauth_db->where( 'email', $email ); - $query = $this->aauth_db->get( $this->config_vars['users'] ); - - if ($query->num_rows() > 0){ - $row = $query->row(); - - $ver_code = sha1(strtotime("now")); - - $data['verification_code'] = $ver_code; - - $this->aauth_db->where('email', $email); - $this->aauth_db->update($this->config_vars['users'], $data); - - $this->CI->load->library('email'); - $this->CI->load->helper('url'); - - if(isset($this->config_vars['email_config']) && is_array($this->config_vars['email_config'])){ - $this->CI->email->initialize($this->config_vars['email_config']); - } - - $this->CI->email->from( $this->config_vars['email'], $this->config_vars['name']); - $this->CI->email->to($row->email); - $this->CI->email->subject($this->CI->lang->line('aauth_email_reset_subject')); - $this->CI->email->message($this->CI->lang->line('aauth_email_reset_text') . site_url() . $this->config_vars['reset_password_link'] . $ver_code ); - $this->CI->email->send(); - - return TRUE; - } - return FALSE; - } - - /** - * Reset password - * Generate new password and email it to the user - * @param string $ver_code Verification code for account - * @return bool Password reset fails/succeeds - */ - public function reset_password($ver_code){ - - $query = $this->aauth_db->where('verification_code', $ver_code); - $query = $this->aauth_db->get( $this->config_vars['users'] ); - - $this->CI->load->helper('string'); - $pass_length = ($this->config_vars['min']&1 ? $this->config_vars['min']+1 : $this->config_vars['min']); - $pass = random_string('alnum', $pass_length); - - if( $query->num_rows() > 0 ){ - - $row = $query->row(); - $data = array( - 'verification_code' => '', - 'pass' => $this->hash_password($pass, $row->id) - ); - - if($this->config_vars['totp_active'] == TRUE AND $this->config_vars['totp_reset_over_reset_password'] == TRUE){ - $data['totp_secret'] = NULL; - } - - $email = $row->email; - - $this->aauth_db->where('id', $row->id); - $this->aauth_db->update($this->config_vars['users'] , $data); - - $this->CI->load->library('email'); - - if(isset($this->config_vars['email_config']) && is_array($this->config_vars['email_config'])){ - $this->CI->email->initialize($this->config_vars['email_config']); - } - - $this->CI->email->from( $this->config_vars['email'], $this->config_vars['name']); - $this->CI->email->to($email); - $this->CI->email->subject($this->CI->lang->line('aauth_email_reset_success_subject')); - $this->CI->email->message($this->CI->lang->line('aauth_email_reset_success_new_password') . $pass); - $this->CI->email->send(); - - return TRUE; - } - - return FALSE; - } - - //tested - /** - * Update last login - * Update user's last login date - * @param int|bool $user_id User id to update or FALSE for current user - * @return bool Update fails/succeeds - */ - public function update_last_login($user_id = FALSE) { - - if ($user_id == FALSE) - $user_id = $this->CI->session->userdata('id'); - - $data['last_login'] = date("Y-m-d H:i:s"); - $data['ip_address'] = $this->CI->input->ip_address(); - - $this->aauth_db->where('id', $user_id); - return $this->aauth_db->update($this->config_vars['users'], $data); - } - - - //tested - /** - * Update login attempt and if exceeds return FALSE - * @return bool - */ - public function update_login_attempts() { - $ip_address = $this->CI->input->ip_address(); - $query = $this->aauth_db->where( - array( - 'ip_address'=>$ip_address, - 'timestamp >='=>date("Y-m-d H:i:s", strtotime("-".$this->config_vars['max_login_attempt_time_period'])) - ) - ); - $query = $this->aauth_db->get( $this->config_vars['login_attempts'] ); - - if($query->num_rows() == 0){ - $data = array(); - $data['ip_address'] = $ip_address; - $data['timestamp']= date("Y-m-d H:i:s"); - $data['login_attempts']= 1; - $this->aauth_db->insert($this->config_vars['login_attempts'], $data); - return TRUE; - }else{ - $row = $query->row(); - $data = array(); - $data['timestamp'] = date("Y-m-d H:i:s"); - $data['login_attempts'] = $row->login_attempts + 1; - $this->aauth_db->where('id', $row->id); - $this->aauth_db->update($this->config_vars['login_attempts'], $data); - - if ( $data['login_attempts'] > $this->config_vars['max_login_attempt'] ) { - return FALSE; - } else { - return TRUE; - } - } - - } - - /** - * Get login attempt - * @return int - */ - public function get_login_attempts() { - $ip_address = $this->CI->input->ip_address(); - $query = $this->aauth_db->where( - array( - 'ip_address'=>$ip_address, - 'timestamp >='=>date("Y-m-d H:i:s", strtotime("-".$this->config_vars['max_login_attempt_time_period'])) - ) - ); - $query = $this->aauth_db->get( $this->config_vars['login_attempts'] ); - - if($query->num_rows() != 0){ - $row = $query->row(); - return $row->login_attempts; - } - - return 0; - } - - /** - * Update remember - * Update amount of time a user is remembered for - * @param int $user_id User id to update - * @param int $expression - * @param int $expire - * @return bool Update fails/succeeds - */ - public function update_remember($user_id, $expression=null, $expire=null) { - - $data['remember_time'] = $expire; - $data['remember_exp'] = $expression; - - $query = $this->aauth_db->where('id',$user_id); - return $this->aauth_db->update($this->config_vars['users'], $data); - } - - - ######################## - # User Functions - ######################## - - //tested - /** - * Create user - * Creates a new user - * @param string $email User's email address - * @param string $pass User's password - * @param string $username User's username - * @return int|bool False if create fails or returns user id if successful - */ - public function create_user($email, $pass, $username = FALSE) { - - $valid = TRUE; - - if($this->config_vars['login_with_name'] == TRUE){ - if (empty($username)){ - $this->error($this->CI->lang->line('aauth_error_username_required')); - $valid = FALSE; - } - } - if ($this->user_exist_by_username($username) && $username != FALSE) { - $this->error($this->CI->lang->line('aauth_error_username_exists')); - $valid = FALSE; - } - - if ($this->user_exist_by_email($email)) { - $this->error($this->CI->lang->line('aauth_error_email_exists')); - $valid = FALSE; - } - $valid_email = (bool) filter_var($email, FILTER_VALIDATE_EMAIL); - if (!$valid_email){ - $this->error($this->CI->lang->line('aauth_error_email_invalid')); - $valid = FALSE; - } - if ( strlen($pass) < $this->config_vars['min'] OR strlen($pass) > $this->config_vars['max'] ){ - $this->error($this->CI->lang->line('aauth_error_password_invalid')); - $valid = FALSE; - } - if ($username != FALSE && !ctype_alnum(str_replace($this->config_vars['additional_valid_chars'], '', $username))){ - $this->error($this->CI->lang->line('aauth_error_username_invalid')); - $valid = FALSE; - } - if (!$valid) { - return FALSE; - } - - $data = array( - 'email' => $email, - 'pass' => $this->hash_password($pass, 0), // Password cannot be blank but user_id required for salt, setting bad password for now - 'username' => (!$username) ? '' : $username , - 'date_created' => date("Y-m-d H:i:s"), - ); - - if ( $this->aauth_db->insert($this->config_vars['users'], $data )){ - - $user_id = $this->aauth_db->insert_id(); - - // set default group - $this->add_member($user_id, $this->config_vars['default_group']); - - // if verification activated - if($this->config_vars['verification'] && !$this->is_admin()){ - $data = null; - $data['banned'] = 1; - - $this->aauth_db->where('id', $user_id); - $this->aauth_db->update($this->config_vars['users'], $data); - - // sends verifition ( !! e-mail settings must be set) - $this->send_verification($user_id); - } - - // Update to correct salted password - if( !$this->config_vars['use_password_hash']){ - $data = null; - $data['pass'] = $this->hash_password($pass, $user_id); - $this->aauth_db->where('id', $user_id); - $this->aauth_db->update($this->config_vars['users'], $data); - } - - return $user_id; - - } else { - return FALSE; - } - } - - //tested - /** - * Update user - * Updates existing user details - * @param int $user_id User id to update - * @param string|bool $email User's email address, or FALSE if not to be updated - * @param string|bool $pass User's password, or FALSE if not to be updated - * @param string|bool $name User's name, or FALSE if not to be updated - * @return bool Update fails/succeeds - */ - public function update_user($user_id, $email = FALSE, $pass = FALSE, $username = FALSE) { - - $data = array(); - $valid = TRUE; - $user = $this->get_user($user_id); - - if ($user->email == $email) { - $email = FALSE; - } - - if ($email != FALSE) { - if ($this->user_exist_by_email($email)) { - $this->error($this->CI->lang->line('aauth_error_update_email_exists')); - $valid = FALSE; - } - $valid_email = (bool) filter_var($email, FILTER_VALIDATE_EMAIL); - if (!$valid_email){ - $this->error($this->CI->lang->line('aauth_error_email_invalid')); - $valid = FALSE; - } - $data['email'] = $email; - } - - if ($pass != FALSE) { - if ( strlen($pass) < $this->config_vars['min'] OR strlen($pass) > $this->config_vars['max'] ){ - $this->error($this->CI->lang->line('aauth_error_password_invalid')); - $valid = FALSE; - } - $data['pass'] = $this->hash_password($pass, $user_id); - } - - if ($user->username == $username) { - $username = FALSE; - } - - if ($username != FALSE) { - if ($this->user_exist_by_username($username)) { - $this->error($this->CI->lang->line('aauth_error_update_username_exists')); - $valid = FALSE; - } - if ($username !='' && !ctype_alnum(str_replace($this->config_vars['additional_valid_chars'], '', $username))){ - $this->error($this->CI->lang->line('aauth_error_username_invalid')); - $valid = FALSE; - } - $data['username'] = $username; - } - - if ( !$valid || empty($data)) { - return FALSE; - } - - $this->aauth_db->where('id', $user_id); - return $this->aauth_db->update($this->config_vars['users'], $data); - } - - //tested - /** - * List users - * Return users as an object array - * @param bool|int $group_par Specify group id to list group or FALSE for all users - * @param string $limit Limit of users to be returned - * @param bool $offset Offset for limited number of users - * @param bool $include_banneds Include banned users - * @param string $sort Order by MYSQL string (e.g. 'name ASC', 'email DESC') - * @return array Array of users - */ - public function list_users($group_par = FALSE, $limit = FALSE, $offset = FALSE, $include_banneds = FALSE, $sort = FALSE) { - - // if group_par is given - if ($group_par != FALSE) { - - $group_par = $this->get_group_id($group_par); - $this->aauth_db->select('*') - ->from($this->config_vars['users']) - ->join($this->config_vars['user_to_group'], $this->config_vars['users'] . ".id = " . $this->config_vars['user_to_group'] . ".user_id") - ->where($this->config_vars['user_to_group'] . ".group_id", $group_par); - - // if group_par is not given, lists all users - } else { - - $this->aauth_db->select('*') - ->from($this->config_vars['users']); - } - - // banneds - if (!$include_banneds) { - $this->aauth_db->where('banned != ', 1); - } - - // order_by - if ($sort) { - $this->aauth_db->order_by($sort); - } - - // limit - if ($limit) { - - if ($offset == FALSE) - $this->aauth_db->limit($limit); - else - $this->aauth_db->limit($limit, $offset); - } - - $query = $this->aauth_db->get(); - - return $query->result(); - } - - //tested - /** - * Get user - * Get user information - * @param int|bool $user_id User id to get or FALSE for current user - * @return object User information - */ - public function get_user($user_id = FALSE) { - - if ($user_id == FALSE) - $user_id = $this->CI->session->userdata('id'); - - $query = $this->aauth_db->where('id', $user_id); - $query = $this->aauth_db->get($this->config_vars['users']); - - if ($query->num_rows() <= 0){ - $this->error($this->CI->lang->line('aauth_error_no_user')); - return FALSE; - } - return $query->row(); - } - - /** - * Verify user - * Activates user account based on verification code - * @param int $user_id User id to activate - * @param string $ver_code Code to validate against - * @return bool Activation fails/succeeds - */ - public function verify_user($user_id, $ver_code){ - - $query = $this->aauth_db->where('id', $user_id); - $query = $this->aauth_db->where('verification_code', $ver_code); - $query = $this->aauth_db->get( $this->config_vars['users'] ); - - // if ver code is TRUE - if( $query->num_rows() > 0 ){ - - $data = array( - 'verification_code' => '', - 'banned' => 0 - ); - - $this->aauth_db->where('id', $user_id); - $this->aauth_db->update($this->config_vars['users'] , $data); - return TRUE; - } - return FALSE; - } - - /** - * Send verification email - * Sends a verification email based on user id - * @param int $user_id User id to send verification email to - * @todo return success indicator - */ - public function send_verification($user_id){ - - $query = $this->aauth_db->where( 'id', $user_id ); - $query = $this->aauth_db->get( $this->config_vars['users'] ); - - if ($query->num_rows() > 0){ - $row = $query->row(); - - $this->CI->load->helper('string'); - $ver_code = random_string('alnum', 16); - - $data['verification_code'] = $ver_code; - - $this->aauth_db->where('id', $user_id); - $this->aauth_db->update($this->config_vars['users'], $data); - - $this->CI->load->library('email'); - $this->CI->load->helper('url'); - - if(isset($this->config_vars['email_config']) && is_array($this->config_vars['email_config'])){ - $this->CI->email->initialize($this->config_vars['email_config']); - } - - $this->CI->email->from( $this->config_vars['email'], $this->config_vars['name']); - $this->CI->email->to($row->email); - $this->CI->email->subject($this->CI->lang->line('aauth_email_verification_subject')); - $this->CI->email->message($this->CI->lang->line('aauth_email_verification_code') . $ver_code . - $this->CI->lang->line('aauth_email_verification_text') . site_url() .$this->config_vars['verification_link'] . $user_id . '/' . $ver_code ); - $this->CI->email->send(); - } - } - - //not tested excatly - /** - * Delete user - * Delete a user from database. WARNING Can't be undone - * @param int $user_id User id to delete - * @return bool Delete fails/succeeds - */ - public function delete_user($user_id) { - - // delete from perm_to_user - $this->aauth_db->where('user_id', $user_id); - $this->aauth_db->delete($this->config_vars['perm_to_user']); - - // delete from user_to_group - $this->aauth_db->where('user_id', $user_id); - $this->aauth_db->delete($this->config_vars['user_to_group']); - - // delete user vars - $this->aauth_db->where('user_id', $user_id); - $this->aauth_db->delete($this->config_vars['user_variables']); - - // delete user - $this->aauth_db->where('id', $user_id); - return $this->aauth_db->delete($this->config_vars['users']); - - } - - //tested - /** - * Ban user - * Bans a user account - * @param int $user_id User id to ban - * @return bool Ban fails/succeeds - */ - public function ban_user($user_id) { - - $data = array( - 'banned' => 1, - 'verification_code' => '' - ); - - $this->aauth_db->where('id', $user_id); - - return $this->aauth_db->update($this->config_vars['users'], $data); - } - - //tested - /** - * Unban user - * Activates user account - * Same with unlock_user() - * @param int $user_id User id to activate - * @return bool Activation fails/succeeds - */ - public function unban_user($user_id) { - - $data = array( - 'banned' => 0 - ); - - $this->aauth_db->where('id', $user_id); - - return $this->aauth_db->update($this->config_vars['users'], $data); - } - - //tested - /** - * Check user banned - * Checks if a user is banned - * @param int $user_id User id to check - * @return bool False if banned, True if not - */ - public function is_banned($user_id) { - - $query = $this->aauth_db->where('id', $user_id); - $query = $this->aauth_db->where('banned', 1); - - $query = $this->aauth_db->get($this->config_vars['users']); - - if ($query->num_rows() > 0) - return TRUE; - else - return FALSE; - } - - /** - * user_exist_by_username - * Check if user exist by username - * @param $user_id - * - * @return bool - */ - public function user_exist_by_username( $name ) { - $query = $this->aauth_db->where('username', $name); - - $query = $this->aauth_db->get($this->config_vars['users']); - - if ($query->num_rows() > 0) - return TRUE; - else - return FALSE; - } - - /** - * user_exist_by_name !DEPRECATED! - * Check if user exist by name - * @param $user_id - * - * @return bool - */ - public function user_exist_by_name( $name ) { - return $this->user_exist_by_username($name); - } - - /** - * user_exist_by_email - * Check if user exist by user email - * @param $user_email - * - * @return bool - */ - public function user_exist_by_email( $user_email ) { - $query = $this->aauth_db->where('email', $user_email); - - $query = $this->aauth_db->get($this->config_vars['users']); - - if ($query->num_rows() > 0) - return TRUE; - else - return FALSE; - } - - /** - * user_exist_by_id - * Check if user exist by user email - * @param $user_email - * - * @return bool - */ - public function user_exist_by_id( $user_id ) { - $query = $this->aauth_db->where('id', $user_id); - - $query = $this->aauth_db->get($this->config_vars['users']); - - if ($query->num_rows() > 0) - return TRUE; - else - return FALSE; - } - - /** - * Get user id - * Get user id from email address, if par. not given, return current user's id - * @param string|bool $email Email address for user - * @return int User id - */ - public function get_user_id($email=FALSE) { - - if( ! $email){ - $query = $this->aauth_db->where('id', $this->CI->session->userdata('id')); - } else { - $query = $this->aauth_db->where('email', $email); - } - - $query = $this->aauth_db->get($this->config_vars['users']); - - if ($query->num_rows() <= 0){ - $this->error($this->CI->lang->line('aauth_error_no_user')); - return FALSE; - } - return $query->row()->id; - } - - /** - * Get user groups - * Get groups a user is in - * @param int|bool $user_id User id to get or FALSE for current user - * @return array Groups - */ - public function get_user_groups($user_id = FALSE){ - - if( !$user_id) { $user_id = $this->CI->session->userdata('id'); } - if( !$user_id){ - $this->aauth_db->where('name', $this->config_vars['public_group']); - $query = $this->aauth_db->get($this->config_vars['groups']); - }else if($user_id){ - $this->aauth_db->join($this->config_vars['groups'], "id = group_id"); - $this->aauth_db->where('user_id', $user_id); - $query = $this->aauth_db->get($this->config_vars['user_to_group']); - } - return $query->result(); - } - - //tested - /** - * Update activity - * Update user's last activity date - * @param int|bool $user_id User id to update or FALSE for current user - * @return bool Update fails/succeeds - */ - public function update_activity($user_id = FALSE) { - - if ($user_id == FALSE) - $user_id = $this->CI->session->userdata('id'); - - if($user_id==FALSE){return FALSE;} - - $data['last_activity'] = date("Y-m-d H:i:s"); - - $query = $this->aauth_db->where('id',$user_id); - return $this->aauth_db->update($this->config_vars['users'], $data); - } - - //tested - /** - * Hash password - * Hash the password for storage in the database - * (thanks to Jacob Tomlinson for contribution) - * @param string $pass Password to hash - * @param $userid - * @return string Hashed password - */ - function hash_password($pass, $userid) { - if($this->config_vars['use_password_hash']){ - return password_hash($pass, $this->config_vars['password_hash_algo'], $this->config_vars['password_hash_options']); - }else{ - $salt = md5($userid); - return hash($this->config_vars['hash'], $salt.$pass); - } - } - - /** - * Verify password - * Verfies the hashed password - * @param string $password Password - * @param string $hash Hashed Password - * @param string $user_id - * @return bool False or True - */ - function verify_password($password, $hash) { - if($this->config_vars['use_password_hash']){ - return password_verify($password, $hash); - }else{ - return ($password == $hash ? TRUE : FALSE); - } - } - - ######################## - # Group Functions - ######################## - - //tested - /** - * Create group - * Creates a new group - * @param string $group_name New group name - * @param string $definition Description of the group - * @return int|bool Group id or FALSE on fail - */ - public function create_group($group_name, $definition = '') { - - $query = $this->aauth_db->get_where($this->config_vars['groups'], array('name' => $group_name)); - - if ($query->num_rows() < 1) { - - $data = array( - 'name' => $group_name, - 'definition'=> $definition - ); - $this->aauth_db->insert($this->config_vars['groups'], $data); - return $this->aauth_db->insert_id(); - } - - $this->info($this->CI->lang->line('aauth_info_group_exists')); - return FALSE; - } - - //tested - /** - * Update group - * Change a groups name - * @param int $group_id Group id to update - * @param string $group_name New group name - * @return bool Update success/failure - */ - public function update_group($group_par, $group_name=FALSE, $definition=FALSE) { - - $group_id = $this->get_group_id($group_par); - - if ($group_name != FALSE) { - $data['name'] = $group_name; - } - - if ($definition != FALSE) { - $data['definition'] = $definition; - } - - - $this->aauth_db->where('id', $group_id); - return $this->aauth_db->update($this->config_vars['groups'], $data); - } - - //tested - /** - * Delete group - * Delete a group from database. WARNING Can't be undone - * @param int $group_id User id to delete - * @return bool Delete success/failure - */ - public function delete_group($group_par) { - - $group_id = $this->get_group_id($group_par); - - $this->aauth_db->where('id',$group_id); - $query = $this->aauth_db->get($this->config_vars['groups']); - if ($query->num_rows() == 0){ - return FALSE; - } - - // bug fixed - // now users are deleted from user_to_group table - $this->aauth_db->where('group_id', $group_id); - $this->aauth_db->delete($this->config_vars['user_to_group']); - - $this->aauth_db->where('group_id', $group_id); - $this->aauth_db->delete($this->config_vars['perm_to_group']); - - $this->aauth_db->where('group_id', $group_id); - $this->aauth_db->delete($this->config_vars['group_to_group']); - - $this->aauth_db->where('subgroup_id', $group_id); - $this->aauth_db->delete($this->config_vars['group_to_group']); - - $this->aauth_db->where('id', $group_id); - return $this->aauth_db->delete($this->config_vars['groups']); - } - - //tested - /** - * Add member - * Add a user to a group - * @param int $user_id User id to add to group - * @param int|string $group_par Group id or name to add user to - * @return bool Add success/failure - */ - public function add_member($user_id, $group_par) { - - $group_id = $this->get_group_id($group_par); - - if( ! $group_id ) { - - $this->error( $this->CI->lang->line('aauth_error_no_group') ); - return FALSE; - } - - $query = $this->aauth_db->where('user_id',$user_id); - $query = $this->aauth_db->where('group_id',$group_id); - $query = $this->aauth_db->get($this->config_vars['user_to_group']); - - if ($query->num_rows() < 1) { - $data = array( - 'user_id' => $user_id, - 'group_id' => $group_id - ); - - return $this->aauth_db->insert($this->config_vars['user_to_group'], $data); - } - $this->info($this->CI->lang->line('aauth_info_already_member')); - return TRUE; - } - - //tested - /** - * Remove member - * Remove a user from a group - * @param int $user_id User id to remove from group - * @param int|string $group_par Group id or name to remove user from - * @return bool Remove success/failure - */ - public function remove_member($user_id, $group_par) { - - $group_par = $this->get_group_id($group_par); - $this->aauth_db->where('user_id', $user_id); - $this->aauth_db->where('group_id', $group_par); - return $this->aauth_db->delete($this->config_vars['user_to_group']); - } - - /** - * Add subgroup - * Add a subgroup to a group - * @param int $user_id User id to add to group - * @param int|string $group_par Group id or name to add user to - * @return bool Add success/failure - */ - public function add_subgroup($group_par, $subgroup_par) { - - $group_id = $this->get_group_id($group_par); - $subgroup_id = $this->get_group_id($subgroup_par); - - if( ! $group_id ) { - $this->error( $this->CI->lang->line('aauth_error_no_group') ); - return FALSE; - } - - if( ! $subgroup_id ) { - $this->error( $this->CI->lang->line('aauth_error_no_subgroup') ); - return FALSE; - } - - $query = $this->aauth_db->where('group_id',$group_id); - $query = $this->aauth_db->where('subgroup_id',$subgroup_id); - $query = $this->aauth_db->get($this->config_vars['group_to_group']); - - if ($query->num_rows() < 1) { - $data = array( - 'group_id' => $group_id, - 'subgroup_id' => $subgroup_id, - ); - - return $this->aauth_db->insert($this->config_vars['group_to_group'], $data); - } - $this->info($this->CI->lang->line('aauth_info_already_subgroup')); - return TRUE; - } - - /** - * Remove subgroup - * Remove a subgroup from a group - * @param int|string $group_par Group id or name to remove - * @param int|string $subgroup_par Sub-Group id or name to remove - * @return bool Remove success/failure - */ - public function remove_subgroup($group_par, $subgroup_par) { - - $group_par = $this->get_group_id($group_par); - $subgroup_par = $this->get_group_id($subgroup_par); - $this->aauth_db->where('group_id', $group_par); - $this->aauth_db->where('subgroup_id', $subgroup_par); - return $this->aauth_db->delete($this->config_vars['group_to_group']); - } - - //tested - /** - * Remove member - * Remove a user from all groups - * @param int $user_id User id to remove from all groups - * @return bool Remove success/failure - */ - public function remove_member_from_all($user_id) { - - $this->aauth_db->where('user_id', $user_id); - return $this->aauth_db->delete($this->config_vars['user_to_group']); - } - //tested - /** - * Is member - * Check if current user is a member of a group - * @param int|string $group_par Group id or name to check - * @param int|bool $user_id User id, if not given current user - * @return bool - */ - public function is_member( $group_par, $user_id = FALSE ) { - - // if user_id FALSE (not given), current user - if( ! $user_id){ - $user_id = $this->CI->session->userdata('id'); - } - - $group_id = $this->get_group_id($group_par); - - $query = $this->aauth_db->where('user_id', $user_id); - $query = $this->aauth_db->where('group_id', $group_id); - $query = $this->aauth_db->get($this->config_vars['user_to_group']); - - $row = $query->row(); - - if ($query->num_rows() > 0) { - return TRUE; - } else { - return FALSE; - } - } - - //tested - /** - * Is admin - * Check if current user is a member of the admin group - * @param int $user_id User id to check, if it is not given checks current user - * @return bool - */ - public function is_admin( $user_id = FALSE ) { - - return $this->is_member($this->config_vars['admin_group'], $user_id); - } - - //tested - /** - * List groups - * List all groups - * @return object Array of groups - */ - public function list_groups() { - - $query = $this->aauth_db->get($this->config_vars['groups']); - return $query->result(); - } - - - //tested - /** - * Get group name - * Get group name from group id - * @param int $group_id Group id to get - * @return string Group name - */ - public function get_group_name($group_id) { - - $query = $this->aauth_db->where('id', $group_id); - $query = $this->aauth_db->get($this->config_vars['groups']); - - if ($query->num_rows() == 0) - return FALSE; - - $row = $query->row(); - return $row->name; - } - - //tested - /** - * Get group id - * Get group id from group name or id ( ! Case sensitive) - * @param int|string $group_par Group id or name to get - * @return int Group id - */ - public function get_group_id ( $group_par ) { - - if( is_numeric($group_par) ) { return $group_par; } - - $query = $this->aauth_db->where('name', $group_par); - $query = $this->aauth_db->get($this->config_vars['groups']); - - if ($query->num_rows() == 0) - return FALSE; - - $row = $query->row(); - return $row->id; - } - - /** - * Get subgroups - * Get subgroups from group name or id ( ! Case sensitive) - * @param int|string $group_par Group id or name to get - * @return object Array of subgroup_id's - */ - public function get_subgroups ( $group_par ) { - - $group_id = $this->get_group_id($group_par); - - $query = $this->aauth_db->where('group_id', $group_id); - $query = $this->aauth_db->select('subgroup_id'); - $query = $this->aauth_db->get($this->config_vars['group_to_group']); - - if ($query->num_rows() == 0) - return FALSE; - - return $query->result(); - } - - ######################## - # Permission Functions - ######################## - - //tested - /** - * Create permission - * Creates a new permission type - * @param string $perm_name New permission name - * @param string $definition Permission description - * @return int|bool Permission id or FALSE on fail - */ - public function create_perm($perm_name, $definition='') { - - $query = $this->aauth_db->get_where($this->config_vars['perms'], array('name' => $perm_name)); - - if ($query->num_rows() < 1) { - - $data = array( - 'name' => $perm_name, - 'definition'=> $definition - ); - $this->aauth_db->insert($this->config_vars['perms'], $data); - return $this->aauth_db->insert_id(); - } - $this->info($this->CI->lang->line('aauth_info_perm_exists')); - return FALSE; - } - - //tested - /** - * Update permission - * Updates permission name and description - * @param int|string $perm_par Permission id or permission name - * @param string $perm_name New permission name - * @param string $definition Permission description - * @return bool Update success/failure - */ - public function update_perm($perm_par, $perm_name=FALSE, $definition=FALSE) { - - $perm_id = $this->get_perm_id($perm_par); - - if ($perm_name != FALSE) - $data['name'] = $perm_name; - - if ($definition != FALSE) - $data['definition'] = $definition; - - $this->aauth_db->where('id', $perm_id); - return $this->aauth_db->update($this->config_vars['perms'], $data); - } - - //not ok - /** - * Delete permission - * Delete a permission from database. WARNING Can't be undone - * @param int|string $perm_par Permission id or perm name to delete - * @return bool Delete success/failure - */ - public function delete_perm($perm_par) { - - $perm_id = $this->get_perm_id($perm_par); - - // deletes from perm_to_gropup table - $this->aauth_db->where('perm_id', $perm_id); - $this->aauth_db->delete($this->config_vars['perm_to_group']); - - // deletes from perm_to_user table - $this->aauth_db->where('perm_id', $perm_id); - $this->aauth_db->delete($this->config_vars['perm_to_user']); - - // deletes from permission table - $this->aauth_db->where('id', $perm_id); - return $this->aauth_db->delete($this->config_vars['perms']); - } - - /** - * Is user allowed - * Check if user allowed to do specified action, admin always allowed - * first checks user permissions then check group permissions - * @param int $perm_par Permission id or name to check - * @param int|bool $user_id User id to check, or if FALSE checks current user - * @return bool - */ - public function is_allowed($perm_par, $user_id=FALSE){ - - $this->CI->load->helper('url'); - - if($this->CI->session->userdata('totp_required')){ - $this->error($this->CI->lang->line('aauth_error_totp_verification_required')); - redirect($this->config_vars['totp_two_step_login_redirect']); - } - - if( $user_id == FALSE){ - $user_id = $this->CI->session->userdata('id'); - } - - if($this->is_admin($user_id)) - { - return true; - } - - $perm_id = $this->get_perm_id($perm_par); - - $query = $this->aauth_db->where('perm_id', $perm_id); - $query = $this->aauth_db->where('user_id', $user_id); - $query = $this->aauth_db->get( $this->config_vars['perm_to_user'] ); - - if( $query->num_rows() > 0){ - return TRUE; - } else { - $g_allowed=FALSE; - foreach( $this->get_user_groups($user_id) as $group ){ - if ( $this->is_group_allowed($perm_id, $group->id) ){ - $g_allowed=TRUE; - break; - } - } - return $g_allowed; - } - } - - /** - * Is Group allowed - * Check if group is allowed to do specified action, admin always allowed - * @param int $perm_par Permission id or name to check - * @param int|string|bool $group_par Group id or name to check, or if FALSE checks all user groups - * @return bool - */ - public function is_group_allowed($perm_par, $group_par=FALSE){ - - $perm_id = $this->get_perm_id($perm_par); - - // if group par is given - if($group_par != FALSE){ - - $subgroup_ids = $this->get_subgroups($group_par); - $group_par = $this->get_group_id($group_par); - $query = $this->aauth_db->where('perm_id', $perm_id); - $query = $this->aauth_db->where('group_id', $group_par); - $query = $this->aauth_db->get( $this->config_vars['perm_to_group'] ); - - $g_allowed=FALSE; - if(is_array($subgroup_ids)){ - foreach ($subgroup_ids as $g ){ - if($this->is_group_allowed($perm_id, $g->subgroup_id)){ - $g_allowed=TRUE; - } - } - } - - if( $query->num_rows() > 0){ - $g_allowed=TRUE; - } - return $g_allowed; - } - // if group par is not given - // checks current user's all groups - else { - // if public is allowed or he is admin - if ( $this->is_admin( $this->CI->session->userdata('id')) OR - $this->is_group_allowed($perm_id, $this->config_vars['public_group']) ) - {return TRUE;} - - // if is not login - if (!$this->is_loggedin()){return FALSE;} - - $group_pars = $this->get_user_groups(); - foreach ($group_pars as $g ){ - if($this->is_group_allowed($perm_id, $g->id)){ - return TRUE; - } - } - return FALSE; - } - } - - //tested - /** - * Allow User - * Add User to permission - * @param int $user_id User id to deny - * @param int $perm_par Permission id or name to allow - * @return bool Allow success/failure - */ - public function allow_user($user_id, $perm_par) { - - $perm_id = $this->get_perm_id($perm_par); - - if( ! $perm_id) { - return FALSE; - } - - $query = $this->aauth_db->where('user_id',$user_id); - $query = $this->aauth_db->where('perm_id',$perm_id); - $query = $this->aauth_db->get($this->config_vars['perm_to_user']); - - // if not inserted before - if ($query->num_rows() < 1) { - - $data = array( - 'user_id' => $user_id, - 'perm_id' => $perm_id - ); - - return $this->aauth_db->insert($this->config_vars['perm_to_user'], $data); - } - return TRUE; - } - - //tested - /** - * Deny User - * Remove user from permission - * @param int $user_id User id to deny - * @param int $perm_par Permission id or name to deny - * @return bool Deny success/failure - */ - public function deny_user($user_id, $perm_par) { - - $perm_id = $this->get_perm_id($perm_par); - - $this->aauth_db->where('user_id', $user_id); - $this->aauth_db->where('perm_id', $perm_id); - - return $this->aauth_db->delete($this->config_vars['perm_to_user']); - } - - //tested - /** - * Allow Group - * Add group to permission - * @param int|string|bool $group_par Group id or name to allow - * @param int $perm_par Permission id or name to allow - * @return bool Allow success/failure - */ - public function allow_group($group_par, $perm_par) { - - $perm_id = $this->get_perm_id($perm_par); - - if( ! $perm_id) { - return FALSE; - } - - $group_id = $this->get_group_id($group_par); - - if( ! $group_id) { - return FALSE; - } - - $query = $this->aauth_db->where('group_id',$group_id); - $query = $this->aauth_db->where('perm_id',$perm_id); - $query = $this->aauth_db->get($this->config_vars['perm_to_group']); - - if ($query->num_rows() < 1) { - - $data = array( - 'group_id' => $group_id, - 'perm_id' => $perm_id - ); - - return $this->aauth_db->insert($this->config_vars['perm_to_group'], $data); - } - - return TRUE; - } - - //tested - /** - * Deny Group - * Remove group from permission - * @param int|string|bool $group_par Group id or name to deny - * @param int $perm_par Permission id or name to deny - * @return bool Deny success/failure - */ - public function deny_group($group_par, $perm_par) { - - $perm_id = $this->get_perm_id($perm_par); - $group_id = $this->get_group_id($group_par); - - $this->aauth_db->where('group_id', $group_id); - $this->aauth_db->where('perm_id', $perm_id); - - return $this->aauth_db->delete($this->config_vars['perm_to_group']); - } - - //tested - /** - * List Permissions - * List all permissions - * @return object Array of permissions - */ - public function list_perms() { - - $query = $this->aauth_db->get($this->config_vars['perms']); - return $query->result(); - } - - //tested - /** - * Get permission id - * Get permission id from permisison name or id - * @param int|string $perm_par Permission id or name to get - * @return int Permission id or NULL if perm does not exist - */ - public function get_perm_id($perm_par) { - - if( is_numeric($perm_par) ) { return $perm_par; } - - $query = $this->aauth_db->where('name', $perm_par); - $query = $this->aauth_db->get($this->config_vars['perms']); - - if ($query->num_rows() == 0) - return FALSE; - - $row = $query->row(); - return $row->id; - } - - ######################## - # Private Message Functions - ######################## - - //tested - /** - * Send Private Message - * Send a private message to another user - * @param int $sender_id User id of private message sender - * @param int $receiver_id User id of private message receiver - * @param string $title Message title/subject - * @param string $message Message body/content - * @return bool Send successful/failed - */ - public function send_pm( $sender_id, $receiver_id, $title, $message ){ - - if ( !is_numeric($receiver_id) OR $sender_id == $receiver_id ){ - $this->error($this->CI->lang->line('aauth_error_self_pm')); - return FALSE; - } - if (($this->is_banned($receiver_id) || !$this->user_exist_by_id($receiver_id)) || ($sender_id && ($this->is_banned($sender_id) || !$this->user_exist_by_id($sender_id)))){ - $this->error($this->CI->lang->line('aauth_error_no_user')); - return FALSE; - } - if ( !$sender_id){ - $sender_id = 0; - } - - if ($this->config_vars['pm_encryption']){ - $this->CI->load->library('encrypt'); - $title = $this->CI->encrypt->encode($title); - $message = $this->CI->encrypt->encode($message); - } - - $data = array( - 'sender_id' => $sender_id, - 'receiver_id' => $receiver_id, - 'title' => $title, - 'message' => $message, - 'date_sent' => date('Y-m-d H:i:s') - ); - - return $this->aauth_db->insert( $this->config_vars['pms'], $data ); - } - - /** - * Send multiple Private Messages - * Send multiple private messages to another users - * @param int $sender_id User id of private message sender - * @param array $receiver_ids Array of User ids of private message receiver - * @param string $title Message title/subject - * @param string $message Message body/content - * @return array/bool Array with User ID's as key and TRUE or a specific error message OR FALSE if sender doesn't exist - */ - public function send_pms( $sender_id, $receiver_ids, $title, $message ){ - if ($this->config_vars['pm_encryption']){ - $this->CI->load->library('encrypt'); - $title = $this->CI->encrypt->encode($title); - $message = $this->CI->encrypt->encode($message); - } - if ($sender_id && ($this->is_banned($sender_id) || !$this->user_exist_by_id($sender_id))){ - $this->error($this->CI->lang->line('aauth_error_no_user')); - return FALSE; - } - if ( !$sender_id){ - $sender_id = 0; - } - if (is_numeric($receiver_ids)) { - $receiver_ids = array($receiver_ids); - } - - $return_array = array(); - foreach ($receiver_ids as $receiver_id) { - if ($sender_id == $receiver_id ){ - $return_array[$receiver_id] = $this->CI->lang->line('aauth_error_self_pm'); - continue; - } - if ($this->is_banned($receiver_id) || !$this->user_exist_by_id($receiver_id)){ - $return_array[$receiver_id] = $this->CI->lang->line('aauth_error_no_user'); - continue; - } - - $data = array( - 'sender_id' => $sender_id, - 'receiver_id' => $receiver_id, - 'title' => $title, - 'message' => $message, - 'date_sent' => date('Y-m-d H:i:s') - ); - $return_array[$receiver_id] = $this->aauth_db->insert( $this->config_vars['pms'], $data ); - } - - return $return_array; - } - - //tested - /** - * List Private Messages - * If receiver id not given retruns current user's pms, if sender_id given, it returns only pms from given sender - * @param int $limit Number of private messages to be returned - * @param int $offset Offset for private messages to be returned (for pagination) - * @param int $sender_id User id of private message sender - * @param int $receiver_id User id of private message receiver - * @return object Array of private messages - */ - public function list_pms($limit=5, $offset=0, $receiver_id=NULL, $sender_id=NULL){ - if (is_numeric($receiver_id)){ - $query = $this->aauth_db->where('receiver_id', $receiver_id); - $query = $this->aauth_db->where('pm_deleted_receiver', NULL); - } - if (is_numeric($sender_id)){ - $query = $this->aauth_db->where('sender_id', $sender_id); - $query = $this->aauth_db->where('pm_deleted_sender', NULL); - } - - $query = $this->aauth_db->order_by('id','DESC'); - $query = $this->aauth_db->get( $this->config_vars['pms'], $limit, $offset); - - $result = $query->result(); - - if ($this->config_vars['pm_encryption']){ - $this->CI->load->library('encrypt'); - - foreach ($result as $k => $r) - { - $result[$k]->title = $this->CI->encrypt->decode($r->title); - $result[$k]->message = $this->CI->encrypt->decode($r->message); - } - } - - return $result; - } - - //tested - /** - * Get Private Message - * Get private message by id - * @param int $pm_id Private message id to be returned - * @param int $user_id User ID of Sender or Receiver - * @param bool $set_as_read Whether or not to mark message as read - * @return object Private message - */ - public function get_pm($pm_id, $user_id = NULL, $set_as_read = TRUE){ - if(!$user_id){ - $user_id = $this->CI->session->userdata('id'); - } - if( !is_numeric($user_id) || !is_numeric($pm_id)){ - $this->error( $this->CI->lang->line('aauth_error_no_pm') ); - return FALSE; - } - - $query = $this->aauth_db->where('id', $pm_id); - $query = $this->aauth_db->group_start(); - $query = $this->aauth_db->where('receiver_id', $user_id); - $query = $this->aauth_db->or_where('sender_id', $user_id); - $query = $this->aauth_db->group_end(); - $query = $this->aauth_db->get( $this->config_vars['pms'] ); - - if ($query->num_rows() < 1) { - $this->error( $this->CI->lang->line('aauth_error_no_pm') ); - return FALSE; - } - - $result = $query->row(); - - if ($user_id == $result->receiver_id && $set_as_read){ - $this->set_as_read_pm($pm_id); - } - - if ($this->config_vars['pm_encryption']){ - $this->CI->load->library('encrypt'); - $result->title = $this->CI->encrypt->decode($result->title); - $result->message = $this->CI->encrypt->decode($result->message); - } - - return $result; - } - - //tested - /** - * Delete Private Message - * Delete private message by id - * @param int $pm_id Private message id to be deleted - * @return bool Delete success/failure - */ - public function delete_pm($pm_id, $user_id = NULL){ - if(!$user_id){ - $user_id = $this->CI->session->userdata('id'); - } - if( !is_numeric($user_id) || !is_numeric($pm_id)){ - $this->error( $this->CI->lang->line('aauth_error_no_pm') ); - return FALSE; - } - - $query = $this->aauth_db->where('id', $pm_id); - $query = $this->aauth_db->group_start(); - $query = $this->aauth_db->where('receiver_id', $user_id); - $query = $this->aauth_db->or_where('sender_id', $user_id); - $query = $this->aauth_db->group_end(); - $query = $this->aauth_db->get( $this->config_vars['pms'] ); - $result = $query->row(); - if ($user_id == $result->sender_id){ - if($result->pm_deleted_receiver == 1){ - return $this->aauth_db->delete( $this->config_vars['pms'], array('id' => $pm_id)); - } - - return $this->aauth_db->update( $this->config_vars['pms'], array('pm_deleted_sender'=>1), array('id' => $pm_id)); - }else if ($user_id == $result->receiver_id){ - if($result->pm_deleted_sender == 1){ - return $this->aauth_db->delete( $this->config_vars['pms'], array('id' => $pm_id)); - } - - return $this->aauth_db->update( $this->config_vars['pms'], array('pm_deleted_receiver'=>1, 'date_read'=>date('Y-m-d H:i:s')), array('id' => $pm_id) ); - } - } - - /** - * Cleanup PMs - * Removes PMs older than 'pm_cleanup_max_age' (definied in aauth config). - * recommend for a cron job - */ - public function cleanup_pms(){ - $pm_cleanup_max_age = $this->config_vars['pm_cleanup_max_age']; - $date_sent = date('Y-m-d H:i:s', strtotime("now -".$pm_cleanup_max_age)); - $this->aauth_db->where('date_sent <', $date_sent); - - return $this->aauth_db->delete($this->config_vars['pms']); - } - - //tested - /** - * Count unread Private Message - * Count number of unread private messages - * @param int|bool $receiver_id User id for message receiver, if FALSE returns for current user - * @return int Number of unread messages - */ - public function count_unread_pms($receiver_id=FALSE){ - - if(!$receiver_id){ - $receiver_id = $this->CI->session->userdata('id'); - } - - $query = $this->aauth_db->where('receiver_id', $receiver_id); - $query = $this->aauth_db->where('date_read', NULL); - $query = $this->aauth_db->where('pm_deleted_sender', NULL); - $query = $this->aauth_db->where('pm_deleted_receiver', NULL); - $query = $this->aauth_db->get( $this->config_vars['pms'] ); - - return $query->num_rows(); - } - - //tested - /** - * Set Private Message as read - * Set private message as read - * @param int $pm_id Private message id to mark as read - */ - public function set_as_read_pm($pm_id){ - - $data = array( - 'date_read' => date('Y-m-d H:i:s') - ); - - $this->aauth_db->update( $this->config_vars['pms'], $data, "id = $pm_id"); - } - - ######################## - # Error / Info Functions - ######################## - - /** - * Error - * Add message to error array and set flash data - * @param string $message Message to add to array - * @param boolean $flashdata if TRUE add $message to CI flashdata (deflault: FALSE) - */ - public function error($message = '', $flashdata = FALSE){ - $this->errors[] = $message; - if($flashdata) - { - $this->flash_errors[] = $message; - $this->CI->session->set_flashdata('errors', $this->flash_errors); - } - } - - /** - * Keep Errors - * - * Keeps the flashdata errors for one more page refresh. Optionally adds the default errors into the - * flashdata list. This should be called last in your controller, and with care as it could continue - * to revive all errors and not let them expire as intended. - * Benefitial when using Ajax Requests - * @see http://ellislab.com/codeigniter/user-guide/libraries/sessions.html - * @param boolean $include_non_flash TRUE if it should stow basic errors as flashdata (default = FALSE) - */ - public function keep_errors($include_non_flash = FALSE) - { - // NOTE: keep_flashdata() overwrites anything new that has been added to flashdata so we are manually reviving flash data - // $this->CI->session->keep_flashdata('errors'); - - if($include_non_flash) - { - $this->flash_errors = array_merge($this->flash_errors, $this->errors); - } - $this->flash_errors = array_merge($this->flash_errors, (array)$this->CI->session->flashdata('errors')); - $this->CI->session->set_flashdata('errors', $this->flash_errors); - } - - //tested - /** - * Get Errors Array - * Return array of errors - * @return array Array of messages, empty array if no errors - */ - public function get_errors_array() - { - return $this->errors; - } - - /** - * Print Errors - * - * Prints string of errors separated by delimiter - * @param string $divider Separator for errors - */ - public function print_errors($divider = '
') - { - $msg = ''; - $msg_num = count($this->errors); - $i = 1; - foreach ($this->errors as $e) - { - $msg .= $e; - - if ($i != $msg_num) - { - $msg .= $divider; - } - $i++; - } - echo $msg; - } - - /** - * Clear Errors - * - * Removes errors from error list and clears all associated flashdata - */ - public function clear_errors() - { - $this->errors = array(); - $this->CI->session->set_flashdata('errors', $this->errors); - } - - /** - * Info - * - * Add message to info array and set flash data - * - * @param string $message Message to add to infos array - * @param boolean $flashdata if TRUE add $message to CI flashdata (deflault: FALSE) - */ - public function info($message = '', $flashdata = FALSE) - { - $this->infos[] = $message; - if($flashdata) - { - $this->flash_infos[] = $message; - $this->CI->session->set_flashdata('infos', $this->flash_infos); - } - } - - /** - * Keep Infos - * - * Keeps the flashdata infos for one more page refresh. Optionally adds the default infos into the - * flashdata list. This should be called last in your controller, and with care as it could continue - * to revive all infos and not let them expire as intended. - * Benefitial by using Ajax Requests - * @see http://ellislab.com/codeigniter/user-guide/libraries/sessions.html - * @param boolean $include_non_flash TRUE if it should stow basic infos as flashdata (default = FALSE) - */ - public function keep_infos($include_non_flash = FALSE) - { - // NOTE: keep_flashdata() overwrites anything new that has been added to flashdata so we are manually reviving flash data - // $this->CI->session->keep_flashdata('infos'); - - if($include_non_flash) - { - $this->flash_infos = array_merge($this->flash_infos, $this->infos); - } - $this->flash_infos = array_merge($this->flash_infos, (array)$this->CI->session->flashdata('infos')); - $this->CI->session->set_flashdata('infos', $this->flash_infos); - } - - /** - * Get Info Array - * - * Return array of infos - * @return array Array of messages, empty array if no errors - */ - public function get_infos_array() - { - return $this->infos; - } - - - /** - * Print Info - * - * Print string of info separated by delimiter - * @param string $divider Separator for info - * - */ - public function print_infos($divider = '
') - { - - $msg = ''; - $msg_num = count($this->infos); - $i = 1; - foreach ($this->infos as $e) - { - $msg .= $e; - - if ($i != $msg_num) - { - $msg .= $divider; - } - $i++; - } - echo $msg; - } - - /** - * Clear Info List - * - * Removes info messages from info list and clears all associated flashdata - */ - public function clear_infos() - { - $this->infos = array(); - $this->CI->session->set_flashdata('infos', $this->infos); - } - - ######################## - # User Variables - ######################## - - //tested - /** - * Set User Variable as key value - * if variable not set before, it will ve set - * if set, overwrites the value - * @param string $key - * @param string $value - * @param int $user_id ; if not given current user - * @return bool - */ - public function set_user_var( $key, $value, $user_id = FALSE ) { - - if ( ! $user_id ){ - $user_id = $this->CI->session->userdata('id'); - } - - // if specified user is not found - if ( ! $this->get_user($user_id)){ - return FALSE; - } - - // if var not set, set - if ($this->get_user_var($key,$user_id) ===FALSE) { - - $data = array( - 'data_key' => $key, - 'value' => $value, - 'user_id' => $user_id - ); - - return $this->aauth_db->insert( $this->config_vars['user_variables'] , $data); - } - // if var already set, overwrite - else { - - $data = array( - 'data_key' => $key, - 'value' => $value, - 'user_id' => $user_id - ); - - $this->aauth_db->where( 'data_key', $key ); - $this->aauth_db->where( 'user_id', $user_id); - - return $this->aauth_db->update( $this->config_vars['user_variables'], $data); - } - } - - //tested - /** - * Unset User Variable as key value - * @param string $key - * @param int $user_id ; if not given current user - * @return bool - */ - public function unset_user_var( $key, $user_id = FALSE ) { - - if ( ! $user_id ){ - $user_id = $this->CI->session->userdata('id'); - } - - // if specified user is not found - if ( ! $this->get_user($user_id)){ - return FALSE; - } - - $this->aauth_db->where('data_key', $key); - $this->aauth_db->where('user_id', $user_id); - - return $this->aauth_db->delete( $this->config_vars['user_variables'] ); - } - - //tested - /** - * Get User Variable by key - * Return string of variable value or FALSE - * @param string $key - * @param int $user_id ; if not given current user - * @return bool|string , FALSE if var is not set, the value of var if set - */ - public function get_user_var( $key, $user_id = FALSE){ - - if ( ! $user_id ){ - $user_id = $this->CI->session->userdata('id'); - } - - // if specified user is not found - if ( ! $this->get_user($user_id)){ - return FALSE; - } - - $query = $this->aauth_db->where('user_id', $user_id); - $query = $this->aauth_db->where('data_key', $key); - - $query = $this->aauth_db->get( $this->config_vars['user_variables'] ); - - // if variable not set - if ($query->num_rows() < 1) { return FALSE;} - - else { - - $row = $query->row(); - return $row->value; - } - - } - - - /** - * Get User Variables by user id - * Return array with all user keys & variables - * @param int $user_id ; if not given current user - * @return bool|array , FALSE if var is not set, the value of var if set - */ - public function get_user_vars( $user_id = FALSE){ - - if ( ! $user_id ){ - $user_id = $this->CI->session->userdata('id'); - } - - // if specified user is not found - if ( ! $this->get_user($user_id)){ - return FALSE; - } - - $query = $this->aauth_db->select('data_key, value'); - - $query = $this->aauth_db->where('user_id', $user_id); - - $query = $this->aauth_db->get( $this->config_vars['user_variables'] ); - - return $query->result(); - - } - - /** - * List User Variable Keys by UserID - * Return array of variable keys or FALSE - * @param int $user_id ; if not given current user - * @return bool|array, FALSE if no user vars, otherwise array - */ - public function list_user_var_keys($user_id = FALSE){ - - if ( ! $user_id ){ - $user_id = $this->CI->session->userdata('id'); - } - - // if specified user is not found - if ( ! $this->get_user($user_id)){ - return FALSE; - } - $query = $this->aauth_db->select('data_key'); - - $query = $this->aauth_db->where('user_id', $user_id); - - $query = $this->aauth_db->get( $this->config_vars['user_variables'] ); - - // if variable not set - if ($query->num_rows() < 1) { return FALSE;} - else { - return $query->result(); - } - } - - public function generate_recaptcha_field(){ - $content = ''; - if($this->config_vars['ddos_protection'] && $this->config_vars['recaptcha_active'] && $this->get_login_attempts() >= $this->config_vars['recaptcha_login_attempts']){ - $content .= ""; - $siteKey = $this->config_vars['recaptcha_siteKey']; - $content .= "
"; - } - return $content; - } - - public function update_user_totp_secret($user_id = FALSE, $secret) { - - if ($user_id == FALSE) - $user_id = $this->CI->session->userdata('id'); - - $data['totp_secret'] = $secret; - - $this->aauth_db->where('id', $user_id); - return $this->aauth_db->update($this->config_vars['users'], $data); - } - - public function generate_unique_totp_secret(){ - $this->CI->load->helper('googleauthenticator'); - $ga = new PHPGangsta_GoogleAuthenticator(); - $stop = false; - while (!$stop) { - $secret = $ga->createSecret(); - $query = $this->aauth_db->where('totp_secret', $secret); - $query = $this->aauth_db->get($this->config_vars['users']); - if ($query->num_rows() == 0) { - return $secret; - $stop = true; - } - } - } - - public function generate_totp_qrcode($secret){ - $this->CI->load->helper('googleauthenticator'); - $ga = new PHPGangsta_GoogleAuthenticator(); - return $ga->getQRCodeGoogleUrl($this->config_vars['name'], $secret); - } - - public function verify_user_totp_code($totp_code, $user_id = FALSE){ - if ( !$this->is_totp_required()) { - return TRUE; - } - if ($user_id == FALSE) { - $user_id = $this->CI->session->userdata('id'); - } - if (empty($totp_code)) { - $this->error($this->CI->lang->line('aauth_error_totp_code_required')); - return FALSE; - } - $query = $this->aauth_db->where('id', $user_id); - $query = $this->aauth_db->get($this->config_vars['users']); - $totp_secret = $query->row()->totp_secret; - $this->CI->load->helper('googleauthenticator'); - $ga = new PHPGangsta_GoogleAuthenticator(); - $checkResult = $ga->verifyCode($totp_secret, $totp_code, 0); - if (!$checkResult) { - $this->error($this->CI->lang->line('aauth_error_totp_code_invalid')); - return FALSE; - }else{ - $this->CI->session->unset_userdata('totp_required'); - return TRUE; - } - } - - public function is_totp_required(){ - if ( !$this->CI->session->userdata('totp_required')) { - return FALSE; - }else if ( $this->CI->session->userdata('totp_required')) { - return TRUE; - } - } - -} // end class - -// $this->CI->session->userdata('id') - -/* coming with v3 ----------------- - * captcha (hmm bi bakalım) - * parametre olarak array alma - * stacoverflow - * public id sini 0 a eşitleyip öyle kontrol yapabilirdik (oni boşver uşağum) - * lock_user (until parametrsi) - * unlock_user - * send_pm() in errounda receiver ve sender için ayrı errorlar olabilür - * ddos protect olayını daha mantıklı hale getür - * geçici ban ve e-mail ile tkrar aktifleştime olayı -*/ - -/** - * Coming with v2 - * ------------- - * - * tmam // permission id yi permission parametre yap - * mail fonksiyonları imtihanı - * tamam // login e ip aderesi de eklemek lazım - * list_users da grup_par verilirse ve adamın birden fazla grubu varsa nolurkun? // bi denemek lazım belki distinct ile düzelir - * tamam // eğer grup silinmişse kullanıcıları da o gruptan sil (fire) - * tamam // ismember la is admine 2. parametre olarak user id ekle - * tamam // kepp infos errors die bişey yap ajax requestlerinde silinir errorlar - * tmam // user variables - * tamam // sistem variables - * tmam // user perms - * tamam gibi // 4mysql index fulltext index?? - * tamam //delete_user dan sonra grup ve perms ler de silinmeli - * login() içinde login'i doğru şekilde olsa da yine de login attempt artıyo kesin düzeltilecek - * keep_errors ve keep_infos calismiyor - * - * - * - * ----------- - * ok - * - * unban_user() added // unlock_user - * remove member added // fire_member - * allow() changed to allow_group - * deny() changed to deny_group - * is member a yeni parametre eklendi - * allow_user() added - * deny_user() added - * keep_infos() added - * kepp_errors() added - * get_errors() changed to print_errors() - * get_infos() changed to print_infos() - * User and Aauth System Variables. -set_user_var( $key, $value, $user_id = FALSE ) -get_user_var( $key, $user_id = FALSE) -unset -set_system_var( $key, $value, $user_id = FALSE ) -get_system_var( $key, $user_id = FALSE) -unset -functions added - * - * - * - * - * - * Done staff v1 - * ----------- - * tamam hacı // control die bi fonksiyon yazıp adam önce login omuşmu sonra da yetkisi var mı die kontrol et. yetkisi yoksa yönlendir ve aktivitiyi güncelle - * tamam hacı // grupları yetkilendirme, yetki ekleme, alma alow deny - * tamam gibi // Email and pass validation with form helper - * biraz oldu // laguage file support - * tamam // forget pass - * tamam // yetkilendirme sistemi - * tamam // Login e remember eklencek - * tamam // şifremi unuttum ve random string - * sanırım şimdi tamam // hatalı girişde otomatik süreli kilit - * ?? tamam heral // mail ile bilgilendirme - * tamam heral // activasyon emaili - * tamam gibi // yerine email check // username check - * tamamlandı // public erişimi - * tamam // Private messsages - * tamam össen // errorlar düzenlenecek hepisiiii - * tamam ama engelleme ve limit olayı koymadım. // pm için okundu ve göster, sil, engelle? die fonksiyonlar eklencek , gönderilen pmler, alınan pmler, arasındaki pmler, - * tamm// already existedleri info yap onlar error değil hacım - * - - - - -/* -// if user's email is found -if ($query->num_rows() > 0) { -$row = $query->row(); - -// DDos protection -if ( $this->config_vars['dos_protection'] and $row->last_login_attempt != '' and -(strtotime("now") + 30 * $this->config_vars['try'] ) < strtotime($row->last_login_attempt) ) { -$this->error($this->CI->lang->line('exceeded')); -return FALSE; -} -} - */ - - - -/* End of file Aauth.php */ -/* Location: ./application/libraries/Aauth.php */ diff --git a/book.json b/book.json new file mode 100644 index 0000000..dc7a9fc --- /dev/null +++ b/book.json @@ -0,0 +1,13 @@ +{ + "root": "./docs", + "gitbook": ">=3.0.0", + "plugins": [ "phpclassdisplayer@1.0.4" ], + "pluginsConfig": { + "phpclassdisplayer": { + "scope": "->", + "anchors": true, + "hint_iconcenter": true, + "hint_iconsize": "fa-3x" + } + } +} diff --git a/config/aauth.php b/config/aauth.php new file mode 100644 index 0000000..9b01a5e --- /dev/null +++ b/config/aauth.php @@ -0,0 +1,81 @@ + array( + '_profile' => 'default', + 'users' => 'aauth_users', + 'login_attempts' => 'aauth_login_attempts', + 'user_variables' => 'aauth_user_variables', + 'groups' => 'aauth_groups', + 'group_to_user' => 'aauth_user_to_group', + 'group_to_subgroup' => 'aauth_group_to_group', + 'permissions' => 'aauth_perms', + 'permission_to_user' => 'aauth_perm_to_user', + 'permission_to_group' => 'aauth_perm_to_group', + ), + + 'group' => array( + 'admin' => 'admin', + 'default' => 'default', + 'public' => 'public', + ), + + 'login' => array( + 'remember_time' => '3 days', + 'use_username' => FALSE, + ), + + 'username' => array( + 'additional_valid_chars' => array(), + ), + + 'password' => array( + 'min_length' => 5, + 'max_length' => 13, + 'hash_algo' => PASSWORD_DEFAULT, + 'hash_options' => array(), + ), + + 'email' => array( + 'email' => 'admin@admin.com', + 'name' => 'Emre Akay', + ), + + 'ddos_protection' => array( + 'enabled' => TRUE, + 'time_period' => '5 minutes', + 'max_attempts' => 10, + 'remove_successful_attempts' => TRUE, + ), + + 'totp' => array( + 'enabled' => FALSE, + 'only_on_ip_change' => FALSE, + 'reset_over_reset_password' => FALSE, + 'two_step_login_active' => FALSE, + ), + + 'recaptcha' => array( + 'enabled' => FALSE, + 'login_attempts' => 4, + 'site_key' => '', + 'secret' => '', + ), + + 'redirect' => array( + 'no_permission' => FALSE, + ), + + 'link' => array( + 'verification' => '/account/verification/', + 'reset_password' => '/account/reset_password/', + 'two_step_login' => '/account/twofactor_verification/', + ), +); + + + +$config['aauth'] = $config_aauth; diff --git a/config/aauth_init.php b/config/aauth_init.php new file mode 100644 index 0000000..e65e7d8 --- /dev/null +++ b/config/aauth_init.php @@ -0,0 +1,30 @@ +]+$/i +| +| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!! +| +*/ +$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-'; + +/* +|-------------------------------------------------------------------------- +| Enable Query Strings +|-------------------------------------------------------------------------- +| +| By default CodeIgniter uses search-engine friendly segment based URLs: +| example.com/who/what/where/ +| +| By default CodeIgniter enables access to the $_GET array. If for some +| reason you would like to disable it, set 'allow_get_array' to FALSE. +| +| You can optionally enable standard query string based URLs: +| example.com?who=me&what=something&where=here +| +| Options are: TRUE or FALSE (boolean) +| +| The other items let you set the query string 'words' that will +| invoke your controllers and its functions: +| example.com/index.php?c=controller&m=function +| +| Please note that some of the helpers won't work as expected when +| this feature is enabled, since CodeIgniter is designed primarily to +| use segment based URLs. +| +*/ +$config['allow_get_array'] = TRUE; +$config['enable_query_strings'] = FALSE; +$config['controller_trigger'] = 'c'; +$config['function_trigger'] = 'm'; +$config['directory_trigger'] = 'd'; + +/* +|-------------------------------------------------------------------------- +| Error Logging Threshold +|-------------------------------------------------------------------------- +| +| You can enable error logging by setting a threshold over zero. The +| threshold determines what gets logged. Threshold options are: +| +| 0 = Disables logging, Error logging TURNED OFF +| 1 = Error Messages (including PHP errors) +| 2 = Debug Messages +| 3 = Informational Messages +| 4 = All Messages +| +| You can also pass an array with threshold levels to show individual error types +| +| array(2) = Debug Messages, without Error Messages +| +| For a live site you'll usually only enable Errors (1) to be logged otherwise +| your log files will fill up very fast. +| +*/ +$config['log_threshold'] = 0; + +/* +|-------------------------------------------------------------------------- +| Error Logging Directory Path +|-------------------------------------------------------------------------- +| +| Leave this BLANK unless you would like to set something other than the default +| application/logs/ directory. Use a full server path with trailing slash. +| +*/ +$config['log_path'] = ''; + +/* +|-------------------------------------------------------------------------- +| Log File Extension +|-------------------------------------------------------------------------- +| +| The default filename extension for log files. The default 'php' allows for +| protecting the log files via basic scripting, when they are to be stored +| under a publicly accessible directory. +| +| Note: Leaving it blank will default to 'php'. +| +*/ +$config['log_file_extension'] = ''; + +/* +|-------------------------------------------------------------------------- +| Log File Permissions +|-------------------------------------------------------------------------- +| +| The file system permissions to be applied on newly created log files. +| +| IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal +| integer notation (i.e. 0700, 0644, etc.) +*/ +$config['log_file_permissions'] = 0644; + +/* +|-------------------------------------------------------------------------- +| Date Format for Logs +|-------------------------------------------------------------------------- +| +| Each item that is logged has an associated date. You can use PHP date +| codes to set your own date formatting +| +*/ +$config['log_date_format'] = 'Y-m-d H:i:s'; + +/* +|-------------------------------------------------------------------------- +| Error Views Directory Path +|-------------------------------------------------------------------------- +| +| Leave this BLANK unless you would like to set something other than the default +| application/views/errors/ directory. Use a full server path with trailing slash. +| +*/ +$config['error_views_path'] = ''; + +/* +|-------------------------------------------------------------------------- +| Cache Directory Path +|-------------------------------------------------------------------------- +| +| Leave this BLANK unless you would like to set something other than the default +| application/cache/ directory. Use a full server path with trailing slash. +| +*/ +$config['cache_path'] = ''; + +/* +|-------------------------------------------------------------------------- +| Cache Include Query String +|-------------------------------------------------------------------------- +| +| Whether to take the URL query string into consideration when generating +| output cache files. Valid options are: +| +| FALSE = Disabled +| TRUE = Enabled, take all query parameters into account. +| Please be aware that this may result in numerous cache +| files generated for the same page over and over again. +| array('q') = Enabled, but only take into account the specified list +| of query parameters. +| +*/ +$config['cache_query_string'] = FALSE; + +/* +|-------------------------------------------------------------------------- +| Encryption Key +|-------------------------------------------------------------------------- +| +| If you use the Encryption class, you must set an encryption key. +| See the user guide for more info. +| +| https://codeigniter.com/user_guide/libraries/encryption.html +| +*/ +$config['encryption_key'] = ''; + +/* +|-------------------------------------------------------------------------- +| Session Variables +|-------------------------------------------------------------------------- +| +| 'sess_driver' +| +| The storage driver to use: files, database, redis, memcached +| +| 'sess_cookie_name' +| +| The session cookie name, must contain only [0-9a-z_-] characters +| +| 'sess_expiration' +| +| The number of SECONDS you want the session to last. +| Setting to 0 (zero) means expire when the browser is closed. +| +| 'sess_save_path' +| +| The location to save sessions to, driver dependent. +| +| For the 'files' driver, it's a path to a writable directory. +| WARNING: Only absolute paths are supported! +| +| For the 'database' driver, it's a table name. +| Please read up the manual for the format with other session drivers. +| +| IMPORTANT: You are REQUIRED to set a valid save path! +| +| 'sess_match_ip' +| +| Whether to match the user's IP address when reading the session data. +| +| WARNING: If you're using the database driver, don't forget to update +| your session table's PRIMARY KEY when changing this setting. +| +| 'sess_time_to_update' +| +| How many seconds between CI regenerating the session ID. +| +| 'sess_regenerate_destroy' +| +| Whether to destroy session data associated with the old session ID +| when auto-regenerating the session ID. When set to FALSE, the data +| will be later deleted by the garbage collector. +| +| Other session cookie settings are shared with the rest of the application, +| except for 'cookie_prefix' and 'cookie_httponly', which are ignored here. +| +*/ +$config['sess_driver'] = 'files'; +$config['sess_cookie_name'] = 'ci_session'; +$config['sess_expiration'] = 7200; +$config['sess_save_path'] = '/application/tmp'; +$config['sess_match_ip'] = FALSE; +$config['sess_time_to_update'] = 300; +$config['sess_regenerate_destroy'] = FALSE; + +/* +|-------------------------------------------------------------------------- +| Cookie Related Variables +|-------------------------------------------------------------------------- +| +| 'cookie_prefix' = Set a cookie name prefix if you need to avoid collisions +| 'cookie_domain' = Set to .your-domain.com for site-wide cookies +| 'cookie_path' = Typically will be a forward slash +| 'cookie_secure' = Cookie will only be set if a secure HTTPS connection exists. +| 'cookie_httponly' = Cookie will only be accessible via HTTP(S) (no javascript) +| +| Note: These settings (with the exception of 'cookie_prefix' and +| 'cookie_httponly') will also affect sessions. +| +*/ +$config['cookie_prefix'] = ''; +$config['cookie_domain'] = ''; +$config['cookie_path'] = '/'; +$config['cookie_secure'] = FALSE; +$config['cookie_httponly'] = FALSE; + +/* +|-------------------------------------------------------------------------- +| Standardize newlines +|-------------------------------------------------------------------------- +| +| Determines whether to standardize newline characters in input data, +| meaning to replace \r\n, \r, \n occurrences with the PHP_EOL value. +| +| This is particularly useful for portability between UNIX-based OSes, +| (usually \n) and Windows (\r\n). +| +*/ +$config['standardize_newlines'] = FALSE; + +/* +|-------------------------------------------------------------------------- +| Global XSS Filtering +|-------------------------------------------------------------------------- +| +| Determines whether the XSS filter is always active when GET, POST or +| COOKIE data is encountered +| +| WARNING: This feature is DEPRECATED and currently available only +| for backwards compatibility purposes! +| +*/ +$config['global_xss_filtering'] = FALSE; + +/* +|-------------------------------------------------------------------------- +| Cross Site Request Forgery +|-------------------------------------------------------------------------- +| Enables a CSRF cookie token to be set. When set to TRUE, token will be +| checked on a submitted form. If you are accepting user data, it is strongly +| recommended CSRF protection be enabled. +| +| 'csrf_token_name' = The token name +| 'csrf_cookie_name' = The cookie name +| 'csrf_expire' = The number in seconds the token should expire. +| 'csrf_regenerate' = Regenerate token on every submission +| 'csrf_exclude_uris' = Array of URIs which ignore CSRF checks +*/ +$config['csrf_protection'] = FALSE; +$config['csrf_token_name'] = 'csrf_test_name'; +$config['csrf_cookie_name'] = 'csrf_cookie_name'; +$config['csrf_expire'] = 7200; +$config['csrf_regenerate'] = TRUE; +$config['csrf_exclude_uris'] = array(); + +/* +|-------------------------------------------------------------------------- +| Output Compression +|-------------------------------------------------------------------------- +| +| Enables Gzip output compression for faster page loads. When enabled, +| the output class will test whether your server supports Gzip. +| Even if it does, however, not all browsers support compression +| so enable only if you are reasonably sure your visitors can handle it. +| +| Only used if zlib.output_compression is turned off in your php.ini. +| Please do not use it together with httpd-level output compression. +| +| VERY IMPORTANT: If you are getting a blank page when compression is enabled it +| means you are prematurely outputting something to your browser. It could +| even be a line of whitespace at the end of one of your scripts. For +| compression to work, nothing can be sent before the output buffer is called +| by the output class. Do not 'echo' any values with compression enabled. +| +*/ +$config['compress_output'] = FALSE; + +/* +|-------------------------------------------------------------------------- +| Master Time Reference +|-------------------------------------------------------------------------- +| +| Options are 'local' or any PHP supported timezone. This preference tells +| the system whether to use your server's local time as the master 'now' +| reference, or convert it to the configured one timezone. See the 'date +| helper' page of the user guide for information regarding date handling. +| +*/ +$config['time_reference'] = 'local'; + +/* +|-------------------------------------------------------------------------- +| Rewrite PHP Short Tags +|-------------------------------------------------------------------------- +| +| If your PHP installation does not have short tag support enabled CI +| can rewrite the tags on-the-fly, enabling you to utilize that syntax +| in your view files. Options are TRUE or FALSE (boolean) +| +| Note: You need to have eval() enabled for this to work. +| +*/ +$config['rewrite_short_tags'] = FALSE; + +/* +|-------------------------------------------------------------------------- +| Reverse Proxy IPs +|-------------------------------------------------------------------------- +| +| If your server is behind a reverse proxy, you must whitelist the proxy +| IP addresses from which CodeIgniter should trust headers such as +| HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP in order to properly identify +| the visitor's IP address. +| +| You can use both an array or a comma-separated list of proxy addresses, +| as well as specifying whole subnets. Here are a few examples: +| +| Comma-separated: '10.0.1.200,192.168.5.0/24' +| Array: array('10.0.1.200', '192.168.5.0/24') +*/ +$config['proxy_ips'] = ''; diff --git a/config/testing/database.php b/config/testing/database.php new file mode 100644 index 0000000..427edc3 --- /dev/null +++ b/config/testing/database.php @@ -0,0 +1,96 @@ +db->last_query() and profiling of DB queries. +| When you run a query, with this setting set to TRUE (default), +| CodeIgniter will store the SQL statement for debugging purposes. +| However, this may cause high memory usage, especially if you run +| a lot of SQL queries ... disable this to avoid that problem. +| +| The $active_group variable lets you choose which connection group to +| make active. By default there is only one group (the 'default' group). +| +| The $query_builder variables lets you determine whether or not to load +| the query builder class. +*/ +$active_group = 'default'; +$query_builder = TRUE; + +$db['default'] = array( + 'dsn' => '', + 'hostname' => '127.0.0.1', + 'username' => 'root', + 'password' => '', + 'database' => 'aauth_test', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => (ENVIRONMENT !== 'production'), + 'cache_on' => FALSE, + 'cachedir' => '', + 'char_set' => 'utf8', + 'dbcollat' => 'utf8_general_ci', + 'swap_pre' => '', + 'encrypt' => FALSE, + 'compress' => FALSE, + 'stricton' => FALSE, + 'failover' => array(), + 'save_queries' => TRUE +); diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..609b5ca --- /dev/null +++ b/docs/README.md @@ -0,0 +1,27 @@ +# CodeIgniter-Aauth + +Aauth is a User Authorization Library for CodeIgniter 2.x and 3.x, which aims to make easy some essential jobs such as login, permissions and access operations. Despite its ease of use, it has also very advanced features like private messages, groupping, access management, and public access. + +*** +### Features +* User Management and Operations (login, logout, register, verification via e-mail, forgotten password, user ban, login DDoS protection) +* Group Operations (creating/deleting groups, membership management) +* Admin and Public Group support (Public permissions) +* Permission Management (creating/deleting permissions, allow/deny groups, public permissions, permission checking) +* Group Permissions +* User Permissions +* User and System Variables +* Login DDoS Protection +* Private Messages (between users) +* Error Messages and Validations +* Langugage and config file support +* Flexible implementation + +*** +### What is new in Version 2 +* User Permissions +* User and System Variables +* Login DDoS Protection +* Updated functions (check documentation for details) +* Bugs fixes +* TOTP (Time-based One-time Password) \ No newline at end of file diff --git a/docs/SUMMARY.md b/docs/SUMMARY.md new file mode 100644 index 0000000..a05a908 --- /dev/null +++ b/docs/SUMMARY.md @@ -0,0 +1,14 @@ +# Summary + +* [Introduction](README.md) +* [Models](models/README.md) + * [Users](models/users.md) + * [User Variables](models/user-variables.md) + * [Login Attempts](models/login-attempts.md) + * [Groups](models/groups.md) + * [Group to User](models/group_to_user.md) + * [Group to SubGroup](models/group_to_subgroup.md) + * [Permissions](models/permissions.md) + * [Permission to User](models/permission_to_user.md) + * [Permission to Group](models/permission_to_group.md) + diff --git a/docs/cover.jpg b/docs/cover.jpg new file mode 100644 index 0000000..0c8407d Binary files /dev/null and b/docs/cover.jpg differ diff --git a/docs/library/README.md b/docs/library/README.md new file mode 100644 index 0000000..7ff1b2e --- /dev/null +++ b/docs/library/README.md @@ -0,0 +1,7 @@ +# Functions +* [User](user.md) + * [Examples](user.md#examples) + * [References](user.md#references) +* [Login](login.md) + * [Examples](login.md#examples) + * [References](login.md#references) \ No newline at end of file diff --git a/docs/library/login.md b/docs/library/login.md new file mode 100644 index 0000000..c02b9bb --- /dev/null +++ b/docs/library/login.md @@ -0,0 +1,93 @@ +# Login Functions + +## Examples + +## References + +{% PHPclassDisplayer "Aauth" %} + User Authorization Library for CodeIgniter 2.x and 3.x +{% endPHPclassDisplayer %} + +{% PHPmethodDisplayer "login($identifier, $pass [, $remember = FALSE, $totp_code = NULL ])" %} + Login User + {% param "$identifier", type="string" %} + User's Identifier (email or name definied by Config-Var `login_with_name`) + {% param "$pass", type="string" %} + User's Password + {% param "$remember", type="bool" %} + Remember + {% param "$totp_code", type="string" %} + TOTP Code + {% return %} + Either `TRUE`, or `FALSE` on failure. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "is_loggedin()" %} + Checks if user is logged in + {% return %} + Either `TRUE`, or `FALSE` if not logged in. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "is_loggedin()" %} + Log a user out / Kills user session + {% return %} + Either `TRUE`, or `FALSE` on failure. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "login_fast($user_id)" %} + Login User only with user_id + {% param "$user_id", type="int" %} + User's ID + {% return %} + Either `TRUE`, or `FALSE` on failure. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "reset_login_attempts()" %} + Removes login attempts based on IP-Address & Timestamp + {% return %} + Either `TRUE`, or `FALSE` on failure. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "remind_password($email)" %} + Sends a user a link to reset password + {% param "$email", type="string" %} + User's email address + {% return %} + Either `TRUE`, or `FALSE` on failure. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "reset_password($ver_code)" %} + Generate new password and email it to the user + {% param "$ver_code", type="string" %} + Verification code + {% return %} + Either `TRUE`, or `FALSE` on failure. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "update_last_login([ $user_id = FALSE ])" %} + Updates last login timestamp + {% param "$user_id", type="int" %} + User's ID + {% return %} + Either `TRUE`, or `FALSE` on failure. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "update_login_attempts()" %} + Update login attempt + {% param "$user_id", type="int" %} + User's ID + {% return %} + Either `TRUE`, or `FALSE` if login attempt exceeded. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "update_remember($user_id [, $expression = NULL, $expire = NULL ])" %} + Update amount of time a user is remembered for + {% param "$user_id", type="int" %} + User's ID + {% param "$expression", type="string" %} + Expression + {% param "$expire", type="string" %} + Expire Date + {% return %} + Either `TRUE`, or `FALSE` if login attempt exceeded. +{% endPHPmethodDisplayer %} diff --git a/docs/library/user.md b/docs/library/user.md new file mode 100644 index 0000000..ed6ee0f --- /dev/null +++ b/docs/library/user.md @@ -0,0 +1,57 @@ +# User Functions + +## Examples + +## References + +{% PHPclassDisplayer "Aauth" %} + User Authorization Library for CodeIgniter 2.x and 3.x +{% endPHPclassDisplayer %} + +{% PHPmethodDisplayer "create_user($email, $pass [, $name = FALSE ])" %} + Update amount of time a user is remembered for + {% param "$email", type="string" %} + User's email address + {% param "$pass", type="string" %} + User's password + {% param "$name", type="string" %} + User's name + {% return %} + Either `User_ID` of created user, or `FALSE` on failure. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "update_user($user_id [, $email = FALSE, $pass = FALSE, $name = FALSE ])" %} + Update amount of time a user is remembered for + {% param "$user_id", type="int" %} + User's ID + {% param "$email", type="bool|string" %} + User's email address + {% param "$pass", type="bool|string" %} + User's password + {% param "$name", type="bool|string" %} + User's name + {% return %} + Either `TRUE`, or `FALSE` on failure. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "list_users([ $group_par = FALSE, $limit = FALSE, $offset = FALSE, $include_banneds = FALSE ])" %} + Return users as an object array + {% param "$group_par", type="int|string" %} + Specify group, to list all users in specific group + {% param "$limit", type="int" %} + Limit of users to be returned + {% param "$offset", type="int" %} + Offset for limited number of users + {% param "$include_banneds", type="bool" %} + Includes banned users + {% return %} + Array of objects. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "get_user([ $user_id = FALSE ])" %} + Get user information + {% param "$user_id", type="bool|int" %} + User's ID or `FALSE` for current user + {% return %} + Either object, or `FALSE` on failure. +{% endPHPmethodDisplayer %} diff --git a/docs/models/README.md b/docs/models/README.md new file mode 100644 index 0000000..a66cf4e --- /dev/null +++ b/docs/models/README.md @@ -0,0 +1,20 @@ +# Models + +* [Users](users.md) + * [Examples](user.md#examples) + * [References](user.md#references) +* [User Variables](user-variables.md) + * [Examples](user-variables.md#examples) + * [References](user-variables.md#references) +* [Login Attempts](login-attempts.md) + * [Examples](login-attempts.md#examples) + * [References](login-attempts.md#references) +* [Groups](groups.md) + * [Examples](groups.md#examples) + * [References](groups.md#references) +* [Group to User](group_to_user.md) + * [Examples](group_to_user.md#examples) + * [References](group_to_user.md#references) +* [Group to SubGroup](group_to_subgroup.md) + * [Examples](group_to_subgroup.md#examples) + * [References](group_to_subgroup.md#references) diff --git a/docs/models/group_to_subgroup.md b/docs/models/group_to_subgroup.md new file mode 100644 index 0000000..f20d919 --- /dev/null +++ b/docs/models/group_to_subgroup.md @@ -0,0 +1,54 @@ +# Group to Subgroup Model + +## Examples + +## References + +{% PHPclassDisplayer "Group_to_subgroup_model" %} +{% endPHPclassDisplayer %} + +{% PHPmethodDisplayer "create($group_id, $subgroup_id)" %} + Assigns a group to a subgroup. + {% param "$group_id", type="int" %} + Group's ID + {% param "$subgroup_id", type="int" %} + Sub-Groub's ID + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "delete($group_id, $subgroup_id)" %} + Removes a assigned group from a subgroup. + {% param "$group_id", type="int" %} + Group's ID + {% param "$subgroup_id", type="int" %} + Sub-Group's ID + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "delete_by_subgroup($subgroup_id)" %} + Removes all assigned groups from a subgroup. + {% param "$subgroup_id", type="int" %} + Sub-Group's ID + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "delete_by_group($group_id)" %} + Removes all assigned subgroups from a group. + {% param "$group_id", type="int" %} + Group's ID + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "exist($group_id, $subgroup_id)" %} + Checks if a group is already assigned to a subgroup. + {% param "$group_id", type="int" %} + Group's ID + {% param "$subgroup_id", type="int" %} + Sub-Group's ID + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} diff --git a/docs/models/group_to_user.md b/docs/models/group_to_user.md new file mode 100644 index 0000000..2739b62 --- /dev/null +++ b/docs/models/group_to_user.md @@ -0,0 +1,54 @@ +# Group to User Model + +## Examples + +## References + +{% PHPclassDisplayer "Group_to_user_model" %} +{% endPHPclassDisplayer %} + +{% PHPmethodDisplayer "create($group_id, $user_id)" %} + Assigns a group to a user. + {% param "$group_id", type="int" %} + Group's ID + {% param "$user_id", type="int" %} + User's ID + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "delete($group_id, $user_id)" %} + Removes a assigned group from a user. + {% param "$group_id", type="int" %} + Group's ID + {% param "$user_id", type="int" %} + User's ID + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "delete_by_user($user_id)" %} + Removes all assigned groups from a user. + {% param "$user_id", type="int" %} + User's ID + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "delete_by_group($group_id)" %} + Removes a groups from any user. + {% param "$group_id", type="int" %} + Group's ID + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "exist($group_id, $user_id)" %} + Checks if a group is already assigned to a user. + {% param "$group_id", type="int" %} + Group's ID + {% param "$user_id", type="int" %} + User's ID + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} diff --git a/docs/models/groups.md b/docs/models/groups.md new file mode 100644 index 0000000..ab2cf97 --- /dev/null +++ b/docs/models/groups.md @@ -0,0 +1,60 @@ +# Groups Model + +## Examples + +## References + +{% PHPclassDisplayer "Groups_model" %} +{% endPHPclassDisplayer %} + +{% PHPmethodDisplayer "create($name [, $definition = ''])" %} + Adds a group to database. + {% param "$name", type="string" %} + Group's name + {% param "$definition", type="string" %} + Group's definition + {% return %} + Either `Group_ID` of created group, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "update($group_id [, $name = NULL, $definition = NULL])" %} + Updates a group in database. + {% param "$group_id", type="int" %} + Group's ID + {% param "$name", type="string" %} + Group's name + {% param "$definition", type="string" %} + Group's definition + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "delete($group_id)" %} + Removes a group from database. + {% param "$group_id", type="int" %} + Group's ID + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "get($group_id)" %} + Retrieves a group from database. + {% param "$group_id", type="int" %} + Group's ID + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "get_id($name)" %} + Retrieves a group id from database. + {% param "$name", type="int" %} + Group's name + {% return %} + Either `Group_ID`, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "get_all()" %} + Retrieves all groups from database. + {% return %} + Array of all groups as object. +{% endPHPmethodDisplayer %} diff --git a/docs/models/login-attempts.md b/docs/models/login-attempts.md new file mode 100644 index 0000000..a844273 --- /dev/null +++ b/docs/models/login-attempts.md @@ -0,0 +1,26 @@ +# Login Attempts Model + +## Examples + +## References + +{% PHPclassDisplayer "Login_Attempts_model" %} +{% endPHPclassDisplayer %} + +{% PHPmethodDisplayer "get()" %} + Retrieves a login attempt from database, based on IP-Address and timestamp. + {% return %} + Value of login attempts +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "update()" %} + Updates/Created a login attempt in database, based on IP-Address and timestamp. + {% return %} + Either `TRUE` if login attempt below `max_attempts`, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "delete()" %} + Removes a login attempt from database, based on IP-Address and timestamp. + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} diff --git a/docs/models/permission_to_group.md b/docs/models/permission_to_group.md new file mode 100644 index 0000000..bf01e90 --- /dev/null +++ b/docs/models/permission_to_group.md @@ -0,0 +1,54 @@ +# Permission to Group Model + +## Examples + +## References + +{% PHPclassDisplayer "Permission_to_group_model" %} +{% endPHPclassDisplayer %} + +{% PHPmethodDisplayer "create($permission_id, $group_id)" %} + Assigns a permission to a group. + {% param "$permission_id", type="int" %} + Permission's ID + {% param "$group_id", type="int" %} + Group's ID + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "delete($permission_id, $group_id)" %} + Removes a assigned permission from a group. + {% param "$permission_id", type="int" %} + Permission's ID + {% param "$group_id", type="int" %} + Group's ID + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "delete_by_group($group_id)" %} + Removes all assigned permissions from a group. + {% param "$group_id", type="int" %} + Group's ID + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "delete_by_permission($permission_id)" %} + Remove a permission from any group. + {% param "$permission_id", type="int" %} + Permission's ID + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "exist($permission_id, $group_id)" %} + Checks if a permission is already assigned to a group. + {% param "$permission_id", type="int" %} + Permission's ID + {% param "$group_id", type="int" %} + Group's ID + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} diff --git a/docs/models/permission_to_user.md b/docs/models/permission_to_user.md new file mode 100644 index 0000000..75ba865 --- /dev/null +++ b/docs/models/permission_to_user.md @@ -0,0 +1,54 @@ +# Permission to User Model + +## Examples + +## References + +{% PHPclassDisplayer "Permission_to_user_model" %} +{% endPHPclassDisplayer %} + +{% PHPmethodDisplayer "create($permission_id, $user_id)" %} + Assigns a permission to a user. + {% param "$permission_id", type="int" %} + Permission's ID + {% param "$user_id", type="int" %} + User's ID + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "delete($permission_id, $user_id)" %} + Removes a assigned permission from a user. + {% param "$permission_id", type="int" %} + Permission's ID + {% param "$user_id", type="int" %} + User's ID + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "delete_by_user($user_id)" %} + Removes all assigned permissions from a user. + {% param "$user_id", type="int" %} + User's ID + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "delete_by_permission($permission_id)" %} + Remove a permission from any user. + {% param "$permission_id", type="int" %} + Permission's ID + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "exist($permission_id, $user_id)" %} + Checks if a permission is already assigned to a user. + {% param "$permission_id", type="int" %} + Permission's ID + {% param "$user_id", type="int" %} + User's ID + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} diff --git a/docs/models/permissions.md b/docs/models/permissions.md new file mode 100644 index 0000000..23ee4a6 --- /dev/null +++ b/docs/models/permissions.md @@ -0,0 +1,60 @@ +# Permissions Model + +## Examples + +## References + +{% PHPclassDisplayer "Permissions_model" %} +{% endPHPclassDisplayer %} + +{% PHPmethodDisplayer "create($name [, $definition = ''])" %} + Creates a permission. + {% param "$name", type="string" %} + Permission's name + {% param "$definition", type="string" %} + Permission's definition + {% return %} + Either `Permission_ID` of created permission, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "update($permission_id [, $name = NULL, $definition = NULL])" %} + Updates a permission. + {% param "$permission_id", type="int" %} + Permission's ID + {% param "$name", type="string" %} + Permission's name + {% param "$definition", type="string" %} + Permission's definition + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "delete($id)" %} + Removes a permission. + {% param "$permission_id", type="int" %} + Permission's ID + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "get($permission_id)" %} + Retrieves a permission. + {% param "$permission_id", type="int" %} + Permission's ID + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "get_id($name)" %} + Retrieves permission_id. + {% param "$name", type="int" %} + Permission's name + {% return %} + Either `Permission_ID`, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "get_all()" %} + Retrieves all permissions. + {% return %} + Array of all permission as object. +{% endPHPmethodDisplayer %} diff --git a/docs/models/user-variables.md b/docs/models/user-variables.md new file mode 100644 index 0000000..696d0e6 --- /dev/null +++ b/docs/models/user-variables.md @@ -0,0 +1,48 @@ +# User Variables Model + +## Examples + +## References + +{% PHPclassDisplayer "User_Variables_model" %} +{% endPHPclassDisplayer %} + +{% PHPmethodDisplayer "update($user_id, $key, $value)" %} + Updates/Creates a user uariable for a user in database. + {% param "$user_id", type="int" %} + User's ID + {% param "$key", type="string" %} + User Variable Key + {% param "$value", type="string" %} + User Variable Value + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "get($user_id, $key)" %} + Retrieves a user variable from a user in database. + {% param "$user_id", type="int" %} + User's ID + {% param "$key", type="string" %} + User Variable Key + {% return %} + Either the value of the user variable, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "get_by_user_id($user_id)" %} + Retrieves all user variables from a user in database. + {% param "$user_id", type="int" %} + User's ID + {% return %} + Either a array of all user variables, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "delete($user_id [, $key = NULL])" %} + Removes all user variables or only one user variable from a user in database. + {% param "$user_id", type="int" %} + User's ID + {% param "$key", type="string" %} + User Variable Key + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} diff --git a/docs/models/users.md b/docs/models/users.md new file mode 100644 index 0000000..4508c88 --- /dev/null +++ b/docs/models/users.md @@ -0,0 +1,135 @@ +# Users Model + +## Examples + +## References + +{% PHPclassDisplayer "Users_model" %} +{% endPHPclassDisplayer %} + +{% PHPmethodDisplayer "create($email, $pass [, $username = '' ])" %} + Adds a user to the database. + {% param "$email", type="string" %} + User's email address + {% param "$pass", type="string" %} + User's password + {% param "$name", type="string" %} + User's name + {% return %} + Either `User_ID` of created user, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "update($user_id, $data)" %} + Updates data of a user in database. + {% param "$user_id", type="int" %} + User's ID + {% param "$data", type="array" %} + Array of data to update + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "delete($user_id)" %} + Removes a user from database. + {% param "$user_id", type="int" %} + User's ID + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "get_all([$options = array()])" %} + Retrieves all users from database. + {% hint %} + Available options: + - `filters` (_array_) - A associative array with 'column'-name as key and value + - `include_banneds` (_bool_) - Whether to include banned user's + - `only_banneds` (_bool_) - Whether to include only banned user's + - `offset` (_int_) - Number of rows to limit the results to + - `limit` (_int_) - Number of rows to skip + {% param "$options", type="array" %} + Array of options. + {% return %} + Array of all users as object. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "ban($user_id [, $ver_code = NULL])" %} + Bans/Unverfies a user. + {% param "$user_id", type="int" %} + User's ID + {% param "$ver_code", type="string" %} + Verification Code + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "unban($user_id [, $ver_code = NULL])" %} + Unbans/Verfies a user. + {% param "$user_id", type="int" %} + User's ID + {% param "$ver_code", type="string" %} + Verification Code + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "update_($user_id, $type)" %} + Updates last_activity or last_login of a user. + {% param "$user_id", type="int" %} + User's ID + {% param "$type", type="string" %} + Update Type + {% hint %} + Available types: + - `activity` + - `last_login` + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "exist_by_($filters = array())" %} + Checks if a user exist in database depending on filters. + {% param "$filters", type="array" %} + A associative array with 'column'-name as key and value + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "get_($filters, $result_column)" %} + Retrieves a user depending on filters with a result column. + {% param "$filters", type="array" %} + A associative array with 'column'-name as key and value + {% param "$result_column", type="string" %} + Column name thats get returned + {% return %} + Either `value` of selected column on success, or `FALSE`. +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "get_by_($filters [, $options = NULL])" %} + Retrieves users from database depending on filters and options. + {% param "$filters", type="array" %} + A associative array with column name as key and value + {% param "$options", type="array" %} + Array of options. + {% hint %} + Available options: + - `select` (_bool_) - Single column name or Multiple column names comma separeated + - `offset` (_int_) - Number of rows to limit the results to + - `limit` (_int_) - Number of rows to skip + {% return %} + CI's Database `get()` +{% endPHPmethodDisplayer %} + +{% PHPmethodDisplayer "is_($user_id, $type)" %} + Checks if a user is banned or verified. + {% param "$user_id", type="int" %} + User's ID + {% param "$type", type="string" %} + Is Type + {% hint %} + Available types: + - `banned` + - `verified` + {% return %} + Either `TRUE` on success, or `FALSE`. +{% endPHPmethodDisplayer %} + diff --git a/docs/quick-start.md b/docs/quick-start.md new file mode 100644 index 0000000..f31b783 --- /dev/null +++ b/docs/quick-start.md @@ -0,0 +1,146 @@ +# Quck Start + +Let's get started :) + +First, we will load the Aauth Library into the system +```php +$this->load->library("Aauth"); +``` + +That was easy! + +Now let's create two new users, `Frodo` and `Legolas`. + +```php +$this->aauth->create_user('frodo@example.com','frodopass','Frodo Baggins'); +$this->aauth->create_user('legolas@example.com','legolaspass','Legolas'); +``` + +We now we have two users. + +OK, now we can create two groups, `hobbits` and `elves`. +```php +$this->aauth->create_group('hobbits'); +$this->aauth->create_group('elves'); +``` + +Now, let's create a user with power, Gandalf (for our example, let's assume he was given the `id` of 12). +```php +$this->aauth->create_user('gandalf@example.com', 'gandalfpass', 'Gandalf the Gray'); +``` + +OK, now we have two groups and three users. + +Let's create two permissions `walk_unseen` and `immortality` + +```php +$this->aauth->create_perm('walk_unseen'); +$this->aauth->create_perm('immortality'); +``` + +Ok, now let's give accesses to our groups. The Hobbits seem to have ability to walk unseen, so we will assign that privilage to them. The Elves have imortality, so we will assign that privilage to them. +We will assign access with `allow_group()` function. + +```php +$this->aauth->allow_group('hobbits','walk_unseen'); +$this->aauth->allow_group('elves','immortality'); + + +$this->aauth->allow_group('hobbits','immortality'); +``` + +Wait a minute! Hobbits should not have `immortality`. We need to fix this, we can use `deny_group()` to remove the permission. + +```php +$this->aauth->deny_group('hobbits','immortality'); +``` + +Gandalf can also live forever. + +```php +$this->aauth->allow_user(12,'immortality'); +``` + +Ok now let's check if Hobbits have `immortality`. + +```php +if($this->aauth->is_group_allowed('hobbits','immortality')){ + echo "Hobbits are immortal"; +} else { + echo "Hobbits are NOT immortal"; +} +``` +Results: +``` +Hobbits are NOT immortal +``` + +Does Gandalf have the ability to live forever? + +```php +if($this->aauth->is_allowed(12,'immortality')){ + echo "Gandalf is immortal"; +} else { + echo "Gandalf is NOT immortal"; +} +``` +Results: +``` +Gandalf is immortal +``` + +Since we don't accually live in Middle Earth, we are not aware of actual immortality. Alas, we must delete the permission. + +```php +$this->aauth->delete_perm('immortality'); +``` +It is gone. + +#### Un-authenticated Users + +So, how about un-authenticated users? In Aauth they are part of the `public` group. Let's give them permissions to `travel`. +We will assume we already have a permission set up named `travel`. + +```php +$this->aauth->allow_group('public','travel'); +``` + +#### Admin Users +What about the Admin users? The `Admin` user and any member of the `Admin` group is a superuser who had access everthing, There is no need to grant additional permissions. + +#### User Parameters/Variables +For each user, variables can be defined as individual key/value pairs. + +```php +$this->aauth->set_user_var("key","value"); +``` + +For example, if you want to store a user's phone number. +```php +$this->aauth->set_user_var("phone","1-507-555-1234"); +``` + +To retreive value you will use `get_user_var()`: +```php +$this->aauth->get_user_var("key"); +``` + +Aauth also permits you to define System Variables. These can be which can be accesed by all users in the system. +```php +$this->aauth->set_system_var("key","value"); +$this->aauth->get_system_var("key"); +``` + +#### Private Messages +OK, let's look at private messages. Frodo (`id` = 3) will send a PM to Legolas (`id` = 4); + +```php +$this->aauth->send_pm(3,4,'New cloaks','These new cloaks are fantastic!') +``` + +#### Banning users + +Frodo has broke the rules and will now need to be banned from the system. +```php +$this->aauth->ban_user(3); +``` diff --git a/application/language/english/aauth_lang.php b/language/english/aauth_lang.php similarity index 76% rename from application/language/english/aauth_lang.php rename to language/english/aauth_lang.php index 6086fc9..672e7f9 100644 --- a/application/language/english/aauth_lang.php +++ b/language/english/aauth_lang.php @@ -5,11 +5,11 @@ // Account verification $lang['aauth_email_verification_subject'] = 'Account Verification'; $lang['aauth_email_verification_code'] = 'Your verification code is: '; -$lang['aauth_email_verification_text'] = " You can also click on (or copy and paste) the following link\n\n"; +$lang['aauth_email_verification_text'] = ' You can also click on (or copy and paste) the following link\n\n'; // Password reset $lang['aauth_email_reset_subject'] = 'Reset Password'; -$lang['aauth_email_reset_text'] = "To reset your password click on (or copy and paste in your browser address bar) the link below:\n\n"; +$lang['aauth_email_reset_text'] = 'To reset your password click on (or copy and paste in your browser address bar) the link below:\n\n'; // Password reset success $lang['aauth_email_reset_success_subject'] = 'Successful Pasword Reset'; @@ -20,25 +20,25 @@ $lang['aauth_email_reset_success_new_password'] = 'Your password has successfull // Account creation errors $lang['aauth_error_email_exists'] = 'Email address already exists on the system. If you forgot your password, you can click the link below.'; -$lang['aauth_error_username_exists'] = "Account already exists on the system with that username. Please enter a different username, or if you forgot your password, please click the link below."; +$lang['aauth_error_username_exists'] = 'Account already exists on the system with that username. Please enter a different username, or if you forgot your password, please click the link below.'; $lang['aauth_error_email_invalid'] = 'Invalid e-mail address'; $lang['aauth_error_password_invalid'] = 'Invalid password'; $lang['aauth_error_username_invalid'] = 'Invalid Username'; $lang['aauth_error_username_required'] = 'Username required'; -$lang['aauth_error_totp_code_required'] = 'Authentication Code required'; -$lang['aauth_error_totp_code_invalid'] = 'Invalid Authentication Code'; +$lang['aauth_error_totp_code_required'] = 'TOTP Code required'; +$lang['aauth_error_totp_code_invalid'] = 'Invalid TOTP Code'; // Account update errors $lang['aauth_error_update_email_exists'] = 'Email address already exists on the system. Please enter a different email address.'; -$lang['aauth_error_update_username_exists'] = "Username already exists on the system. Please enter a different username."; +$lang['aauth_error_update_username_exists'] = 'Username already exists on the system. Please enter a different username.'; // Access errors $lang['aauth_error_no_access'] = 'Sorry, you do not have access to the resource you requested.'; $lang['aauth_error_login_failed_email'] = 'E-mail Address and Password do not match.'; $lang['aauth_error_login_failed_name'] = 'Username and Password do not match.'; -$lang['aauth_error_login_failed_all'] = 'E-mail, Username or Password do not match.'; +$lang['aauth_error_login_failed_banned'] = 'Your account is banned, contact the Page Admin.'; $lang['aauth_error_login_attempts_exceeded'] = 'You have exceeded your login attempts, your account has now been locked.'; $lang['aauth_error_recaptcha_not_correct'] = 'Sorry, the reCAPTCHA text entered was incorrect.'; @@ -46,13 +46,11 @@ $lang['aauth_error_recaptcha_not_correct'] = 'Sorry, the reCAPTCHA text entered $lang['aauth_error_no_user'] = 'User does not exist'; $lang['aauth_error_account_not_verified'] = 'Your account has not been verified. Please check your e-mail and verify your account.'; $lang['aauth_error_no_group'] = 'Group does not exist'; -$lang['aauth_error_no_subgroup'] = 'Subgroup does not exist'; $lang['aauth_error_self_pm'] = 'It is not possible to send a Message to yourself.'; $lang['aauth_error_no_pm'] = 'Private Message not found'; /* Info messages */ $lang['aauth_info_already_member'] = 'User is already member of group'; -$lang['aauth_info_already_subgroup'] = 'Subgroup is already member of group'; $lang['aauth_info_group_exists'] = 'Group name already exists'; $lang['aauth_info_perm_exists'] = 'Permission name already exists'; diff --git a/libraries/Aauth.php b/libraries/Aauth.php new file mode 100644 index 0000000..555f811 --- /dev/null +++ b/libraries/Aauth.php @@ -0,0 +1,16 @@ +CII = &get_instance(); + + $this->CII->load->library('aauth_init'); + $this->CII->aauth_init->version('v'.$this->version); + } +} diff --git a/libraries/Aauth_init.php b/libraries/Aauth_init.php new file mode 100644 index 0000000..7d866e5 --- /dev/null +++ b/libraries/Aauth_init.php @@ -0,0 +1,123 @@ + $val) + { + $key = str_replace('aauthinit', '', $key); + $this->{$key} = $val; + } + + $this->_regex = '/^(\w+)_v(\d{1})\.(\d{2})$/';'' !== $this->_path OR $this->_path = APPPATH.'libraries/Aauth_init/'; + $this->_path = rtrim($this->_path, '/').'/'; + $this->CII = &get_instance(); + $this->CII->config->load('aauth'); + $this->config_vars = $this->CII->config->item('aauth'); + $this->aauth_db = $this->CII->load->database($this->config_vars['database']['_profile'], TRUE); + $this->aauth_db_forge = $this->CII->load->dbforge($this->aauth_db, TRUE); + + if ( ! $this->aauth_db->table_exists($this->_table)) + { + $this->aauth_db_forge->add_field(array( + 'version' => array('type' => 'VARCHAR', 'constraint' => 20), + )); + + $this->aauth_db_forge->create_table($this->_table, TRUE); + $this->aauth_db->insert($this->_table, array('version' => 0)); + } + } + + public function version($target_version) + { + $current_version = $this->_get_version(); + $target_version = (string) $target_version; + $updates = $this->find_updates(); + $previous = FALSE; + + if ($current_version == 0) + { + $method = 'install'; + } + else if ($target_version > $current_version) + { + $method = 'update'; + } + foreach ($updates as $number => $file) + { + include_once $file; + $class = 'Aauth_v'.str_replace('.', '', $number); + $previous = $number; + + if ( + ($method === 'install' && $number > $current_version && $number <= $target_version) OR + ($method === 'update' && $number > $current_version && $number <= $target_version) + ) + { + $instance = new $class(); + + if (is_callable(array($instance, $method))) + { + call_user_func(array($instance, $method)); + $current_version = $number; + $this->_update_version($current_version); + } + } + } + if ($current_version !== $target_version) + { + $current_version = $target_version; + $this->_update_version($current_version); + } + + return $current_version; + } + + public function find_updates() + { + $updates = array(); + + foreach (glob($this->_path.'*_v*.php') as $file) + { + $name = basename($file, '.php'); + + if (preg_match($this->_regex, $name)) + { + $number = $this->_get_number($name); + $updates[$number] = $file; + } + } + + ksort($updates); + return $updates; + } + + protected function _get_number($update) + { + return str_replace('Aauth_v', '', $update); + } + + protected function _get_version() + { + $row = $this->aauth_db->select('version')->get($this->_table)->row(); + return $row->version; + } + + protected function _update_version($update) + { + $update = str_replace('v', '', $update); + $this->aauth_db->update($this->_table, array( + 'version' => $update, + )); + } +} \ No newline at end of file diff --git a/libraries/Aauth_init/Aauth_v3.00.php b/libraries/Aauth_init/Aauth_v3.00.php new file mode 100644 index 0000000..96a37b8 --- /dev/null +++ b/libraries/Aauth_init/Aauth_v3.00.php @@ -0,0 +1,219 @@ +CII = &get_instance(); + $this->config_vars = $this->CII->config->item('aauth'); + $this->CII->aauth_db = $this->CII->load->database($this->config_vars['database']['_profile'], TRUE); + $this->CII->aauth_db_forge = $this->CII->load->dbforge($this->CII->aauth_db, TRUE); + } + + public function install() + { + // Users TABLE + $this->CII->aauth_db_forge->add_field(array( + 'id' => array( + 'type' => 'INT', + 'constraint' => 11, + 'unsigned' => TRUE, + 'auto_increment' => TRUE, + ), + 'email' => array( + 'type' => 'VARCHAR', + 'constraint' => '254', + ), + 'username' => array( + 'type' => 'VARCHAR', + 'constraint' => '150', + 'null' => TRUE, + ), + 'password' => array( + 'type' => 'VARCHAR', + 'constraint' => '60', + ), + 'banned' => array( + 'type' => 'TINYINT', + 'constraint' => '1', + 'null' => TRUE, + 'default' => '0', + ), + 'created_since' => array( + 'type' => 'DATETIME', + 'default' => NULL, + ), + 'last_ip_address' => array( + 'type' => 'VARCHAR', + 'constraint' => '39', + 'default' => '', + ), + 'last_login' => array( + 'type' => 'DATETIME', + 'default' => NULL, + ), + 'last_activity' => array( + 'type' => 'DATETIME', + 'default' => NULL, + ), + )); + $this->CII->aauth_db_forge->add_key('id', TRUE); + $this->CII->aauth_db_forge->create_table($this->config_vars['database']['users'], FALSE, array('ENGINE' => 'InnoDB')); + + // Login Attempts TABLE + $this->CII->aauth_db_forge->add_field(array( + 'id' => array( + 'type' => 'INT', + 'constraint' => 11, + 'unsigned' => TRUE, + 'auto_increment' => TRUE, + ), + 'ip_address' => array( + 'type' => 'VARCHAR', + 'constraint' => '39', + 'default' => '0', + ), + 'timestamp' => array( + 'type' => 'DATETIME', + 'default' => NULL, + ), + 'login_attempts' => array( + 'type' => 'TINYINT', + 'constraint' => '2', + 'default' => '0', + ), + + )); + $this->CII->aauth_db_forge->add_key('id', TRUE); + $this->CII->aauth_db_forge->create_table($this->config_vars['database']['login_attempts'], FALSE, array('ENGINE' => 'InnoDB')); + + // User Variables TABLE + $this->CII->aauth_db_forge->add_field(array( + 'id' => array( + 'type' => 'INT', + 'constraint' => 11, + 'unsigned' => TRUE, + 'auto_increment' => TRUE, + ), + 'user_id' => array( + 'type' => 'INT', + 'constraint' => 11, + 'unsigned' => TRUE, + ), + 'data_key' => array( + 'type' => 'VARCHAR', + 'constraint' => '100', + ), + 'data_value' => array( + 'type' => 'text', + ), + )); + $this->CII->aauth_db_forge->add_key('id', TRUE); + $this->CII->aauth_db_forge->add_key('user_id'); + $this->CII->aauth_db_forge->create_table($this->config_vars['database']['user_variables'], FALSE, array('ENGINE' => 'InnoDB')); + + // Groups TABLE + $this->CII->aauth_db_forge->add_field(array( + 'id' => array( + 'type' => 'INT', + 'constraint' => 11, + 'unsigned' => TRUE, + 'auto_increment' => TRUE, + ), + 'name' => array( + 'type' => 'VARCHAR', + 'constraint' => '100', + ), + 'definition' => array( + 'type' => 'TEXT', + ), + )); + $this->CII->aauth_db_forge->add_key('id', TRUE); + $this->CII->aauth_db_forge->create_table($this->config_vars['database']['groups'], FALSE, array('ENGINE' => 'InnoDB')); + + // Group To User TABLE + $this->CII->aauth_db_forge->add_field(array( + 'group_id' => array( + 'type' => 'INT', + 'constraint' => 11, + 'unsigned' => TRUE, + ), + 'user_id' => array( + 'type' => 'INT', + 'constraint' => 11, + 'unsigned' => TRUE, + ), + )); + $this->CII->aauth_db_forge->add_key(array('group_id','user_id'), TRUE); + $this->CII->aauth_db_forge->create_table($this->config_vars['database']['group_to_user'], FALSE, array('ENGINE' => 'InnoDB')); + + // Group To SubGroup TABLE + $this->CII->aauth_db_forge->add_field(array( + 'group_id' => array( + 'type' => 'INT', + 'constraint' => 11, + 'unsigned' => TRUE, + ), + 'subgroup_id' => array( + 'type' => 'INT', + 'constraint' => 11, + 'unsigned' => TRUE, + ), + )); + $this->CII->aauth_db_forge->add_key(array('group_id','subgroup_id'), TRUE); + $this->CII->aauth_db_forge->create_table($this->config_vars['database']['group_to_subgroup'], FALSE, array('ENGINE' => 'InnoDB')); + + // Permissions TABLE + $this->CII->aauth_db_forge->add_field(array( + 'id' => array( + 'type' => 'INT', + 'constraint' => 11, + 'unsigned' => TRUE, + 'auto_increment' => TRUE, + ), + 'name' => array( + 'type' => 'VARCHAR', + 'constraint' => '100', + ), + 'definition' => array( + 'type' => 'TEXT', + ), + )); + $this->CII->aauth_db_forge->add_key('id', TRUE); + $this->CII->aauth_db_forge->create_table($this->config_vars['database']['permissions'], FALSE, array('ENGINE' => 'InnoDB')); + + // Permission To User TABLE + $this->CII->aauth_db_forge->add_field(array( + 'permission_id' => array( + 'type' => 'INT', + 'constraint' => 11, + 'unsigned' => TRUE, + ), + 'user_id' => array( + 'type' => 'INT', + 'constraint' => 11, + 'unsigned' => TRUE, + ), + )); + $this->CII->aauth_db_forge->add_key(array('permission_id','user_id'), TRUE); + $this->CII->aauth_db_forge->create_table($this->config_vars['database']['permission_to_user'], FALSE, array('ENGINE' => 'InnoDB')); + + // Permission To Group TABLE + $this->CII->aauth_db_forge->add_field(array( + 'permission_id' => array( + 'type' => 'INT', + 'constraint' => 11, + 'unsigned' => TRUE, + ), + 'group_id' => array( + 'type' => 'INT', + 'constraint' => 11, + 'unsigned' => TRUE, + ), + )); + $this->CII->aauth_db_forge->add_key(array('permission_id','group_id'), TRUE); + $this->CII->aauth_db_forge->create_table($this->config_vars['database']['permission_to_group'], FALSE, array('ENGINE' => 'InnoDB')); + + } + +} diff --git a/models/aauth/Group_to_subgroup_model.php b/models/aauth/Group_to_subgroup_model.php new file mode 100644 index 0000000..0bed248 --- /dev/null +++ b/models/aauth/Group_to_subgroup_model.php @@ -0,0 +1,77 @@ +cii = &get_instance(); + $this->cii->config->load('aauth'); + $this->cii->load->model('aauth/Groups_model', 'groups'); + $this->config_vars = $this->cii->config->item('aauth'); + } + + public function create($group_id, $subgroup_id) + { + if ($this->cii->groups->get_id($group_id) && $this->cii->groups->get_id($subgroup_id) && ! $this->exist($group_id, $subgroup_id) && $group_id != $subgroup_id) + { + $data['group_id'] = $group_id; + $data['subgroup_id'] = $subgroup_id; + return $this->db->insert($this->config_vars['database']['group_to_subgroup'], $data); + } + + return FALSE; + } + + public function delete($group_id, $subgroup_id) + { + $this->db->where('group_id', $group_id); + $this->db->where('subgroup_id', $subgroup_id); + return $this->db->delete($this->config_vars['database']['group_to_subgroup']); + } + + public function delete_by_subgroup($subgroup_id) + { + if ($this->cii->groups->get_id($subgroup_id)) + { + $this->db->where('subgroup_id', $subgroup_id); + return $this->db->delete($this->config_vars['database']['group_to_subgroup']); + } + + return FALSE; + } + + public function delete_by_group($group_id) + { + if ($this->cii->groups->get_id($group_id)) + { + $this->db->where('group_id', $group_id); + return $this->db->delete($this->config_vars['database']['group_to_subgroup']); + } + + return FALSE; + } + + public function exist($group_id, $subgroup_id) + { + if ($this->cii->groups->get_id($group_id) && $this->cii->groups->get_id($subgroup_id)) + { + $this->db->where('group_id', $group_id); + $this->db->where('subgroup_id', $subgroup_id); + $query = $this->db->get($this->config_vars['database']['group_to_subgroup']); + + if ($query->num_rows() === 1) + { + return TRUE; + } + + return FALSE; + } + + return FALSE; + } +} diff --git a/models/aauth/Group_to_user_model.php b/models/aauth/Group_to_user_model.php new file mode 100644 index 0000000..4cd9d55 --- /dev/null +++ b/models/aauth/Group_to_user_model.php @@ -0,0 +1,78 @@ +cii = &get_instance(); + $this->cii->config->load('aauth'); + $this->cii->load->model('aauth/Users_model', 'users'); + $this->cii->load->model('aauth/Groups_model', 'groups'); + $this->config_vars = $this->cii->config->item('aauth'); + } + + public function create($group_id, $user_id) + { + if ($this->cii->groups->get_id($group_id) && $this->cii->users->exist_by_(array('id' => $user_id)) && ! $this->exist($group_id, $user_id)) + { + $data['group_id'] = $group_id; + $data['user_id'] = $user_id; + return $this->db->insert($this->config_vars['database']['group_to_user'], $data); + } + + return FALSE; + } + + public function delete($group_id, $user_id) + { + $this->db->where('group_id', $group_id); + $this->db->where('user_id', $user_id); + return $this->db->delete($this->config_vars['database']['group_to_user']); + } + + public function delete_by_user($user_id) + { + if ($this->cii->users->exist_by_(array('id' => $user_id))) + { + $this->db->where('user_id', $user_id); + return $this->db->delete($this->config_vars['database']['group_to_user']); + } + + return FALSE; + } + + public function delete_by_group($group_id) + { + if ($this->cii->groups->get_id($group_id)) + { + $this->db->where('group_id', $group_id); + return $this->db->delete($this->config_vars['database']['group_to_user']); + } + + return FALSE; + } + + public function exist($group_id, $user_id) + { + if ($this->cii->groups->get_id($group_id) && $this->cii->users->exist_by_(array('id' => $user_id))) + { + $this->db->where('group_id', $group_id); + $this->db->where('user_id', $user_id); + $query = $this->db->get($this->config_vars['database']['group_to_user']); + + if ($query->num_rows() === 1) + { + return TRUE; + } + + return FALSE; + } + + return FALSE; + } +} diff --git a/models/aauth/Groups_model.php b/models/aauth/Groups_model.php new file mode 100644 index 0000000..f5d74ed --- /dev/null +++ b/models/aauth/Groups_model.php @@ -0,0 +1,111 @@ +cii = &get_instance(); + $this->cii->config->load('aauth'); + $this->config_vars = $this->cii->config->item('aauth'); + } + + public function create($name, $definition = '') + { + if ($name && ! $this->get_id($name)) + { + $data['name'] = $name; + $data['definition'] = $definition; + $this->db->insert($this->config_vars['database']['groups'], $data); + return $this->db->insert_id(); + } + + return FALSE; + } + + public function update($group_id, $name = NULL, $definition = NULL) + { + $group_id = $this->get_id($group_id); + + if ($group_id) + { + if ($name) + { + $data['name'] = $name; + } + if ($definition) + { + $data['definition'] = $definition; + } + + $this->db->where('id', $group_id); + return $this->db->update($this->config_vars['database']['groups'], $data); + } + + return FALSE; + } + + public function delete($group_id) + { + $this->cii->load->model('aauth/Group_to_subgroup_model', 'group_to_subgroup'); + $this->cii->load->model('aauth/Group_to_user_model', 'group_to_user'); + + $this->cii->group_to_user->delete_by_group($group_id); + $this->cii->group_to_subgroup->delete_by_group($group_id); + //DELETE PERM_TO_GROUP + $this->db->where('id', $group_id); + return $this->db->delete($this->config_vars['database']['groups']); + } + + public function get($group_id) + { + $query = $this->_get(array('id' => $group_id)); + + if ($query->num_rows() === 1) + { + return $query->row(); + } + + return FALSE; + } + + public function get_id($name) + { + if (is_numeric($name)) + { + $query = $this->_get(array('id' => $name)); + } + else if ( ! is_numeric($name)) + { + $query = $this->_get(array('name' => $name)); + } + if ($query->num_rows() === 1) + { + return $query->row()->id; + } + + return FALSE; + } + + public function get_all() + { + $query = $this->_get(); + + if ($query->num_rows() !== 0) + { + return $query->result(); + } + + return FALSE; + } + + private function _get($where = array()) + { + $this->db->where($where); + return $this->db->get($this->config_vars['database']['groups']); + } +} diff --git a/models/aauth/Login_attempts_model.php b/models/aauth/Login_attempts_model.php new file mode 100644 index 0000000..74210eb --- /dev/null +++ b/models/aauth/Login_attempts_model.php @@ -0,0 +1,74 @@ +cii = &get_instance(); + $this->cii->config->load('aauth'); + $this->config_vars = $this->cii->config->item('aauth'); + } + + public function get() + { + $query = $this->_get(); + + if ($query->num_rows() === 1) + { + return $query->row()->login_attempts; + } + + return 0; + } + + public function update() + { + $query = $this->_get(); + + if ($query->num_rows() === 1) + { + $row = $query->row(); + $data['timestamp'] = date('Y-m-d H:i:s'); + $data['login_attempts'] = $row->login_attempts + 1; + $this->db->update($this->config_vars['database']['login_attempts'], $data, array('id' => $row->id)); + + if ($data['login_attempts'] > $this->config_vars['ddos_protection']['max_attempts']) + { + return FALSE; + } + + return TRUE; + } + + return $this->_create(); + } + + public function delete() + { + $data['ip_address'] = $this->cii->input->ip_address(); + $data['timestamp >='] = date('Y-m-d H:i:s', strtotime('-'.$this->config_vars['ddos_protection']['time_period'])); + $this->db->where($data); + return $this->db->delete($this->config_vars['database']['login_attempts']); + } + + private function _create() + { + $data['ip_address'] = $this->cii->input->ip_address(); + $data['timestamp'] = date('Y-m-d H:i:s'); + $data['login_attempts'] = 1; + return $this->db->insert($this->config_vars['database']['login_attempts'], $data); + } + + private function _get() + { + $data['ip_address'] = $this->cii->input->ip_address(); + $data['timestamp >='] = date('Y-m-d H:i:s', strtotime('-'.$this->config_vars['ddos_protection']['time_period'])); + $this->db->where($data); + return $this->db->get($this->config_vars['database']['login_attempts']); + } +} diff --git a/models/aauth/Permission_to_group_model.php b/models/aauth/Permission_to_group_model.php new file mode 100644 index 0000000..6e11dfa --- /dev/null +++ b/models/aauth/Permission_to_group_model.php @@ -0,0 +1,78 @@ +cii = &get_instance(); + $this->cii->config->load('aauth'); + $this->cii->load->model('aauth/Groups_model', 'groups'); + $this->cii->load->model('aauth/Permissions_model', 'permissions'); + $this->config_vars = $this->cii->config->item('aauth'); + } + + public function create($permission_id, $group_id) + { + if ($this->cii->permissions->get_id($permission_id) && $this->cii->groups->get_id($group_id) && ! $this->exist($permission_id, $group_id)) + { + $data['permission_id'] = $permission_id; + $data['group_id'] = $group_id; + return $this->db->insert($this->config_vars['database']['permission_to_group'], $data); + } + + return FALSE; + } + + public function delete($permission_id, $group_id) + { + $this->db->where('permission_id', $permission_id); + $this->db->where('group_id', $group_id); + return $this->db->delete($this->config_vars['database']['permission_to_group']); + } + + public function delete_by_group($group_id) + { + if ($this->cii->groups->get_id($group_id)) + { + $this->db->where('group_id', $group_id); + return $this->db->delete($this->config_vars['database']['permission_to_group']); + } + + return FALSE; + } + + public function delete_by_permission($permission_id) + { + if ($this->cii->permissions->get_id($permission_id)) + { + $this->db->where('permission_id', $permission_id); + return $this->db->delete($this->config_vars['database']['permission_to_group']); + } + + return FALSE; + } + + public function exist($permission_id, $group_id) + { + if ($this->cii->permissions->get_id($permission_id) && $this->cii->groups->get_id($group_id)) + { + $this->db->where('permission_id', $permission_id); + $this->db->where('group_id', $group_id); + $query = $this->db->get($this->config_vars['database']['permission_to_group']); + + if ($query->num_rows() === 1) + { + return TRUE; + } + + return FALSE; + } + + return FALSE; + } +} diff --git a/models/aauth/Permission_to_user_model.php b/models/aauth/Permission_to_user_model.php new file mode 100644 index 0000000..eef264b --- /dev/null +++ b/models/aauth/Permission_to_user_model.php @@ -0,0 +1,78 @@ +cii = &get_instance(); + $this->cii->config->load('aauth'); + $this->cii->load->model('aauth/Users_model', 'users'); + $this->cii->load->model('aauth/Permissions_model', 'permissions'); + $this->config_vars = $this->cii->config->item('aauth'); + } + + public function create($permission_id, $user_id) + { + if ($this->cii->permissions->get_id($permission_id) && $this->cii->users->exist_by_(array('id' => $user_id)) && ! $this->exist($permission_id, $user_id)) + { + $data['permission_id'] = $permission_id; + $data['user_id'] = $user_id; + return $this->db->insert($this->config_vars['database']['permission_to_user'], $data); + } + + return FALSE; + } + + public function delete($permission_id, $user_id) + { + $this->db->where('permission_id', $permission_id); + $this->db->where('user_id', $user_id); + return $this->db->delete($this->config_vars['database']['permission_to_user']); + } + + public function delete_by_user($user_id) + { + if ($this->cii->users->exist_by_(array('id' => $user_id))) + { + $this->db->where('user_id', $user_id); + return $this->db->delete($this->config_vars['database']['permission_to_user']); + } + + return FALSE; + } + + public function delete_by_permission($permission_id) + { + if ($this->cii->permissions->get_id($permission_id)) + { + $this->db->where('permission_id', $permission_id); + return $this->db->delete($this->config_vars['database']['permission_to_user']); + } + + return FALSE; + } + + public function exist($permission_id, $user_id) + { + if ($this->cii->permissions->get_id($permission_id) && $this->cii->users->exist_by_(array('id' => $user_id))) + { + $this->db->where('permission_id', $permission_id); + $this->db->where('user_id', $user_id); + $query = $this->db->get($this->config_vars['database']['permission_to_user']); + + if ($query->num_rows() === 1) + { + return TRUE; + } + + return FALSE; + } + + return FALSE; + } +} diff --git a/models/aauth/Permissions_model.php b/models/aauth/Permissions_model.php new file mode 100644 index 0000000..4ad2a26 --- /dev/null +++ b/models/aauth/Permissions_model.php @@ -0,0 +1,107 @@ +cii = &get_instance(); + $this->cii->config->load('aauth'); + $this->config_vars = $this->cii->config->item('aauth'); + } + + public function create($name, $definition = '') + { + if ($name && ! $this->get_id($name)) + { + $data['name'] = $name; + $data['definition'] = $definition; + $this->db->insert($this->config_vars['database']['permissions'], $data); + return $this->db->insert_id(); + } + + return FALSE; + } + + public function update($permission_id, $name = NULL, $definition = NULL) + { + $permission_id = $this->get_id($permission_id); + + if ($permission_id) + { + if ($name) + { + $data['name'] = $name; + } + if ($definition) + { + $data['definition'] = $definition; + } + + $this->db->where('id', $permission_id); + return $this->db->update($this->config_vars['database']['permissions'], $data); + } + + return FALSE; + } + + public function delete($permission_id) + { + //DELETE PERM_TO_USER + //DELETE PERM_TO_GROUP + $this->db->where('id', $permission_id); + return $this->db->delete($this->config_vars['database']['permissions']); + } + + public function get($permission_id) + { + $query = $this->_get(array('id' => $permission_id)); + + if ($query->num_rows() === 1) + { + return $query->row(); + } + + return FALSE; + } + + public function get_id($name) + { + if (is_numeric($name)) + { + $query = $this->_get(array('id' => $name)); + } + else if ( ! is_numeric($name)) + { + $query = $this->_get(array('name' => $name)); + } + if ($query->num_rows() === 1) + { + return $query->row()->id; + } + + return FALSE; + } + + public function get_all() + { + $query = $this->_get(); + + if ($query->num_rows() !== 0) + { + return $query->result(); + } + + return FALSE; + } + + private function _get($where = array()) + { + $this->db->where($where); + return $this->db->get($this->config_vars['database']['permissions']); + } +} \ No newline at end of file diff --git a/models/aauth/User_variables_model.php b/models/aauth/User_variables_model.php new file mode 100644 index 0000000..63cdc3a --- /dev/null +++ b/models/aauth/User_variables_model.php @@ -0,0 +1,93 @@ +cii = &get_instance(); + $this->cii->config->load('aauth'); + $this->cii->load->model('aauth/Users_model', 'users'); + $this->config_vars = $this->cii->config->item('aauth'); + } + + public function update($user_id, $key, $value) + { + if ($this->cii->users->exist_by_(array('id' => $user_id))) + { + $data['data_value'] = $value; + + if ($this->_exist($user_id, $key)) + { + $this->db->where('data_key', $key); + $this->db->where('user_id', $user_id); + return $this->db->update($this->config_vars['database']['user_variables'], $data); + } + + $data['data_key'] = $key; + $data['user_id'] = $user_id; + return $this->db->insert($this->config_vars['database']['user_variables'], $data); + } + + return FALSE; + } + + public function get($user_id, $key) + { + if ($this->cii->users->exist_by_(array('id' => $user_id)) && $this->_exist($user_id, $key)) + { + $query = $this->_get($user_id, $key); + return $query->row()->data_value; + } + + return FALSE; + } + + public function get_by_user_id($user_id) + { + if ($this->cii->users->exist_by_(array('id' => $user_id))) + { + return $this->_get($user_id)->result(); + } + + return FALSE; + } + + public function delete($user_id, $key = NULL) + { + if ($key) + { + $this->db->where('data_key', $key); + } + + $this->db->where('user_id', $user_id); + return $this->db->delete($this->config_vars['database']['user_variables']); + } + + private function _exist($user_id, $key) + { + if ($this->_get($user_id, $key)->num_rows() === 1) + { + return TRUE; + } + + return FALSE; + } + + private function _get($user_id, $key = NULL) + { + if ($key) + { + $where['data_key'] = $key; + } + + $where['user_id'] = $user_id; + $this->db->select('data_key, data_value'); + $this->db->where($where); + return $this->db->get($this->config_vars['database']['user_variables']); + } +} diff --git a/models/aauth/Users_model.php b/models/aauth/Users_model.php new file mode 100644 index 0000000..f7bc751 --- /dev/null +++ b/models/aauth/Users_model.php @@ -0,0 +1,207 @@ +cii = &get_instance(); + $this->cii->config->load('aauth'); + $this->cii->load->model('aauth/User_variables_model', 'user_variables'); + $this->cii->load->model('aauth/Group_to_user_model', 'group_to_user'); + $this->config_vars = $this->cii->config->item('aauth'); + } + + public function create($email, $pass, $username = '') + { + if (filter_var($email, FILTER_VALIDATE_EMAIL) && ! $this->exist_by_(array('email' => $email)) && ( ! empty($username) && ! $this->exist_by_(array('username' => $username)))) + { + $data = array(); + $data['email'] = $email; + $data['username'] = $username; + $data['password'] = password_hash($pass, $this->config_vars['password']['hash_algo'], $this->config_vars['password']['hash_options']); + $data['created_since'] = date('Y-m-d H:i:s'); + $this->db->insert($this->config_vars['database']['users'], $data); + + return $this->db->insert_id(); + } + + return FALSE; + } + + public function update($user_id, $data = array()) + { + if ($this->exist_by_(array('id' => $user_id))) + { + return $this->db->update($this->config_vars['database']['users'], $data, array('id' => $user_id)); + } + + return FALSE; + } + + public function delete($user_id) + { + $this->cii->user_variables->delete($user_id); + $this->cii->group_to_user->delete_by_user($user_id); + return $this->db->delete($this->config_vars['database']['users'], array('id' => $user_id)); + } + + public function get_all($options = array()) + { + $filters = array(); + $args = array(); + $filters['banned'] = '0'; + + if (isset($options['filters'])) + { + $filters = $options['filters']; + } + if (isset($options['include_banneds']) && $options['include_banneds']) + { + unset($filters['banned']); + } + if (isset($options['only_banneds']) && $options['only_banneds']) + { + $filters['banned'] = '1'; + } + if (isset($options['offset'])) + { + $args['offset'] = $options['offset']; + } + if (isset($options['limit'])) + { + $args['limit'] = $options['limit']; + } + + $query = $this->get_by_($filters, $args); + return $query->result(); + } + + public function ban($user_id, $ver_code = NULL) + { + if ($this->exist_by_(array('id' => $user_id))) + { + if ($ver_code) + { + $this->cii->user_variables->update($user_id, 'verification_code', $ver_code); + } + + $data['banned'] = '1'; + return $this->update($user_id, $data); + } + + return FALSE; + } + + public function unban($user_id, $ver_code = NULL) + { + if ($this->exist_by_(array('id' => $user_id)) && $this->is_($user_id, 'banned')) + { + if ( ! $this->is_($user_id, 'verified')) + { + if ($this->cii->user_variables->get($user_id, 'verification_code') !== $ver_code) + { + return FALSE; + } + + $this->cii->user_variables->delete($user_id, 'verification_code'); + } + + return $this->update($user_id, array('banned' => '0')); + } + + return FALSE; + } + + public function update_($user_id, $type) + { + if ($this->exist_by_(array('id' => $user_id))) + { + if ($type === 'activity') + { + $data['last_activity'] = date('Y-m-d H:i:s'); + } + else if ($type === 'last_login') + { + $data['last_login'] = date('Y-m-d H:i:s'); + $data['last_ip_address'] = $this->input->ip_address(); + } + + return $this->update($user_id, $data); + } + + return FALSE; + } + + public function exist_by_($filters = array()) + { + if ($this->get_by_($filters)->num_rows() === 1) + { + return TRUE; + } + + return FALSE; + } + + public function get_($filters, $result_column) + { + $query = $this->get_by_($filters, array('select' => $result_column)); + + if ($query->num_rows() === 1) + { + return $query->row($result_column); + } + + return FALSE; + } + + public function get_by_($filters, $options = NULL) + { + if ($filters) + { + foreach ($filters as $column => $value) + { + $this->db->where($column, $value); + } + } + if (isset($options['limit'])) + { + $this->db->limit($options['limit']); + } + if (isset($options['offset'])) + { + $this->db->offset($options['offset']); + } + if (isset($options['select'])) + { + $this->db->select($options['select']); + } + + return $this->db->get($this->config_vars['database']['users']); + } + + public function is_($user_id, $type) + { + if ($this->exist_by_(array('id' => $user_id))) + { + $data['banned'] = '1'; + $data['id'] = $user_id; + $query = $this->get_by_($data); + + if ($type === 'banned' && $query->num_rows() === 1) + { + return TRUE; + } + else if ($type === 'verified' && ! $this->cii->user_variables->get($user_id, 'verification_code')) + { + return TRUE; + } + } + + return FALSE; + } +} diff --git a/sql/Aauth_v2.sql b/sql/Aauth_v2.sql deleted file mode 100644 index 360c646..0000000 --- a/sql/Aauth_v2.sql +++ /dev/null @@ -1,178 +0,0 @@ -/* - Aauth SQL Table Structure -*/ - -SET FOREIGN_KEY_CHECKS=0; - --- ---------------------------- --- Table structure for `aauth_groups` --- ---------------------------- -DROP TABLE IF EXISTS `aauth_groups`; -CREATE TABLE `aauth_groups` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(100), - `definition` text, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of aauth_groups --- ---------------------------- -INSERT INTO `aauth_groups` VALUES ('1', 'Admin', 'Super Admin Group'); -INSERT INTO `aauth_groups` VALUES ('2', 'Public', 'Public Access Group'); -INSERT INTO `aauth_groups` VALUES ('3', 'Default', 'Default Access Group'); - --- ---------------------------- --- Table structure for `aauth_perms` --- ---------------------------- -DROP TABLE IF EXISTS `aauth_perms`; -CREATE TABLE `aauth_perms` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(100), - `definition` text, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of aauth_perms --- ---------------------------- - --- ---------------------------- --- Table structure for `aauth_perm_to_group` --- ---------------------------- -DROP TABLE IF EXISTS `aauth_perm_to_group`; -CREATE TABLE `aauth_perm_to_group` ( - `perm_id` int(11) unsigned NOT NULL, - `group_id` int(11) unsigned NOT NULL, - PRIMARY KEY (`perm_id`,`group_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of aauth_perm_to_group --- ---------------------------- - --- ---------------------------- --- Table structure for `aauth_perm_to_user` --- ---------------------------- -DROP TABLE IF EXISTS `aauth_perm_to_user`; -CREATE TABLE `aauth_perm_to_user` ( - `perm_id` int(11) unsigned NOT NULL, - `user_id` int(11) unsigned NOT NULL, - PRIMARY KEY (`perm_id`,`user_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of aauth_perm_to_user --- ---------------------------- - --- ---------------------------- --- Table structure for `aauth_pms` --- ---------------------------- -DROP TABLE IF EXISTS `aauth_pms`; -CREATE TABLE `aauth_pms` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `sender_id` int(11) unsigned NOT NULL, - `receiver_id` int(11) unsigned NOT NULL, - `title` varchar(255) NOT NULL, - `message` text, - `date_sent` datetime DEFAULT NULL, - `date_read` datetime DEFAULT NULL, - `pm_deleted_sender` int(1) DEFAULT NULL, - `pm_deleted_receiver` int(1) DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `full_index` (`id`,`sender_id`,`receiver_id`,`date_read`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of aauth_pms --- ---------------------------- - --- ---------------------------- --- Table structure for `aauth_users` --- ---------------------------- -DROP TABLE IF EXISTS `aauth_users`; -CREATE TABLE `aauth_users` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `email` varchar(100) COLLATE utf8_general_ci NOT NULL, - `pass` varchar(64) COLLATE utf8_general_ci NOT NULL, - `username` varchar(100) COLLATE utf8_general_ci, - `banned` tinyint(1) DEFAULT '0', - `last_login` datetime DEFAULT NULL, - `last_activity` datetime DEFAULT NULL, - `date_created` datetime DEFAULT NULL, - `forgot_exp` text COLLATE utf8_general_ci, - `remember_time` datetime DEFAULT NULL, - `remember_exp` text COLLATE utf8_general_ci, - `verification_code` text COLLATE utf8_general_ci, - `totp_secret` varchar(16) COLLATE utf8_general_ci DEFAULT NULL, - `ip_address` text COLLATE utf8_general_ci, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci; - --- ---------------------------- --- Records of aauth_users --- ---------------------------- -INSERT INTO `aauth_users` VALUES ('1', 'admin@example.com', 'dd5073c93fb477a167fd69072e95455834acd93df8fed41a2c468c45b394bfe3', 'Admin', '0', null, null, null, null, null, null, null, null, '0'); - --- ---------------------------- --- Table structure for `aauth_user_to_group` --- ---------------------------- -DROP TABLE IF EXISTS `aauth_user_to_group`; -CREATE TABLE `aauth_user_to_group` ( - `user_id` int(11) unsigned NOT NULL, - `group_id` int(11) unsigned NOT NULL, - PRIMARY KEY (`user_id`,`group_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of aauth_user_to_group --- ---------------------------- -INSERT INTO `aauth_user_to_group` VALUES ('1', '1'); -INSERT INTO `aauth_user_to_group` VALUES ('1', '3'); - --- ---------------------------- --- Table structure for `aauth_user_variables` --- ---------------------------- -DROP TABLE IF EXISTS `aauth_user_variables`; -CREATE TABLE `aauth_user_variables` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `user_id` int(11) unsigned NOT NULL, - `data_key` varchar(100) NOT NULL, - `value` text, - PRIMARY KEY (`id`), - KEY `user_id_index` (`user_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of aauth_user_variables --- ---------------------------- - --- ---------------------------- --- Table structure for `aauth_group_to_group` --- ---------------------------- -DROP TABLE IF EXISTS `aauth_group_to_group`; -CREATE TABLE `aauth_group_to_group` ( - `group_id` int(11) unsigned NOT NULL, - `subgroup_id` int(11) unsigned NOT NULL, - PRIMARY KEY (`group_id`,`subgroup_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of aauth_group_to_group --- ---------------------------- - --- ---------------------------- --- Table structure for `aauth_login_attempts` --- ---------------------------- - -CREATE TABLE IF NOT EXISTS `aauth_login_attempts` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `ip_address` varchar(39) DEFAULT '0', - `timestamp` datetime DEFAULT NULL, - `login_attempts` tinyint(2) DEFAULT '0', - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=latin1; - --- ---------------------------- --- Records of aauth_login_attempts --- ---------------------------- diff --git a/sql/Aauth_v2_BCrypt.sql b/sql/Aauth_v2_BCrypt.sql deleted file mode 100644 index d47e5d2..0000000 --- a/sql/Aauth_v2_BCrypt.sql +++ /dev/null @@ -1,178 +0,0 @@ -/* - Aauth SQL Table Structure -*/ - -SET FOREIGN_KEY_CHECKS=0; - --- ---------------------------- --- Table structure for `aauth_groups` --- ---------------------------- -DROP TABLE IF EXISTS `aauth_groups`; -CREATE TABLE `aauth_groups` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(100), - `definition` text, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of aauth_groups --- ---------------------------- -INSERT INTO `aauth_groups` VALUES ('1', 'Admin', 'Super Admin Group'); -INSERT INTO `aauth_groups` VALUES ('2', 'Public', 'Public Access Group'); -INSERT INTO `aauth_groups` VALUES ('3', 'Default', 'Default Access Group'); - --- ---------------------------- --- Table structure for `aauth_perms` --- ---------------------------- -DROP TABLE IF EXISTS `aauth_perms`; -CREATE TABLE `aauth_perms` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(100), - `definition` text, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of aauth_perms --- ---------------------------- - --- ---------------------------- --- Table structure for `aauth_perm_to_group` --- ---------------------------- -DROP TABLE IF EXISTS `aauth_perm_to_group`; -CREATE TABLE `aauth_perm_to_group` ( - `perm_id` int(11) unsigned NOT NULL, - `group_id` int(11) unsigned NOT NULL, - PRIMARY KEY (`perm_id`,`group_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of aauth_perm_to_group --- ---------------------------- - --- ---------------------------- --- Table structure for `aauth_perm_to_user` --- ---------------------------- -DROP TABLE IF EXISTS `aauth_perm_to_user`; -CREATE TABLE `aauth_perm_to_user` ( - `perm_id` int(11) unsigned NOT NULL, - `user_id` int(11) unsigned NOT NULL, - PRIMARY KEY (`perm_id`,`user_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of aauth_perm_to_user --- ---------------------------- - --- ---------------------------- --- Table structure for `aauth_pms` --- ---------------------------- -DROP TABLE IF EXISTS `aauth_pms`; -CREATE TABLE `aauth_pms` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `sender_id` int(11) unsigned NOT NULL, - `receiver_id` int(11) unsigned NOT NULL, - `title` varchar(255) NOT NULL, - `message` text, - `date_sent` datetime DEFAULT NULL, - `date_read` datetime DEFAULT NULL, - `pm_deleted_sender` int(1) DEFAULT NULL, - `pm_deleted_receiver` int(1) DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `full_index` (`id`,`sender_id`,`receiver_id`,`date_read`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of aauth_pms --- ---------------------------- - --- ---------------------------- --- Table structure for `aauth_users` --- ---------------------------- -DROP TABLE IF EXISTS `aauth_users`; -CREATE TABLE `aauth_users` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `email` varchar(100) COLLATE utf8_general_ci NOT NULL, - `pass` varchar(60) COLLATE utf8_general_ci NOT NULL, - `username` varchar(100) COLLATE utf8_general_ci, - `banned` tinyint(1) DEFAULT '0', - `last_login` datetime DEFAULT NULL, - `last_activity` datetime DEFAULT NULL, - `date_created` datetime DEFAULT NULL, - `forgot_exp` text COLLATE utf8_general_ci, - `remember_time` datetime DEFAULT NULL, - `remember_exp` text COLLATE utf8_general_ci, - `verification_code` text COLLATE utf8_general_ci, - `totp_secret` varchar(16) COLLATE utf8_general_ci DEFAULT NULL, - `ip_address` text COLLATE utf8_general_ci, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci; - --- ---------------------------- --- Records of aauth_users --- ---------------------------- -INSERT INTO `aauth_users` VALUES ('1', 'admin@example.com', '$2y$10$h19Lblcr6amOIUL1TgYW2.VVZOhac/e1kHMgAwCubMTlYXZrL0wS2', 'Admin', '0', null, null, null, null, null, null, null, null, '0'); - --- ---------------------------- --- Table structure for `aauth_user_to_group` --- ---------------------------- -DROP TABLE IF EXISTS `aauth_user_to_group`; -CREATE TABLE `aauth_user_to_group` ( - `user_id` int(11) unsigned NOT NULL, - `group_id` int(11) unsigned NOT NULL, - PRIMARY KEY (`user_id`,`group_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of aauth_user_to_group --- ---------------------------- -INSERT INTO `aauth_user_to_group` VALUES ('1', '1'); -INSERT INTO `aauth_user_to_group` VALUES ('1', '3'); - --- ---------------------------- --- Table structure for `aauth_user_variables` --- ---------------------------- -DROP TABLE IF EXISTS `aauth_user_variables`; -CREATE TABLE `aauth_user_variables` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `user_id` int(11) unsigned NOT NULL, - `data_key` varchar(100) NOT NULL, - `value` text, - PRIMARY KEY (`id`), - KEY `user_id_index` (`user_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of aauth_user_variables --- ---------------------------- - --- ---------------------------- --- Table structure for `aauth_group_to_group` --- ---------------------------- -DROP TABLE IF EXISTS `aauth_group_to_group`; -CREATE TABLE `aauth_group_to_group` ( - `group_id` int(11) unsigned NOT NULL, - `subgroup_id` int(11) unsigned NOT NULL, - PRIMARY KEY (`group_id`,`subgroup_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of aauth_group_to_group --- ---------------------------- - --- ---------------------------- --- Table structure for `aauth_login_attempts` --- ---------------------------- - -CREATE TABLE IF NOT EXISTS `aauth_login_attempts` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `ip_address` varchar(39) DEFAULT '0', - `timestamp` datetime DEFAULT NULL, - `login_attempts` tinyint(2) DEFAULT '0', - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=latin1; - --- ---------------------------- --- Records of aauth_login_attempts --- ---------------------------- diff --git a/sql/readme.txt b/sql/readme.txt deleted file mode 100644 index 8a0bff0..0000000 --- a/sql/readme.txt +++ /dev/null @@ -1,8 +0,0 @@ -Aauth V2 Database ------------------ - -- First open your database (or create one if you have not already done so) -- Execute sql "Aauth_v2.sql" file in your database -- If you have not already, don't forget to change database connection settings in application/config/database.php - -That's All :) diff --git a/tests/mocks/autoloader.php b/tests/mocks/autoloader.php new file mode 100644 index 0000000..76e065f --- /dev/null +++ b/tests/mocks/autoloader.php @@ -0,0 +1,122 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +class Mock_Libraries_Email +{ + private $data = array(); + + /** + * @var bool return value of send() + */ + public $return_send = TRUE; + + public function initialize() + { + } + + public function from($from) + { + $this->data['from'] = $from; + } + + public function to($to) + { + $this->data['to'] = $to; + } + + public function bcc($bcc) + { + $this->data['bcc'] = $bcc; + } + + public function subject($subject) + { + $this->data['subject'] = $subject; + } + + public function message($message) + { + $this->data['message'] = $message; + } + + public function send() + { + return $this->return_send; + } + + public function _get_data() + { + return $this->data; + } +} diff --git a/tests/models/0001-Users_test.php b/tests/models/0001-Users_test.php new file mode 100644 index 0000000..64b2722 --- /dev/null +++ b/tests/models/0001-Users_test.php @@ -0,0 +1,120 @@ +resetInstance(); + $this->CI->config->load('aauth'); + $this->config_vars = $this->CI->config->item('aauth'); + $this->CI->load->library('aauth'); + $this->CI->load->model('aauth/Users_model', 'users', $this->CI->load->database($this->config_vars['database']['_profile'])); + $this->obj = $this->CI->users; + } + + public function test_create() + { + $AT_create = $this->obj->create('admin@example.com', 'password', 'Admin'); + $this->assertInternalType('int', $AT_create); + $AF_email_exist = $this->obj->create('admin@example.com', 'password'); + $this->assertFalse($AF_email_exist); + $AF_username_exist = $this->obj->create('admin@examples.com', 'password', 'Admin'); + $this->assertFalse($AF_username_exist); + $AF_email_wrong = $this->obj->create('adminexample.com', 'password', 'Admin'); + $this->assertFalse($AF_email_wrong); + } + + public function test_update() + { + $AT_update = $this->obj->update(1, array('username' => 'Admin1')); + $this->assertTrue($AT_update); + $AF_userid_false = $this->obj->update(0, array('username' => 'Admin1')); + $this->assertFalse($AF_userid_false); + $AF_column_unkown = $this->obj->update(0, array('user' => 'Admin1')); + $this->assertFalse($AF_column_unkown); + } + + public function test_delete() + { + $this->obj->create('admin@examples.com', 'password', 'Admin'); + $AT_delete = $this->obj->delete(2); + $this->assertTrue($AT_delete); + } + + public function test_get_all() + { + $this->obj->create('admin@examples.com', 'password', 'Admin'); + $AE_default = $this->obj->get_all(); + $this->assertEquals(2, count($AE_default)); + $this->obj->ban($this->obj->get_(array('email' => 'admin@examples.com'), 'id')); + $AE_include_banneds = $this->obj->get_all(array('include_banneds' => TRUE)); + $this->assertEquals(2, count($AE_include_banneds)); + $AE_only_banneds = $this->obj->get_all(array('only_banneds' => TRUE)); + $this->assertEquals(1, count($AE_only_banneds)); + $AE_filters = $this->obj->get_all(array('filters' => array('username =' => 'TestUser'))); + $this->assertEquals(0, count($AE_filters)); + $AE_offset_preTest = $this->obj->get_all(array('include_banneds' => TRUE)); + $this->assertEquals(2, count($AE_offset_preTest)); + $AE_offset_1 = $this->obj->get_all(array('limit' => 1, 'offset' => 1, 'include_banneds' => TRUE)); + $this->assertEquals($this->obj->get_(array('email' => 'admin@examples.com'), 'id'), $AE_offset_1[0]->id); + $AE_limit_1 = $this->obj->get_all(array('limit' => 1)); + $this->assertEquals(1, count($AE_limit_1)); + + } + + public function test_ban() + { + $AT_ban = $this->obj->ban($this->obj->get_(array('email' => 'admin@examples.com'), 'id')); + $this->assertTrue($AT_ban); + $AT_is_banned = $this->obj->is_($this->obj->get_(array('email' => 'admin@examples.com'), 'id'), 'banned'); + $this->assertTrue($AT_is_banned); + $AT_ban_verifiy = $this->obj->ban($this->obj->get_(array('email' => 'admin@examples.com'), 'id'), 'verifiy'); + $this->assertTrue($AT_ban_verifiy); + $AF_is_not_verified = $this->obj->is_($this->obj->get_(array('email' => 'admin@examples.com'), 'id'), 'verified'); + $this->assertFalse($AF_is_not_verified); + $AF_userid_false = $this->obj->ban(0); + $this->assertFalse($AF_userid_false); + } + + public function test_unban() + { + $this->obj->ban(1); + $AT_unban = $this->obj->unban(1); + $this->assertTrue($AT_unban); + $AT_unban_verifiy = $this->obj->unban($this->obj->get_(array('email' => 'admin@examples.com'), 'id'), 'verifiy'); + $this->assertTrue($AT_unban_verifiy); + $this->obj->ban($this->obj->get_(array('email' => 'admin@examples.com'), 'id'), 'verifiy'); + $AF_no_verCode = $this->obj->unban($this->obj->get_(array('email' => 'admin@examples.com'), 'id')); + $this->assertFalse($AF_no_verCode); + $AF_userid_false = $this->obj->unban(0); + $this->assertFalse($AF_userid_false); + $AF_not_banned = $this->obj->unban(1); + $this->assertFalse($AF_not_banned); + + } + + public function test_update_() + { + $AT_activity = $this->obj->update_(1, 'activity'); + $this->assertTrue($AT_activity); + $AT_last_login = $this->obj->update_(1, 'last_login'); + $this->assertTrue($AT_last_login); + $AF_userid_false = $this->obj->update_(0, 'activity'); + $this->assertFalse($AF_userid_false); + } + + public function test_is_() + { + $AT_verified = $this->obj->is_(1, 'verified'); + $this->assertTrue($AT_verified); + $AF_userid_false = $this->obj->is_(0, 'verified'); + $this->assertFalse($AF_userid_false); + $this->obj->delete($this->obj->get_(array('email' => 'admin@examples.com'), 'id')); + } + + public function test_get_() + { + $AF_user_unknown = $this->obj->get_(array('email' => 'admin@examples.com'), 'id'); + $this->assertFalse($AF_user_unknown); + } +} diff --git a/tests/models/0002-User_variables_test.php b/tests/models/0002-User_variables_test.php new file mode 100644 index 0000000..4251c4c --- /dev/null +++ b/tests/models/0002-User_variables_test.php @@ -0,0 +1,55 @@ +resetInstance(); + $this->CI->config->load('aauth'); + $this->config_vars = $this->CI->config->item('aauth'); + $this->CI->load->library('aauth'); + $this->CI->load->model('aauth/User_variables_model', 'user_variables', $this->CI->load->database($this->config_vars['database']['_profile'])); + $this->obj = $this->CI->user_variables; + } + + public function test_update() + { + $AT_create_user_var = $this->obj->update(1, 'test_key', 'test_var'); + $this->assertTrue($AT_create_user_var); + $AE_create_user_var = $this->obj->get(1, 'test_key'); + $this->assertEquals('test_var', $AE_create_user_var); + $AT_update_user_var = $this->obj->update(1, 'test_key', 'test_var_var'); + $this->assertTrue($AT_update_user_var); + $AE_update_user_var = $this->obj->get(1, 'test_key'); + $this->assertEquals('test_var_var', $AE_update_user_var); + $AF_wrong_user_id = $this->obj->update(0, 'test_key', 'test_var_var'); + $this->assertFalse($AF_wrong_user_id); + } + + public function test_get() + { + $AF_wrong_user_id = $this->obj->get(0, 'test_key'); + $this->assertFalse($AF_wrong_user_id); + } + + public function test_get_by_user_id() + { + $this->obj->update(1, 'test_key2', 'test_var'); + $this->obj->update(1, 'test_key3', 'test_var'); + $this->obj->update(1, 'test_key4', 'test_var'); + + $AE_get_user_vars_1 = $this->obj->get_by_user_id(1); + $this->assertEquals(4, count($AE_get_user_vars_1)); + $AT_delete_by_user_var = $this->obj->delete(1, 'test_key'); + $this->assertTrue($AT_delete_by_user_var); + $AE_get_user_vars_2 = $this->obj->get_by_user_id(1); + $this->assertEquals(3, count($AE_get_user_vars_2)); + $AT_delete_by_user_vars = $this->obj->delete(1); + $this->assertTrue($AT_delete_by_user_vars); + $AE_get_user_vars_3 = $this->obj->get_by_user_id(1); + $this->assertEquals(0, count($AE_get_user_vars_3)); + $AF_wrong_user_id = $this->obj->get_by_user_id(0); + $this->assertFalse($AF_wrong_user_id); + } + +} diff --git a/tests/models/0003-Login_attempts_test.php b/tests/models/0003-Login_attempts_test.php new file mode 100644 index 0000000..12fd3be --- /dev/null +++ b/tests/models/0003-Login_attempts_test.php @@ -0,0 +1,44 @@ +resetInstance(); + $this->CI->config->load('aauth'); + $this->config_vars = $this->CI->config->item('aauth'); + $this->CI->load->library('aauth'); + $this->CI->load->model('aauth/Login_attempts_model', 'login_attempts', $this->CI->load->database($this->config_vars['database']['_profile'])); + $this->obj = $this->CI->login_attempts; + } + + public function test_update() + { + $AE_get_0 = $this->obj->get(); + $this->assertEquals(0, $AE_get_0); + $AT_update_create = $this->obj->update(); + $this->assertTrue($AT_update_create); + $AE_get_1 = $this->obj->get(); + $this->assertEquals(1, $AE_get_1); + $AT_update_update = $this->obj->update(); + $this->assertTrue($AT_update_update); + $AE_get_2 = $this->obj->get(); + $this->assertEquals(2, $AE_get_2); + + for ($i=$this->obj->get(); $i < $this->config_vars['ddos_protection']['max_attempts']; $i++) { + $this->obj->update(); + } + + $this->assertEquals($this->config_vars['ddos_protection']['max_attempts'], $this->obj->get()); + $AF_max_attempts = $this->obj->update(); + $this->assertFalse($AF_max_attempts); + } + + public function test_delete() + { + $AT_delete = $this->obj->delete(); + $this->assertTrue($AT_delete); + $AE_get_0 = $this->obj->get(); + $this->assertEquals(0, $AE_get_0); + } +} diff --git a/tests/models/0011-Groups_test.php b/tests/models/0011-Groups_test.php new file mode 100644 index 0000000..56345dc --- /dev/null +++ b/tests/models/0011-Groups_test.php @@ -0,0 +1,65 @@ +resetInstance(); + $this->CI->config->load('aauth'); + $this->config_vars = $this->CI->config->item('aauth'); + $this->CI->load->library('aauth'); + $this->CI->load->model('aauth/Groups_model', 'groups', $this->CI->load->database($this->config_vars['database']['_profile'])); + $this->obj = $this->CI->groups; + } + + public function test_create() + { + $AIT_create = $this->obj->create('test_group'); + $this->assertInternalType('int', $AIT_create); + $AF_same_group = $this->obj->create('test_group'); + $this->assertFalse($AF_same_group); + $AF_no_group = $this->obj->create(''); + $this->assertFalse($AF_no_group); + + } + + public function test_update() + { + $AT_update_1 = $this->obj->update(1, 'new_test_group'); + $this->assertTrue($AT_update_1); + $AE_update_1_confirm = $this->obj->get_id('new_test_group'); + $this->assertEquals('1', $AE_update_1_confirm); + $AT_update_2 = $this->obj->update(1, 'test_group', 'testGroup'); + $this->assertTrue($AT_update_2); + $AE_update_2_confirm = $this->obj->get($this->obj->get_id('test_group')); + $this->assertEquals('testGroup', $AE_update_2_confirm->definition); + $AF_wrong_id = $this->obj->update(0, 'test_group_1', 'test grp 1'); + $this->assertFalse($AF_wrong_id); + } + + public function test_get_id() + { + $AF_wrong_name = $this->obj->get_id(''); + $this->assertFalse($AF_wrong_name); + $AIT_id_given = $this->obj->get_id(1); + $this->assertEquals('1', $AIT_id_given); + } + + public function test_get() + { + $AF_wrong_name = $this->obj->get($this->obj->get_id('testGrp')); + $this->assertFalse($AF_wrong_name); + } + + public function test_get_all() + { + $AE_get_all = $this->obj->get_all(); + $this->assertEquals(1, count($AE_get_all)); + $AT_delete = $this->obj->delete(1); + $this->assertTrue($AT_delete); + $AF_get_all = $this->obj->get_all(); + $this->assertFalse($AF_get_all); + + } + +} diff --git a/tests/models/0012-Group_to_user_test.php b/tests/models/0012-Group_to_user_test.php new file mode 100644 index 0000000..1853d77 --- /dev/null +++ b/tests/models/0012-Group_to_user_test.php @@ -0,0 +1,61 @@ +resetInstance(); + $this->CI->config->load('aauth'); + $this->config_vars = $this->CI->config->item('aauth'); + $this->CI->load->library('aauth'); + $this->CI->load->model('aauth/Group_to_user_model', 'group_to_user', $this->CI->load->database($this->config_vars['database']['_profile'])); + $this->CI->load->model('aauth/Groups_model', 'groups', $this->CI->load->database($this->config_vars['database']['_profile'])); + $this->obj = $this->CI->group_to_user; + } + + public function test_create() + { + $this->CI->groups->create('test_group'); + $test_group_id = $this->CI->groups->get_id('test_group'); + $AT_create = $this->obj->create($test_group_id, 1); + $this->assertTrue($AT_create); + $AF_already_member = $this->obj->create($test_group_id, 1); + $this->assertFalse($AF_already_member); + $AF_wrong_user = $this->obj->create($test_group_id, 0); + $this->assertFalse($AF_wrong_user); + $AF_wrong_group = $this->obj->create(0, 1); + $this->assertFalse($AF_wrong_group); + } + + public function test_delete() + { + $test_group_id = $this->CI->groups->get_id('test_group'); + $AT_pre_test = $this->obj->exist($test_group_id, 1); + $this->assertTrue($AT_pre_test); + $AT_delete = $this->obj->delete($test_group_id, 1); + $this->assertTrue($AT_delete); + $AF_after_test = $this->obj->exist($test_group_id, 1); + $this->assertFalse($AF_after_test); + } + + public function test_delete_by_user() + { + $AF_wrong_user = $this->obj->delete_by_user(0); + $this->assertFalse($AF_wrong_user); + } + + public function test_delete_by_group() + { + $AF_wrong_group = $this->obj->delete_by_group(0); + $this->assertFalse($AF_wrong_group); + } + + public function test_exist() + { + $AF_wrong_user = $this->obj->exist(1, 0); + $this->assertFalse($AF_wrong_user); + $AF_wrong_group = $this->obj->exist(0, 1); + $this->assertFalse($AF_wrong_group); + } + +} diff --git a/tests/models/0013-Group_to_subgroup_test.php b/tests/models/0013-Group_to_subgroup_test.php new file mode 100644 index 0000000..28fc392 --- /dev/null +++ b/tests/models/0013-Group_to_subgroup_test.php @@ -0,0 +1,81 @@ +resetInstance(); + $this->CI->config->load('aauth'); + $this->config_vars = $this->CI->config->item('aauth'); + $this->CI->load->library('aauth'); + $this->CI->load->model('aauth/Group_to_subgroup_model', 'group_to_subgroup', $this->CI->load->database($this->config_vars['database']['_profile'])); + $this->CI->load->model('aauth/Groups_model', 'groups', $this->CI->load->database($this->config_vars['database']['_profile'])); + $this->obj = $this->CI->group_to_subgroup; + } + + public function test_create() + { + $this->CI->groups->create('test_subgroup_1'); + $this->CI->groups->create('test_subgroup_2'); + $test_maingroup_id = $this->CI->groups->get_id('test_subgroup_1'); + $test_subgroup_id = $this->CI->groups->get_id('test_subgroup_2'); + $AT_create = $this->obj->create($test_maingroup_id, $test_subgroup_id); + $this->assertTrue($AT_create); + $AF_already_member = $this->obj->create($test_maingroup_id, $test_subgroup_id); + $this->assertFalse($AF_already_member); + $AF_wrong_subgroup = $this->obj->create($test_maingroup_id, 0); + $this->assertFalse($AF_wrong_subgroup); + $AF_wrong_maingroup = $this->obj->create(0, $test_subgroup_id); + $this->assertFalse($AF_wrong_maingroup); + $AF_same_group = $this->obj->create($test_subgroup_id, $test_subgroup_id); + $this->assertFalse($AF_same_group); + } + + public function test_delete() + { + $test_maingroup_id = $this->CI->groups->get_id('test_subgroup_1'); + $test_subgroup_id = $this->CI->groups->get_id('test_subgroup_2'); + $AT_pre_test = $this->obj->exist($test_maingroup_id, $test_subgroup_id); + $this->assertTrue($AT_pre_test); + $AT_delete = $this->obj->delete($test_maingroup_id, $test_subgroup_id); + $this->assertTrue($AT_delete); + $AF_after_test = $this->obj->exist($test_maingroup_id, $test_subgroup_id); + $this->assertFalse($AF_after_test); + } + + public function test_delete_by_subgroup() + { + $test_maingroup_id = $this->CI->groups->get_id('test_subgroup_1'); + $test_subgroup_id = $this->CI->groups->get_id('test_subgroup_2'); + $AT_create = $this->obj->create($test_maingroup_id, $test_subgroup_id); + $AT_delete_by_subgroup = $this->obj->delete_by_subgroup($test_subgroup_id); + $this->assertTrue($AT_delete_by_subgroup); + + $AF_wrong_subgroup = $this->obj->delete_by_subgroup(0); + $this->assertFalse($AF_wrong_subgroup); + } + + public function test_delete_by_group() + { + $test_maingroup_id = $this->CI->groups->get_id('test_subgroup_1'); + $test_subgroup_id = $this->CI->groups->get_id('test_subgroup_2'); + $AT_create = $this->obj->create($test_maingroup_id, $test_subgroup_id); + $AT_delete_by_group = $this->obj->delete_by_group($test_maingroup_id); + $this->assertTrue($AT_delete_by_group); + $AF_wrong_group = $this->obj->delete_by_group(0); + $this->assertFalse($AF_wrong_group); + } + + public function test_exist() + { + $test_maingroup_id = $this->CI->groups->get_id('test_subgroup_1'); + $test_subgroup_id = $this->CI->groups->get_id('test_subgroup_2'); + $AF_wrong_subgroup = $this->obj->exist($test_maingroup_id, 0); + $this->assertFalse($AF_wrong_subgroup); + $AF_wrong_group = $this->obj->exist(0, $test_subgroup_id); + $this->assertFalse($AF_wrong_group); + } + + +} \ No newline at end of file diff --git a/tests/models/0021-Permissions_test.php b/tests/models/0021-Permissions_test.php new file mode 100644 index 0000000..572d831 --- /dev/null +++ b/tests/models/0021-Permissions_test.php @@ -0,0 +1,65 @@ +resetInstance(); + $this->CI->config->load('aauth'); + $this->config_vars = $this->CI->config->item('aauth'); + $this->CI->load->library('aauth'); + $this->CI->load->model('aauth/Permissions_model', 'permissions', $this->CI->load->database($this->config_vars['database']['_profile'])); + $this->obj = $this->CI->permissions; + } + + public function test_create() + { + $AIT_create = $this->obj->create('test_permission'); + $this->assertInternalType('int', $AIT_create); + $AF_same_permission = $this->obj->create('test_permission'); + $this->assertFalse($AF_same_permission); + $AF_no_permission = $this->obj->create(''); + $this->assertFalse($AF_no_permission); + + } + + public function test_update() + { + $AT_update_1 = $this->obj->update(1, 'new_test_permission'); + $this->assertTrue($AT_update_1); + $AE_update_1_confirm = $this->obj->get_id('new_test_permission'); + $this->assertEquals('1', $AE_update_1_confirm); + $AT_update_2 = $this->obj->update(1, 'test_permission', 'testPermission'); + $this->assertTrue($AT_update_2); + $AE_update_2_confirm = $this->obj->get($this->obj->get_id('test_permission')); + $this->assertEquals('testPermission', $AE_update_2_confirm->definition); + $AF_wrong_id = $this->obj->update(0, 'test_permission_1', 'test perm 1'); + $this->assertFalse($AF_wrong_id); + } + + public function test_get_id() + { + $AF_wrong_name = $this->obj->get_id(''); + $this->assertFalse($AF_wrong_name); + $AIT_id_given = $this->obj->get_id(1); + $this->assertEquals('1', $AIT_id_given); + } + + public function test_get() + { + $AF_wrong_name = $this->obj->get($this->obj->get_id('testPerm')); + $this->assertFalse($AF_wrong_name); + } + + public function test_get_all() + { + $AE_get_all = $this->obj->get_all(); + $this->assertEquals(1, count($AE_get_all)); + $AT_delete = $this->obj->delete(1); + $this->assertTrue($AT_delete); + $AF_get_all = $this->obj->get_all(); + $this->assertFalse($AF_get_all); + + } + +} diff --git a/tests/models/0022-Permissions_to_user_test.php b/tests/models/0022-Permissions_to_user_test.php new file mode 100644 index 0000000..fbaa94c --- /dev/null +++ b/tests/models/0022-Permissions_to_user_test.php @@ -0,0 +1,69 @@ +resetInstance(); + $this->CI->config->load('aauth'); + $this->config_vars = $this->CI->config->item('aauth'); + $this->CI->load->library('aauth'); + $this->CI->load->model('aauth/Permission_to_user_model', 'permission_to_user', $this->CI->load->database($this->config_vars['database']['_profile'])); + $this->CI->load->model('aauth/Permissions_model', 'permissions', $this->CI->load->database($this->config_vars['database']['_profile'])); + $this->obj = $this->CI->permission_to_user; + } + + public function test_create() + { + $this->CI->permissions->create('test_permission'); + $test_permission_id = $this->CI->permissions->get_id('test_permission'); + $AT_create = $this->obj->create($test_permission_id, 1); + $this->assertTrue($AT_create); + $AF_already_member = $this->obj->create($test_permission_id, 1); + $this->assertFalse($AF_already_member); + $AF_wrong_user = $this->obj->create($test_permission_id, 0); + $this->assertFalse($AF_wrong_user); + $AF_wrong_permission = $this->obj->create(0, 1); + $this->assertFalse($AF_wrong_permission); + } + + public function test_delete() + { + $test_permission_id = $this->CI->permissions->get_id('test_permission'); + $AT_pre_test = $this->obj->exist($test_permission_id, 1); + $this->assertTrue($AT_pre_test); + $AT_delete = $this->obj->delete($test_permission_id, 1); + $this->assertTrue($AT_delete); + $AF_after_test = $this->obj->exist($test_permission_id, 1); + $this->assertFalse($AF_after_test); + } + + public function test_delete_by_user() + { + $test_permission_id = $this->CI->permissions->get_id('test_permission'); + $this->obj->create(1, $test_permission_id); + $AT_delete_by_user = $this->obj->delete_by_user(1); + $this->assertTrue($AT_delete_by_user); + $AF_wrong_user = $this->obj->delete_by_user(0); + $this->assertFalse($AF_wrong_user); + } + + public function test_delete_by_permission() + { + $test_permission_id = $this->CI->permissions->get_id('test_permission'); + $this->obj->create(1, $test_permission_id); + $AT_delete_by_permission = $this->obj->delete_by_permission($test_permission_id); + $this->assertTrue($AT_delete_by_permission); + $AF_wrong_permission = $this->obj->delete_by_permission(0); + $this->assertFalse($AF_wrong_permission); + } + + public function test_exist() + { + $AF_wrong_user = $this->obj->exist(1, 0); + $this->assertFalse($AF_wrong_user); + $AF_wrong_permission = $this->obj->exist(0, 1); + $this->assertFalse($AF_wrong_permission); + } + +} diff --git a/tests/models/0023-Permissions_to_group_test.php b/tests/models/0023-Permissions_to_group_test.php new file mode 100644 index 0000000..1337e6b --- /dev/null +++ b/tests/models/0023-Permissions_to_group_test.php @@ -0,0 +1,72 @@ +resetInstance(); + $this->CI->config->load('aauth'); + $this->config_vars = $this->CI->config->item('aauth'); + $this->CI->load->library('aauth'); + $this->CI->load->model('aauth/Permission_to_group_model', 'permission_to_group', $this->CI->load->database($this->config_vars['database']['_profile'])); + $this->CI->load->model('aauth/Permissions_model', 'permissions', $this->CI->load->database($this->config_vars['database']['_profile'])); + $this->CI->load->model('aauth/Groups_model', 'groups', $this->CI->load->database($this->config_vars['database']['_profile'])); + $this->obj = $this->CI->permission_to_group; + $this->CI->groups->create('test_group'); + $this->test_group_id = $this->CI->groups->get_id('test_group'); + } + + public function test_create() + { + $this->CI->permissions->create('test_permission'); + $test_permission_id = $this->CI->permissions->get_id('test_permission'); + $AT_create = $this->obj->create($test_permission_id, $this->test_group_id); + $this->assertTrue($AT_create); + $AF_already_member = $this->obj->create($test_permission_id, $this->test_group_id); + $this->assertFalse($AF_already_member); + $AF_wrong_group = $this->obj->create($test_permission_id, 0); + $this->assertFalse($AF_wrong_group); + $AF_wrong_permission = $this->obj->create(0, $this->test_group_id); + $this->assertFalse($AF_wrong_permission); + } + + public function test_delete() + { + $test_permission_id = $this->CI->permissions->get_id('test_permission'); + $AT_pre_test = $this->obj->exist($test_permission_id, $this->test_group_id); + $this->assertTrue($AT_pre_test); + $AT_delete = $this->obj->delete($test_permission_id, $this->test_group_id); + $this->assertTrue($AT_delete); + $AF_after_test = $this->obj->exist($test_permission_id, $this->test_group_id); + $this->assertFalse($AF_after_test); + } + + public function test_delete_by_group() + { + $test_permission_id = $this->CI->permissions->get_id('test_permission'); + $this->obj->create($test_permission_id, $this->test_group_id); + $AT_delete_by_group = $this->obj->delete_by_group($this->test_group_id); + $this->assertTrue($AT_delete_by_group); + $AF_wrong_group = $this->obj->delete_by_group(0); + $this->assertFalse($AF_wrong_group); + } + + public function test_delete_by_permission() + { + $test_permission_id = $this->CI->permissions->get_id('test_permission'); + $this->obj->create($test_permission_id, $this->test_group_id); + $AT_delete_by_permission = $this->obj->delete_by_permission($test_permission_id); + $this->assertTrue($AT_delete_by_permission); + $AF_wrong_permission = $this->obj->delete_by_permission(0); + $this->assertFalse($AF_wrong_permission); + } + + public function test_exist() + { + $AF_wrong_group = $this->obj->exist(1, 0); + $this->assertFalse($AF_wrong_group); + $AF_wrong_permission = $this->obj->exist(0, $this->test_group_id); + $this->assertFalse($AF_wrong_permission); + } + +} diff --git a/tests/phpunit.xml b/tests/phpunit.xml new file mode 100644 index 0000000..46ac2f5 --- /dev/null +++ b/tests/phpunit.xml @@ -0,0 +1,34 @@ + + + + ./models + ./controllers + ./language + ./libraries + ./views + ./_ci_phpunit_test/ + + + + + ../config/aauth.php + ../config/aauth_init.php + ../controllers + ../models/aauth + ../language + ../libraries + ../views + + ../views + ../controllers + ../language + + + + + + + +