Beispiel #1
0
    public function action_facebookConnect()
    {
        assert(Auth::guest());
        $profile = Helper::facebook()->api('/me');
        $user = Model\User::where_facebook_id($profile['id'])->first();
        if (!$user) {
            $user = new Model\User();
            $user->facebook_id = $profile['id'];
            $user->name = $profile['name'];
            $user->save();
        }
        Auth::login($user->id);
        ?>
		<html>
			<head>
				<script type="text/javascript">
					if (window.opener) {
						window.opener.location = '<?php 
        echo URL::to_route('login');
        ?>
';
						window.close();
					} else {
						window.location = '<?php 
        echo URL::to_route('login');
        ?>
';
					}
				</script>
			</head>	
			<body>
			</body>
		</html>
		<?php 
    }
 /**
  * Login Procedure
  * @param $f3
  * @param $params
  */
 public function login($f3, $params)
 {
     if ($f3->exists('POST.username') && $f3->exists('POST.password')) {
         sleep(3);
         // login should take a while to kick-ass brute force attacks
         $user = new \Model\User();
         $user->load(array('username = ?', $f3->get('POST.username')));
         if (!$user->dry()) {
             // check hash engine
             $hash_engine = $f3->get('password_hash_engine');
             $valid = false;
             if ($hash_engine == 'bcrypt') {
                 $valid = \Bcrypt::instance()->verify($f3->get('POST.password'), $user->password);
             } elseif ($hash_engine == 'md5') {
                 $valid = md5($f3->get('POST.password') . $f3->get('password_md5_salt')) == $user->password;
             }
             if ($valid) {
                 @$f3->clear('SESSION');
                 //recreate session id
                 $f3->set('SESSION.user_id', $user->_id);
                 if ($f3->get('CONFIG.ssl_backend')) {
                     $f3->reroute('https://' . $f3->get('HOST') . $f3->get('BASE') . '/');
                 } else {
                     $f3->reroute('/cnc');
                 }
             }
         }
         \Flash::instance()->addMessage('Wrong Username/Password', 'danger');
     }
     $this->response->setTemplate('templates/login.html');
 }
Beispiel #3
0
 public function install($db_type)
 {
     $f3 = \Base::instance();
     $db_type = strtoupper($db_type);
     if ($db = storage::instance()->get($db_type)) {
         $f3->set('DB', $db);
     } else {
         $f3->error(256, 'no valid DB specified');
     }
     // setup the models
     \Model\Post::setup();
     \Model\Tag::setup();
     \Model\Comment::setup();
     \Model\User::setup();
     // create demo admin user
     $user = new \Model\User();
     $user->load(array('username = ?', 'admin'));
     if ($user->dry()) {
         $user->username = '******';
         $user->name = 'Administrator';
         $user->password = '******';
         $user->save();
         \Flash::instance()->addMessage('Admin User created,' . ' username: admin, password: fabulog', 'success');
     }
     \Flash::instance()->addMessage('Setup complete', 'success');
 }
Beispiel #4
0
 /**
  * Require a user to be logged in. Redirects to /login if a session is not found.
  * @param  int $rank
  * @return int|bool
  */
 protected function _requireLogin($rank = \Model\User::RANK_CLIENT)
 {
     $f3 = \Base::instance();
     if ($id = $f3->get("user.id")) {
         if ($f3->get("user.rank") >= $rank) {
             return $id;
         } else {
             $f3->error(403);
             $f3->unload();
             return false;
         }
     } else {
         if ($f3->get("site.demo") && is_numeric($f3->get("site.demo"))) {
             $user = new \Model\User();
             $user->load($f3->get("site.demo"));
             if ($user->id) {
                 $session = new \Model\Session($user->id);
                 $session->setCurrent();
                 $f3->reroute("/");
                 return;
             } else {
                 $f3->set("error", "Auto-login failed, demo user was not found.");
             }
         }
         if (empty($_GET)) {
             $f3->reroute("/login?to=" . urlencode($f3->get("PATH")));
         } else {
             $f3->reroute("/login?to=" . urlencode($f3->get("PATH")) . urlencode("?" . http_build_query($_GET)));
         }
         $f3->unload();
         return false;
     }
 }
