function show()
 {
     $method = HTTP::_GP('method', '');
     $method = strtolower(str_replace(array('_', '\\', '/', '.', ""), '', $method));
     $path = 'includes/classes/extauth/' . $method . '.class.php';
     if (!file_exists($path)) {
         HTTP::redirectTo('index.php');
     }
     $session = Session::create();
     require 'includes/classes/extauth/externalAuth.interface.php';
     require $path;
     $methodClass = ucwords($method) . 'Auth';
     /** @var $authObj externalAuth */
     $authObj = new $methodClass();
     if (!$authObj->isActiveMode()) {
         $session->delete();
         $this->redirectTo('index.php?code=5');
     }
     if (!$authObj->isValid()) {
         $session->delete();
         $this->redirectTo('index.php?code=4');
     }
     $loginData = $authObj->getLoginData();
     if (empty($loginData)) {
         $session->delete();
         $this->redirectTo('index.php?page=register&externalAuth[account]=' . $authObj->getAccount() . '&externalAuth[method]=facebook');
     }
     $session->userId = (int) $loginData['id'];
     $session->adminAccess = 0;
     $session->save();
     $this->redirectTo("game.php");
 }
예제 #2
0
 public static function Create($p_sessionId, &$p_objectId, $p_objectTypeId = null, $p_userId = null, $p_updateStats = false)
 {
     if (empty($p_sessionId)) {
         throw new SessionIdNotSet();
     }
     $session = new Session($p_sessionId);
     if (!$session->exists()) {
         $sessionParams = array('start_time' => strftime("%Y-%m-%d %T"));
         if (!empty($p_userId)) {
             $sessionParams['user_id'] = $p_userId;
         }
         $session->create($sessionParams);
     }
     $sessionUserId = $session->getUserId();
     if (!empty($p_userId) && !empty($sessionUserId) && $sessionUserId != $p_userId) {
         throw new InvalidUserId();
     }
     $requestObject = new RequestObject($p_objectId);
     if (!$requestObject->exists()) {
         if (empty($p_objectTypeId)) {
             throw new ObjectTypeIdNotSet();
         }
         $requestObject->create(array('object_type_id' => $p_objectTypeId));
         $p_objectId = $requestObject->getObjectId();
     } elseif (empty($p_objectId)) {
         throw new ObjectIdNotSet();
     }
     if ($p_updateStats) {
         self::UpdateStats($p_sessionId, $p_objectId);
     }
 }
 public function run()
 {
     $faker = Faker::create();
     foreach (range(1, 10) as $index) {
         Session::create([]);
     }
 }
예제 #4
0
 function show()
 {
     if (empty($_POST)) {
         HTTP::redirectTo('index.php');
     }
     $db = Database::get();
     $username = HTTP::_GP('username', '', UTF8_SUPPORT);
     $password = HTTP::_GP('password', '', true);
     $sql = "SELECT id, password FROM %%USERS%% WHERE universe = :universe AND username = :username;";
     $loginData = $db->selectSingle($sql, array(':universe' => Universe::current(), ':username' => $username));
     if (isset($loginData)) {
         $hashedPassword = PlayerUtil::cryptPassword($password);
         if ($loginData['password'] != $hashedPassword) {
             // Fallback pre 1.7
             if ($loginData['password'] == md5($password)) {
                 $sql = "UPDATE %%USERS%% SET password = :hashedPassword WHERE id = :loginID;";
                 $db->update($sql, array(':hashedPassword' => $hashedPassword, ':loginID' => $loginData['id']));
             } else {
                 HTTP::redirectTo('index.php?code=1');
             }
         }
         $session = Session::create();
         $session->userId = (int) $loginData['id'];
         $session->adminAccess = 0;
         $session->save();
         HTTP::redirectTo('game.php');
     } else {
         HTTP::redirectTo('index.php?code=1');
     }
 }
