Esempio n. 1
0
 public function Start()
 {
     // If user is already logged in
     if (jf::CurrentUser()) {
         if (isset($_GET["return"])) {
             $return = $_GET["return"];
         } else {
             $return = "";
         }
         $this->Redirect(SiteRoot . $return);
         // Site root does not contain trailing '/'
     }
     // TODO: Implement a secure 'Remember Me'
     if (isset($_POST["Username"]) && isset($_POST['Password'])) {
         $this->Result = jf::Login($_POST['Username'], $_POST['Password']);
     }
     //Login Successful
     if (isset($this->Result) && $this->Result) {
         if (isset($_GET["return"])) {
             $return = $_GET["return"];
         } else {
             $return = "";
         }
         $this->Redirect(SiteRoot . $return);
     }
     return $this->Present();
 }
Esempio n. 2
0
 /**
  * Fetch submission details from the database
  *
  * @param int $id ID to search for
  *
  * @return array Result of the query
  * @throws \Exception Required parameter missing
  */
 public static function getByID($id = null)
 {
     if ($id === null) {
         throw new InvalidArgumentException("Required parameter missing");
     }
     return \jf::SQL("SELECT * FROM " . self::TABLE_NAME . " WHERE ID = ?", $id);
 }
Esempio n. 3
0
 public function Start()
 {
     // Check if the user is logged in and
     // have the required permissions
     if (jf::CurrentUser() && jf::Check(self::PERMISSION_NAME)) {
         // Check if POST parameter present
         if (isset($_POST['username'])) {
             $username = $_POST['username'];
             if (jf::$User->UserExists($username)) {
                 // First remove the user role association
                 $userId = jf::$User->UserID($username);
                 $roleId = jf::$RBAC->Roles->TitleId(self::ROLE_NAME);
                 jf::$RBAC->Users->Unassign($roleId, $userId);
                 // Delete the user
                 jf::$User->DeleteUser($username);
                 echo json_encode(array('status' => true, 'message' => self::SUCCESS_MESSAGE));
             } else {
                 // User does not exists. Error!
                 echo json_encode(array('status' => false, 'message' => self::USER_NOT_EXISTS_MESSAGE));
             }
         } else {
             echo json_encode(array('status' => false, 'message' => self::PARAMETER_MISSING_MESSAGE));
         }
     } else {
         echo json_encode(array('status' => false, 'message' => self::UNAUTHORIZED_MESSAGE));
     }
     return true;
 }
Esempio n. 4
0
/**
 * need to supply me with $result and $profiler
 * first one being test result object of PHPUnit and second an instance of profiler
 */
function DumpResultRows($ResultArray, $Symbol, $Text, $Odd = false)
{
    if (count($ResultArray)) {
        echo $Symbol . count($ResultArray) . " " . $Text . "\n";
        $n = 0;
        foreach ($ResultArray as $test) {
            echo ++$n;
            echo ")  ";
            $t = $test->failedTest();
            echo get_class($t);
            echo " :: ";
            echo $t->getName();
            echo "\t";
            $e = new Exception();
            echo $test->getExceptionAsString();
            echo "\t";
            $trace = $test->thrownException()->getTrace();
            if ($Odd) {
                $file = $trace[0]['file'];
            } else {
                $file = $trace[3]['file'];
            }
            $dir = substr($file, 0, strlen(jf::root()));
            $dir = substr($file, 0, strpos($file, DIRECTORY_SEPARATOR, strlen($dir) + 1));
            $dir = substr($file, 0, strpos($file, DIRECTORY_SEPARATOR, strlen($dir) + 1));
            $filename = substr($file, strlen($dir) + 1);
            echo $filename;
            echo "\n";
        }
        echo str_repeat("-", 80) . "\n";
    }
}
Esempio n. 5
0
 function testStrings()
 {
     $this->assertEquals(Jalali::DateString($this->Timestamp), "1391-11-15");
     $this->assertEquals(Jalali::TimeString($this->Timestamp), "01:39:26");
     $this->assertEquals(new Jalali($this->Timestamp), "1391-11-15 01:39:26");
     $this->assertEquals(new Jalali(), new Jalali(jf::time()));
 }
