Example #1
1
 /**
  * When visiting any page on the site, check if the user is already logged in,
  * or they are visiting a page that is allowed when logged out. Otherwise,
  * redirect to the login page. If visiting the login page, check the browser
  * supports cookies.
  */
 public function check()
 {
     $uri = new URI();
     // Skip check when accessing the data services, as it is redundant but would slow the services down.
     // Also no need to login when running the scheduled tasks.
     if ($uri->segment(1) == 'services' || $uri->segment(1) == 'scheduled_tasks') {
         return;
     }
     // check for setup request
     //
     if ($uri->segment(1) == 'setup_check') {
         // get kohana paths
         //
         $ipaths = Kohana::include_paths();
         // check if indicia_setup module folder exists
         //
         clearstatcache();
         foreach ($ipaths as $path) {
             if (preg_match("/indicia_setup/", $path) && file_exists($path)) {
                 return;
             }
         }
     }
     // Always logged in
     $auth = new Auth();
     if (!$auth->logged_in() and !$auth->auto_login() and $uri->segment(1) != 'login' and $uri->segment(1) != 'logout' and $uri->segment(1) != 'new_password' and $uri->segment(1) != 'forgotten_password') {
         $_SESSION['requested_page'] = $uri->string();
         url::redirect('login');
     } else {
         if ($auth->logged_in() and is_null($_SESSION['auth_user']->password) and $uri->segment(1) != 'new_password' and $uri->segment(1) != 'logout' and $uri->segment(1) != 'setup_check') {
             $_SESSION['requested_page'] = $uri->string();
             url::redirect('new_password');
         }
     }
 }
Example #2
1
/**
 * Authentication & authorization middleware for routes
 *
 * Checks if User is signed in & has required privileges. Otherwise redirects to login page
 *
 * @param int $minRole  Minimum required User role
 *
 * @return callable
 */
function authForRole($minRole)
{
    return function () use($minRole) {
        $app = Slim\Slim::getInstance();
        $auth = new Auth();
        $signedIn = $auth->checkSession();
        if (!$signedIn) {
            $app->flash('error', 'Sign in required');
            $app->redirect('/signin');
        } else {
            $user = unserialize($_SESSION['User']);
            switch ($minRole) {
                case User::ADMIN:
                    if (in_array($user['role'], [User::ADMIN])) {
                        return;
                    }
                    break;
                case User::EXTENDED:
                    if (in_array($user['role'], [User::ADMIN, User::EXTENDED])) {
                        return;
                    }
                    break;
                case User::NORMAL:
                    if (in_array($user['role'], [User::ADMIN, User::EXTENDED, User::NORMAL])) {
                        return;
                    }
                    break;
            }
            $app->flash('error', 'You are not authorized to view this page');
            $app->redirect('/signin');
        }
    };
}
Example #3
1
 public function __construct()
 {
     parent::__construct();
     $this->template->links = array('Home' => 'home', 'Browse' => 'folders', 'Search' => 'search', 'About' => 'about', 'Contact' => 'contact');
     $this->db = Database::instance();
     // makes database object available to all controllers
     $this->session = Session::instance();
     $authentic = new Auth();
     if ($authentic->logged_in() || $authentic->auto_login()) {
         $this->user = $authentic->get_user();
     } else {
         $this->session->set("requested_url", "/" . url::current());
         // this will redirect from the login page back to this page
         url::redirect('/auth/login');
     }
     // if ($authentic->auto_login()) {
     //     $this->user = $authentic->get_user();
     //     url::redirect('/document/view/1');
     // }
     // if (!$authentic->logged_in()) {
     //
     //     $this->session->set("requested_url","/".url::current()); // this will redirect from the login page back to this page
     //     url::redirect('/auth/login');
     // } else {
     //     $this->user = $authentic->get_user(); //now you have access to user information stored in the database
     // }
 }
 public function start()
 {
     $authenticator = new Auth();
     if ($authenticator->auth()) {
         $this->startDownload();
     }
 }