예제 #5
0
 public static function createForLogin($app, $steamID, $user)
 {
     $steamProfile = $app->steam->getUser($steamID);
     $steamInventory = $app->steam->getInventory($steamID);
     $steamBans = $app->steam->getBans($steamID);
     if ($app->config->get('mode') == 'production') {
         if (!empty($steamProfile->timecreated) && time() - $steamProfile->timecreated < Steam::STEAM_AGE_THRESHOLD) {
             throw new User_TooNew();
         }
     }
     if (!empty($steamBans->VACBanned)) {
         throw new User_SteamBanned('VAC Banned');
     }
     if (!empty($steamBans->CommunityBanned)) {
         throw new User_SteamBanned('Steam Community Banned');
     }
     if (!empty($steamBans->EconomyBan) && strcmp($steamBans->EconomyBan, 'none') != 0) {
         throw new User_SteamBanned('Steam Economy Banned');
     }
     $hash = Session::createHash($steamID);
     $session = Session::create(['hash' => $hash, 'user_id' => $steamID, 'user_agent' => $_SERVER['HTTP_USER_AGENT'], 'ip' => $_SERVER['REMOTE_ADDR']]);
     $user->name = $steamProfile->personaname;
     $user->profile_private = $steamProfile->communityvisibilitystate == 3 ? 0 : 1;
     $user->inventory_private = $steamInventory ? 0 : 1;
     $user->ip_last = $_SERVER['REMOTE_ADDR'];
     if (empty($user->ip_register)) {
         $user->ip_register = $_SERVER['REMOTE_ADDR'];
         $user->name_register = $steamProfile->personaname;
     }
     $user->save();
     setcookie('csgoshop_session', $hash, time() + 60 * 60 * 24 * 30, '/');
     setcookie('csrf', $session->csrf_token, time() + 60 * 60 * 24 * 30, '/');
 }
예제 #6
0
 public static function get_session()
 {
     if (!self::$session) {
         // Generate the session ID.  This is slightly wasteful.
         $data = array();
         $data['type'] = 'stream';
         // This shouldn't be done here but at backend endpoint side
         if (isset($_REQUEST['client'])) {
             $data['agent'] = $_REQUEST['client'];
         }
         // Copy session geolocation
         // Same thing, should be done elsewhere
         $sid = session_id();
         if ($sid) {
             $location = Session::get_geolocation($sid);
             if (isset($location['latitude'])) {
                 $data['geo_latitude'] = $location['latitude'];
             }
             if (isset($location['longitude'])) {
                 $data['geo_longitude'] = $location['longitude'];
             }
             if (isset($location['name'])) {
                 $data['geo_name'] = $location['name'];
             }
         }
         self::$session = Session::create($data);
     }
     return self::$session;
 }
예제 #7
0
		public static function login($model){
			$model = self::authenticate($model);
			
			if(!$model['valid']){
				return $model;
			}
			
			return Session::create($model);
		}
예제 #8
0
 function show()
 {
     $userData = $this->_activeUser();
     $session = Session::create();
     $session->userId = (int) $userData['userID'];
     $session->adminAccess = 0;
     $session->save();
     HTTP::redirectTo('game.php');
 }
 private function change_password($user_id, $change_password_pass, $password)
 {
     PHPBoostAuthenticationMethod::update_auth_infos($user_id, null, null, KeyGenerator::string_hash($password), null, '');
     $session = AppContext::get_session();
     if ($session != null) {
         Session::delete($session);
     }
     AppContext::set_session(Session::create($user_id, true));
     AppContext::get_response()->redirect(Environment::get_home_page());
 }
예제 #10
0
 /**
  * Method to load and check if a session is available.
  * @param string $redirectURL The url which will be used for redirect.
  * @since 0.0.1-dev
  */
 protected function needSession($redirectURL = URL)
 {
     //create the session.
     $session = new Session();
     $session->create(Database::getInstance()->getConnection());
     //check if the session is available.
     if (isset($_SESSION['user_username']) === false) {
         $this->redirect($redirectURL);
     }
 }