Esempio n. 6
0
 function Present()
 {
     //only update the csrf token on the session when outputting the field.
     $this->Token = jf::$Security->RandomToken();
     jf::SaveSessionSetting(jFormCsrf::SettingNamePrefix . $this->Name(), $this->Token);
     echo "<input class='jWidget jFormCSRF' type='hidden' name='{$this->Name()}' value='{$this->Token}' />\n";
 }
Esempio n. 7
0
 public function Start()
 {
     if (jf::CurrentUser() && jf::Check(self::PERMISSION_NAME)) {
         if (isset($_POST['username']) && isset($_POST['password'])) {
             $username = $_POST['username'];
             $password = $_POST['password'];
             if (empty($username) || empty($password)) {
                 echo json_encode(array('status' => false, 'message' => self::PARAMETER_MISSING_MESSAGE));
             } else {
                 if (jf::$User->UserExists($username)) {
                     // If user already exists
                     echo json_encode(array('status' => false, 'message' => self::USER_EXISTS_MESSAGE));
                 } else {
                     // Everything OK. Create a new user and assign the role
                     $userId = jf::$User->CreateUser($username, $password);
                     // Create user
                     $roleId = jf::$RBAC->Roles->TitleId(self::ROLE_NAME);
                     jf::$RBAC->Users->Assign($roleId, $userId);
                     // Assign role to the newly created user
                     echo json_encode(array('status' => true, 'message' => self::SUCCESS_MESSAGE, 'id' => $userId));
                 }
             }
         } else {
             // Required parameters are missing
             echo json_encode(array('status' => false, 'message' => self::PARAMETER_MISSING_MESSAGE));
         }
     } else {
         // User is not authorized
         echo json_encode(array('status' => false, 'message' => self::UNAUTHORIZED_MESSAGE));
     }
     return true;
 }
Esempio n. 8
0
 public function Start()
 {
     $request = jf::$BaseRequest;
     if (jf::CurrentUser()) {
         // User is logged in, check if the user is authorized
         if (jf::Check("view_contest_chal")) {
             if (($activeContest = \webgoat\ContestDetails::getActive()) !== null) {
                 $this->ContestName = $activeContest[0]['ContestName'];
                 $startTime = $activeContest[0]['StartTimestamp'];
                 $currentTime = time();
                 if ($currentTime < $startTime) {
                     $this->TimeRemaining = $startTime - $currentTime;
                 } else {
                     $challenges = \webgoat\ContestChallenges::getByContestID();
                     if (count($challenges) == 0) {
                         $this->Error = "Currently there are no challenges in this contest";
                     } else {
                         $this->Challenges = $challenges;
                     }
                 }
             } else {
                 $this->Error = "Currently there is no active contest. Check back later!!";
             }
             return $this->Present();
         } else {
             // User is not authorized
             $this->Redirect(SiteRoot);
         }
     } else {
         // User is not logged in
         $this->Redirect(jf::url() . "/user/login?return=/{$request}");
     }
 }
Esempio n. 9
0
 function Insert()
 {
     if (jf::$RunMode->IsCLI()) {
         return false;
     }
     $res = jf::SQL("INSERT INTO {$this->TablePrefix()}stats (UserID,SessionID,Timestamp,Page,Query,IP,Host,Protocol,UserAgent) VALUES\n\t\t\t(?,?,?,?,?,?,?,?,?)", jf::CurrentUser() ?: 0, jf::$Session->SessionID(), jf::time(), HttpRequest::URI(), HttpRequest::QueryString(), HttpRequest::IP(), HttpRequest::Host(), HttpRequest::Protocol(), HttpRequest::UserAgent());
     return $res;
 }
Esempio n. 10
0
 function ActivationMail($Email, $UserID, $Username)
 {
     $ActivationToken = jf::$Security->RandomToken();
     jf::SaveGeneralSetting("activation_{$ActivationToken}", $UserID);
     $MyEmail = "admin@" . HttpRequest::Host();
     $Content = "Thank you for joininig " . constant("jf_Application_Title") . " {$Username},\n\t\t\t\tPlease open the following link in order to activate your account:\n\n\t\t\t\t" . SiteRoot . "/sys/xuser/signup?validate={$ActivationToken}\n\n\t\t\t\tIf you did not sign up on this site, just ignore this email.";
     return mail($Email, "Account Confirmation", $Content, "From: " . constant("jf_Application_Name") . " <{$MyEmail}>");
 }