Example #5
1
 /**
  * Custom validation for this model - complements the default validate()
  *
  * @param   array  array to validate
  * @param   Auth   instance of Auth class; used for testing purposes
  * @return bool TRUE if validation succeeds, FALSE otherwise
  */
 public static function custom_validate(array &$post, Auth $auth = null)
 {
     // Initalize validation
     $post = Validation::factory($post)->pre_filter('trim', TRUE);
     if ($auth === null) {
         $auth = new Auth();
     }
     $post->add_rules('username', 'required', 'length[3,100]', 'alpha_numeric');
     $post->add_rules('name', 'required', 'length[3,100]');
     $post->add_rules('email', 'required', 'email', 'length[4,64]');
     // If user id is not specified, check if the username already exists
     if (empty($post->user_id)) {
         $post->add_callbacks('username', array('User_Model', 'unique_value_exists'));
         $post->add_callbacks('email', array('User_Model', 'unique_value_exists'));
     }
     // Only check for the password if the user id has been specified
     if (empty($post->user_id)) {
         $post->add_rules('password', 'required', 'length[5,50]', 'alpha_numeric');
     }
     // If Password field is not blank
     if (!empty($post->password) or empty($post->password) and !empty($post->password_again)) {
         $post->add_rules('password', 'required', 'length[5,50]', 'alpha_numeric', 'matches[password_again]');
     }
     $post->add_rules('role', 'required', 'length[3,30]', 'alpha_numeric');
     $post->add_rules('notify', 'between[0,1]');
     if (!$auth->logged_in('superadmin')) {
         $post->add_callbacks('role', array('User_Model', 'prevent_superadmin_modification'));
     }
     // Additional validation checks
     Event::run('ushahidi_action.user_submit_admin', $post);
     // Return
     return $post->validate();
 }
Example #6
1
 /**
  * 
  */
 public function Confirm()
 {
     $auth = new Auth();
     $shop = new ShoppingCart();
     $user = $auth->id();
     $myShop = $shop->all();
     $objDetails = new DetalleCompra();
     $total = 0;
     if (empty($myShop)) {
         return false;
     }
     foreach ($myShop as $key => $val) {
         $total += $val->precio * $val->cantidad;
     }
     $result_insert = $this->create($user, $total);
     if ($result_insert->success) {
         foreach ($myShop as $k => $v) {
             try {
                 $objDetails->create($result_insert->id, $v->id_prod, $v->name, $v->cantidad, $v->precio, $v->talle, $v->color);
                 //$stock = new TempStock();
                 //echo $stock->removeTempStock($user,$v->id_prod,$v->id_talle,$v->id_color,$v->type);
             } catch (Exception $e) {
                 echo $e->getMessage();
             }
         }
         $auth->restPoints($total);
         $auth->sumConsumed($total);
         $shop->removeAll();
         return true;
     }
 }
Example #7
0
 public function add(Auth $auth)
 {
     if ($auth === $this) {
         die('Fail add!');
     }
     $this->_authList[$auth->getName()] = $auth;
 }
 /**
  * Gets user authentication token.
  *
  * @param email - required -
  *            The email address of the user.
  * @param password - required -
  *            The password of the user.
  * @return An Auth object. If the call is successful, the authentication token is set.
  * If unsuccessful, the object contains the error code and message thrown by the server.
  */
 public function login($email, $password)
 {
     $parameters = array('email' => $email, 'password' => $password);
     $urld = 'dpi/v1/auth';
     $headers = array('X-Api-Key' => $this->apiKey);
     $this->response = $this->restTransportInstance->sendRequest($urld, $parameters, self::HTTP_POST);
     $responseBody = simplexml_load_string($this->response);
     $returnObject = new Auth();
     if ($responseBody === false) {
         $errorCode = 'N/A';
         $errorMessage = 'The server has encountered an error, please try again.';
         $errorObject = new ErrorStatus($errorCode, $errorMessage);
         $returnObject->setErrorStatus($errorObject);
     } else {
         $errorStatus = $responseBody->errorStatus;
         if (empty($errorStatus)) {
             $authToken = (string) $responseBody->authToken;
             $returnObject->setAuthToken($authToken);
         } else {
             $errorCode = (string) $responseBody->errorStatus->code;
             $errorMessage = (string) $responseBody->errorStatus->message;
             $errorObject = new ErrorStatus($errorCode, $errorMessage);
             $returnObject->setErrorStatus($errorObject);
         }
     }
     return $returnObject;
 }