예제 #11
0
 public function login($login, $password)
 {
     $results = $this->db_handler->query('SELECT id FROM users WHERE login = "******" AND password = "******"');
     $user = $results->fetch_assoc();
     if ($results->num_rows) {
         Session::create($user['id']);
         return true;
     } else {
         return false;
     }
 }
예제 #12
0
 public function testCreateAndDestroy()
 {
     Session::create(__FILE__);
     $instance1 = Session::getCurrent();
     Session::create(__FILE__);
     $instance2 = Session::getCurrent();
     $instance3 = Session::getCurrent();
     Session::destroy();
     $instance4 = Session::getCurrent();
     $this->assertSame($instance1, $instance4);
     $this->assertSame($instance2, $instance3);
     $this->assertTrue($instance1 !== $instance2);
 }
 /**
  * @desc Tries to authenticate the user using the given authentication method.
  * @param AuthenticationMethod $authentication the authentication method to use
  * @param bool $autoconnect If true, an autoconnect cookie will be created
  * @return int $user_id, if authentication has been performed successfully
  */
 public static function authenticate(AuthenticationMethod $authentication, $autoconnect = false)
 {
     $user_id = $authentication->authenticate();
     if ($user_id) {
         $session = AppContext::get_session();
         if ($session != null) {
             Session::delete($session);
         }
         $session_data = Session::create($user_id, $autoconnect);
         AppContext::set_session($session_data);
     }
     return $user_id;
 }
 private function check_activation($registration_pass)
 {
     $user_id = PHPBoostAuthenticationMethod::registration_pass_exists($registration_pass);
     if ($user_id) {
         PHPBoostAuthenticationMethod::update_auth_infos($user_id, null, true, null, '');
         $session = AppContext::get_session();
         if ($session != null) {
             Session::delete($session);
         }
         AppContext::set_session(Session::create($user_id, true));
         AppContext::get_response()->redirect(Environment::get_home_page());
     } else {
         $controller = new UserErrorController($this->lang['profile'], LangLoader::get_message('process.error', 'status-messages-common'), UserErrorController::WARNING);
         DispatchManager::redirect($controller);
     }
 }
예제 #15
0
 public static function login($email, $password, $remember)
 {
     $row = self::find_one_by(array('user_email' => $email, 'user_status' => St::VALID));
     if (empty($row)) {
         return false;
     }
     if ($row->user_password != Auth::hash_password($password)) {
         return false;
     }
     $row->user_last_login = System::now();
     $row->save();
     Session::create();
     $close = !(bool) $remember;
     Session::set('expire_on_close', $close);
     Session::set(self::$_table_name, $row);
     return true;
 }
예제 #16
0
function ShowLoginPage()
{
    global $USER;
    $session = Session::create();
    if ($session->adminAccess == 1) {
        HTTP::redirectTo('admin.php');
    }
    if (isset($_REQUEST['admin_pw'])) {
        $password = PlayerUtil::cryptPassword($_REQUEST['admin_pw']);
        if ($password == $USER['password']) {
            $session->adminAccess = 1;
            HTTP::redirectTo('admin.php');
        }
    }
    $template = new template();
    $template->assign_vars(array('bodyclass' => 'standalone', 'username' => $USER['username']));
    $template->show('LoginPage.tpl');
}
예제 #17
0
 /**
  * @see AuthInterface::login()
  * @param string $username
  * @param string $password
  * @return bool
  */
 public function login($username, $password)
 {
     if ($username and $password) {
         $system_log = new SystemLog(null);
         if (User::exist_username($username)) {
             $user_id = User::get_user_id_by_username($username);
             $user = new User($user_id);
             if ($user->check_password($password)) {
                 if ($user->get_boolean_user_entry("user_inactive") == false) {
                     $session = new Session(null);
                     $session_id = $session->create($user_id);
                     $this->session_id = $session_id;
                     if ($user->get_boolean_user_entry("must_change_password") == true) {
                         $session->write_value("must_change_password", true, true);
                     }
                     if ($user->get_boolean_user_entry("user_locked") == true) {
                         $session->write_value("user_locked", true, false);
                     }
                     // Login Successful
                     $system_log->create($user_id, 1, 1, "Login Successful", "Login", "auth.php", null, null);
                     return true;
                 } else {
                     // Inactive Login
                     $system_log->create($user_id, 1, 1, "Inactive User", "Login", "auth.php", null, null);
                     return false;
                 }
             } else {
                 // Wring Password
                 $system_log->create($user_id, 1, 0, "Wrong Password", "Login", "auth.php", null, null);
                 return false;
             }
         } else {
             // User Not Found
             $system_log->create(null, 1, 0, "User \"" . $username . "\" Not Found", "Login", "auth.php", null, null);
             return false;
         }
     } else {
         return false;
     }
 }