Beispiel #5
0
 /**
  * Require an API key. Sends an HTTP 401 if one is not supplied.
  * @return int|bool
  */
 protected function _requireAuth()
 {
     $f3 = \Base::instance();
     $user = new \Model\User();
     // Use the logged in user if there is one
     if ($f3->get("user.api_key")) {
         $key = $f3->get("user.api_key");
     } else {
         $key = false;
     }
     // Check all supported key methods
     if (!empty($_GET["key"])) {
         $key = $_GET["key"];
     } elseif ($f3->get("HEADERS.X-Redmine-API-Key")) {
         $key = $f3->get("HEADERS.X-Redmine-API-Key");
     } elseif ($f3->get("HEADERS.X-API-Key")) {
         $key = $f3->get("HEADERS.X-API-Key");
     } elseif ($f3->get("HEADERS.X-Api-Key")) {
         $key = $f3->get("HEADERS.X-Api-Key");
     }
     $user->load(array("api_key = ?", $key));
     if ($key && $user->id && $user->api_key) {
         $f3->set("user", $user->cast());
         $f3->set("user_obj", $user);
         return $user->id;
     } else {
         $f3->error(401);
         return false;
     }
 }
Beispiel #6
0
 /**
  * return data to ajax
  * @author Adrian Berger <*****@*****.**>
  * @version 1.0.0
  * @param $database PDO Object
  * @access public
  * @return json Data
  */
 public function getData($database)
 {
     // checkuserexists = user tried to register and we tell him if the user is available or not, so he can can it
     // if its already in use
     if ($_POST['act'] == 'checkuserexists') {
         $user = new \Model\User('', '', '', '', '', '');
         $userExists = $user->checkUserExists($database, $_POST['user']);
         echo json_encode(array("value" => $userExists));
     }
 }
Beispiel #7
0
 /**
  * Convert a user ID to a user name
  * @param int $id
  * @return string
  */
 public function convertUserId($id)
 {
     if (isset($this->cache['user.' . $id])) {
         $user = $this->cache['user.' . $id];
     } else {
         $user = new \Model\User();
         $user->load($id);
         $this->cache['user.' . $id] = $user;
     }
     return $user->name;
 }
Beispiel #8
0
 public function addAction()
 {
     $this->_layoutRenderDisable();
     $this->_view->form = $form = new \Core\Form('adduser');
     if ($form->isValid()) {
         $model = new \Model\User();
         $model->save($form->getValues());
         $this->_view->success = true;
     } else {
         $this->_view->success = false;
     }
 }
Beispiel #9
0
 /**
  * Check what we have user with credentials
  *
  * @param $login
  * @param $password
  * @return bool
  * @throws \Exception\Model
  */
 public static function checkAuthData($login, $password)
 {
     try {
         $user = new \Model\User();
         $user->loadByLogin($login);
         if ($user->getPasswordHash($password) == $user->password) {
             $_SESSION['uid'] = $user->id;
             return true;
         }
     } catch (\Exception\ModelNotLoad $e) {
     }
     return false;
 }
 /**
  * Setup extended before filter controller.
  *
  * @return void
  */
 protected function extendedBeforeFilter()
 {
     $this->beforeFilter(function ($route, $request) {
         /* set array to query select */
         if (isset($this->model) && in_array("data_lenght", $this->options['before_filter'])) {
             $this->model->setSelectableFields(Input::get('data_lenght'));
         }
         /* Set security login. Role = developer! */
         if ((Input::get('dummy') == "true" || Input::get('dummy') == "1") && in_array("dummy", $this->options['before_filter'])) {
             if (isset($this->model)) {
                 return Response::json($this->model->describe());
             }
             return Response::json(array('data' => array('table' => 'null', 'fields' => [])));
         }
     });
 }