Esempio n. 11
0
 private function activationMail($email, $userId, $username)
 {
     $activationToken = jf::$Security->RandomToken();
     jf::SaveGeneralSetting("activation_{$activationToken}", $userId);
     $myEmail = "*****@*****.**";
     $content = "Thank you for joining " . constant("jf_Application_Title") . " {$username},\n                Please open the following link in order to activate your account:\n                " . CONTEST_MODE_DIR . "user/signup?validate={$activationToken}\n\n                If you did not sign up on this site, just ignore this email.";
     return mail($email, "Account Confirmation", $content, "From: " . constant("jf_Application_Name") . " <{$myEmail}>");
 }
Esempio n. 12
0
 function testGetTime()
 {
     $profiler = new \jf\Profiler();
     $profileTime = (int) $profiler->GetTime(false);
     $jfTime = jf::time();
     $this->assertTrue($profileTime == $jfTime or $profileTime == $jfTime - 1);
     $profileTime = $profiler->GetTime(false);
     $profileTime *= 1000000;
     $time = $profiler->GetTime(true);
     $this->assertGreaterThan($profileTime - $time, 100);
 }
Esempio n. 13
0
 function Start()
 {
     $this->Username = jf::$XUser->Username();
     jf::$XUser->Logout(jf::CurrentUser());
     setcookie("jframework_rememberme", null, null);
     if (isset($_GET["return"])) {
         $this->Return = $_GET["return"];
     } else {
         $this->Return = "./login";
     }
     return $this->Present();
 }
Esempio n. 14
0
 /**
  * Test to check permissions of users
  */
 public function testUserPermissions()
 {
     /**
      * Store id of the user
      */
     $userId = jf::$User->UserID('guest');
     $this->assertTrue(jf::Check('view_single_chal', $userId));
     $this->assertFalse(jf::Check('view_workshop_chal', $userId));
     $this->assertFalse(jf::Check('view_contest_chal', $userId));
     $this->assertFalse(jf::Check('edit_contest_chal', $userId));
     $this->assertFalse(jf::Check('add_workshop_users', $userId));
 }
Esempio n. 15
0
 function Start()
 {
     $this->Username = jf::$XUser->Username();
     $Logged = false;
     if (isset($_COOKIE["jframework_rememberme"])) {
         $rememberMeToken = $_COOKIE["jframework_rememberme"];
         $userID = jf::LoadGeneralSetting("rememberme_" . $rememberMeToken);
         if ($userID > 0) {
             $Result = jf::$XUser->ForceLogin($userID);
             $Logged = true;
         }
     }
     if (isset($_POST["Username"])) {
         $Username = $_POST['Username'];
         $Password = $_POST['Password'];
         $loginResult = jf::$XUser->Login($Username, $Password);
         if ($loginResult == false) {
             $UserID = jf::$XUser->UserID($Username);
             $res = jf::$XUser->LastError;
             if ($res == \jf\ExtendedUserErrors::Inactive) {
                 $ErrorString = "Your account is not activated.";
             } elseif ($res == \jf\ExtendedUserErrors::InvalidCredentials or $res == \jf\ExtendedUserErrors::NotFound) {
                 $ErrorString = "Invalid Credentials.";
             } elseif ($res == \jf\ExtendedUserErrors::Locked) {
                 $ErrorString = "Your account is locked. Try again in " . floor(jf::$XUser->LockTime($Username) / 60) . " minute(s).";
             } elseif ($res == \jf\ExtendedUserErrors::PasswordExpired) {
                 $Link = "./reset?user={$UserID}";
                 $ErrorString = "Your password is expired. You should <a href='{$Link}'>change your password</a>.";
             } elseif ($res == \jf\ExtendedUserErrors::TemporaryValidPassword) {
                 $Link = "./reset?user={$UserID}&temp={$Password}";
                 $ErrorString = "This is a temporary password. You should <a href='{$Link}'>reset your password</a> now.";
             }
             $Logged = false;
             $this->Error = $ErrorString;
         } else {
             $Logged = true;
             if (isset($_POST['Remember'])) {
                 $timeout = 60 * 60 * 24 * 30;
                 $rememberMeToken = jf::$Security->RandomToken();
                 jf::SaveGeneralSetting("rememberme_" . $rememberMeToken, jf::CurrentUser(), $timeout);
                 setcookie('jframework_rememberme', $rememberMeToken, jf::time() + $timeout);
             }
         }
     }
     if ($Logged == true) {
         if (isset($_GET['return'])) {
             $this->Redirect($_GET['return']);
         }
         $this->Success = true;
     }
     return $this->Present();
 }