예제 #18
0
 private function parseDescriptionUrl($descriptionUrl)
 {
     debug_event('upnpdevice', 'parseDescriptionUrl: ' . $descriptionUrl, 5);
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $descriptionUrl);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     $response = curl_exec($ch);
     curl_close($ch);
     //!!debug_event('upnpdevice', 'parseDescriptionUrl response: ' . $response, 5);
     $responseXML = simplexml_load_string($response);
     $services = $responseXML->device->serviceList->service;
     foreach ($services as $service) {
         $serviceType = $service->serviceType;
         $serviceTypeNames = explode(":", $serviceType);
         $serviceTypeName = $serviceTypeNames[3];
         $this->_settings['controlURLs'][$serviceTypeName] = (string) $service->controlURL;
         $this->_settings['eventURLs'][$serviceTypeName] = (string) $service->eventSubURL;
     }
     $urldata = parse_url($descriptionUrl);
     $this->_settings['host'] = $urldata['scheme'] . '://' . $urldata['host'] . ':' . $urldata['port'];
     $this->_settings['descriptionURL'] = $descriptionUrl;
     Session::create(array('type' => 'api', 'sid' => 'upnp_dev_' . $descriptionUrl, 'value' => serialize($this->_settings)));
 }
예제 #19
0
 function indexAction()
 {
     $session = Session::create("admin", "admin", "http://localhost:8080/alfresco/api");
     $spacesStore = new SpacesStore($session);
     $selected = $this->_getParam('id');
     $root = null;
     if (!$selected) {
         $root = $spacesStore->getCompanyHome();
     } else {
         $root = $this->getNode($session, $spacesStore, $selected);
     }
     /* @var $root Node */
     $children = $root->getChildren();
     if ($root->getPrimaryParent() != null) {
         echo '<a href="?id=' . $root->getPrimaryParent()->getId() . '">..</a><br/>';
     }
     foreach ($children as $childAssociation) {
         /* @var $childAssociation ChildAssociation */
         $child = $childAssociation->getChild();
         /* @var $child Node */
         echo '<a href="?id=' . $child->getId() . '">' . $childAssociation->getChild()->cm_name . "</a><br/>";
     }
 }