Beispiel #11
0
 public static function check($url = \GOTEO_REQUEST_URI, $user = null, $node = \GOTEO_NODE)
 {
     $url = static::fixURL($url);
     if (is_null($user)) {
         if (!User::isLogged()) {
             // @FIXME: Ajuste para permitir un perfil público sin usuario registrado.
             // (Es provisional hasta que se decida lo contrario)
             $user = new User();
             $user->id = '*';
             $user->roles = array((object) array('id' => 'public', 'name' => 'Perfil público'));
             $id = $user->id;
         } else {
             $user = $_SESSION['user'];
             $id = $user->id;
         }
     } elseif ($user instanceof User) {
         $id = $user->id;
     } else {
         if ($user = Model\User::get($user)) {
             $id = $user->id;
         }
     }
     $roles = $user->roles;
     array_walk($roles, function (&$role) {
         $role = $role->id;
     });
     $query = Model::query("\r\n                SELECT\r\n                    acl.allow\r\n                FROM acl\r\n                WHERE (:node LIKE REPLACE(acl.node_id, '*', '%'))\r\n                AND (:roles REGEXP REPLACE(acl.role_id, '*', '.'))\r\n                AND (:user LIKE REPLACE(acl.user_id, '*', '%'))\r\n                AND (:url LIKE REPLACE(acl.url, '*', '%'))\r\n                ORDER BY acl.id DESC\r\n                LIMIT 1\r\n                ", array(':node' => $node, ':roles' => implode(', ', $roles), ':user' => $id, ':url' => $url));
     return (bool) $query->fetchColumn();
 }
 public function testHasOneSimple()
 {
     // Find user with id `1`
     $user1 = Model\User::find(1);
     // Consist
     $this->assertInstanceOf('Gas\\ORM', $user1);
     $this->assertInstanceOf('Gas\\Data', $user1->record);
     // Check result
     $this->assertEquals($user1->id, '1');
     $this->assertEquals($user1->name, 'John Doe');
     $this->assertEquals($user1->email, '*****@*****.**');
     $this->assertEquals($user1->username, 'johndoe');
     // Grab related wife
     $user1_wife = $user1->wife();
     // Consist
     $this->assertInstanceOf('Gas\\ORM', $user1_wife);
     $this->assertInstanceOf('Gas\\Data', $user1_wife->record);
     // Check results, this should be `Patricia Doe` with `2` as her id
     $this->assertEquals($user1_wife->id, '2');
     $this->assertEquals($user1_wife->name, 'Patricia Doe');
     // Since the third parameter for user <-> wife relationship
     // contain `select:id,name` for pre-process relation
     // Other fields should be null
     $this->assertNull($user1_wife->hair_color);
 }
Beispiel #13
0
 public function get_group($f3)
 {
     $pagLimit = $f3->get("GET.limit") ?: 30;
     if ($pagLimit == -1) {
         $pagLimit = 100000;
     } elseif ($pagLimit < 0) {
         $pagLimit = 30;
     }
     $user = new \Model\User();
     $result = $user->paginate($f3->get("GET.offset") / $pagLimit, $pagLimit, "deleted_date IS NULL AND role = 'group' AND api_visible != '0'");
     $groups = array();
     foreach ($result["subset"] as $user) {
         $groups[] = $this->user_array($user);
     }
     $this->_printJson(array("total_count" => $result["total"], "limit" => $result["limit"], "groups" => $groups, "offset" => $result["pos"] * $result["limit"]));
 }
Beispiel #14
0
 public function testSaveUpdate()
 {
     // Create new resource
     $data = array('id' => 1, 'name' => 'Mr. Foo', 'username' => 'foo', 'email' => '*****@*****.**');
     Model\User::make($data)->save();
     // Get the new created resource
     $foo = Model\User::find(1);
     // At this moment, resource should contain all Mr. Foo values
     $this->assertEquals($foo->name, 'Mr. Foo');
     $this->assertEquals($foo->email, '*****@*****.**');
     $this->assertEquals($foo->username, 'foo');
     // Change all Foo's attribute into Bar
     $foo->name = 'Mr. Bar';
     $foo->email = '*****@*****.**';
     $foo->username = '******';
     // Update
     $foo->save();
     // Retrive back the user using old id
     $bar = Model\User::find(1);
     // Consist
     $this->assertInstanceOf('Gas\\ORM', $bar);
     $this->assertInstanceOf('Gas\\Data', $bar->record);
     // Check result
     $this->assertEquals($bar->id, '1');
     $this->assertEquals($bar->name, 'Mr. Bar');
     $this->assertEquals($bar->email, '*****@*****.**');
     $this->assertEquals($bar->username, 'bar');
 }