Esempio n. 16
0
 public function Start()
 {
     // If user is logged in
     if (jf::CurrentUser()) {
         jf::Logout();
     }
     if (isset($_GET["return"])) {
         $Return = $_GET["return"];
     } else {
         $Return = "";
     }
     $this->Redirect(SiteRoot . $Return);
 }
Esempio n. 17
0
 /**
  * Launches an application controller. Returns what the controller returns.
  * If it is false, a not found error is displayed.
  * @return boolean
  */
 function Launch()
 {
     $Parts = explode("/", $this->Request);
     $Type = array_shift($Parts);
     if (!array_key_exists($Type, self::$StaticContentPrefix)) {
         return false;
     }
     $Type = self::$StaticContentPrefix[$Type];
     array_unshift($Parts, $Type);
     $file = jf::root() . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $Parts);
     $FileMan = new DownloadManager();
     return $FileMan->Feed($file);
 }
Esempio n. 18
0
 /**
  * Runs a module. The difference with import is that this one uses require instead of require_once
  * @param string $module
  * @param array $scopeVars
  */
 static function run($module, $scopeVars = null)
 {
     $file = jf::moduleFile($module);
     if (!file_exists($file)) {
         throw new ImportException("File not found : {$file}");
     }
     if (is_array($scopeVars)) {
         foreach ($scopeVars as $ArgName => $ArgValue) {
             ${$ArgName} = $ArgValue;
         }
     }
     require $file;
 }
Esempio n. 19
0
 public function Start()
 {
     if (jf::CurrentUser()) {
         if (jf::Check("contest")) {
             if (isset($_POST['challenge']) && isset($_POST['name']) && isset($_POST['points']) && isset($_POST['flag'])) {
                 $hashedFlag = md5($_POST['flag']);
                 $activeContest = \webgoat\ContestDetails::getActive();
                 $activeContestID = $activeContest[0]['ID'];
                 $data = array('ContestID' => $activeContestID, 'ChallengeName' => $_POST['challenge'], 'NameToDisplay' => $_POST['name'], 'Points' => $_POST['points'], 'CorrectFlag' => $hashedFlag);
                 \webgoat\ContestChallenges::add($data);
                 echo json_encode(array('status' => true, 'message' => 'Challenge successfully added'));
                 return true;
             }
         }
     }
 }
Esempio n. 20
0
 /**
  * returns module name for this object in format control/demo/__catch
  */
 protected function ModuleName($Object = null)
 {
     if ($Object === null) {
         $Object = $this;
     }
     $reflector = new \ReflectionClass(get_class($Object));
     $filename = $reflector->getFileName();
     $filename_inside_jf = substr($filename, strlen(jf::root()) + 1);
     $Parts = explode(DIRECTORY_SEPARATOR, $filename_inside_jf);
     $Type = array_shift($Parts);
     if ($Type == "_japp") {
         array_unshift($Parts, "jf");
     }
     return substr(implode("/", $Parts), 0, -4);
     //omit .php
 }