예제 #20
0
 /**
  * Checks to see if the given username and password are valid for this site,
  * and if they are, log the user in.
  * Roles, roles by title and extra user data are all stored in the user's session once
  * they are logged in.
  *
  * Roles are marked differently if the user has the role explicitly or given to them
  * by a title they have.
  *
  * Extra data is stored as key => value pairs within the user's session.
  *
  * @param string $login
  * @param string $password
  * @return boolean Return true on success, false on failure.
  */
 public static function login($login, $password)
 {
     if (user::loggedin()) {
         return true;
     }
     $db = DBFactory::getDBQuery(true);
     $db->execute("SELECT usr_id,usr_login,usr_pass,usr_pilot_id FROM kb3_user" . " WHERE usr_login='******' AND usr_state=0 and usr_site='" . KB_SITE . "' AND usr_pass = '******'");
     if (!$db->recordCount()) {
         return false;
     }
     $roles = array();
     $user = null;
     Session::create();
     $row = $db->getRow();
     $user = $row;
     $userID = $row['usr_id'];
     // Extra data
     $db->execute("SELECT * FROM kb3_user_extra WHERE use_usr_id = " . $userID);
     while ($row = $db->getRow()) {
         $user[$row['use_key']] = $row['use_value'];
     }
     // Titles
     $db->execute("SELECT DISTINCT rol_id FROM kb3_user_titles t INNER JOIN kb3_titles_roles r ON t.ust_ttl_id = r.ttl_id WHERE t.ust_usr_id = " . $userID);
     while ($row = $db->getRow()) {
         $roles[$row['rol_id']] = 2;
     }
     // Roles
     $db->execute("SELECT uro_rol_id FROM kb3_user_roles WHERE uro_usr_id = " . $userID);
     while ($row = $db->getRow()) {
         $roles[$row['uro_rol_id']] = 1;
     }
     $user['roles'] = $roles;
     $_SESSION['user'] = $user;
     user::loggedin(true);
     event::call("user_login", $user);
     return true;
 }
예제 #21
0
 function show()
 {
     $method = HTTP::_GP('method', '');
     $method = strtolower(str_replace(array('_', '\\', '/', '.', ""), '', $method));
     if (!file_exists('includes/extauth/' . $method . '.class.php')) {
         HTTP::redirectTo('index.php');
     }
     Session::init();
     require 'includes/extauth/' . $method . '.class.php';
     $methodClass = ucwords($method) . 'Auth';
     $authObj = new $methodClass();
     if (!$authObj->isActiveMode()) {
         $this->redirectTo('index.php?code=5');
     }
     if (!$authObj->isVaild()) {
         $this->redirectTo('index.php?code=4');
     }
     $loginData = $authObj->getLoginData();
     if (empty($loginData)) {
         $this->redirectTo('index.php?page=register&externalAuth[account]=' . $authObj->getAccount() . '&externalAuth[method]=facebook');
     }
     Session::create($loginData['id'], $loginData['id_planet']);
     $this->redirectTo("game.php");
 }
예제 #22
0
 /**
  * url
  * This returns the constructed URL for the art in question
  * @param int $uid
  * @param string $type
  * @param string $sid
  * @param int|null $thumb
  * @return string
  */
 public static function url($uid, $type, $sid = null, $thumb = null)
 {
     if (!Core::is_library_item($type)) {
         return null;
     }
     if (AmpConfig::get('use_auth') && AmpConfig::get('require_session')) {
         $sid = $sid ? scrub_out($sid) : scrub_out(session_id());
         if ($sid == null) {
             $sid = Session::create(array('type' => 'api'));
         }
     }
     $key = $type . $uid;
     if (parent::is_cached('art', $key . '275x275') && AmpConfig::get('resize_images')) {
         $row = parent::get_from_cache('art', $key . '275x275');
         $mime = $row['mime'];
     }
     if (parent::is_cached('art', $key . 'original')) {
         $row = parent::get_from_cache('art', $key . 'original');
         $thumb_mime = $row['mime'];
     }
     if (!isset($mime) && !isset($thumb_mime)) {
         $sql = "SELECT `object_type`, `object_id`, `mime`, `size` FROM `image` WHERE `object_type` = ? AND `object_id` = ?";
         $db_results = Dba::read($sql, array($type, $uid));
         while ($row = Dba::fetch_assoc($db_results)) {
             parent::add_to_cache('art', $key . $row['size'], $row);
             if ($row['size'] == 'original') {
                 $mime = $row['mime'];
             } else {
                 if ($row['size'] == '275x275' && AmpConfig::get('resize_images')) {
                     $thumb_mime = $row['mime'];
                 }
             }
         }
     }
     $mime = isset($thumb_mime) ? $thumb_mime : (isset($mime) ? $mime : null);
     $extension = self::extension($mime);
     if (AmpConfig::get('stream_beautiful_url')) {
         if (empty($extension)) {
             $extension = 'jpg';
         }
         $url = AmpConfig::get('web_path') . '/play/art/' . $sid . '/' . scrub_out($type) . '/' . scrub_out($uid) . '/thumb';
         if ($thumb) {
             $url .= $thumb;
         }
         $url .= '.' . $extension;
     } else {
         $url = AmpConfig::get('web_path') . '/image.php?object_id=' . scrub_out($uid) . '&object_type=' . scrub_out($type) . '&auth=' . $sid;
         if ($thumb) {
             $url .= '&thumb=' . $thumb;
         }
         if (!empty($extension)) {
             $name = 'art.' . $extension;
             $url .= '&name=' . $name;
         }
     }
     return $url;
 }