Beispiel #15
0
 public static function userDelete(\GO\Base\Model\User $user)
 {
     $dbxUser = Model\User::model()->findByPk($user->id);
     if ($dbxUser) {
         $dbxUser->delete();
     }
 }
Beispiel #16
0
 public function testAll()
 {
     // Populate all users
     $allusers = Model\User::all();
     // Should be an array, contain 4 user object
     $this->assertCount(4, $allusers);
     foreach ($allusers as $user) {
         // Consist
         $this->assertInstanceOf('Gas\\ORM', $user);
         $this->assertInstanceOf('Gas\\Data', $user->record);
         // Check results
         switch ($user->id) {
             case '1':
                 $this->assertEquals($user->name, 'John Doe');
                 $this->assertEquals($user->username, 'johndoe');
                 break;
             case '2':
                 $this->assertEquals($user->name, 'Derek Jones');
                 $this->assertEquals($user->username, 'derek');
                 break;
             case '3':
                 $this->assertEquals($user->name, 'Frank Sinatra');
                 $this->assertEquals($user->username, 'fsinatra');
                 break;
             case '4':
                 $this->assertEquals($user->name, 'Chris Martin');
                 $this->assertEquals($user->username, 'cmartin');
                 break;
         }
     }
 }
 /**
  * Installs tables with default user
  * @param $db_type
  */
 public function install($db_type)
 {
     $f3 = \Base::instance();
     $db_type = strtoupper($db_type);
     if ($db = DBHandler::instance()->get($db_type)) {
         $f3->set('DB', $db);
     } else {
         $f3->error(256, 'no valid Database Type specified');
     }
     // setup the models
     \Model\User::setup();
     \Model\Payload::setup();
     \Model\Webot::setup();
     // create demo admin user
     $user = new \Model\User();
     $user->load(array('username = ?', 'mth3l3m3nt'));
     if ($user->dry()) {
         $user->username = '******';
         $user->name = 'Framework Administrator';
         $user->password = '******';
         $user->email = '*****@*****.**';
         $user->save();
         //migrate payloads successfully
         $payload_file = $f3->ROOT . $f3->BASE . '/db_dump_optional/mth3l3m3nt_payload';
         if (file_exists($payload_file)) {
             $payload = new \Model\Payload();
             $payload_file_data = $f3->read($payload_file);
             $payloadarray = json_decode($payload_file_data, true);
             foreach ($payloadarray as $payloaddata) {
                 $payload->pName = $payloaddata['pName'];
                 $payload->pType = $payloaddata['pType'];
                 $payload->pCategory = $payloaddata['pCategory'];
                 $payload->pDescription = $payloaddata['pDescription'];
                 $payload->payload = $payloaddata['payload'];
                 $payload->save();
                 //ensures values set to null before continuing update
                 $payload->reset();
             }
             //migtate payloads
             \Flash::instance()->addMessage('Payload StarterPack: ,' . 'All Starter Pack Payloads added New database', 'success');
         } else {
             \Flash::instance()->addMessage('Payload StarterPack: ,' . 'StarterPack Database not Found no payloads installed ', 'danger');
         }
         \Flash::instance()->addMessage('Admin User created,' . ' username: mth3l3m3nt, password: mth3l3m3nt', 'success');
     }
     \Flash::instance()->addMessage('New Database Setup Completed', 'success');
 }
Beispiel #18
0
 /**
  * @see Gas\Core   (./classes/core.php)
  * @see Model\User (./tests/dummyModels/user.php)
  * @see Model\Wife (./tests/dummyModels/wife.php)
  */
 public function setUp()
 {
     // Prepare some table(s) for test,
     // and connect using related environment
     Model\User::setUp();
     Model\Wife::setUp();
     $this->db = Gas\Core::$db;
 }