Example #9
0
 /**
	 * 转换word文档
	 */
 public function convert()
 {
     $app_id = isset($this->input['custom_appid']) ? trim($this->input['custom_appid']) : '';
     $app_key = isset($this->input['custom_appkey']) ? trim($this->input['custom_appkey']) : '';
     if (empty($app_id) || empty($app_key)) {
         $this->errorOutput(PARAM_WRONG);
     }
     //先验证是否有权限
     $auth = new Auth();
     $auth_info = $auth->getAccessToken($app_id, $app_key);
     if (!$auth_info) {
         $this->errorOutput(NO_AUTH);
     }
     //处理上传的word文档
     $gGlobalConfig['officeconvert'] = array('host' => '10.0.1.59:8080', 'dir' => 'officeConverter/');
     $curl = new curl($gGlobalConfig['officeconvert']['host'], $gGlobalConfig['officeconvert']['dir']);
     $curl->setSubmitType('post');
     $curl->setReturnFormat('str');
     $curl->initPostData();
     $curl->addFile($_FILES);
     $curl->addRequestData('custom_appid', $app_id);
     $curl->addRequestData('custom_appkey', $app_key);
     $result = $curl->request('converter');
     if (!$result) {
         $this->errorOutput(FAIL_OP);
     }
     $this->addItem($result);
     $this->output();
 }
 private function run()
 {
     if (!empty($this->parts[0])) {
         $ctrl = $this->parts[0];
         if (file_exists("controllers/" . $ctrl . ".php")) {
             include "controllers/" . $ctrl . ".php";
             if (class_exists($ctrl)) {
                 $ctrl_obj = new $ctrl();
                 if (!empty($this->parts[1])) {
                     $method = $this->parts[1];
                     if (method_exists($ctrl_obj, $method)) {
                         if (!empty($this->parts[2])) {
                             $params = array_slice($this->parts, 2);
                             call_user_func_array(array($ctrl_obj, $method), $params);
                         } else {
                             $ctrl_obj->{$method}();
                         }
                     } else {
                         echo "METHOD NOT FOUND!";
                     }
                 } else {
                     $ctrl_obj->index();
                 }
             } else {
                 echo "CLASS NOT FOUND!";
             }
         } else {
             echo "FILE NOT FOUND!";
         }
     } else {
         include "controllers/auth.php";
         $default_obj = new Auth();
         $default_obj->index();
     }
 }
 /**
  * This method try to identicate a user
  *
  * @param $params array of options
  * => login_name : mandatory user name
  * => login_password : mandatory user password
  * => other : optionnal values for post action
  *@param $protocol the communication protocol used
  *
  * @return an response ready to be encode
  * => id of the user
  * => name of the user
  * => realname of the user
  * => firstname of the user
  * => session : ID of the session for future call
  **/
 static function methodLogin($params, $protocol)
 {
     if (isset($params['help'])) {
         return array('login_name' => 'string,mandatory', 'login_password' => 'string,mandatory', 'help' => 'bool,optional');
     }
     if (!isset($params['login_name']) || empty($params['login_name'])) {
         return self::Error($protocol, WEBSERVICES_ERROR_MISSINGPARAMETER, '', 'login_name');
     }
     if (!isset($params['login_password']) || empty($params['login_password'])) {
         return self::Error($protocol, WEBSERVICES_ERROR_MISSINGPARAMETER, '', 'login_password');
     }
     foreach ($params as $name => $value) {
         switch ($name) {
             case 'login_name':
             case 'login_password':
                 break;
             default:
                 // Store to Session, for post login action (retrieve_more_data_from_ldap, p.e.)
                 $_SESSION[$name] = $value;
         }
     }
     $identificat = new Auth();
     if ($identificat->Login($params['login_name'], $params['login_password'], true)) {
         session_write_close();
         return array('id' => Session::getLoginUserID(), 'name' => $_SESSION['glpiname'], 'realname' => $_SESSION['glpirealname'], 'firstname' => $_SESSION['glpifirstname'], 'session' => $_SESSION['valid_id']);
     }
     return self::Error($protocol, WEBSERVICES_ERROR_LOGINFAILED, '', Html::clean($identificat->getErr()));
 }
Example #12
0
 function authenticationCheck()
 {
     $user = new \DB\SQL\Mapper($this->db, 'user');
     $auth = new \Auth($user, array('id' => 'name', 'pw' => 'password'));
     $loginResult = $auth->basic();
     return $loginResult;
 }
Example #13
0
 /**
  * Connect using the test user
  */
 protected function login()
 {
     $auth = new Auth();
     if (!$auth->Login(TU_USER, TU_PASS, true)) {
         $this->markTestSkipped('No login');
     }
 }