Esempio n. 21
0
 /**
  * Returns the object of the lesson from
  * the application settings.
  *
  * @param string $lessonName Name of the lesson to be searched for
  *
  * @return Object Lesson object
  * @throws ArgumentMissingException If $lessonName is missing
  * @throws LessonNotFoundException If the lesson is not found
  * @throws GeneralSettingsMissingException  If there is are no application
  *          settings present
  */
 public static function getLessonObject($lessonName = null)
 {
     if ($lessonName == null) {
         throw new ArgumentMissingException("Please select a lesson");
     }
     if (!\jf::LoadGeneralSetting('categoryLessons')) {
         throw new GeneralSettingsMissingException("No settings found for 'categoryLessons'");
     }
     foreach (\jf::LoadGeneralSetting('categoryLessons') as $lessons) {
         foreach ($lessons as $lesson) {
             if ($lesson[0] == $lessonName) {
                 return $lesson[1];
             }
         }
     }
     throw new LessonNotFoundException("Lesson '{$lessonName}' not found");
 }
Esempio n. 22
0
 private function addSubmission($challenge)
 {
     $challengeDetails = \webgoat\ContestChallenges::getByName($challenge);
     $flag = $_POST['flag'];
     $ip = \jf\HttpRequest::IP();
     $challengeID = $challengeDetails[0]['ID'];
     $userID = jf::CurrentUser();
     $data = array('UserID' => $userID, 'ChallengeID' => $challengeID, 'Flag' => $flag, 'IP' => $ip, 'timestamp' => time());
     \webgoat\ContestSubmissions::add($data);
     \webgoat\ContestChallenges::incrementTotalAttempts($challenge);
     if (\webgoat\ContestSubmissions::evaluate($challengeID, $flag)) {
         $this->Submission = 1;
         // Increment complete count
         \webgoat\ContestChallenges::incrementCompletedCount($challenge);
     } else {
         $this->Submission = 0;
     }
 }
Esempio n. 23
0
 /**
  * Adds a new connection to database manager.
  * If index is set, the connection is added with the index (which could be a string)
  * @param DatabaseSetting $dbConfig
  * @param integer|string $Index
  * @throws ImportException
  * @return unknown
  */
 static function AddConnection(DatabaseSetting $dbConfig, $Index = null)
 {
     $configIndex = self::FindIndex($dbConfig);
     if ($configIndex != -1) {
         return self::$Connections[$configIndex];
     }
     $Classname = "\\jf\\DB_{$dbConfig->Adapter}";
     try {
         jf::import("jf/model/lib/db/adapter/{$dbConfig->Adapter}");
     } catch (ImportException $e) {
         echo "Database adapter '{$dbConfig->Adapter}' not found.";
         throw $e;
     }
     if ($Index === null) {
         return self::$Connections[] = new $Classname($dbConfig);
     } else {
         return self::$Connections[$Index] = new $Classname($dbConfig);
     }
 }
Esempio n. 24
0
 /**
  * Launches a system (admin interface) controller. Returns what the controller returns.
  * If it is false, a not found error is displayed.
  * @return boolean
  */
 function Launch()
 {
     $Parts = explode("/", $this->Request);
     assert($Parts[0] == "sys");
     // or $Parts [0] == "app" );
     $Parts[0] = "control";
     array_unshift($Parts, "jf");
     //go system mode for import
     $RequestedModule = implode("/", $Parts);
     //load the controller module
     if (!$this->StartController($RequestedModule)) {
         //not found!
         if (!headers_sent()) {
             # no output done, this check prevents controllers that don't return true to fail
             jf::run("view/_internal/error/404");
         }
         return false;
     }
     return true;
 }
Esempio n. 25
0
 public function Start()
 {
     if (jf::CurrentUser()) {
         $userName = jf::$XUser->Username();
         $oldPass = $_POST['old_password'];
         $newPass = $_POST['new_password'];
         $cnfNewPass = $_POST['cnew_password'];
         if ($newPass != $cnfNewPass) {
             echo json_encode(array('status' => false, 'error' => 'Password and Confirm Password do not match'));
         } elseif (!jf::Login($userName, $oldPass)) {
             echo json_encode(array('status' => false, 'error' => 'Old Password is incorrect'));
         } else {
             jf::$User->EditUser($userName, $userName, $newPass);
             echo json_encode(array('status' => true, 'message' => 'Password successfully updated'));
         }
     } else {
         echo json_encode(array('status' => false, 'error' => 'You are not authorized for this action'));
     }
     return true;
 }