Beispiel #19
0
 public function __construct(PDO $db, $key = 'user_id')
 {
     if (isset($_SESSION[$key])) {
         if ($user = Model\User::find(array($key => $_SESSION[$key]))) {
             $this->user = new Model\User($user);
         }
     }
 }
Beispiel #20
0
 public function delegate()
 {
     // Analyze route
     $this->getController($module, $controller, $action, $args);
     //assign args
     $this->extractArgs($args);
     $me = new \Model\User();
     $me->updateFromSession($this->registry);
     if ($me->checkPerm($this->registry, $notfound, $notlogin)) {
         $this->registry->me = $me;
     } elseif ($notfound) {
         $classmapList = classmapList();
         if (isset($classmapList[$module . '\\notfound'])) {
             $controller = 'notfound';
         } else {
             $module = 'site';
             $controller = 'notfound';
         }
     } elseif ($notlogin) {
         $returnUrl = base64_encode(Helper::curPageURL());
         $classmapList = classmapList();
         if (isset($classmapList[$module . '\\login'])) {
             $controller = 'login';
             $redirectUrl = $this->registry->conf['rooturl_' . $module] . 'login?redirect=' . $returnUrl;
         } else {
             $module = 'site';
             $controller = 'login';
             $redirectUrl = $this->registry->conf['rooturl'] . 'login?redirect=' . $returnUrl;
         }
         $this->registry->response->setStatusCode(302);
         $this->registry->response->headers->set('location', $redirectUrl);
     }
     if (!$notlogin) {
         //reassign module, controller and action because it can be change on the conditions above
         $this->registry->module = $module;
         $this->registry->controller = $controller;
         $this->registry->action = $action;
         // Initiate the class
         $class = '\\controller\\' . $module . '\\' . $controller;
         $controller = new $class($this->registry);
         //refine action string : append Action
         $action .= 'Action';
         // Run action
         $controller->{$action}();
     }
 }
function select()
{
    $rows = Model\User::find();
    foreach ($rows as $row) {
        $row->actions = "{'username': '******'}";
    }
    return $rows;
}
Beispiel #22
0
 /**
  * POST /login
  * @param \Base $fw
  * @return void
  */
 public function login(\Base $fw)
 {
     if ($this->_getUser()) {
         $fw->reroute('/dashboard');
     }
     $username = $fw->get('POST.username');
     $password = $fw->get('POST.password');
     $user = new \Model\User();
     $user->load(array('username = ?', $username));
     if ($user->id) {
         if (password_verify($password, $user->password)) {
             $fw->set('SESSION.user_id', $user->id);
             $fw->reroute('/dashboard');
         }
     }
     $fw->set('error', 'Invalid username or password.');
     $this->_render('index.html');
 }
Beispiel #23
0
 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
     BaseModel::unguard();
     DB::table('users')->truncate();
     Model\User::create(['act' => '1', 'role_id' => '1', 'email' => '*****@*****.**', 'name' => 'admin', 'password' => 'nthvf8vg8akfq']);
     Model\User::create(['act' => '1', 'role_id' => '2', 'email' => '*****@*****.**', 'name' => 'moderator', 'password' => 'moderator']);
     Model\User::create(['act' => '1', 'role_id' => '3', 'email' => '*****@*****.**', 'name' => 'user1', 'password' => 'user1']);
     Model\User::create(['act' => '1', 'role_id' => '3', 'email' => '*****@*****.**', 'name' => 'user2', 'password' => 'user2']);
 }