Example #14
0
function ShowModifications(&$p, $db_table, $db_id)
{
    global $database;
    $m_mod = new Modification($database);
    $m_auth = new Auth($database);
    $mods = $m_mod->byTableID($db_table, $db_id);
    if (!false_or_null($mods)) {
        $data = array();
        foreach ($mods as $mod) {
            $user = $m_auth->Get($mod['r_Auth']);
            $what = '';
            $w = json_decode($mod['What'], true);
            foreach ($w as $dataset) {
                foreach ($dataset as $table => $change) {
                    $what .= $table . ' #' . $change['I'] . '\'s ' . $change['F'] . (isset($change['E']) ? ' » ' . $change['E'] : '');
                }
            }
            $data[] = array($user['username'], $what, $mod['Message'], human_datetime(intval($mod['Timestamp'])));
        }
        $table = new TableHelper(array('table' => "table wide", 'thead' => "tablehead", 'th' => "tablehead", 'td' => "tablecell", 'headings' => array('Who', 'What', ' ', 'When'), 'data' => $data));
        $p->HTML('<div class="formgroup">');
        $p->HTML('<h4>Recent Activity</h4>');
        $p->Table($table);
        $p->HTML('</div>');
    }
}
 /**
  * Registration
  */
 public function upAction()
 {
     if ($this->request->isPost()) {
         $user = new Users();
         $user->login = $this->request->getPost('login', 'string');
         $user->password = $this->request->getPost('password', 'string');
         $passwordVerify = $this->request->getPost('password-verify', 'string');
         if (md5($user->password) !== md5($passwordVerify)) {
             $this->flashSession->error('Пароли не совпадают');
             return;
         }
         if (!$user->create()) {
             $this->flashSession->error(implode("<br/>", $user->getMessages()));
             return;
         }
         $auth = new Auth();
         $authSucceed = $auth->authorize($user);
         if ($authSucceed) {
             $this->response->redirect();
             return;
         }
         $this->dispatcher->forward(['controller' => 'sign', 'action' => 'in']);
         return;
     }
 }
Example #16
0
 public function settings()
 {
     include_once ROOT_PATH . 'lib/class/auth.class.php';
     $auth = new Auth();
     $role_info = $auth->get_role_list();
     $this->addItem_withkey('role', $role_info);
     parent::settings();
 }
 /**
  * Handle an incoming request.
  *
  * @param \Illuminate\Http\Request $request
  * @param \Closure                 $next
  *
  * @return mixed
  */
 public function handle($request, Closure $next)
 {
     $response = $next($request);
     if ($this->auth->check() && $response instanceof Response) {
         $response->header('Cache-Control', 'no-cache, max-age=0, must-revalidate, no-store');
     }
     return $response;
 }