Esempio n. 26
0
 /**
  * Returns all roles assigned to a permission
  *
  * @param integer $Permission
  *        	ID
  * @param boolean $OnlyIDs
  *        	if true, result would be a 1D array of IDs
  * @return Array 2D or 1D or null
  */
 function Roles($Permission, $OnlyIDs = true)
 {
     if (!is_numeric($Permission)) {
         $Permission = $this->Permission_ID($Permission);
     }
     if ($OnlyIDs) {
         $Res = jf::SQL("SELECT RoleID AS `ID` FROM\n\t\t\t{$this->TablePrefix()}rbac_rolepermissions WHERE PermissionID=? ORDER BY RoleID", $Permission);
         if (is_array($Res)) {
             $out = array();
             foreach ($Res as $R) {
                 $out[] = $R['ID'];
             }
             return $out;
         } else {
             return null;
         }
     } else {
         return jf::SQL("SELECT `TP`.* FROM {$this->TablePrefix()}rbac_rolepermissions AS `TR`\n\t\t\tRIGHT JOIN {$this->TablePrefix()}rbac_roles AS `TP` ON (`TR`.RoleID=`TP`.ID)\n\t\t\tWHERE PermissionID=? ORDER BY TP.RoleID", $Permission);
     }
 }
Esempio n. 27
0
 public function Start()
 {
     if (jf::CurrentUser()) {
         if (jf::Check("contest")) {
             // User is authorized
             if (isset($_POST['contest_submit'])) {
                 // Request to store the contest in the database
                 $this->addContest();
             }
             if (\webgoat\ContestDetails::isActivePresent()) {
                 // If an active contest is present
                 $contestDetails = \webgoat\ContestDetails::getActive();
                 $contestChallenges = \webgoat\ContestChallenges::getByContestID($contestDetails[0]['ID']);
                 $contestUsers = \webgoat\ContestUsers::getAll();
                 $this->ContestName = $contestDetails[0]['ContestName'];
                 $this->ContestStart = date("d/m/Y h:i:s A", $contestDetails[0]['StartTimestamp']);
                 $this->ContestEnd = date("d/m/Y h:i:s A", $contestDetails[0]['EndTimestamp']);
                 $this->UserCount = count($contestUsers);
                 $this->ChallengeCount = count($contestChallenges);
                 $this->Challenges = $contestChallenges;
                 $this->insertNewChallenges();
             } else {
                 // Show the option to start a contest
                 $this->noActiveContest = true;
             }
             return $this->Present();
         } else {
             // User is not authorized
             $this->Redirect(SiteRoot);
             // Redirect to home page
         }
     } else {
         // User is not authenticated
         $this->Redirect(jf::url() . "/user/login?return=/" . jf::$BaseRequest);
     }
 }
Esempio n. 28
0
 /**
  * Outputs a nicely formatted error for web display
  * @param integer $errno
  * @param string $errstr
  * @param string $errfile
  * @param integer $errline
  * @param \Exception $exception
  * @return boolean
  */
 function PresentError($errno, $errstr, $errfile, $errline, $exception = null)
 {
     if (!self::$PresentErrors) {
         return false;
     }
     jf::run("jf/view/_internal/error", array("errno" => $errno, "errstr" => $errstr, "errfile" => $errfile, "errline" => $errline, "exception" => $exception));
     /* Don't execute PHP internal error handler */
     return false;
 }
Esempio n. 29
0
 /**
  * This is a convenient wrapper for AddRule, which calls moduleFile on the module string and then adds the file to rules.
  * @param string $Classname
  * @param string $Module e.g model/folder/file
  * @throws AutoloadRuleException
  */
 static function AddModule($Classname, $Module)
 {
     $File = jf::moduleFile($Module);
     if (!file_exists($File)) {
         throw new AutoloadRuleException("Invalid autoload rule added: {$File} set for autoloading of class '{$Classname}' does not exist.");
     }
     self::$List[$Classname] = $File;
 }
Esempio n. 30
0
 function __construct($Timestamp = null)
 {
     if ($Timestamp === null) {
         $Timestamp = jf::time();
     }
     $this->Timestamp = $Timestamp;
 }