예제 #23
0
파일: admin.php 프로젝트: bergi9/2Moons
 * @author Jan Kröpke <*****@*****.**>
 * @copyright 2012 Jan Kröpke <*****@*****.**>
 * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License
 * @version 1.7.2 (2013-03-18)
 * @info $Id$
 * @link http://2moons.cc/
 */
define('MODE', 'ADMIN');
define('DATABASE_VERSION', 'OLD');
define('ROOT_PATH', str_replace('\\', '/', dirname(__FILE__)) . '/');
require 'includes/common.php';
require 'includes/classes/class.Log.php';
if ($USER['authlevel'] == AUTH_USR) {
    HTTP::redirectTo('game.php');
}
$session = Session::create();
if ($session->adminAccess != 1) {
    include_once 'includes/pages/adm/ShowLoginPage.php';
    ShowLoginPage();
    exit;
}
$uni = HTTP::_GP('uni', 0);
if ($USER['authlevel'] == AUTH_ADM && !empty($uni)) {
    Universe::setEmulated($uni);
}
$page = HTTP::_GP('page', '');
switch ($page) {
    case 'logout':
        include_once 'includes/pages/adm/ShowLogoutPage.php';
        ShowLogoutPage();
        break;
예제 #24
0
 /**
  * Log the user into the system
  *
  * @param unknown_type $oUser
  * @return unknown
  */
 function performLogin(&$oUser)
 {
     if (!is_a($oUser, 'User')) {
     }
     $session = new Session();
     $sessionID = $session->create($oUser);
     if (PEAR::isError($sessionID)) {
         return $sessionID;
     }
     $redirect = strip_tags(KTUtil::arrayGet($_REQUEST, 'redirect'));
     // DEPRECATED initialise page-level authorisation array
     $_SESSION["pageAccess"] = NULL;
     $cookietest = KTUtil::randomString();
     setcookie("CookieTestCookie", $cookietest, 0);
     $this->redirectTo('checkCookie', array('cookieVerify' => $cookietest, 'redirect' => $redirect));
     exit(0);
 }
예제 #25
0
 function declineAction()
 {
     // Check that this is the true reviewer
     $email = $this->getRequest()->getParam("email");
     $password = $this->getRequest()->getParam("password");
     $idSession = session_id();
     // Delete the curent session if any
     $this->deleteCurrentSession();
     // Now, try to open a session with the email and password
     $sessionTbl = new Session();
     if (!$sessionTbl->create($email, $password, $idSession)) {
         // No way to open a session? Something wrong: redirect to the home page.
         $redirect = $this->view->base_url . "/";
         $this->_redirect($redirect);
     }
     // Get the user and remove the 'reviewer' role
     $user = new User();
     $userRow = $user->findByEmail($email);
     $userRow->removeRole(User::REVIEWER_ROLE);
     $userRow->save();
     // Put the user and the config in the view
     $userRow->putInView($this->view);
     // And, finally: send a message to the chair, and show a polite ack.
     $mail = new Mail(Mail::PC_CHAIR, $this->texts->mail->subj_decline_invitation, $this->view->getScriptPaths());
     $mail->loadTemplate($this->lang, "decline_invitation");
     $mail->getEngine()->invited_user = $this->user->fullName();
     $mail->send();
     $this->view->setFile("content", "decline.xml");
     echo $this->view->render("layout");
 }
예제 #26
0
 /**
  * auto_init
  * This is called on class load it sets the session
  */
 public static function _auto_init()
 {
     // Generate the session ID.  This is slightly wasteful.
     $data = array();
     $data['type'] = 'stream';
     if (isset($_REQUEST['client'])) {
         $data['agent'] = $_REQUEST['client'];
     }
     self::$session = Session::create($data);
 }
예제 #27
0
 function performLogin(&$oUser)
 {
     if (!is_a($oUser, 'User')) {
         #var_dump($oUser);
         #var_dump(PEAR::raiseError());
     }
     /*
     Removing the code that redirects to the dashboard as it breaks linking in from external documents.
     The fix below doesn't work if the users are behind a proxy server.
     
     // If the last user from the same IP address timed out within the last hour then redirect to the dashboard
     // Otherwise allow any other redirect to continue.
     // The user might still be taken to the last page of the previous users session but
     // if we always redirect to dashboard then we break other features such as linking in from emails or documents.
     if (checkLastSessionUserID($oUser->getId()))
     {
     	$_REQUEST['redirect'] = generateControllerLink('dashboard');
     }
     */
     $session = new Session();
     $sessionID = $session->create($oUser);
     if (PEAR::isError($sessionID)) {
         return $sessionID;
     }
     $redirect = strip_tags(KTUtil::arrayGet($_REQUEST, 'redirect'));
     // DEPRECATED initialise page-level authorisation array
     $_SESSION["pageAccess"] = NULL;
     $cookietest = KTUtil::randomString();
     setcookie("CookieTestCookie", $cookietest, 0);
     $this->redirectTo('checkCookie', array('cookieVerify' => $cookietest, 'redirect' => $redirect));
     exit(0);
 }
예제 #28
0
파일: auth.php 프로젝트: RHY3756547/FreeSO
 *		{user: "", pass: ""}
 *
 * Response Wrapper Body:
 *		{token: ..., expires: ...}
 */
include_once "utils.php";
include_once "model.php";
/** Validate **/
$username = requireParam("user");
$password = requireParam("pass");
$passwordHash = md5(md5($password) . $salt);
/** Check the DB for this user / pass combination **/
$account = Account::fromCredentials($username, $passwordHash);
if ($account == false) {
    error('User not found', 600);
}
if ($account->status != 1) {
    error('Account suspended', 601);
}
/** Kill old sessions **/
Session::clearForAccount($account->accountId);
/** Create a session **/
$session = new Session();
$session->sessionId = gen_uuid();
$session->accountId = $account->accountId;
$session->expires = sqlDate(time() + 1200);
if ($session->create()) {
    success(array('valid' => true, 'uid' => $account->uuid, 'sessionID' => $session->sessionId, 'sessionStart' => $session->created, 'sessionEnd' => $session->expires));
} else {
    error('Failed to create session', 602);
}
예제 #29
0
 public static function auth_user()
 {
     $isLocal = self::is_local();
     $headers = apache_request_headers();
     $myplex_token = $headers['X-Plex-Token'];
     if (empty($myplex_token)) {
         $myplex_token = $_REQUEST['X-Plex-Token'];
     }
     if (!$isLocal) {
         $match_users = AmpConfig::get('plex_match_email');
         $myplex_username = $headers['X-Plex-Username'];
         if (empty($myplex_token)) {
             // Never fail OPTIONS requests
             if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
                 self::setPlexHeader($headers);
                 exit;
             } else {
                 debug_event('Access Control', 'Authentication token is missing.', '3');
                 self::createError(401);
             }
         }
         $createSession = false;
         Session::gc();
         $username = "";
         $email = trim(Session::read((string) $myplex_token));
         if (empty($email)) {
             $createSession = true;
             $xml = self::get_server_authtokens();
             $validToken = false;
             foreach ($xml->access_token as $tk) {
                 if ((string) $tk['token'] == $myplex_token) {
                     $username = (string) $tk['username'];
                     // We should apply filter and access restriction to shared sections only, but that's not easily possible with current Ampache architecture
                     $validToken = true;
                     break;
                 }
             }
             if (!$validToken) {
                 debug_event('Access Control', 'Auth-Token ' . $myplex_token . ' invalid for this server.', '3');
                 self::createError(401);
             }
         }
         // Need to get a match between Plex and Ampache users
         if ($match_users) {
             if (!AmpConfig::get('access_control')) {
                 debug_event('Access Control', 'Error Attempted to use Plex with Access Control turned off and plex/ampache link enabled.', '3');
                 self::createError(401);
             }
             if (empty($email)) {
                 $xml = self::get_users_account();
                 if ((string) $xml->username == $username) {
                     $email = (string) $xml->email;
                 } else {
                     $xml = self::get_server_friends();
                     foreach ($xml->User as $xuser) {
                         if ((string) $xuser['username'] == $username) {
                             $email = (string) $xuser['email'];
                         }
                     }
                 }
             }
             if (!empty($email)) {
                 $user = User::get_from_email($email);
             }
             if (!isset($user) || !$user->id) {
                 debug_event('Access Denied', 'Unable to get an Ampache user match for email ' . $email, '3');
                 self::createError(401);
             } else {
                 $username = $user->username;
                 if (!Access::check_network('init-api', $username, 5)) {
                     debug_event('Access Denied', 'Unauthorized access attempt to Plex [' . $_SERVER['REMOTE_ADDR'] . ']', '3');
                     self::createError(401);
                 } else {
                     $GLOBALS['user'] = $user;
                     $GLOBALS['user']->load_playlist();
                 }
             }
         } else {
             $email = $username;
             $username = null;
             $GLOBALS['user'] = new User();
             $GLOBALS['user']->load_playlist();
         }
         if ($createSession) {
             // Create an Ampache session from Plex authtoken
             Session::create(array('type' => 'api', 'sid' => $myplex_token, 'username' => $username, 'value' => $email));
         }
     } else {
         AmpConfig::set('cookie_path', '/', true);
         $sid = $_COOKIE[AmpConfig::get('session_name')];
         if (!$sid) {
             $sid = $myplex_token;
             if ($sid) {
                 session_id($sid);
                 Session::create_cookie();
             }
         }
         if (!empty($sid) && Session::exists('api', $sid)) {
             Session::check();
             $GLOBALS['user'] = User::get_from_username($_SESSION['userdata']['username']);
         } else {
             $GLOBALS['user'] = new User();
             $data = array('type' => 'api', 'sid' => $sid);
             Session::create($data);
             Session::check();
         }
         $GLOBALS['user']->load_playlist();
     }
 }
예제 #30
0
 if (!empty($path[$i])) {
     $method = $path[$i];
     ++$i;
 }
 $method = (string) str_replace('-', '_', $method);
 Buffer::set(URL_METHOD, $method);
 if (!empty($path[$i])) {
     for ($j = 0; $j < $i; $j++) {
         unset($path[$j]);
     }
     $options = array_values($path);
 }
 Buffer::set(URL_OPT, $options);
 //Проверяем корректность сессии
 if (!Session::analysis()) {
     Session::create();
 }
 //Разрешён ли вообще доступ пользователю?
 $access_zone = config(URL_AP, 'access', 'zone');
 $access_users = (array) config(URL_AP, 'access', 'user');
 if ($access_zone != Z_PUBLIC) {
     $user = Loader::get_user();
     if (!empty($access_users) and !in_array(User::T_ALL, $access_users) and $user->is_visitor() or !in_array($user->get_type(), $access_users)) {
         require_once PATH_STRATEGIES . 'identification.php';
         $class_name = 'Identification' . $postfix;
         $strategy = new $class_name();
     }
 }
 if (empty($strategy)) {
     //Определяем стратегию поведения
     if (is_ajax()) {