Example #18
0
 /**
  * @return Auth|null
  */
 protected function getUser()
 {
     if (isset($_SERVER['PHP_AUTH_USER']) and isset($_SERVER['PHP_AUTH_PW'])) {
         $auth = new Auth();
         return $auth->set($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
     }
     return null;
 }
Example #19
0
   protected function setUp() {
      global $DB;
      
      $DB->connect();

      // Store Max(id) for each glpi tables
      $result = $DB->list_tables();
      while ($data=$DB->fetch_row($result)) {
         $query = "SELECT MAX(`id`) AS MAXID
                   FROM `".$data[0]."`";
         foreach ($DB->request($query) as $row) {
            $this->tables[$data[0]] = (empty($row['MAXID']) ? 0 : $row['MAXID']);
         }
      }
      $DB->free_result($result);

      $tab  = array();
      $auth = new Auth();
      // First session
      $auth->Login('glpi', 'glpi') ;

      // Create entity tree
      $entity = new Entity();
      $tab['entity'][0] = $entity->add(array('name' => 'PHP Unit root',
                                             'entities_id' => 0));

      if (!$tab['entity'][0]                                   // Crash detection
          || !FieldExists('glpi_profiles','notification')   // Schema detection
          || countElementsInTable('glpi_rules')!=6) {    // Old rules

         if (!$tab['entity'][0]) {
            echo "Couldn't run test (previous run not cleaned)\n";
         } else {
            echo "Schema need to be updated\n";
         }
         echo "Loading a fresh empty database:";
         $DB->runFile(GLPI_ROOT ."/install/mysql/glpi-0.84-empty.sql");
         die(" done\nTry again\n");
      }

      $tab['entity'][1] = $entity->add(array('name'        => 'PHP Unit Child 1',
                                             'entities_id' => $tab['entity'][0]));

      $tab['entity'][2] = $entity->add(array('name'        => 'PHP Unit Child 2',
                                             'entities_id' => $tab['entity'][0]));

      $tab['entity'][3] = $entity->add(array('name'        => 'PHP Unit Child 2.1',
                                             'entities_id' => $tab['entity'][2]));

      $tab['entity'][4] = $entity->add(array('name'        => 'PHP Unit Child 2.2',
                                             'entities_id' => $tab['entity'][2]));

      // New session with all the entities
      $auth->Login('glpi', 'glpi') or die("Login glpi/glpi invalid !\n");

      // Shared this with all tests
      $this->sharedFixture = $tab;
   }
Example #20
0
 public function action_logout()
 {
     if ($this->_auth->logout()) {
         $this->_message = __("Logout succeeded");
         $this->_user = NULL;
     } else {
         $this->_message = __("Couldn't logout");
     }
 }
Example #21
0
 public function index()
 {
     $user = new Auth();
     if ($user->isUserLoggedIn()) {
         $this->viewAdmin('admin/index', ['site_name' => SITE_NAME, 'title' => $this->title, 'description' => 'This is the private administration area of ' . SITE_NAME . '\'s Parish Council']);
     } else {
         header('location: http://localhost/test/login');
     }
 }
Example #22
0
 public function read()
 {
     unset($_SESSION["user"]["password"]);
     $auth = new Auth();
     $rules = $auth->getAuthList(getCurrentUid());
     //        print_r($rules);exit;
     $data = array("authed" => reIndex($rules), "navs" => $this->makeNav());
     $this->response($data);
 }
Example #23
0
 public function registerAction()
 {
     $Auth = new Auth();
     $post = $this->request->getPost();
     if (isset($post['username'])) {
         $Auth->register($post);
         header('Location:' . Url::getUrl('user', 'login'));
     }
 }
Example #24
0
 /**
  * @return Auth|null
  */
 public function getUser()
 {
     $auth = Session::get($this->session_name);
     if ($auth) {
         $a = new Auth();
         return $a->set($auth['user'], $auth['password']);
     }
     return null;
 }
Example #25
0
	public function Obj()
	{
		static $auth;
		if ( !$auth )
		{
			$auth = new Auth();
			$auth->Reconcile();
		}
		return $auth;
	}
 function initInstance()
 {
     //instance conf
     $instanceAuth = new Auth($this->instanceDroit);
     $instanceAuth->auth_deconnexion();
     //test si deconnexion
     //set instance before return
     $this->setInstance($instanceAuth);
     return $instanceAuth;
 }
Example #27
0
 public function test_setCredentials()
 {
     $fs = \Mockery::mock('League\\Flysystem\\Filesystem');
     $fs->shouldReceive('read')->with('/tmp/credentials.php')->andReturn('<?php $credentials = "old hash"; ?>')->once();
     $fs->shouldReceive('put')->with('/tmp/credentials.php', '/new password hash/')->andReturn(true)->once();
     $auth = new Auth($fs, '/tmp/credentials.php');
     $this->assertTrue($auth->authenticate('old hash'));
     $auth->setCredentials('new password hash');
     $this->assertTrue($auth->authenticate('new password hash'));
 }
Example #28
0
 public function eliminar($id = 0)
 {
     $auth = new Auth();
     if (!$auth->check(FALSE)) {
         $this->load->view('panel/login');
     } else {
         $this->configuracion->eliminar($id);
         $this->session->set_flashdata('message', '<div class="success message">Listo! el registro ha sido eliminado.</div>');
         redirect("panel/configuracion/listado");
     }
 }
Example #29
0
function api_login($id, $password)
{
    $auth = new Auth();
    if (!$auth->login($id, $password)) {
        $canon_id = api_get_canonical_id($id);
        if (!$auth->login($canon_id, $password)) {
            return new XMLRPCFault(1, "Authentication failed: {$id}({$canon_id})");
        }
    }
    return false;
}
Example #30
0
 public function auth()
 {
     $auth = new Auth();
     $_SESSION["login"] = $this->data["login"];
     $_SESSION["password"] = $this->format->hash($this->data["password"]);
     if ($auth->checkAdmin($_SESSION["login"], $_SESSION["password"])) {
         return $this->data["r"];
     } else {
         return $this->sm->message("ERROR_AUTH");
     }
 }