Beispiel #24
0
 public function removeAvatar($user_id)
 {
     $user = Model\User::findOrFail($user_id);
     $filename = $user->profile->avatar;
     if (file_exists(PATH_AVATAR . '/' . $filename)) {
         unlink(PATH_AVATAR . '/' . $filename);
     }
     $user->profile->update(['avatar' => '']);
 }
 public function testAggregateSum()
 {
     // Get summed of all users `id`
     $user_sum = Model\User::sum();
     // Consist
     $this->assertInstanceOf('Gas\\ORM', $user_sum);
     $this->assertInstanceOf('Gas\\Data', $user_sum->record);
     // The summed id would be (1+2+3+4) = 10
     $this->assertEquals($user_sum->id, '10');
 }
 public function createAction()
 {
     //	init
     $this->init();
     //  if form submitted
     if ($this->request->getPost('action') == 'save') {
         //  save new user
         $user = new \Model\User();
         $user->firstName = $this->request->getPost('firstName', 'string');
         $user->lastName = $this->request->getPost('lastName', 'string');
         $user->username = $this->request->getPost('username', 'string');
         $user->password = $this->request->getPost('password', 'string');
         $user->save();
         //  redirect
         $this->response->redirect(ROOT . 'admin/users/', true);
     }
     //	set main view
     $this->view->setMainView('block-module-users/admin-create');
 }
function validatePrivileges($privileges = array(), $no_error = false)
{
    return function () use($privileges, $no_error) {
        try {
            // Inicjalizacja modelu użytkownika
            $user = new \Model\User();
            // Pobranie instancji szkieletu Slim Framework
            $app = \Slim\Slim::getInstance();
            // Pobranie tokenu z pola Authorization nagłówka HTTP i jego walidacja
            $token = validateToken($app->request->headers->get('Authorization'));
            try {
                // Pobranie danych uzytkownika o zadanym tokenie
                $u = $user->getByToken($token, 'administrator');
            } catch (Exception $e) {
                throw new Exception('Użytkownik nie jest zalogowany.', 401);
            }
            // Sprawdzenie wymaganych uprawnień
            if (!in_array($u['privileges'], $privileges)) {
                throw new Exception('Brak uprawnień.', 401);
            }
            // Zapamiętanie danych potrzebnych do logowania jako zmienne globalne
            $GLOBALS['user_id'] = $u['user_id'];
            $GLOBALS['token'] = $token;
            $GLOBALS['privileges'] = $u['privileges'];
            try {
                // Jeśli różnica pomiędzy ostatnią aktywnością, a bierzącym czasem
                // wynosi 60 sekund, to odświeżamy autoryzację
                $diff = abs(strtotime(date('Y-m-d H:i:s')) - strtotime($u['last_auth']));
                if ($diff > 60) {
                    $res = $user->refreshAuth($token);
                }
            } catch (Exception $e) {
            }
        } catch (Exception $e) {
            $GLOBALS['user_id'] = -1;
            $GLOBALS['token'] = '';
            $GLOBALS['privileges'] = 'guest';
            if (!$no_error) {
                jsonError($app, $e, true);
            }
        }
    };
}
Beispiel #28
0
 /**
  * Create a User instance given an id from the user table 
  * @param type $userId     id of row in user table
  * @return User or null
  */
 public static function constructById($userId)
 {
     $row = Model\User::getUserById($userId);
     $row = isset($row[0]) ? $row[0] : $row;
     if (isset($row['id'])) {
         $user = self::constructByRow($row);
         $user->setId($row['id']);
         return $user;
     }
     return null;
 }
 public function testApiMake()
 {
     // A model could be either instantiated or use `make` method
     $user_instantiated = new Model\User();
     $user_non_instantiated = Model\User::make();
     // Both should be instance of Gas ORM
     $this->assertInstanceOf('Gas\\ORM', $user_instantiated);
     $this->assertInstanceOf('Gas\\ORM', $user_non_instantiated);
     // Both should be equally same
     $this->assertEquals($user_instantiated, $user_non_instantiated);
 }
Beispiel #30
0
 public function testFindSingle()
 {
     // Find user with id `1`
     $user1 = Model\User::find(1);
     // Consist
     $this->assertInstanceOf('Gas\\ORM', $user1);
     $this->assertInstanceOf('Gas\\Data', $user1->record);
     // Check result
     $this->assertEquals($user1->id, '1');
     $this->assertEquals($user1->name, 'John Doe');
     $this->assertEquals($user1->email, '*****@*****.**');
     $this->assertEquals($user1->username, 'johndoe');
 }