{"code": "function PMA_Process_formset(FormDisplay $form_display)\n{\n if (filter_input(INPUT_GET, 'mode') == 'revert') {\n // revert erroneous fields to their default values\n $form_display->fixErrors();\n PMA_generateHeader303();\n }\n\n if (!$form_display->process(false)) {\n // handle form view and failed POST\n $form_display->display(true, true);\n return;\n }\n\n // check for form errors\n if (!$form_display->hasErrors()) {\n PMA_generateHeader303();\n return;\n }\n\n // form has errors, show warning\n $separator = PMA_URL_getArgSeparator('html');\n $page = filter_input(INPUT_GET, 'page');\n $formset = filter_input(INPUT_GET, 'formset');\n $formset = $formset ? \"{$separator}formset=$formset\" : '';\n $formId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);\n if ($formId === null && $page == 'servers') {\n // we've just added a new server, get its id\n $formId = $form_display->getConfigFile()->getServerCount();\n }\n $formId = $formId ? \"{$separator}id=$formId\" : '';\n ?>\n
\n

\n
\n mode=revert\">\n \n \n
\n displayErrors() ?>\n \n  \n mode=edit\">\n $val) {\n $set .= \"'$val',\";\n $k .= \"`$key`,\";\n }\n \n $set = substr($set, 0,-1);\n $k = substr($k, 0,-1);\n \n $sql = sprintf(\"INSERT INTO `%s` (%s) VALUES (%s) \", $vars['table'], $k, $set) ;\n }else{\n $sql = $vars;\n }\n if(DB_DRIVER == 'mysql') {\n mysql_query('SET CHARACTER SET utf8');\n $q = mysql_query($sql) or die(mysql_error());\n self::$last_id = mysql_insert_id();\n }elseif(DB_DRIVER == 'mysqli'){\n try {\n if(!self::query($sql)){\n printf(\"
Errormessage: %s
\\n\", self::$mysqli->error);\n }else{\n self::$last_id = self::$mysqli->insert_id;\n }\n \n } catch (exception $e) {\n echo $e->getMessage();\n }\n \n }\n \n return true;\n }", "label_name": "CWE-352", "label": 0} {"code": " public static function go($input, $path, $allowed='', $uniq=false, $size='', $width = '', $height = ''){\n $filename = Typo::cleanX($_FILES[$input]['name']);\n $filename = str_replace(' ', '_', $filename);\n if(isset($_FILES[$input]) && $_FILES[$input]['error'] == 0){\n if($uniq == true){\n $uniqfile = sha1(microtime().$filename);\n }else{\n $uniqfile = '';\n }\n\n $extension = pathinfo($_FILES[$input]['name'], PATHINFO_EXTENSION);\n $filetmp = $_FILES[$input]['tmp_name'];\n $filepath = GX_PATH.$path.$uniqfile.$filename;\n\n if(!in_array(strtolower($extension), $allowed)){\n $result['error'] = 'File not allowed';\n }else{\n if(move_uploaded_file(\n $filetmp, \n $filepath)\n ){\n $result['filesize'] = filesize($filepath);\n $result['filename'] = $uniqfile.$filename;\n $result['path'] = $path.$uniqfile.$filename;\n $result['filepath'] = $filepath;\n $result['fileurl'] = Options::get('siteurl').$path.$uniqfile.$filename;\n\n }else{\n $result['error'] = 'Cannot upload to directory, please check \n if directory is exist or You had permission to write it.';\n }\n }\n\n \n }else{\n //$result['error'] = $_FILES[$input]['error'];\n $result['error'] = '';\n }\n\n return $result;\n\n }", "label_name": "CWE-352", "label": 0} {"code": " public function store(CurrencyFormRequest $request)\n {\n /** @var User $user */\n $user = auth()->user();\n $data = $request->getCurrencyData();\n if (!$this->userRepository->hasRole($user, 'owner')) {\n\n Log::error('User ' . auth()->user()->id . ' is not admin, but tried to store a currency.');\n Log::channel('audit')->info('Tried to create (POST) currency without admin rights.', $data);\n\n return redirect($this->getPreviousUri('currencies.create.uri'));\n\n }\n\n $data['enabled'] = true;\n try {\n $currency = $this->repository->store($data);\n } catch (FireflyException $e) {\n Log::error($e->getMessage());\n Log::channel('audit')->info('Could not store (POST) currency without admin rights.', $data);\n $request->session()->flash('error', (string) trans('firefly.could_not_store_currency'));\n $currency = null;\n }\n $redirect = redirect($this->getPreviousUri('currencies.create.uri'));\n\n if (null !== $currency) {\n $request->session()->flash('success', (string) trans('firefly.created_currency', ['name' => $currency->name]));\n Log::channel('audit')->info('Created (POST) currency.', $data);\n if (1 === (int) $request->get('create_another')) {\n\n $request->session()->put('currencies.create.fromStore', true);\n\n $redirect = redirect(route('currencies.create'))->withInput();\n\n }\n }\n\n return $redirect;\n }", "label_name": "CWE-352", "label": 0} {"code": " public function enableCurrency(TransactionCurrency $currency)\n {\n app('preferences')->mark();\n\n $this->repository->enable($currency);\n session()->flash('success', (string) trans('firefly.currency_is_now_enabled', ['name' => $currency->name]));\n Log::channel('audit')->info(sprintf('Enabled currency %s.', $currency->code));\n\n return redirect(route('currencies.index'));\n }", "label_name": "CWE-352", "label": 0} {"code": " public static function rss() {\n switch (SMART_URL) {\n case true:\n # code...\n $url = Options::get('siteurl').\"/rss\".GX_URL_PREFIX;\n break;\n \n default:\n # code...\n $url = Options::get('siteurl').\"/index.php?rss\";\n break;\n\n }\n\n return $url;\n }", "label_name": "CWE-352", "label": 0} {"code": " public function pinCommentAction(ProjectComment $comment)\n {\n $comment->setPinned(!$comment->isPinned());\n try {\n $this->repository->saveComment($comment);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n\n return $this->redirectToRoute('project_details', ['id' => $comment->getProject()->getId()]);\n }", "label_name": "CWE-352", "label": 0} {"code": " public static function page($vars) {\n switch (SMART_URL) {\n case true:\n # code...\n $url = Options::get('siteurl').\"/\".self::slug($vars).GX_URL_PREFIX;\n break;\n \n default:\n # code...\n $url = Options::get('siteurl').\"/index.php?page={$vars}\";\n break;\n\n }\n\n return $url;\n }", "label_name": "CWE-352", "label": 0} {"code": " public function submit(Request $request)\n {\n return logout();\n }", "label_name": "CWE-352", "label": 0} {"code": " public function write($template = '')\n {\n if (!empty($this->script_files)) {\n $this->set_env('request_token', $this->app->get_request_token());\n }\n\n $commands = $this->get_js_commands($framed);\n\n // if all js commands go to parent window we can ignore all\n // script files and skip rcube_webmail initialization (#1489792)\n if ($framed) {\n $this->scripts = array();\n $this->script_files = array();\n $this->header = '';\n $this->footer = '';\n }\n\n // write all javascript commands\n $this->add_script($commands, 'head_top');\n\n // send clickjacking protection headers\n $iframe = $this->framed || $this->env['framed'];\n if (!headers_sent() && ($xframe = $this->app->config->get('x_frame_options', 'sameorigin'))) {\n header('X-Frame-Options: ' . ($iframe && $xframe == 'deny' ? 'sameorigin' : $xframe));\n }", "label_name": "CWE-352", "label": 0} {"code": " $ret = array_merge($ret, csrf_flattenpost2($level+1, $nk, $v));\n }", "label_name": "CWE-352", "label": 0} {"code": " protected static function __Load($path) {\n include_once($path);\n }", "label_name": "CWE-352", "label": 0} {"code": " public function testDeleteTemplateAction()\n {\n $client = $this->getClientForAuthenticatedUser(User::ROLE_ADMIN);\n\n $fixture = new InvoiceTemplateFixtures();\n $template = $this->importFixture($fixture);\n $id = $template[0]->getId();\n\n $this->request($client, '/invoice/template/' . $id . '/delete');\n $this->assertIsRedirect($client, '/invoice/template');\n $client->followRedirect();\n\n $this->assertTrue($client->getResponse()->isSuccessful());\n $this->assertHasFlashSuccess($client);\n\n $this->assertEquals(0, $this->getEntityManager()->getRepository(InvoiceTemplate::class)->count([]));\n }", "label_name": "CWE-352", "label": 0} {"code": " function update_license_status() {\n $status = '';\n $license_key = $this->get_license_key();\n\n if (!empty($license_key) || defined('W3TC_LICENSE_CHECK')) {\n $license = edd_w3edge_w3tc_check_license($license_key, W3TC_VERSION);\n $version = '';\n\n if ($license) {\n $status = $license->license;\n if ('host_valid' == $status) {\n $version = 'pro';\n } elseif (in_array($status, array('site_inactive','valid')) && w3tc_is_pro_dev_mode()) {\n $status = 'valid';\n $version = 'pro_dev';\n }\n }\n\n $this->_config->set('plugin.type', $version);\n } else {\n $status = 'no_key';\n $this->_config->set('plugin.type', '');\n }\n try {\n $this->_config->save();\n } catch(Exception $ex) {}\n return $status;\n }", "label_name": "CWE-352", "label": 0} {"code": "\tpublic static function startup()\n\t{\n\t\t//Override the default expire time of token\n\t\t\\CsrfMagic\\Csrf::$expires = 259200;\n\t\t\\CsrfMagic\\Csrf::$callback = function ($tokens) {\n\t\t\tthrow new \\App\\Exceptions\\AppException('Invalid request - Response For Illegal Access', 403);\n\t\t};\n\t\t$js = 'vendor/yetiforce/csrf-magic/src/Csrf.min.js';\n\t\tif (!IS_PUBLIC_DIR) {\n\t\t\t$js = 'public_html/' . $js;\n\t\t}\n\t\t\\CsrfMagic\\Csrf::$dirSecret = __DIR__;\n\t\t\\CsrfMagic\\Csrf::$rewriteJs = $js;\n\t\t\\CsrfMagic\\Csrf::$cspToken = \\App\\Session::get('CSP_TOKEN');\n\t\t\\CsrfMagic\\Csrf::$frameBreaker = \\Config\\Security::$csrfFrameBreaker;\n\t\t\\CsrfMagic\\Csrf::$windowVerification = \\Config\\Security::$csrfFrameBreakerWindow;\n\n\t\t/*\n\t\t * if an ajax request initiated, then if php serves content with tags\n\t\t * as a response, then unnecessarily we are injecting csrf magic javascipt\n\t\t * in the response html at and using csrf_ob_handler().\n\t\t * So, to overwride above rewriting we need following config.\n\t\t */\n\t\tif (static::isAjax()) {\n\t\t\t\\CsrfMagic\\Csrf::$frameBreaker = false;\n\t\t\t\\CsrfMagic\\Csrf::$rewriteJs = null;\n\t\t}\n\t}", "label_name": "CWE-352", "label": 0} {"code": " public function testConfigurationCookieCreate()\n {\n $_SERVER['REQUEST_METHOD'] = 'GET';\n\n $controller = $this->getMock('Cake\\Controller\\Controller', ['redirect']);\n $controller->request = new Request(['webroot' => '/dir/']);\n $controller->response = new Response();\n\n $component = new CsrfComponent($this->registry, [\n 'cookieName' => 'token',\n 'expiry' => '+1 hour',\n 'secure' => true,\n 'httpOnly' => true\n ]);\n\n $event = new Event('Controller.startup', $controller);\n $component->startup($event);\n\n $this->assertEmpty($controller->response->cookie('csrfToken'));\n $cookie = $controller->response->cookie('token');\n $this->assertNotEmpty($cookie, 'Should set a token.');\n $this->assertRegExp('/^[a-f0-9]+$/', $cookie['value'], 'Should look like a hash.');\n $this->assertWithinRange((new Time('+1 hour'))->format('U'), $cookie['expire'], 1, 'session duration.');\n $this->assertEquals('/dir/', $cookie['path'], 'session path.');\n $this->assertTrue($cookie['secure'], 'cookie security flag missing');\n $this->assertTrue($cookie['httpOnly'], 'cookie httpOnly flag missing');\n }", "label_name": "CWE-352", "label": 0} {"code": " public static function meta($cont_title='', $cont_desc='', $pre =''){\n global $data;\n //print_r($data);\n //if(empty($data['posts'][0]->title)){ \n\n if(is_array($data) && isset($data['posts'][0]->title)){\n \n $sitenamelength = strlen(Options::get('sitename'));\n $limit = 70-$sitenamelength-6;\n $cont_title = substr(Typo::Xclean(Typo::strip($data['posts'][0]->title)),0,$limit);\n $titlelength = strlen($data['posts'][0]->title);\n if($titlelength > $limit+3) { $dotted = \"...\";} else {$dotted = \"\";}\n $cont_title = \"{$pre} {$cont_title}{$dotted} - \";\n }else{\n $cont_title = \"\";\n }\n if(is_array($data) && isset($data['posts'][0]->content)){\n $desc = Typo::strip($data['posts'][0]->content);\n }else{\n $desc = \"\";\n }\n\n $meta = \"\n \n \n {$cont_title}\".Options::get('sitename').\"\n \n \n \n \n \n \n \n \n \";\n \n $meta .= \"\n \";\n echo $meta;\n }", "label_name": "CWE-352", "label": 0} {"code": " public function create(Request $request)\n {\n /** @var User $user */\n $user = auth()->user();\n if (!$this->userRepository->hasRole($user, 'owner')) {\n $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))]));\n\n return redirect(route('currencies.index'));\n }\n\n $subTitleIcon = 'fa-plus';\n $subTitle = (string) trans('firefly.create_currency');\n\n // put previous url in session if not redirect from store (not \"create another\").\n if (true !== session('currencies.create.fromStore')) {\n $this->rememberPreviousUri('currencies.create.uri');\n }\n $request->session()->forget('currencies.create.fromStore');\n\n Log::channel('audit')->info('Create new currency.');\n\n return prefixView('currencies.create', compact('subTitleIcon', 'subTitle'));\n }", "label_name": "CWE-352", "label": 0} {"code": "function phpAds_SessionStart()\n{\n\tglobal $session;\n\tif (empty($_COOKIE['sessionID'])) {\n\t\t$session = array();\n\t\t$_COOKIE['sessionID'] = md5(uniqid('phpads', 1));\n\n phpAds_SessionSetAdminCookie('sessionID', $_COOKIE['sessionID']);\n\t}\n\treturn $_COOKIE['sessionID'];\n}", "label_name": "CWE-384", "label": 1} {"code": "\tfunction handleFormSubmission(&$request, &$output, &$session) {\n\t\tif ($request->getText('action')) {\n\t\t\thandleRequestActionSubmission('admin', $this, $session);\n\t\t} else if ($request->getText('blockSubmit')) {\n\t\t\t$this->handleBlockFormSubmission($request, $output, $session);\n\t\t} else if ($request->getText('unblockSubmit')) {\n\t\t\t$this->handleUnblockFormSubmission($request, $output, $session);\n\t\t} else if ($request->getText('bypassAddUsername') || $request->getText('bypassRemoveUsername')) { //TODO: refactor to move all the subpages into their own files\n\t\t\t$bypassPage = new RequirementsBypassPage($this);\n\t\t\t$bypassPage->handleFormSubmission();\n\t\t}\n\t}", "label_name": "CWE-352", "label": 0} {"code": "\tprivate function _handleCallback(){\n\t\ttry {\n\n\t\t\t// Try to get an access token using the authorization code grant.\n\t\t\t$accessToken = $this->_provider->getAccessToken('authorization_code', [\n\t\t\t\t'code' => $_GET['code']\n\t\t\t]);\n\t\t} catch (\\League\\OAuth2\\Client\\Provider\\Exception\\IdentityProviderException $e) {\n\n\t\t\t// Failed to get the access token or user details.\n\t\t\texit($e->getMessage());\n\n\t\t}\n\n\t\t$resourceOwner = $this->_provider->getResourceOwner($accessToken);\n\t\t$user = $this->_userHandling( $resourceOwner->toArray() );\n\t\t$user->setCookies();\n\n\t\tglobal $wgOut, $wgRequest;\n\t\t$title = null;\n\t\t$wgRequest->getSession()->persist();\n\t\tif( $wgRequest->getSession()->exists('returnto') ) {\n\t\t\t$title = Title::newFromText( $wgRequest->getSession()->get('returnto') );\n\t\t\t$wgRequest->getSession()->remove('returnto');\n\t\t\t$wgRequest->getSession()->save();\n\t\t}\n\n\t\tif( !$title instanceof Title || 0 > $title->mArticleID ) {\n\t\t\t$title = Title::newMainPage();\n\t\t}\n\t\t$wgOut->redirect( $title->getFullURL() );\n\t\treturn true;\n\t}", "label_name": "CWE-352", "label": 0} {"code": " public function setFrom($address, $name = '', $auto = true)\n {\n $address = trim($address);\n $name = trim(preg_replace('/[\\r\\n]+/', '', $name)); //Strip breaks and trim\n if (!$this->validateAddress($address)) {\n $this->setError($this->lang('invalid_address') . ': ' . $address);\n $this->edebug($this->lang('invalid_address') . ': ' . $address);\n if ($this->exceptions) {\n throw new phpmailerException($this->lang('invalid_address') . ': ' . $address);\n }\n return false;\n }\n $this->From = $address;\n $this->FromName = $name;\n if ($auto) {\n if (empty($this->Sender)) {\n $this->Sender = $address;\n }\n }\n return true;\n }", "label_name": "CWE-352", "label": 0} {"code": "function addChannelPageTools($agencyid, $websiteId, $channelid, $channelType)\n{\n if ($channelType == 'publisher') {\n $deleteReturlUrl = MAX::constructUrl(MAX_URL_ADMIN, 'affiliate-channels.php');\n }\n else {\n $deleteReturlUrl = MAX::constructUrl(MAX_URL_ADMIN, 'channel-index.php');\n }\n\n //duplicate\n addPageLinkTool($GLOBALS[\"strDuplicate\"], MAX::constructUrl(MAX_URL_ADMIN, \"channel-modify.php?duplicate=true&agencyid=$agencyid&affiliateid=$websiteId&channelid=$channelid&returnurl=\".urlencode(basename($_SERVER['SCRIPT_NAME']))), \"iconTargetingChannelDuplicate\");\n\n //delete\n $deleteConfirm = phpAds_DelConfirm($GLOBALS['strConfirmDeleteChannel']);\n addPageLinkTool($GLOBALS[\"strDelete\"], MAX::constructUrl(MAX_URL_ADMIN, \"channel-delete.php?token=\" . urlencode(phpAds_SessionGetToken()) . \"&agencyid=$agencyid&affiliateid=$websiteId&channelid=$channelid&returnurl=$deleteReturlUrl\"), \"iconDelete\", null, $deleteConfirm);\n}", "label_name": "CWE-352", "label": 0} {"code": " function storeSerializedSession($serialized_session_data, $session_id)\n {\n $doSession = OA_Dal::staticGetDO('session', $session_id);\n if ($doSession) {\n $doSession->sessiondata = $serialized_session_data;\n $doSession->update();\n }\n else {\n $doSession = OA_Dal::factoryDO('session');\n $doSession->sessionid = $session_id;\n $doSession->sessiondata = $serialized_session_data;\n $doSession->insert();\n }\n }", "label_name": "CWE-384", "label": 1} {"code": " public function __destruct()\n {\n if ($this->Mailer == 'smtp') { //close any open SMTP connection nicely\n $this->smtpClose();\n }\n }", "label_name": "CWE-352", "label": 0} {"code": " $otherPublisherName = MAX_buildName($aOtherPublisher['publisher_id'], $aOtherPublisher['name']);\n if ($aOtherPublisher['publisher_id'] != $affiliateid) {\n $form .= \"\";\n }\n }\n $form .= \"\";\n\n addPageFormTool($GLOBALS['strMoveTo'], 'iconZoneMove', $form);\n }\n\n //delete\n if (OA_Permission::isAccount(OA_ACCOUNT_ADMIN)\n || OA_Permission::isAccount(OA_ACCOUNT_MANAGER)\n || OA_Permission::hasPermission(OA_PERM_ZONE_DELETE)) {\n $deleteConfirm = phpAds_DelConfirm($GLOBALS['strConfirmDeleteZone']);\n addPageLinkTool($GLOBALS[\"strDelete\"], MAX::constructUrl(MAX_URL_ADMIN, \"zone-delete.php?token=\" . urlencode(phpAds_SessionGetToken()) . \"&affiliateid=$affiliateid&zoneid=$zoneid&returnurl=affiliate-zones.php\"), \"iconDelete\", null, $deleteConfirm);\n }\n\n //shortcut\n addPageShortcut($GLOBALS['strBackToZones'], MAX::constructUrl(MAX_URL_ADMIN, \"affiliate-zones.php?affiliateid=$affiliateid\"), \"iconBack\");\n $entityString = _getEntityString($aEntities);\n addPageShortcut($GLOBALS['strZoneHistory'], MAX::constructUrl(MAX_URL_ADMIN, \"stats.php?entity=zone&breakdown=history&$entityString\"), 'iconStatistics');\n}", "label_name": "CWE-352", "label": 0} {"code": " public static function httpMethodProvider()\n {\n return [\n ['PATCH'], ['PUT'], ['POST'], ['DELETE']\n ];\n }", "label_name": "CWE-352", "label": 0} {"code": " foreach ($all_users as &$u) {\n if ($u['username'] == $username && $this->verifyPassword($password, $u['password'])) {\n $user = $this->mapToUserObject($u);\n $this->store($user);\n $this->session->set(self::SESSION_HASH, $u['password']);\n\n return true;\n }\n }", "label_name": "CWE-384", "label": 1} {"code": " function getRights($interface = 'central') {\n\n $values = [READ => __('Read'),\n CREATE => __('Create'),\n PURGE => _x('button', 'Delete permanently'),\n self::CHECKUPDATE => __('Check for upgrade')];\n return $values;\n }", "label_name": "CWE-352", "label": 0} {"code": " public function logout(){\n $login_user = $this->checkLogin();\n D(\"UserToken\")->where(\" uid = '$login_user[uid]' \")->save(array(\"token_expire\"=>0));\n session(\"login_user\" , NULL);\n cookie('cookie_token',NULL);\n session(null);\n $this->sendResult(array());\n }", "label_name": "CWE-352", "label": 0} {"code": "function yourls_verify_nonce( $action, $nonce = false, $user = false, $return = '' ) {\n\t// get user\n\tif( false == $user )\n\t\t$user = defined( 'YOURLS_USER' ) ? YOURLS_USER : '-1';\n\n\t// get current nonce value\n\tif( false == $nonce && isset( $_REQUEST['nonce'] ) )\n\t\t$nonce = $_REQUEST['nonce'];\n\n\t// Allow plugins to short-circuit the rest of the function\n\t$valid = yourls_apply_filter( 'verify_nonce', false, $action, $nonce, $user, $return );\n\tif ($valid) {\n\t\treturn true;\n\t}\n\n\t// what nonce should be\n\t$valid = yourls_create_nonce( $action, $user );\n\n\tif( $nonce == $valid ) {\n\t\treturn true;\n\t} else {\n\t\tif( $return )\n\t\t\tdie( $return );\n\t\tyourls_die( yourls__( 'Unauthorized action or expired link' ), yourls__( 'Error' ), 403 );\n\t}\n}", "label_name": "CWE-352", "label": 0} {"code": " public static function sitemap() {\n switch (SMART_URL) {\n case true:\n # code...\n $url = Options::get('siteurl').\"/sitemap\".GX_URL_PREFIX;\n break;\n \n default:\n # code...\n $url = Options::get('siteurl').\"/index.php?page=sitemap\";\n break;\n\n }\n\n return $url;\n }", "label_name": "CWE-352", "label": 0} {"code": " public function delete(Request $request, TransactionCurrency $currency)\n {\n /** @var User $user */\n $user = auth()->user();\n if (!$this->userRepository->hasRole($user, 'owner')) {\n\n $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))]));\n Log::channel('audit')->info(sprintf('Tried to visit page to delete currency %s but is not site owner.', $currency->code));\n\n return redirect(route('currencies.index'));\n\n }\n\n if ($this->repository->currencyInUse($currency)) {\n $location = $this->repository->currencyInUseAt($currency);\n $message = (string) trans(sprintf('firefly.cannot_disable_currency_%s', $location), ['name' => e($currency->name)]);\n $request->session()->flash('error', $message);\n Log::channel('audit')->info(sprintf('Tried to visit page to delete currency %s but currency is in use.', $currency->code));\n\n return redirect(route('currencies.index'));\n }\n\n // put previous url in session\n $this->rememberPreviousUri('currencies.delete.uri');\n $subTitle = (string) trans('form.delete_currency', ['name' => $currency->name]);\n Log::channel('audit')->info(sprintf('Visit page to delete currency %s.', $currency->code));\n\n return prefixView('currencies.delete', compact('currency', 'subTitle'));\n }", "label_name": "CWE-352", "label": 0} {"code": " public function testDuplicateAction()\n {\n $client = $this->getClientForAuthenticatedUser(User::ROLE_ADMIN);\n /** @var EntityManager $em */\n $em = $this->getEntityManager();\n $project = $em->find(Project::class, 1);\n $project->setMetaField((new ProjectMeta())->setName('foo')->setValue('bar'));\n $project->setEnd(new \\DateTime());\n $em->persist($project);\n $team = new Team();\n $team->addTeamlead($this->getUserByRole(User::ROLE_ADMIN));\n $team->addProject($project);\n $team->setName('project 1');\n $em->persist($team);\n $rate = new ProjectRate();\n $rate->setProject($project);\n $rate->setRate(123.45);\n $em->persist($rate);\n $activity = new Activity();\n $activity->setName('blub');\n $activity->setProject($project);\n $activity->setMetaField((new ActivityMeta())->setName('blub')->setValue('blab'));\n $em->persist($activity);\n $rate = new ActivityRate();\n $rate->setActivity($activity);\n $rate->setRate(123.45);\n $em->persist($rate);\n $em->flush();\n\n $this->request($client, '/admin/project/1/duplicate');\n $this->assertIsRedirect($client, '/details');\n $client->followRedirect();\n $node = $client->getCrawler()->filter('div.box#project_rates_box');\n self::assertEquals(1, $node->count());\n $node = $client->getCrawler()->filter('div.box#project_rates_box table.dataTable tbody tr:not(.summary)');\n self::assertEquals(1, $node->count());\n self::assertStringContainsString('123.45', $node->text(null, true));\n }", "label_name": "CWE-352", "label": 0} {"code": " foreach ($indexToDelete as $indexName) {\n $this->addSql('DROP INDEX ' . $indexName . ' ON ' . $users);\n }", "label_name": "CWE-352", "label": 0} {"code": " public function __construct(){\n\n }", "label_name": "CWE-352", "label": 0} {"code": " public function save(){\n $login_user = $this->checkLogin();\n $uid = $login_user['uid'] ;\n\n $id = I(\"id/d\");\n $member_group_id = I(\"member_group_id/d\");\n $cat_id = I(\"cat_id/d\");\n\n $teamItemMemberInfo = D(\"TeamItemMember\")->where(\" id = '$id' \")->find();\n $item_id = $teamItemMemberInfo['item_id'] ;\n $team_id = $teamItemMemberInfo['team_id'] ;\n\n\n if(!$this->checkItemManage($uid , $item_id)){\n $this->sendError(10303);\n return ;\n }\n\n $teamInfo = D(\"Team\")->where(\" id = '$team_id' and uid = '$login_user[uid]' \")->find();\n if (!$teamInfo) {\n $this->sendError(10209,\"\u65e0\u6b64\u56e2\u961f\u6216\u8005\u4f60\u65e0\u7ba1\u7406\u6b64\u56e2\u961f\u7684\u6743\u9650\");\n return ;\n } \n\n if(isset($_POST['member_group_id'])){\n $return = D(\"TeamItemMember\")->where(\" id = '$id' \")->save(array(\"member_group_id\"=>$member_group_id));\n }\n if(isset($_POST['cat_id'])){\n $return = D(\"TeamItemMember\")->where(\" id = '$id' \")->save(array(\"cat_id\"=>$cat_id));\n }\n $this->sendResult($return);\n \n }", "label_name": "CWE-352", "label": 0} {"code": "\tstatic public function onPost( $par, $out, $request ) {\n\t\tglobal $wgUser;\n\t\tif (!$request->getText('reason')) {\n\t\t\t$out->addHTML(Html::rawElement(\n\t\t\t\t'p',\n\t\t\t\t[ 'class' => 'error '],\n\t\t\t\twfMessage( 'report-error-missing-reason' )->escaped()\n\t\t\t));\n\t\t} else {\n\t\t\t$dbw = wfGetDB( DB_MASTER );\n\t\t\t$dbw->startAtomic(__METHOD__);\n\t\t\t$dbw->insert( 'report_reports', [\n\t\t\t\t'report_revid' => (int)$par,\n\t\t\t\t'report_reason' => $request->getText('reason'),\n\t\t\t\t'report_user' => $wgUser->getId(),\n\t\t\t\t'report_user_text' => $wgUser->getName(),\n\t\t\t\t'report_timestamp' => wfTimestampNow()\n\t\t\t], __METHOD__ );\n\t\t\t$dbw->endAtomic(__METHOD__);\n\t\t\t$out->addWikiMsg( 'report-success' );\n\t\t\t$out->addWikiMsg( 'returnto', '[[' . SpecialPage::getTitleFor('Diff', $par)->getPrefixedText() . ']]' );\n\t\t\treturn;\n\t\t}\n\t}", "label_name": "CWE-352", "label": 0} {"code": " public function defaultCurrency(Request $request, TransactionCurrency $currency)\n {\n app('preferences')->set('currencyPreference', $currency->code);\n app('preferences')->mark();\n\n Log::channel('audit')->info(sprintf('Make %s the default currency.', $currency->code));\n\n $this->repository->enable($currency);\n $request->session()->flash('success', (string) trans('firefly.new_default_currency', ['name' => $currency->name]));\n\n return redirect(route('currencies.index'));\n }", "label_name": "CWE-352", "label": 0} {"code": " function render() {\r\n $output = $this->pageContext->getOutput();\r\n\r\n $output->enableOOUI();\r\n\r\n $this->showAddBypassForm();\r\n $this->showBypassesList();\r\n }\r", "label_name": "CWE-352", "label": 0} {"code": "function phpAds_SessionDataFetch()\n{\n global $session;\n $dal = new MAX_Dal_Admin_Session();\n\n // Guard clause: Can't fetch a session without an ID\n\tif (empty($_COOKIE['sessionID'])) {\n return;\n }\n\n $serialized_session = $dal->getSerializedSession($_COOKIE['sessionID']);\n\n // This is required because 'sessionID' cookie is set to new during logout.\n // According to comments in the file it is because some servers do not\n // support setting cookies during redirect.\n if (empty($serialized_session)) {\n return;\n }\n\n $loaded_session = unserialize($serialized_session);\n\tif (!$loaded_session) {\n // XXX: Consider raising an error\n return;\n }\n\t$session = $loaded_session;\n $dal->refreshSession($_COOKIE['sessionID']);\n}", "label_name": "CWE-384", "label": 1} {"code": " public function pwd(){\n $item_id = I(\"item_id/d\");\n $password = I(\"password\");\n $v_code = I(\"v_code\");\n $refer_url = I('refer_url');\n\n //\u68c0\u67e5\u7528\u6237\u8f93\u9519\u5bc6\u7801\u7684\u6b21\u6570\u3002\u5982\u679c\u8d85\u8fc7\u4e00\u5b9a\u6b21\u6570\uff0c\u5219\u9700\u8981\u9a8c\u8bc1 \u9a8c\u8bc1\u7801\n $key= 'item_pwd_fail_times_'.$item_id;\n if(!D(\"VerifyCode\")->_check_times($key,10)){\n if (!$v_code || $v_code != session('v_code')) {\n $this->sendError(10206,L('verification_code_are_incorrect'));\n return;\n }\n }\n session('v_code',null) ;\n $item = D(\"Item\")->where(\"item_id = '$item_id' \")->find();\n if ($item['password'] == $password) {\n session(\"visit_item_\".$item_id , 1 );\n $this->sendResult(array(\"refer_url\"=>base64_decode($refer_url))); \n }else{\n D(\"VerifyCode\")->_ins_times($key);//\u8f93\u9519\u5bc6\u7801\u5219\u8bbe\u7f6e\u8f93\u9519\u6b21\u6570\n \n if(D(\"VerifyCode\")->_check_times($key,10)){\n $error_code = 10307 ;\n }else{\n $error_code = 10308 ;\n }\n $this->sendError($error_code,L('access_password_are_incorrect'));\n }\n\n }", "label_name": "CWE-352", "label": 0} {"code": "\t\t\t\t\t$formatted = wfMessage( 'datadump-table-column-failed' )->text();\n\t\t\t\t} else {\n\t\t\t\t\t$formatted = wfMessage( 'datadump-table-column-queued' )->text();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'dumps_size':\n\t\t\t\t$formatted = htmlspecialchars(\n\t\t\t\t\t$this->getLanguage()->formatSize( isset( $row->dumps_size ) ? $row->dumps_size : 0 ) );\n\t\t\t\tbreak;\n\t\t\tcase 'dumps_delete':\n\t\t\t\t$linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();\n\n\t\t\t\t$query = [\n\t\t\t\t\t'action' => 'delete',\n\t\t\t\t\t'type' => $row->dumps_type,\n\t\t\t\t\t'dump' => $row->dumps_filename\n\t\t\t\t];\n\n\t\t\t\t$formatted = $linkRenderer->makeLink( $this->pageTitle, wfMessage( 'datadump-delete-button' )->text(), [], $query );\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t$formatted = \"Unable to format $name\";\n\t\t\t\tbreak;\n\t\t}\n\n\t\treturn $formatted;\n\t}", "label_name": "CWE-352", "label": 0} {"code": " public function addReplyTo($address, $name = '')\n {\n return $this->addAnAddress('Reply-To', $address, $name);\n }", "label_name": "CWE-352", "label": 0} {"code": " public function addUser(){\n $login_user = $this->checkLogin();\n $this->checkAdmin();\n $username = I(\"username\");\n $password = I(\"password\");\n $uid = I(\"uid\");\n $name = I(\"name\");\n if(!$username){\n $this->sendError(10101,'\u7528\u6237\u540d\u4e0d\u5141\u8bb8\u4e3a\u7a7a');\n return ;\n }\n if($uid){\n if($password){\n D(\"User\")->updatePwd($uid, $password);\n }\n if($name){\n D(\"User\")->where(\" uid = '$uid' \")->save(array(\"name\"=>$name));\n }\n $this->sendResult(array());\n }else{\n if (D(\"User\")->isExist($username)) {\n $this->sendError(10101,L('username_exists'));\n return ;\n }\n $new_uid = D(\"User\")->register($username,$password);\n if (!$new_uid) {\n $this->sendError(10101);\n }else{\n if($name){\n D(\"User\")->where(\" uid = '$new_uid' \")->save(array(\"name\"=>$name));\n }\n $this->sendResult($return);\n }\n }\n\n }", "label_name": "CWE-352", "label": 0} {"code": "function csrf_get_tokens()\n{\n $has_cookies = !empty($_COOKIE);\n\n // $ip implements a composite key, which is sent if the user hasn't sent\n // any cookies. It may or may not be used, depending on whether or not\n // the cookies \"stick\"\n $secret = csrf_get_secret();\n if (!$has_cookies && $secret) {\n // :TODO: Harden this against proxy-spoofing attacks\n $ip = ';ip:' . csrf_hash($_SERVER['IP_ADDRESS']);\n } else {\n $ip = '';\n }\n csrf_start();\n\n // These are \"strong\" algorithms that don't require per se a secret\n if (session_id()) {\n return 'sid:' . csrf_hash(session_id()) . $ip;\n }\n if ($GLOBALS['csrf']['cookie']) {\n $val = csrf_generate_secret();\n setcookie($GLOBALS['csrf']['cookie'], $val);\n return 'cookie:' . csrf_hash($val) . $ip;\n }\n if ($GLOBALS['csrf']['key']) {\n return 'key:' . csrf_hash($GLOBALS['csrf']['key']) . $ip;\n }\n // These further algorithms require a server-side secret\n if (!$secret) {\n return 'invalid';\n }\n if ($GLOBALS['csrf']['user'] !== false) {\n return 'user:' . csrf_hash($GLOBALS['csrf']['user']);\n }\n if ($GLOBALS['csrf']['allow-ip']) {\n return ltrim($ip, ';');\n }\n return 'invalid';\n}", "label_name": "CWE-352", "label": 0} {"code": " public function attorn(){\n $login_user = $this->checkLogin();\n\n $username = I(\"username\");\n $item_id = I(\"item_id/d\");\n $password = I(\"password\");\n\n $item = D(\"Item\")->where(\"item_id = '$item_id' \")->find();\n\n if(!$this->checkItemManage($login_user['uid'] , $item['item_id'])){\n $this->sendError(10303);\n return ;\n }\n\n if(! D(\"User\")-> checkLogin($item['username'],$password)){\n $this->sendError(10208);\n return ;\n }\n\n $member = D(\"User\")->where(\" username = '%s' \",array($username))->find();\n\n if (!$member) {\n $this->sendError(10209);\n return ;\n }\n\n $data['username'] = $member['username'] ;\n $data['uid'] = $member['uid'] ;\n \n\n $id = D(\"Item\")->where(\" item_id = '$item_id' \")->save($data);\n\n $return = D(\"Item\")->where(\"item_id = '$item_id' \")->find();\n\n if (!$return) {\n $this->sendError(10101);\n }\n\n $this->sendResult($return);\n }", "label_name": "CWE-352", "label": 0} {"code": " public static function error ($vars=\"\") {\n if( isset($vars) && $vars != \"\" ) {\n include(GX_PATH.'/inc/lib/Control/Error/'.$vars.'.control.php');\n }else{\n include(GX_PATH.'/inc/lib/Control/Error/404.control.php');\n }\n }", "label_name": "CWE-352", "label": 0} {"code": " function handleFormSubmission() {\r\n $request = $request = $this->pageContext->getRequest();\r\n\r\n $dbw = getTransactableDatabase('scratch-confirmaccount-bypasses');\r\n\r\n foreach (self::requestVariableActionMapping as $fieldKey => $action) {\r\n if ($request->getText($fieldKey)) {\r\n $action($request->getText($fieldKey), $dbw);\r\n }\r\n }\r\n\r\n commitTransaction($dbw, 'scratch-confirmaccount-bypasses');\r\n\r\n $this->render();\r\n }\r", "label_name": "CWE-352", "label": 0} {"code": " public function password()\n {\n $user = Auth::user();\n\n return view('account/change-password', compact('user'));\n }", "label_name": "CWE-384", "label": 1} {"code": " public static function get_param($key = NULL) {\n $info = [\n 'stype' => htmlentities(self::$search_type),\n 'stext' => htmlentities(self::$search_text),\n 'method' => htmlentities(self::$search_method),\n 'datelimit' => self::$search_date_limit,\n 'fields' => self::$search_fields,\n 'sort' => self::$search_sort,\n 'chars' => htmlentities(self::$search_chars),\n 'order' => self::$search_order,\n 'forum_id' => self::$forum_id,\n 'memory_limit' => self::$memory_limit,\n 'composevars' => self::$composevars,\n 'rowstart' => self::$rowstart,\n 'search_param' => htmlentities(self::$search_param),\n ];\n\n return $key === NULL ? $info : (isset($info[$key]) ? $info[$key] : NULL);\n }", "label_name": "CWE-352", "label": 0} {"code": " public function enable($id) {\n $this->active($id, TRUE);\n }", "label_name": "CWE-352", "label": 0} {"code": " public function deleteCommentAction(ProjectComment $comment)\n {\n $projectId = $comment->getProject()->getId();\n\n try {\n $this->repository->deleteComment($comment);\n } catch (\\Exception $ex) {\n $this->flashDeleteException($ex);\n }\n\n return $this->redirectToRoute('project_details', ['id' => $projectId]);\n }", "label_name": "CWE-352", "label": 0} {"code": "\tpublic static function simple($input)\n\t{\n\t\treturn empty($str) ? '' : pts_strings::keep_in_string($input, pts_strings::CHAR_LETTER | pts_strings::CHAR_NUMERIC | pts_strings::CHAR_DASH | pts_strings::CHAR_DECIMAL | pts_strings::CHAR_SPACE | pts_strings::CHAR_UNDERSCORE | pts_strings::CHAR_COMMA | pts_strings::CHAR_AT | pts_strings::CHAR_COLON);\n\t}", "label_name": "CWE-352", "label": 0} {"code": " public function testSettingCookie()\n {\n $_SERVER['REQUEST_METHOD'] = 'GET';\n\n $controller = $this->getMock('Cake\\Controller\\Controller', ['redirect']);\n $controller->request = new Request(['webroot' => '/dir/']);\n $controller->response = new Response();\n\n $event = new Event('Controller.startup', $controller);\n $this->component->startup($event);\n\n $cookie = $controller->response->cookie('csrfToken');\n $this->assertNotEmpty($cookie, 'Should set a token.');\n $this->assertRegExp('/^[a-f0-9]+$/', $cookie['value'], 'Should look like a hash.');\n $this->assertEquals(0, $cookie['expire'], 'session duration.');\n $this->assertEquals('/dir/', $cookie['path'], 'session path.');\n\n $this->assertEquals($cookie['value'], $controller->request->params['_csrfToken']);\n }", "label_name": "CWE-352", "label": 0} {"code": " protected function edebug($str)\n {\n if (!$this->SMTPDebug) {\n return;\n }\n switch ($this->Debugoutput) {\n case 'error_log':\n error_log($str);\n break;\n case 'html':\n //Cleans up output a bit for a better looking display that's HTML-safe\n echo htmlentities(preg_replace('/[\\r\\n]+/', '', $str), ENT_QUOTES, $this->CharSet) . \"
\\n\";\n break;\n case 'echo':\n default:\n echo $str.\"\\n\";\n }\n }", "label_name": "CWE-352", "label": 0} {"code": " public function pinCommentAction(CustomerComment $comment)\n {\n $comment->setPinned(!$comment->isPinned());\n try {\n $this->repository->saveComment($comment);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n\n return $this->redirectToRoute('customer_details', ['id' => $comment->getCustomer()->getId()]);\n }", "label_name": "CWE-352", "label": 0} {"code": " public static function desc($vars){\n if(!empty($vars)){\n $desc = substr(strip_tags(htmlspecialchars_decode($vars).\". \".Options::get('sitedesc')),0,150);\n }else{\n $desc = substr(Options::get('sitedesc'),0,150);\n }\n \n return $desc;\n }", "label_name": "CWE-352", "label": 0} {"code": " function logon($username, $password, &$sessionId)\n {\n global $_POST, $_COOKIE;\n global $strUsernameOrPasswordWrong;\n\n /**\n * @todo Please check if the following statement is in correct place because\n * it seems illogical that user can get session ID from internal login with\n * a bad username or password.\n */\n\n if (!$this->_verifyUsernameAndPasswordLength($username, $password)) {\n return false;\n }\n\n $_POST['username'] = $username;\n $_POST['password'] = $password;\n\n $_POST['login'] = 'Login';\n\n $_COOKIE['sessionID'] = uniqid('phpads', 1);\n $_POST['phpAds_cookiecheck'] = $_COOKIE['sessionID'];\n\n $this->preInitSession();\n if ($this->_internalLogin($username, $password)) {\n // Check if the user has administrator access to Openads.\n if (OA_Permission::isUserLinkedToAdmin()) {\n\n $this->postInitSession();\n\n $sessionId = $_COOKIE['sessionID'];\n return true;\n } else {\n\n $this->raiseError('User must be OA installation admin');\n return false;\n }\n } else {\n\n $this->raiseError($strUsernameOrPasswordWrong);\n return false;\n }\n }", "label_name": "CWE-384", "label": 1} {"code": " public static function cat($vars) {\n switch (SMART_URL) {\n case true:\n # code...\n $url = Options::get('siteurl').\"/\".$vars.\"/\".Typo::slugify(Categories::name($vars));\n break;\n \n default:\n # code...\n $url = Options::get('siteurl').\"/index.php?cat={$vars}\";\n break;\n\n }\n\n return $url;\n }", "label_name": "CWE-352", "label": 0} {"code": " public function testPinCommentAction()\n {\n $client = $this->getClientForAuthenticatedUser(User::ROLE_ADMIN);\n $this->assertAccessIsGranted($client, '/admin/project/1/details');\n $form = $client->getCrawler()->filter('form[name=project_comment_form]')->form();\n $client->submit($form, [\n 'project_comment_form' => [\n 'message' => 'Foo bar blub',\n ]\n ]);\n $this->assertIsRedirect($client, $this->createUrl('/admin/project/1/details'));\n $client->followRedirect();\n $node = $client->getCrawler()->filter('div.box#comments_box .direct-chat-text');\n self::assertStringContainsString('Foo bar blub', $node->html());\n $node = $client->getCrawler()->filter('div.box#comments_box .box-body a.btn.active');\n self::assertEquals(0, $node->count());\n\n $comments = $this->getEntityManager()->getRepository(ProjectComment::class)->findAll();\n $id = $comments[0]->getId();\n\n $this->request($client, '/admin/project/' . $id . '/comment_pin');\n $this->assertIsRedirect($client, $this->createUrl('/admin/project/1/details'));\n $client->followRedirect();\n $node = $client->getCrawler()->filter('div.box#comments_box .box-body a.btn.active');\n self::assertEquals(1, $node->count());\n self::assertEquals($this->createUrl('/admin/project/' . $id . '/comment_pin'), $node->attr('href'));\n }", "label_name": "CWE-352", "label": 0} {"code": " public function test_invite_set_password()\n {\n Notification::fake();\n $user = $this->getViewer();\n $inviteService = app(UserInviteService::class);\n\n $inviteService->sendInvitation($user);\n $token = DB::table('user_invites')->where('user_id', '=', $user->id)->first()->token;\n\n $setPasswordPageResp = $this->get('/register/invite/' . $token);\n $setPasswordPageResp->assertSuccessful();\n $setPasswordPageResp->assertSee('Welcome to BookStack!');\n $setPasswordPageResp->assertSee('Password');\n $setPasswordPageResp->assertSee('Confirm Password');\n\n $setPasswordResp = $this->followingRedirects()->post('/register/invite/' . $token, [\n 'password' => 'my test password',\n ]);\n $setPasswordResp->assertSee('Password set, you now have access to BookStack!');\n $newPasswordValid = auth()->validate([\n 'email' => $user->email,\n 'password' => 'my test password',\n ]);\n $this->assertTrue($newPasswordValid);\n $this->assertDatabaseMissing('user_invites', [\n 'user_id' => $user->id,\n ]);\n }", "label_name": "CWE-352", "label": 0} {"code": "function compression_test() {\n?>\n\t\n\n \n
\n

'. $_SESSION['error_msg'] .'

\n
\n '.\"\\n\";\n unset($_SESSION['error_msg']);\n }\n}", "label_name": "CWE-352", "label": 0} {"code": " public function up(RuleGroup $ruleGroup)\n {\n $order = (int)$ruleGroup->order;\n if ($order > 1) {\n $newOrder = $order - 1;\n $this->repository->setOrder($ruleGroup, $newOrder);\n }\n\n return redirect(route('rules.index'));\n }", "label_name": "CWE-352", "label": 0} {"code": "function csrf_check($fatal = true)\n{\n if ($_SERVER['REQUEST_METHOD'] !== 'POST') {\n return true;\n }\n csrf_start();\n $name = $GLOBALS['csrf']['input-name'];\n $ok = false;\n $tokens = '';\n do {\n if (!isset($_POST[$name])) {\n break;\n }\n // we don't regenerate a token and check it because some token creation\n // schemes are volatile.\n $tokens = $_POST[$name];\n if (!csrf_check_tokens($tokens)) {\n break;\n }\n $ok = true;\n } while (false);\n if ($fatal && !$ok) {\n $callback = $GLOBALS['csrf']['callback'];\n if (trim($tokens, 'A..Za..z0..9:;,') !== '') {\n $tokens = 'hidden';\n }\n $callback($tokens);\n exit;\n }\n return $ok;\n}", "label_name": "CWE-352", "label": 0} {"code": "\t\tfunction verifyCSRFToken() {\n\t\t\t$clean_referer = str_replace(array(\"http://\",\"https://\"),\"//\",$_SERVER[\"HTTP_REFERER\"]);\n\t\t\t$clean_domain = str_replace(array(\"http://\",\"https://\"),\"//\",DOMAIN);\n\t\t\t$token = isset($_POST[$this->CSRFTokenField]) ? $_POST[$this->CSRFTokenField] : $_GET[$this->CSRFTokenField];\n\t\t\t\n\t\t\tif (strpos($clean_referer, $clean_domain) === false || $token != $this->CSRFToken) {\n\t\t\t\t$this->stop(\"Cross site request forgery detected.\");\n\t\t\t}\n\t\t}", "label_name": "CWE-352", "label": 0} {"code": " public function update(){\n $login_user = $this->checkLogin();\n $item_id = I(\"item_id/d\"); \n $item_name = I(\"item_name\"); \n $item_description = I(\"item_description\"); \n $item_domain = I(\"item_domain\"); \n $password = I(\"password\");\n $uid = $login_user['uid'] ;\n if(!$this->checkItemManage($uid , $item_id)){\n $this->sendError(10303);\n return ;\n }\n\n if ($item_domain) {\n \n if(!ctype_alnum($item_domain) || is_numeric($item_domain) ){\n //echo '\u4e2a\u6027\u57df\u540d\u53ea\u80fd\u662f\u5b57\u6bcd\u6216\u6570\u5b57\u7684\u7ec4\u5408';exit;\n $this->sendError(10305);\n return false;\n }\n\n $item = D(\"Item\")->where(\"item_domain = '%s' and item_id !='%s' \",array($item_domain,$item_id))->find();\n if ($item) {\n //\u4e2a\u6027\u57df\u540d\u5df2\u7ecf\u5b58\u5728\n $this->sendError(10304);\n return false;\n }\n }\n $save_data = array(\n \"item_name\" => $item_name ,\n \"item_description\" => $item_description ,\n \"item_domain\" => $item_domain ,\n \"password\" => $password ,\n );\n $items = D(\"Item\")->where(\"item_id = '$item_id' \")->save($save_data);\n $items = $items ? $items : array();\n $this->sendResult($items); \n }", "label_name": "CWE-352", "label": 0} {"code": "function clean_input_value($value) {\n if (is_string($value)) {\n return descript($value);\n }\n if (is_array($value)) {\n return array_map('descript', $value);\n }\n return '';\n}", "label_name": "CWE-352", "label": 0} {"code": " public function testDeleteCommentAction()\n {\n $client = $this->getClientForAuthenticatedUser(User::ROLE_ADMIN);\n $this->assertAccessIsGranted($client, '/admin/customer/1/details');\n $form = $client->getCrawler()->filter('form[name=customer_comment_form]')->form();\n $client->submit($form, [\n 'customer_comment_form' => [\n 'message' => 'Blah foo bar',\n ]\n ]);\n $this->assertIsRedirect($client, $this->createUrl('/admin/customer/1/details'));\n $client->followRedirect();\n $node = $client->getCrawler()->filter('div.box#comments_box .direct-chat-msg');\n self::assertStringContainsString('Blah foo bar', $node->html());\n $node = $client->getCrawler()->filter('div.box#comments_box .box-body a.confirmation-link');\n self::assertStringEndsWith('/comment_delete', $node->attr('href'));\n\n $comments = $this->getEntityManager()->getRepository(CustomerComment::class)->findAll();\n $id = $comments[0]->getId();\n\n $this->request($client, '/admin/customer/' . $id . '/comment_delete');\n $this->assertIsRedirect($client, $this->createUrl('/admin/customer/1/details'));\n $client->followRedirect();\n $node = $client->getCrawler()->filter('div.box#comments_box .box-body');\n self::assertStringContainsString('There were no comments posted yet', $node->html());\n }", "label_name": "CWE-352", "label": 0} {"code": " public function cloneGroup(TransactionGroup $group)\n {\n\n /** @var GroupCloneService $service */\n $service = app(GroupCloneService::class);\n $newGroup = $service->cloneGroup($group);\n\n // event!\n event(new StoredTransactionGroup($newGroup));\n\n app('preferences')->mark();\n\n $title = $newGroup->title ?? $newGroup->transactionJournals->first()->description;\n $link = route('transactions.show', [$newGroup->id]);\n session()->flash('success', trans('firefly.stored_journal', ['description' => $title]));\n session()->flash('success_url', $link);\n\n return redirect(route('transactions.show', [$newGroup->id]));\n }", "label_name": "CWE-352", "label": 0} {"code": " public function changePassword(){\n $login_user = $this->checkLogin();\n $this->checkAdmin();\n $uid = I(\"uid/d\");\n $new_password = I(\"new_password\");\n\n $return = D(\"User\")->updatePwd($uid, $new_password);\n if (!$return) {\n $this->sendError(10101);\n }else{\n $this->sendResult($return);\n }\n }", "label_name": "CWE-352", "label": 0} {"code": " public function save(){\n $login_user = $this->checkLogin();\n\n $team_name = I(\"team_name\");\n $id = I(\"id/d\");\n\n if ($id) {\n \n D(\"Team\")->where(\" id = '$id' \")->save(array(\"team_name\"=>$team_name));\n\n }else{\n $data['username'] = $login_user['username'] ;\n $data['uid'] = $login_user['uid'] ;\n $data['team_name'] = $team_name ;\n $data['addtime'] = time() ;\n $id = D(\"Team\")->add($data); \n }\n\n $return = D(\"Team\")->where(\" id = '$id' \")->find();\n\n if (!$return) {\n $return['error_code'] = 10103 ;\n $return['error_message'] = 'request fail' ;\n }\n\n $this->sendResult($return);\n \n }", "label_name": "CWE-352", "label": 0} {"code": " public function loadUserByUsername($username)\n {\n return $this->inner->loadUserByUsername($username);\n }", "label_name": "CWE-384", "label": 1} {"code": " public function delete(AvailableBudget $availableBudget)\n {\n $this->abRepository->destroyAvailableBudget($availableBudget);\n session()->flash('success', trans('firefly.deleted_ab'));\n\n return redirect(route('budgets.index'));\n }", "label_name": "CWE-352", "label": 0} {"code": " public static function isHadSub($parent, $menuid =''){\n $sql = sprintf(\"SELECT * FROM `menus` WHERE `parent` = '%s' %s\", $parent, $where);\n }", "label_name": "CWE-352", "label": 0} {"code": " public function confirm(string $token)\n {\n try {\n $userId = $this->emailConfirmationService->checkTokenAndGetUserId($token);\n } catch (UserTokenNotFoundException $exception) {\n $this->showErrorNotification(trans('errors.email_confirmation_invalid'));\n\n return redirect('/register');\n } catch (UserTokenExpiredException $exception) {\n $user = $this->userRepo->getById($exception->userId);\n $this->emailConfirmationService->sendConfirmation($user);\n $this->showErrorNotification(trans('errors.email_confirmation_expired'));\n\n return redirect('/register/confirm');\n }\n\n $user = $this->userRepo->getById($userId);\n $user->email_confirmed = true;\n $user->save();\n\n $this->emailConfirmationService->deleteByUser($user);\n $this->showSuccessNotification(trans('auth.email_confirm_success'));\n $this->loginService->login($user, auth()->getDefaultDriver());\n\n return redirect('/');\n }", "label_name": "CWE-352", "label": 0} {"code": " public function down(RuleGroup $ruleGroup)\n {\n $maxOrder = $this->repository->maxOrder();\n $order = (int)$ruleGroup->order;\n if ($order < $maxOrder) {\n $newOrder = $order + 1;\n $this->repository->setOrder($ruleGroup, $newOrder);\n }\n\n return redirect(route('rules.index'));\n }", "label_name": "CWE-352", "label": 0} {"code": " $logo = \"\";\n }else{\n $logo = \"\";\n }\n return $logo;\n }", "label_name": "CWE-352", "label": 0} {"code": " public function delete(){\n $id = I(\"id/d\")? I(\"id/d\") : 0;\n $login_user = $this->checkLogin();\n if ($id && $login_user['uid']) {\n $ret = D(\"Team\")->where(\" id = '$id' and uid = '$login_user[uid]'\")->delete();\n }\n if ($ret) {\n D(\"TeamItem\")->where(\" team_id = '$id' \")->delete();\n D(\"TeamItemMember\")->where(\" team_id = '$id' \")->delete();\n D(\"TeamMember\")->where(\" team_id = '$id' \")->delete();\n $this->sendResult($ret);\n }else{\n $return['error_code'] = 10103 ;\n $return['error_message'] = 'request fail' ;\n $this->sendResult($return);\n }\n }", "label_name": "CWE-352", "label": 0} {"code": "\t\tpublic function init()\n\t\t{\n\n\t\t\tif(!e_QUERY)\n\t\t\t{\n\t\t\t\te107::getPlug()->clearCache();\n\t\t\t}\n\n\n\n\t\t\tif($this->getMode()=== 'avail')\n\t\t\t{\n\t\t\t\t$this->listQry = \"SELECT * FROM `#plugin` WHERE plugin_installflag = 0 AND plugin_category != 'menu' \";\n\t\t\t}\n\n\t\t\t// Set drop-down values (if any).\n\n\t\t}", "label_name": "CWE-352", "label": 0} {"code": "function ttMitigateCSRF() {\n // No need to do anything for get requests.\n global $request;\n if ($request->isGet())\n return true;\n\n $origin = $_SERVER['HTTP_ORIGIN'];\n if ($origin) {\n $pos = strpos($origin, '//');\n $origin = substr($origin, $pos+2); // Strip protocol.\n }\n if (!$origin) {\n // Try using referer.\n $origin = $_SERVER['HTTP_REFERER'];\n if ($origin) {\n $pos = strpos($origin, '//');\n $origin = substr($origin, $pos+2); // Strip protocol.\n $pos = strpos($origin, '/');\n $origin = substr($origin, 0, $pos); // Leave host only.\n }\n }\n error_log(\"origin: \".$origin);\n $target = defined('HTTP_TARGET') ? HTTP_TARGET : $_SERVER['HTTP_HOST'];\n error_log(\"target: \".$target);\n if (strcmp($origin, $target)) {\n error_log(\"Potential cross site request forgery. Origin: '$origin' does not match target: '$target'.\");\n return false; // Origin and target do not match,\n }\n\n // TODO: review and improve this function for custom ports.\n return true;\n}", "label_name": "CWE-352", "label": 0} {"code": " public function refreshUser(UserInterface $user)\n {\n $user = $this->inner->refreshUser($user);\n\n $alterUser = \\Closure::bind(function (InMemoryUser $user) { $user->password = 'foo'; }, null, class_exists(User::class) ? User::class : InMemoryUser::class);\n $alterUser($user);\n\n return $user;\n }", "label_name": "CWE-384", "label": 1} {"code": "\t\t\\CsrfMagic\\Csrf::$callback = function ($tokens) {\n\t\t\tthrow new \\App\\Exceptions\\AppException('Invalid request - Response For Illegal Access', 403);\n\t\t};", "label_name": "CWE-352", "label": 0} {"code": "\tpublic static function simple($input)\n\t{\n\t\treturn empty($str) ? '' : pts_strings::keep_in_string($input, pts_strings::CHAR_LETTER | pts_strings::CHAR_NUMERIC | pts_strings::CHAR_DASH | pts_strings::CHAR_DECIMAL | pts_strings::CHAR_SPACE | pts_strings::CHAR_UNDERSCORE | pts_strings::CHAR_COMMA | pts_strings::CHAR_AT | pts_strings::CHAR_COLON);\n\t}", "label_name": "CWE-352", "label": 0} {"code": " public function deleteByName(){\n $item_id = I(\"item_id/d\"); \n $env_id = I(\"env_id/d\"); \n $var_name = I(\"var_name\"); \n $login_user = $this->checkLogin();\n $uid = $login_user['uid'] ;\n if(!$this->checkItemEdit($uid , $item_id)){\n $this->sendError(10303);\n return ;\n } \n $ret = D(\"ItemVariable\")->where(\" item_id = '%d' and env_id = '%d' and var_name = '%s' \",array($item_id,$env_id,$var_name))->delete();\n if ($ret) {\n $this->sendResult($ret);\n }else{\n $this->sendError(10101);\n }\n }", "label_name": "CWE-352", "label": 0} {"code": "\tpublic function test_create_nonce_url() {\n $url = yourls_nonce_url( rand_str(), rand_str(), rand_str(), rand_str() );\n $this->assertTrue( is_string($url) );\n // $this->assertIsString($url);\n }", "label_name": "CWE-352", "label": 0} {"code": "\tpublic function AdminObserver()\r\n\t{\r\n\t\tif($this->getPosted('go_back'))\r\n\t\t{\r\n\t\t\t$this->redirect('list', 'main', true);\r\n\t\t}\r\n\t\t\r\n\t\t$userid = $this->getId();\r\n\t\t$sql = e107::getDb();\r\n\t\t$user = e107::getUser();\r\n\t\t$sysuser = e107::getSystemUser($userid, false);\r\n\t\t$admin_log = e107::getAdminLog();\r\n\t\t$mes = e107::getMessage();\r\n\t\t\r\n\t\tif(!$user->checkAdminPerms('3'))\r\n\t\t{\r\n\t\t\t// TODO lan\r\n\t\t\t$mes->addError(\"You don't have enough permissions to do this.\", 'default', true);\r\n\t\t\t// TODO lan\r\n\t\t\t$lan = 'Security violation (not enough permissions) - Administrator --ADMIN_UID-- (--ADMIN_NAME--, --ADMIN_EMAIL--) tried to make --UID-- (--NAME--, --EMAIL--) system admin';\r\n\t\t\t$search = array('--UID--', '--NAME--', '--EMAIL--', '--ADMIN_UID--', '--ADMIN_NAME--', '--ADMIN_EMAIL--');\r\n\t\t\t$replace = array($sysuser->getId(), $sysuser->getName(), $sysuser->getValue('email'), $user->getId(), $user->getName(), $user->getValue('email'));\r\n\t\t\t\r\n\t\t\te107::getLog()->add('USET_08', str_replace($search, $replace, $lan), E_LOG_INFORMATIVE);\r\n\t\t\t\r\n\t\t\t$this->redirect('list', 'main', true);\r\n\t\t}\r\n\t\t\r\n\t\tif(!$sysuser->getId())\r\n\t\t{\r\n\t\t\t// TODO lan\r\n\t\t\t$mes->addError(\"User not found.\", 'default', true);\r\n\t\t\t$this->redirect('list', 'main', true);\r\n\t\t}\r\n\t\t\r\n\t\tif(!$sysuser->isAdmin())\r\n\t\t{\r\n\t\t\t$sysuser->set('user_admin', 1)->save(); //\"user\",\"user_admin='1' WHERE user_id={$userid}\"\r\n\t\t\t$lan = str_replace(array('--UID--', '--NAME--', '--EMAIL--'), array($sysuser->getId(), $sysuser->getName(), $sysuser->getValue('email')), USRLAN_164);\r\n\t\t\te107::getLog()->add('USET_08', $lan, E_LOG_INFORMATIVE);\r\n\t\t\t$mes->addSuccess($lan);\r\n\t\t}\r\n\t\t\r\n\t\tif($this->getPosted('update_admin')) e107::getUserPerms()->updatePerms($userid, $_POST['perms']);\r\n\t}\r", "label_name": "CWE-352", "label": 0} {"code": " public function handle(Request $request, Closure $next, int $keyType)\n {\n if (is_null($request->bearerToken()) && is_null($request->user())) {\n throw new HttpException(401, null, null, ['WWW-Authenticate' => 'Bearer']);\n }\n\n // This is a request coming through using cookies, we have an authenticated user\n // not using an API key. Make some fake API key models and continue on through\n // the process.\n if ($request->user() instanceof User) {\n $model = (new ApiKey())->forceFill([\n 'user_id' => $request->user()->id,\n 'key_type' => ApiKey::TYPE_ACCOUNT,\n ]);\n } else {\n $model = $this->authenticateApiKey($request->bearerToken(), $keyType);\n\n $this->auth->guard()->loginUsingId($model->user_id);\n }\n\n $request->attributes->set('api_key', $model);\n\n return $next($request);\n }", "label_name": "CWE-352", "label": 0} {"code": "\tpublic function __construct()\n\t{\n\t\tparent::__construct();\n\n\t\t// for flash data\n\t\t$this->load->library('session');\n\n\t\tif (!$this->fuel->config('admin_enabled')) show_404();\n\n\t\t$this->load->vars(array(\n\t\t\t'js' => '', \n\t\t\t'css' => css($this->fuel->config('xtra_css')), // use CSS function here because of the asset library path changes below\n\t\t\t'js_controller_params' => array(), \n\t\t\t'keyboard_shortcuts' => $this->fuel->config('keyboard_shortcuts')));\n\n\t\t// change assets path to admin\n\t\t$this->asset->assets_path = $this->fuel->config('fuel_assets_path');\n\n\t\t// set asset output settings\n\t\t$this->asset->assets_output = $this->fuel->config('fuel_assets_output');\n\t\t\n\t\t$this->lang->load('fuel');\n\t\t$this->load->helper('ajax');\n\t\t$this->load->library('form_builder');\n\n\t\t$this->load->module_model(FUEL_FOLDER, 'fuel_users_model');\n\n\t\t// set configuration paths for assets in case they are different from front end\n\t\t$this->asset->assets_module ='fuel';\n\t\t$this->asset->assets_folders = array(\n\t\t\t\t'images' => 'images/',\n\t\t\t\t'css' => 'css/',\n\t\t\t\t'js' => 'js/',\n\t\t\t);\n\n\t}", "label_name": "CWE-352", "label": 0} {"code": " public function notify_edge_mode() {\n w3_require_once(W3TC_INC_FUNCTIONS_DIR . '/ui.php');\n w3_require_once(W3TC_INC_FUNCTIONS_DIR . '/admin_ui.php');\n $message = sprintf(__('

You can now keep W3 Total Cache up-to-date without having to worry about new features breaking your website. There will be more releases with bug fixes, security fixes and settings updates.

\n

Also, you can now try out our new features as soon as they\\'re ready. %s to enable \"edge mode\" and unlock pre-release features. %s

', 'w3-total-cache')\n ,'' . __('Click Here', 'w3-total-cache') . ''\n , w3_button_hide_note(__('Hide this message', 'w3-total-cache'), 'edge_mode', '', true,'','w3tc_default_hide_note_custom')\n );\n w3_e_notification_box($message, 'edge-mode');\n }", "label_name": "CWE-352", "label": 0} {"code": " public function update(CurrencyFormRequest $request, TransactionCurrency $currency)\n {\n /** @var User $user */\n $user = auth()->user();\n $data = $request->getCurrencyData();\n\n if (false === $data['enabled'] && $this->repository->currencyInUse($currency)) {\n $data['enabled'] = true;\n }\n if (!$this->userRepository->hasRole($user, 'owner')) {\n\n $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))]));\n Log::channel('audit')->info('Tried to update (POST) currency without admin rights.', $data);\n\n return redirect(route('currencies.index'));\n\n }\n $currency = $this->repository->update($currency, $data);\n Log::channel('audit')->info('Updated (POST) currency.', $data);\n $request->session()->flash('success', (string) trans('firefly.updated_currency', ['name' => $currency->name]));\n app('preferences')->mark();\n\n if (1 === (int) $request->get('return_to_edit')) {\n\n $request->session()->put('currencies.edit.fromUpdate', true);\n\n return redirect(route('currencies.edit', [$currency->id]));\n\n }\n\n return redirect($this->getPreviousUri('currencies.edit.uri'));\n }", "label_name": "CWE-352", "label": 0} {"code": " public function addCC($address, $name = '')\n {\n return $this->addAnAddress('cc', $address, $name);\n }", "label_name": "CWE-352", "label": 0} {"code": " protected function _validateSecretKey()\n {\n if (is_array($this->_publicActions) && in_array($this->getRequest()->getActionName(), $this->_publicActions)) {\n return true;\n }\n\n if (!($secretKey = $this->getRequest()->getParam(Mage_Adminhtml_Model_Url::SECRET_KEY_PARAM_NAME, null))\n || $secretKey != Mage::getSingleton('adminhtml/url')->getSecretKey()) {\n return false;\n }\n return true;\n }", "label_name": "CWE-352", "label": 0} {"code": " $values = [READ => __('Read'),\n CREATE => __('Create'),", "label_name": "CWE-352", "label": 0} {"code": " $ret = array_merge($ret, csrf_flattenpost2(1, $n, $v));\n }", "label_name": "CWE-352", "label": 0} {"code": " foreach ($data['alertred'] as $alert) {\n # code...\n echo \"
  • $alert
  • \\n\";\n }", "label_name": "CWE-352", "label": 0} {"code": " public function deleteItem(){\n $login_user = $this->checkLogin();\n $this->checkAdmin();\n $item_id = I(\"item_id/d\");\n $return = D(\"Item\")->soft_delete_item($item_id);\n if (!$return) {\n $this->sendError(10101);\n }else{\n $this->sendResult($return);\n }\n }", "label_name": "CWE-352", "label": 0} {"code": " function showAddBypassForm() {\r\n $output = $this->pageContext->getOutput();\r\n $request = $this->pageContext->getRequest();\r\n \r\n $output->addHTML(\r\n new OOUI\\FormLayout([\r\n 'action' => SpecialPage::getTitleFor('ConfirmAccounts', wfMessage('scratch-confirmaccount-requirements-bypasses-url')->text())->getFullURL(),\r\n 'method' => 'post',\r\n 'items' => [\r\n new OOUI\\ActionFieldLayout(\r\n new OOUI\\TextInputWidget( [\r\n 'name' => 'bypassAddUsername',\r\n 'required' => true,\r\n 'value' => $request->getText('username')\r\n ] ),\r\n new OOUI\\ButtonInputWidget([\r\n 'type' => 'submit',\r\n 'flags' => ['primary', 'progressive'],\r\n 'label' => wfMessage('scratch-confirmaccount-requirements-bypasses-add')->parse()\r\n ])\r\n )\r\n ],\r\n ])\r\n );\r\n }\r", "label_name": "CWE-352", "label": 0} {"code": " protected function addAnAddress($kind, $address, $name = '')\n {\n if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {\n $this->setError($this->lang('Invalid recipient array') . ': ' . $kind);\n $this->edebug($this->lang('Invalid recipient array') . ': ' . $kind);\n if ($this->exceptions) {\n throw new phpmailerException('Invalid recipient array: ' . $kind);\n }\n return false;\n }\n $address = trim($address);\n $name = trim(preg_replace('/[\\r\\n]+/', '', $name)); //Strip breaks and trim\n if (!$this->validateAddress($address)) {\n $this->setError($this->lang('invalid_address') . ': ' . $address);\n $this->edebug($this->lang('invalid_address') . ': ' . $address);\n if ($this->exceptions) {\n throw new phpmailerException($this->lang('invalid_address') . ': ' . $address);\n }\n return false;\n }\n if ($kind != 'Reply-To') {\n if (!isset($this->all_recipients[strtolower($address)])) {\n array_push($this->$kind, array($address, $name));\n $this->all_recipients[strtolower($address)] = true;\n return true;\n }\n } else {\n if (!array_key_exists(strtolower($address), $this->ReplyTo)) {\n $this->ReplyTo[strtolower($address)] = array($address, $name);\n return true;\n }\n }\n return false;\n }", "label_name": "CWE-352", "label": 0} {"code": " public function action_edge_mode_enable() {\n w3_require_once(W3TC_INC_FUNCTIONS_DIR . '/activation.php');\n $config_path = w3_get_wp_config_path();\n\n $config_data = @file_get_contents($config_path);\n if ($config_data === false)\n return;\n\n $new_config_data = $this->wp_config_evaluation_mode_remove_from_content($config_data);\n $new_config_data = preg_replace(\n '~<\\?(php)?~',\n \"\\\\0\\r\\n\" . $this->wp_config_evaluation_mode(),\n $new_config_data,\n 1);\n\n if ($new_config_data != $config_data) {\n try {\n w3_wp_write_to_file($config_path, $new_config_data);\n } catch (FilesystemOperationException $ex) {\n throw new FilesystemModifyException(\n $ex->getMessage(), $ex->credentials_form(),\n 'Edit file ' . $config_path .\n ' and add the next lines:', $config_path,\n $this->wp_config_evaluation_mode());\n }\n try {\n $this->_config_admin->set('notes.edge_mode', false);\n $this->_config_admin->save();\n } catch (Exception $ex) {}\n }\n w3_admin_redirect(array('w3tc_note' => 'enabled_edge'));\n }", "label_name": "CWE-352", "label": 0} {"code": " static function cronCheckUpdate($task) {\n\n $result = Toolbox::checkNewVersionAvailable(1);\n $task->log($result);\n\n return 1;\n }", "label_name": "CWE-352", "label": 0} {"code": " protected function __construct() {\n parent::__construct();\n self::$locale = fusion_get_locale('', LOCALE.LOCALESET.'search.php');\n }", "label_name": "CWE-352", "label": 0} {"code": " public static function recent($vars, $type = 'post') {\n $sql = \"SELECT * FROM `posts` WHERE `type` = '{$type}' ORDER BY `date` DESC LIMIT {$vars}\";\n $posts = Db::result($sql);\n if(isset($posts['error'])){\n $posts['error'] = \"No Posts found.\";\n }else{\n $posts = $posts;\n }\n return $posts;\n }", "label_name": "CWE-352", "label": 0} {"code": " public static function getId($id=''){\n if(isset($id)){\n $sql = sprintf(\"SELECT * FROM `menus` WHERE `id` = '%d' ORDER BY `order` ASC\", $id);\n $menus = Db::result($sql);\n $n = Db::$num_rows;\n }else{\n $menus = '';\n }\n \n return $menus;\n }", "label_name": "CWE-352", "label": 0} {"code": " public function archive(){\n $login_user = $this->checkLogin();\n\n $item_id = I(\"item_id/d\");\n $password = I(\"password\");\n\n $item = D(\"Item\")->where(\"item_id = '$item_id' \")->find();\n\n if(!$this->checkItemManage($login_user['uid'] , $item['item_id'])){\n $this->sendError(10303);\n return ;\n }\n\n if(! D(\"User\")-> checkLogin($item['username'],$password)){\n $this->sendError(10208);\n return ;\n }\n\n $return = D(\"Item\")->where(\"item_id = '$item_id' \")->save(array(\"is_archived\"=>1));\n\n if (!$return) {\n $this->sendError(10101);\n }else{\n $this->sendResult($return);\n }\n\n \n }", "label_name": "CWE-352", "label": 0} {"code": " static function canView() {\n return Session::haveRight(self::$rightname, READ);\n }", "label_name": "CWE-352", "label": 0} {"code": "\tpublic static function RemoveTransaction($id)\n\t{\n\t\t$sFilepath = APPROOT.'data/transactions/'.$id;\n\t\tclearstatcache(true, $sFilepath);\n\t\tif (!file_exists($sFilepath)) {\n\t\t\t$bSuccess = false;\n\t\t\tself::Error(\"RemoveTransaction: Transaction '$id' not found. Pending transactions for this user:\\n\"\n\t\t\t\t.implode(\"\\n\", self::GetPendingTransactions()));\n\t\t} else {\n\t\t\t$bSuccess = @unlink($sFilepath);\n\t\t}\n\n\t\tif (!$bSuccess) {\n\t\t\tself::Error('RemoveTransaction: FAILED to remove transaction '.$id);\n\t\t} else {\n\t\t\tself::Info('RemoveTransaction: OK '.$id);\n\t\t}\n\n\t\treturn $bSuccess;\n\t}", "label_name": "CWE-352", "label": 0} {"code": " public function startup(Event $event)\n {\n $controller = $event->subject();\n $request = $controller->request;\n $response = $controller->response;\n $cookieName = $this->_config['cookieName'];\n\n $cookieData = $request->cookie($cookieName);\n if ($cookieData) {\n $request->params['_csrfToken'] = $cookieData;\n }\n\n if ($request->is('requested')) {\n return;\n }\n\n if ($request->is('get') && $cookieData === null) {\n $this->_setCookie($request, $response);\n }\n if ($request->is(['patch', 'put', 'post', 'delete'])) {\n $this->_validateToken($request);\n unset($request->data[$this->_config['field']]);\n }\n }", "label_name": "CWE-352", "label": 0} {"code": " public function testPinCommentAction()\n {\n $client = $this->getClientForAuthenticatedUser(User::ROLE_ADMIN);\n $this->assertAccessIsGranted($client, '/admin/customer/1/details');\n $form = $client->getCrawler()->filter('form[name=customer_comment_form]')->form();\n $client->submit($form, [\n 'customer_comment_form' => [\n 'message' => 'Blah foo bar',\n ]\n ]);\n $this->assertIsRedirect($client, $this->createUrl('/admin/customer/1/details'));\n $client->followRedirect();\n $node = $client->getCrawler()->filter('div.box#comments_box .direct-chat-text');\n self::assertStringContainsString('Blah foo bar', $node->html());\n $node = $client->getCrawler()->filter('div.box#comments_box .direct-chat-text a.btn.active');\n self::assertEquals(0, $node->count());\n\n $comments = $this->getEntityManager()->getRepository(CustomerComment::class)->findAll();\n $id = $comments[0]->getId();\n\n $this->request($client, '/admin/customer/' . $id . '/comment_pin');\n $this->assertIsRedirect($client, $this->createUrl('/admin/customer/1/details'));\n $client->followRedirect();\n $node = $client->getCrawler()->filter('div.box#comments_box .box-body a.btn.active');\n self::assertEquals(1, $node->count());\n self::assertEquals($this->createUrl('/admin/customer/' . $id . '/comment_pin'), $node->attr('href'));\n }", "label_name": "CWE-352", "label": 0} {"code": " public function delete(){\n $login_user = $this->checkLogin();\n $uid = $login_user['uid'] ;\n\n $id = I(\"id/d\")? I(\"id/d\") : 0;\n $teamItemInfo = D(\"TeamItem\")->where(\" id = '$id' \")->find();\n $item_id = $teamItemInfo['item_id'] ;\n $team_id = $teamItemInfo['team_id'] ;\n\n if(!$this->checkItemManage($uid , $item_id)){\n $this->sendError(10303);\n return ;\n }\n\n $ret = D(\"TeamItemMember\")->where(\" item_id = '$item_id' and team_id = '$team_id' \")->delete();\n $ret = D(\"TeamItem\")->where(\" id = '$id' \")->delete();\n\n if ($ret) {\n $this->sendResult($ret);\n }else{\n $return['error_code'] = 10103 ;\n $return['error_message'] = 'request fail' ;\n $this->sendResult($return);\n }\n }", "label_name": "CWE-352", "label": 0} {"code": " public function deleteUser(){\n $login_user = $this->checkLogin();\n $this->checkAdmin();\n $uid = I(\"uid/d\");\n\n if (D(\"Item\")->where(\"uid = '$uid' and is_del = 0 \")->find()) {\n $this->sendError(10101,\"\u8be5\u7528\u6237\u540d\u4e0b\u8fd8\u6709\u9879\u76ee\uff0c\u4e0d\u5141\u8bb8\u5220\u9664\u3002\u8bf7\u5148\u5c06\u5176\u9879\u76ee\u5220\u9664\u6216\u8005\u91cd\u65b0\u5206\u914d/\u8f6c\u8ba9\"); \n return ;\n }\n $return = D(\"User\")->delete_user($uid);\n if (!$return) {\n $this->sendError(10101);\n }else{\n $this->sendResult($return);\n }\n }", "label_name": "CWE-352", "label": 0} {"code": " foreach ($indexesOld as $index) {\n if (\\in_array('name', $index->getColumns()) || \\in_array('mail', $index->getColumns())) {\n $this->indexesOld[] = $index;\n $this->addSql('DROP INDEX ' . $index->getName() . ' ON ' . $users);\n }\n }", "label_name": "CWE-352", "label": 0} {"code": " $debug_info .= sprintf(\"%s%s\\r\\n\", str_pad($header_name . ': ', 20), w3_escape_comment($header_value));\n }\n }", "label_name": "CWE-352", "label": 0} {"code": "function append_token_to_url()\n{\n\treturn '/&token_submit=' . $_SESSION['Token'];\n}", "label_name": "CWE-352", "label": 0} {"code": " public function delete($id) {\n $this->auth->checkIfOperationIsAllowed('delete_user');\n //Test if user exists\n $data['users_item'] = $this->users_model->getUsers($id);\n if (empty($data['users_item'])) {\n redirect('notfound');\n } else {\n $this->users_model->deleteUser($id);\n }\n log_message('error', 'User #' . $id . ' has been deleted by user #' . $this->session->userdata('id'));\n $this->session->set_flashdata('msg', lang('users_delete_flash_msg_success'));\n redirect('users');\n }", "label_name": "CWE-352", "label": 0} {"code": " public function __construct()\n {\n parent::__construct();\n\n $this->middleware(\n function ($request, $next) {\n app('view')->share('title', (string) trans('firefly.currencies'));\n app('view')->share('mainTitleIcon', 'fa-usd');\n $this->repository = app(CurrencyRepositoryInterface::class);\n $this->userRepository = app(UserRepositoryInterface::class);\n\n return $next($request);\n }\n );\n }", "label_name": "CWE-352", "label": 0} {"code": "\tfunction execute( $par ) {\t\t\n\t\t$request = $this->getRequest();\n\t\t$output = $this->getOutput();\n\t\t$language = $this->getLanguage();\n\t\t\n\t\t$output->setPageTitle( $this->msg( \"confirmaccounts\" )->escaped() );\n\t\t\n\t\t$output->addModules('ext.scratchConfirmAccount.js');\n\t\t$output->addModuleStyles('ext.scratchConfirmAccount.css');\n\t\t\n\t\t$session = $request->getSession();\n\t\t\n\t\t$this->setHeaders();\n\t\t$this->checkReadOnly();\n\n\t\t$this->showTopLinks();\n\n\t\t//check permissions\n\t\t$user = $this->getUser();\n\n\t\tif (!$user->isAllowed('createaccount')) {\n\t\t\tthrow new PermissionsError('createaccount');\n\t\t}\n\n\t\tif ($request->wasPosted()) {\n\t\t\treturn $this->handleFormSubmission($request, $output, $session);\n\t\t} else if (strpos($par, wfMessage('scratch-confirmaccount-blocks')->text()) === 0) {\n\t\t\treturn $this->blocksPage($par, $request, $output, $session);\n\t\t} else if (strpos($par, wfMessage('scratch-confirmaccount-requirements-bypasses-url')->text()) === 0) {\n\t\t\t$bypassPage = new RequirementsBypassPage($this);\n\t\t\treturn $bypassPage->render();\n\t\t} else if ($request->getText('username')) {\n\t\t\treturn $this->searchByUsername($request->getText('username'), $request, $output);\n\t\t} else if (isset(statuses[$par])) {\n\t\t\treturn $this->listRequestsByStatus($par, $output);\n\t\t} else if (ctype_digit($par)) {\n\t\t\treturn requestPage($par, 'admin', $this, $request->getSession());\n\t\t} else if (empty($par)) {\n\t\t\treturn $this->defaultPage($output);\n\t\t} else {\n\t\t\t$output->showErrorPage('error', 'scratch-confirmaccount-nosuchrequest');\n\t\t}\n\t}", "label_name": "CWE-352", "label": 0} {"code": " public static function get_param($key = NULL) {\n $info = [\n 'stype' => self::$search_type,\n 'stext' => self::$search_text,\n 'method' => self::$search_method,\n 'datelimit' => self::$search_date_limit,\n 'fields' => self::$search_fields,\n 'sort' => self::$search_sort,\n 'chars' => self::$search_chars,\n 'order' => self::$search_order,\n 'forum_id' => self::$forum_id,\n 'memory_limit' => self::$memory_limit,\n 'composevars' => self::$composevars,\n 'rowstart' => self::$rowstart,\n 'search_param' => self::$search_param,\n ];\n\n return $key === NULL ? $info : (isset($info[$key]) ? $info[$key] : NULL);\n }", "label_name": "CWE-352", "label": 0} {"code": " public function disable($id) {\n $this->active($id, FALSE);\n }", "label_name": "CWE-352", "label": 0} {"code": "\t\techo '';\n}", "label_name": "CWE-352", "label": 0} {"code": " public function updateInfo(){\n $user = $this->checkLogin();\n $uid = $user['uid'];\n $name = I(\"name\");\n\n D(\"User\")->where(\" uid = '$uid' \")->save(array(\"name\"=>$name));\n $this->sendResult(array());\n\n }", "label_name": "CWE-352", "label": 0} {"code": " public function delete(){\n $page_id = I(\"page_id/d\")? I(\"page_id/d\") : 0;\n $page = D(\"Page\")->where(\" page_id = '$page_id' \")->find();\n\n $login_user = $this->checkLogin();\n if (!$this->checkItemManage($login_user['uid'] , $page['item_id']) && $login_user['uid'] != $page['author_uid']) {\n $this->sendError(10303);\n return ;\n }\n\n if ($page) {\n \n $ret = D(\"Page\")->softDeletePage($page_id);\n //\u66f4\u65b0\u9879\u76ee\u65f6\u95f4\n D(\"Item\")->where(\" item_id = '$page[item_id]' \")->save(array(\"last_update_time\"=>time()));\n\n }\n if ($ret) {\n $this->sendResult(array());\n }else{\n $this->sendError(10101);\n }\n }", "label_name": "CWE-352", "label": 0} {"code": " public static function getParent($parent='', $menuid = ''){\n if(isset($menuid)){\n $where = \" AND `menuid` = '{$menuid}'\";\n }else{\n $where = '';\n }\n $sql = sprintf(\"SELECT * FROM `menus` WHERE `parent` = '%s' %s\", $parent, $where);\n $menu = Db::result($sql);\n return $menu;\n }", "label_name": "CWE-352", "label": 0} {"code": " public static function secureCompare($known, $user)\n {\n if (function_exists('hash_equals')) {\n // use hash_equals() if available (PHP >= 5.6)\n return hash_equals($known, $user);\n }\n\n // compare manually in constant time\n $len = mb_strlen($known, '8bit'); // see mbstring.func_overload\n if ($len !== mb_strlen($user, '8bit')) {\n return false; // length differs\n }\n $diff = 0;\n for ($i = 0; $i < $len; ++$i) {\n $diff |= $known[$i] ^ $user[$i];\n }\n // if all the bytes in $a and $b are identical, $diff should be equal to 0\n return $diff === 0;\n }", "label_name": "CWE-384", "label": 1} {"code": " public function resetKey(){\n\n $login_user = $this->checkLogin();\n\n $item_id = I(\"item_id/d\");\n\n $item = D(\"Item\")->where(\"item_id = '$item_id' \")->find();\n\n if(!$this->checkItemManage($login_user['uid'] , $item['item_id'])){\n $this->sendError(10303);\n return ;\n }\n\n $ret = D(\"ItemToken\")->where(\"item_id = '$item_id' \")->delete();\n\n if ($ret) {\n $this->getKey();\n }else{\n $this->sendError(10101);\n }\n }", "label_name": "CWE-352", "label": 0} {"code": " function load() {\n w3_require_once(W3TC_INC_FUNCTIONS_DIR . '/admin.php');\n $this->_page = w3tc_get_current_page();\n\n /**\n * Run plugin action\n */\n $action = false;\n\n foreach ($_REQUEST as $key => $value) {\n if (strpos($key, 'w3tc_') === 0) {\n $action = 'action_' . substr($key, 5);\n break;\n }\n }\n $flush = false;\n $cdn = false;\n $support = false;\n $action_handler = w3_instance('W3_AdminActions_ActionHandler');\n $action_handler->set_default($this);\n $action_handler->set_current_page($this->_page);\n if ($action && $action_handler->exists($action)) {\n if (strpos($action, 'view') !== false)\n if (!wp_verify_nonce(W3_Request::get_string('_wpnonce'), 'w3tc'))\n wp_nonce_ays('w3tc');\n else\n check_admin_referer('w3tc');\n\n try {\n $action_handler->execute($action);\n } catch (Exception $e) {\n w3_admin_redirect_with_custom_messages(array(), array($e->getMessage()));\n }\n\n exit();\n }\n }", "label_name": "CWE-352", "label": 0} {"code": " public function duplicateTeam(Team $team, Request $request)\n {\n $newTeam = clone $team;\n $newTeam->setName($team->getName() . ' [COPY]');\n\n try {\n $this->repository->saveTeam($newTeam);\n $this->flashSuccess('action.update.success');\n\n return $this->redirectToRoute('admin_team_edit', ['id' => $newTeam->getId()]);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n\n return $this->redirectToRoute('admin_team');\n }", "label_name": "CWE-352", "label": 0} {"code": "function csrf_start()\n{\n if ($GLOBALS['csrf']['auto-session'] && session_status() == PHP_SESSION_NONE) {\n session_start();\n }\n}", "label_name": "CWE-352", "label": 0} {"code": "function yourls_create_nonce( $action, $user = false ) {\n\tif( false == $user )\n\t\t$user = defined( 'YOURLS_USER' ) ? YOURLS_USER : '-1';\n\t$tick = yourls_tick();\n\t$nonce = substr( yourls_salt($tick . $action . $user), 0, 10 );\n\t// Allow plugins to alter the nonce\n\treturn yourls_apply_filter( 'create_nonce', $nonce, $action, $user );\n}", "label_name": "CWE-352", "label": 0} {"code": " public function deleteCommentAction(CustomerComment $comment)\n {\n $customerId = $comment->getCustomer()->getId();\n\n try {\n $this->repository->deleteComment($comment);\n } catch (\\Exception $ex) {\n $this->flashDeleteException($ex);\n }\n\n return $this->redirectToRoute('customer_details', ['id' => $customerId]);\n }", "label_name": "CWE-352", "label": 0} {"code": " public function edit(Request $request, TransactionCurrency $currency)\n {\n /** @var User $user */\n $user = auth()->user();\n if (!$this->userRepository->hasRole($user, 'owner')) {\n\n $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))]));\n Log::channel('audit')->info(sprintf('Tried to edit currency %s but is not owner.', $currency->code));\n\n return redirect(route('currencies.index'));\n\n }\n\n $subTitleIcon = 'fa-pencil';\n $subTitle = (string) trans('breadcrumbs.edit_currency', ['name' => $currency->name]);\n $currency->symbol = htmlentities($currency->symbol);\n\n // code to handle active-checkboxes\n $hasOldInput = null !== $request->old('_token');\n $preFilled = [\n 'enabled' => $hasOldInput ? (bool) $request->old('enabled') : $currency->enabled,\n ];\n\n $request->session()->flash('preFilled', $preFilled);\n Log::channel('audit')->info('Edit currency.', $currency->toArray());\n\n // put previous url in session if not redirect from store (not \"return_to_edit\").\n if (true !== session('currencies.edit.fromUpdate')) {\n $this->rememberPreviousUri('currencies.edit.uri');\n }\n $request->session()->forget('currencies.edit.fromUpdate');\n\n return prefixView('currencies.edit', compact('currency', 'subTitle', 'subTitleIcon'));\n }", "label_name": "CWE-352", "label": 0} {"code": " public function active($id, $active) {\n $this->auth->checkIfOperationIsAllowed('list_users');\n $this->users_model->setActive($id, $active);\n $this->session->set_flashdata('msg', lang('users_edit_flash_msg_success'));\n redirect('users');\n }", "label_name": "CWE-352", "label": 0} {"code": " static function getTypeName($nb = 0) {\n return __('Maintenance');\n }", "label_name": "CWE-352", "label": 0} {"code": " public static function post($vars) {\n switch (SMART_URL) {\n case true:\n # code...\n $url = Options::get('siteurl').\"/\".self::slug($vars).\"/{$vars}\";\n break;\n \n default:\n # code...\n $url = Options::get('siteurl').\"/index.php?post={$vars}\";\n break;\n\n }\n\n return $url;\n }", "label_name": "CWE-352", "label": 0} {"code": " public function __construct(UserInviteService $inviteService, LoginService $loginService, UserRepo $userRepo)\n {\n $this->middleware('guest');\n $this->middleware('guard:standard');\n\n $this->inviteService = $inviteService;\n $this->loginService = $loginService;\n $this->userRepo = $userRepo;\n }", "label_name": "CWE-352", "label": 0} {"code": "function OA_runMPE()\n{\n $objResponse = new xajaxResponse();\n $objResponse->addAssign(\"run-mpe\", \"innerHTML\", \"\");\n return $objResponse;\n}", "label_name": "CWE-352", "label": 0} {"code": " private function mailPassthru($to, $subject, $body, $header, $params)\n {\n //Check overloading of mail function to avoid double-encoding\n if (ini_get('mbstring.func_overload') & 1) {\n $subject = $this->secureHeader($subject);\n } else {\n $subject = $this->encodeHeader($this->secureHeader($subject));\n }\n if (ini_get('safe_mode') || !($this->UseSendmailOptions)) {\n $result = @mail($to, $subject, $body, $header);\n } else {\n $result = @mail($to, $subject, $body, $header, $params);\n }\n return $result;\n }", "label_name": "CWE-352", "label": 0} {"code": " public function addAddress($address, $name = '')\n {\n return $this->addAnAddress('to', $address, $name);\n }", "label_name": "CWE-352", "label": 0} {"code": " public function __construct () {\n if (self::existConf()) {\n # code...\n self::config('config');\n self::lang(GX_LANG);\n }else{\n GxMain::install();\n }\n \n }", "label_name": "CWE-352", "label": 0} {"code": " public function attorn(){\n $login_user = $this->checkLogin();\n $this->checkAdmin();\n $username = I(\"username\");\n $item_id = I(\"item_id/d\");\n\n $item = D(\"Item\")->where(\"item_id = '$item_id' \")->find();\n\n\n $member = D(\"User\")->where(\" username = '%s' \",array($username))->find();\n\n if (!$member) {\n $this->sendError(10209);\n return ;\n }\n\n $data['username'] = $member['username'] ;\n $data['uid'] = $member['uid'] ;\n \n\n $id = D(\"Item\")->where(\" item_id = '$item_id' \")->save($data);\n\n $return = D(\"Item\")->where(\"item_id = '$item_id' \")->find();\n\n if (!$return) {\n $this->sendError(10101);\n return ;\n }\n\n $this->sendResult($return);\n }", "label_name": "CWE-352", "label": 0} {"code": "\tpublic function validateRequest(App\\Request $request)\n\t{\n\t\t$request->validateReadAccess();\n\t}", "label_name": "CWE-352", "label": 0} {"code": " public function __construct($exceptions = false)\n {\n $this->exceptions = ($exceptions == true);\n }", "label_name": "CWE-352", "label": 0} {"code": " public function batUpdate(){\n $cats = I(\"cats\");\n $item_id = I(\"item_id/d\");\n $login_user = $this->checkLogin();\n if (!$this->checkItemEdit($login_user['uid'] , $item_id)) {\n $this->sendError(10103);\n return ;\n }\n $ret = '';\n $data_array = json_decode(htmlspecialchars_decode($cats) , true) ;\n if ($data_array) {\n foreach ($data_array as $key => $value) {\n if ($value['cat_name']) {\n $ret = D(\"Catalog\")->where(\" cat_id = '%d' and item_id = '%d' \",array($value['cat_id'],$item_id) )->save(array(\n \"cat_name\" => $value['cat_name'] ,\n \"parent_cat_id\" => $value['parent_cat_id'] ,\n \"level\" => $value['level'] ,\n \"s_number\" => $value['s_number'] ,\n ));\n }\n if ($value['page_id'] > 0) {\n $ret = D(\"Page\")->where(\" page_id = '%d' and item_id = '%d' \" ,array($value['page_id'],$item_id) )->save(array(\n \"cat_id\" => $value['parent_cat_id'] ,\n \"s_number\" => $value['s_number'] ,\n ));\n }\n\n }\n }\n\n $this->sendResult(array());\n }", "label_name": "CWE-352", "label": 0} {"code": " public static function get_param($key = NULL) {\n $info = [\n 'stype' => htmlentities(self::$search_type),\n 'stext' => htmlentities(self::$search_text),\n 'method' => htmlentities(self::$search_method),\n 'datelimit' => self::$search_date_limit,\n 'fields' => self::$search_fields,\n 'sort' => self::$search_sort,\n 'chars' => htmlentities(self::$search_chars),\n 'order' => self::$search_order,\n 'forum_id' => self::$forum_id,\n 'memory_limit' => self::$memory_limit,\n 'composevars' => self::$composevars,\n 'rowstart' => self::$rowstart,\n 'search_param' => self::$search_param,\n ];\n\n return $key === NULL ? $info : (isset($info[$key]) ? $info[$key] : NULL);\n }", "label_name": "CWE-352", "label": 0} {"code": " public function duplicateAction(Project $project, Request $request, ProjectDuplicationService $projectDuplicationService)\n {\n $newProject = $projectDuplicationService->duplicate($project, $project->getName() . ' [COPY]');\n\n return $this->redirectToRoute('project_details', ['id' => $newProject->getId()]);\n }", "label_name": "CWE-352", "label": 0} {"code": " public function addBCC($address, $name = '')\n {\n return $this->addAnAddress('bcc', $address, $name);\n }", "label_name": "CWE-352", "label": 0} {"code": " click: function(p,o) {\n p.on(o.event, o.children, function(e){\n if(f.detect.leftMouse(e)) {\n if ($(e.target).hasClass('ch-toggle') ||\n $(e.target).hasClass('check-label') ||\n ( $(e.target).hasClass('l-unit-toolbar__col--left')) ) {\n\n var c = f.get.clicks(p,o,$(this));\n \n var ref = $(e.target);\n if (ref.parents('.l-unit').hasClass('selected') && $('.l-unit.selected').length == 1) {\n ref.parents('.l-unit').find('.ch-toggle').attr('checked', false);\n ref.parents('.l-unit').removeClass('selected');\n ref.parents('.l-unit').removeClass('selected-current');\n $('.toggle-all').removeClass('clicked-on');\n return;\n }\n\n if (!(f.detect.ctrl(e) && o.enableCtrlClick) && (f.detect.shift(e) && o.enableShiftClick)) {\n f.t.deleteSelection(o);\n f.t.shiftClick(p,c,o);\n }\n\n if (((f.detect.ctrl(e) && o.enableCtrlClick) || (f.detect.touch() && o.enableTouchCtrlDefault) || o.enableDesktopCtrlDefault) && !(f.detect.shift(e) && o.enableShiftClick)) {\n f.t.toggleClick(p,c,o);\n }\n\n if (!(f.detect.ctrl(e) && o.enableCtrlClick) && !(f.detect.shift(e) && o.enableShiftClick) && o.enableSingleClick && !o.enableDesktopCtrlDefault) {\n f.t.singleClick(p,c,o);\n }\n }\n }\n\n o.onFinish(e);\n });\n },", "label_name": "CWE-352", "label": 0} {"code": " $scope.reset = function() {\n bootbox.confirm('Are you sure you want to reset the foreign source definition to the default ?', function(ok) {\n if (ok) {\n RequisitionsService.startTiming();\n RequisitionsService.deleteForeignSourceDefinition($scope.foreignSource).then(\n function() { // success\n growl.success('The foreign source definition for ' + $scope.foreignSource + 'has been reseted.');\n $scope.initialize();\n },\n $scope.errorHandler\n );\n }\n });\n };", "label_name": "CWE-352", "label": 0} {"code": "\twp.updates.requestFilesystemCredentials = function( event ) {\n\t\tif ( wp.updates.updateDoneSuccessfully === false ) {\n\t\t\t/*\n\t\t\t * For the plugin install screen, return the focus to the install button\n\t\t\t * after exiting the credentials request modal.\n\t\t\t */\n\t\t\tif ( 'plugin-install' === pagenow && event ) {\n\t\t\t\twp.updates.$elToReturnFocusToFromCredentialsModal = $( event.target );\n\t\t\t}\n\n\t\t\twp.updates.updateLock = true;\n\n\t\t\twp.updates.requestForCredentialsModalOpen();\n\t\t}\n\t};", "label_name": "CWE-352", "label": 0} {"code": "function set_utilization(type, entity_id, name, value) {\n var data = {\n name: name,\n value: value\n };\n if (type == \"node\") {\n data[\"node\"] = entity_id;\n } else if (type == \"resource\") {\n data[\"resource_id\"] = entity_id;\n } else return false;\n var url = get_cluster_remote_url() + \"set_\" + type + \"_utilization\";\n\n $.ajax({\n type: 'POST',\n url: url,\n data: data,\n timeout: pcs_timeout,\n error: function (xhr, status, error) {\n alert(\n \"Unable to set utilization: \"\n + ajax_simple_error(xhr, status, error)\n );\n },\n complete: function() {\n Pcs.update();\n }\n });\n}", "label_name": "CWE-384", "label": 1} {"code": "function genericAjaxPopupDestroy($layer) {\n\t$popup = genericAjaxPopupFetch($layer);\n\tif(null != $popup) {\n\t\tgenericAjaxPopupClose($layer);\n\t\ttry {\n\t\t\t$popup.dialog('destroy');\n\t\t\t$popup.unbind();\n\t\t} catch(e) { }\n\t\t$($('#devblocksPopups').data($layer)).remove(); // remove DOM\n\t\t$('#devblocksPopups').removeData($layer); // remove from registry\n\t\treturn true;\n\t}\n\treturn false;\n}", "label_name": "CWE-352", "label": 0} {"code": " $scope.provision = function() {\n $scope.isSaving = true;\n growl.info($sanitize('The node ' + $scope.node.nodeLabel + ' is being added to requisition ' + $scope.node.foreignSource + '. Please wait...'));\n var successMessage = $sanitize('The node ' + $scope.node.nodeLabel + ' has been added to requisition ' + $scope.node.foreignSource);\n RequisitionsService.quickAddNode($scope.node).then(\n function() { // success\n $scope.reset();\n bootbox.dialog({\n message: successMessage,\n title: 'Success',\n buttons: {\n main: {\n label: 'Ok',\n className: 'btn-secondary'\n }\n }\n });\n },\n $scope.errorHandler\n );\n };", "label_name": "CWE-352", "label": 0} {"code": "\t\t\t\t\tplugin: $( this ).data( 'plugin' ),\n\t\t\t\t\tslug: $( this ).data( 'slug' )\n\t\t\t\t}\n\t\t\t};\n\n\t\t\ttarget.postMessage( JSON.stringify( job ), window.location.origin );\n\t\t});\n\n\t} );\n\n\t$( window ).on( 'message', function( e ) {\n\t\tvar event = e.originalEvent,\n\t\t\tmessage,\n\t\t\tloc = document.location,\n\t\t\texpectedOrigin = loc.protocol + '//' + loc.hostname;\n\n\t\tif ( event.origin !== expectedOrigin ) {\n\t\t\treturn;\n\t\t}\n\n\t\tmessage = $.parseJSON( event.data );\n\n\t\tif ( typeof message.action === 'undefined' ) {\n\t\t\treturn;\n\t\t}\n\n\t\tswitch (message.action){\n\t\t\tcase 'decrementUpdateCount' :\n\t\t\t\twp.updates.decrementCount( message.upgradeType );\n\t\t\t\tbreak;\n\t\t\tcase 'updatePlugin' :\n\t\t\t\ttb_remove();\n\n\t\t\t\twp.updates.updateQueue.push( message );\n\t\t\t\twp.updates.queueChecker();\n\t\t\t\tbreak;\n\t\t}\n\n\t} );\n\n\t$( window ).on( 'beforeunload', wp.updates.beforeunload );\n\n})( jQuery, window.wp, window.pagenow, window.ajaxurl );", "label_name": "CWE-352", "label": 0} {"code": "\trender: function() {\n\t\tvar data = this.model.toJSON();\n\t\t// Render themes using the html template\n\t\tthis.$el.html( this.html( data ) ).attr({\n\t\t\ttabindex: 0,\n\t\t\t'aria-describedby' : data.id + '-action ' + data.id + '-name'\n\t\t});\n\n\t\t// Renders active theme styles\n\t\tthis.activeTheme();\n\n\t\tif ( this.model.get( 'displayAuthor' ) ) {\n\t\t\tthis.$el.addClass( 'display-author' );\n\t\t}\n\n\t\tif ( this.model.get( 'installed' ) ) {\n\t\t\tthis.$el.addClass( 'is-installed' );\n\t\t}\n\t},", "label_name": "CWE-352", "label": 0} {"code": "function remove_cluster(ids) {\n var data = {};\n $.each(ids, function(_, cluster) {\n data[ \"clusterid-\" + cluster] = true;\n });\n $.ajax({\n type: 'POST',\n url: '/manage/removecluster',\n data: data,\n timeout: pcs_timeout,\n success: function () {\n $(\"#dialog_verify_remove_clusters.ui-dialog-content\").each(function(key, item) {$(item).dialog(\"destroy\")});\n Pcs.update();\n },\n error: function (xhr, status, error) {\n alert(\"Unable to remove cluster: \" + res + \" (\"+error+\")\");\n $(\"#dialog_verify_remove_clusters.ui-dialog-content\").each(function(key, item) {$(item).dialog(\"destroy\")});\n }\n });\n}", "label_name": "CWE-384", "label": 1} {"code": " $scope.deleteNode = function(node) {\n bootbox.confirm('Are you sure you want to remove the node ' + node.nodeLabel + '?', function(ok) {\n if (ok) {\n RequisitionsService.startTiming();\n RequisitionsService.deleteNode(node).then(\n function() { // success\n var index = -1;\n for(var i = 0; i < $scope.filteredNodes.length; i++) {\n if ($scope.filteredNodes[i].foreignId === node.foreignId) {\n index = i;\n }\n }\n if (index > -1) {\n $scope.filteredNodes.splice(index,1);\n }\n growl.success('The node ' + node.nodeLabel + ' has been deleted.');\n },\n $scope.errorHandler\n );\n }\n });\n };", "label_name": "CWE-352", "label": 0} {"code": "\t\t\t\tform.append($('', { name: i, value: JSON.stringify(postData[i]) }));\n\t\t\t}\n\t\t\t$('body').append(form);\n\t\t\tform.submit();\n\t\t} else {\n\t\t\twindow.location.href = url;\n\t\t}\n\t},", "label_name": "CWE-352", "label": 0} {"code": "\twp.updates.showErrorInCredentialsForm = function( message ) {\n\t\tvar $modal = $( '.notification-dialog' );\n\n\t\t// Remove any existing error.\n\t\t$modal.find( '.error' ).remove();\n\n\t\t$modal.find( 'h3' ).after( '
    ' + message + '
    ' );\n\t};", "label_name": "CWE-352", "label": 0} {"code": " $scope.initialize = function(customHandler) {\n var value = $cookies.get('requisitions_page_size');\n if (value) {\n $scope.pageSize = value;\n }\n growl.success('Retrieving requisition ' + $scope.foreignSource + '...');\n RequisitionsService.getRequisition($scope.foreignSource).then(\n function(requisition) { // success\n $scope.requisition = requisition;\n $scope.filteredNodes = requisition.nodes;\n $scope.updateFilteredNodes();\n if (customHandler) {\n customHandler();\n }\n },\n $scope.errorHandler\n );\n };", "label_name": "CWE-352", "label": 0} {"code": " $scope.refresh = function() {\n growl.success('Retrieving node ' + $scope.foreignId + ' from requisition ' + $scope.foreignSource + '...');\n RequisitionsService.getNode($scope.foreignSource, $scope.foreignId).then(\n function(node) { // success\n $scope.node = node;\n },\n $scope.errorHandler\n );\n };", "label_name": "CWE-352", "label": 0} {"code": " this.goto_url('export', { _source: this.env.source, _gid: this.env.group, _cid: this.contact_list.get_selection().join(',') });\n }\n break;\n\n case 'upload-photo':\n this.upload_contact_photo(props || this.gui_objects.uploadform);\n break;\n\n case 'delete-photo':\n this.replace_contact_photo('-del-');\n break;\n\n // user settings commands\n case 'preferences':\n case 'identities':\n case 'responses':\n case 'folders':\n this.goto_url('settings/' + command);\n break;\n\n case 'undo':\n this.http_request('undo', '', this.display_message('', 'loading'));\n break;\n\n // unified command call (command name == function name)\n default:\n var func = command.replace(/-/g, '_');\n if (this[func] && typeof this[func] === 'function') {\n ret = this[func](props, obj, event);\n }\n break;\n }\n\n if (!aborted && this.triggerEvent('after'+command, props) === false)\n ret = false;\n this.triggerEvent('actionafter', { props:props, action:command, aborted:aborted });\n\n return ret === false ? false : obj ? false : true;\n };", "label_name": "CWE-352", "label": 0} {"code": "function genericAjaxPopupFind($sel) {\n\t$devblocksPopups = $('#devblocksPopups');\n\t$data = $devblocksPopups.data();\n\t$element = $($sel).closest('DIV.devblocks-popup');\n\tfor($key in $data) {\n\t\tif($element.attr('id') == $data[$key].attr('id'))\n\t\t\treturn $data[$key];\n\t}\n\t\n\treturn null;\n}", "label_name": "CWE-352", "label": 0} {"code": " $scope.removeAllNodes = function(foreignSource) {\n bootbox.confirm('Are you sure you want to remove all the nodes from ' + foreignSource + '?', function(ok) {\n if (ok) {\n RequisitionsService.startTiming();\n RequisitionsService.removeAllNodesFromRequisition(foreignSource).then(\n function() { // success\n growl.success('All the nodes from ' + foreignSource + ' have been removed, and the requisition has been synchronized.');\n var req = $scope.requisitionsData.getRequisition(foreignSource);\n req.reset();\n },\n $scope.errorHandler\n );\n }\n });\n };", "label_name": "CWE-352", "label": 0} {"code": " $scope.add = function() {\n bootbox.prompt('Please enter the name for the new requisition', function(foreignSource) {\n if (foreignSource) {\n // Validate Requisition\n if (foreignSource.match(/[/\\\\?:&*'\"]/)) {\n bootbox.alert('Cannot add the requisition ' + foreignSource + ' because the following characters are invalid:
    :, /, \\\\, ?, &, *, \\', \"');\n return;\n }\n var r = $scope.requisitionsData.getRequisition(foreignSource);\n if (r) {\n bootbox.alert('Cannot add the requisition ' + foreignSource+ ' because there is already a requisition with that name');\n return;\n }\n // Create Requisition\n RequisitionsService.addRequisition(foreignSource).then(\n function(r) { // success\n growl.success('The requisition ' + r.foreignSource + ' has been created.');\n },\n $scope.errorHandler\n );\n }\n });\n };", "label_name": "CWE-352", "label": 0} {"code": "function checkExistingNode() {\n var node = \"\";\n $('input[name=\"node-name\"]').each(function(i,e) {\n node = e.value;\n });\n\n $.ajax({\n type: 'GET',\n url: '/manage/check_pcsd_status',\n data: {\"nodes\": node},\n timeout: pcs_timeout,\n success: function (data) {\n mydata = jQuery.parseJSON(data);\n update_existing_cluster_dialog(mydata);\n\n },\n error: function (XMLHttpRequest, textStatus, errorThrown) {\n alert(\"ERROR: Unable to contact server\");\n }\n });\n}", "label_name": "CWE-384", "label": 1} {"code": " var doSynchronize = function(requisition, rescanExisting) {\n RequisitionsService.startTiming();\n RequisitionsService.synchronizeRequisition(requisition.foreignSource, rescanExisting).then(\n function() { // success\n growl.success('The import operation has been started for ' + requisition.foreignSource + ' (rescanExisting? ' + rescanExisting + ')
    Use refresh to update the deployed statistics');\n requisition.setDeployed(true);\n },\n errorHandler\n );\n };", "label_name": "CWE-352", "label": 0} {"code": "\texpand: function( id ) {\n\t\tvar self = this;\n\n\t\t// Set the current theme model\n\t\tthis.model = self.collection.get( id );\n\n\t\t// Trigger a route update for the current model\n\t\tthemes.router.navigate( themes.router.baseUrl( themes.router.themePath + this.model.id ) );\n\n\t\t// Sets this.view to 'detail'\n\t\tthis.setView( 'detail' );\n\t\t$( 'body' ).addClass( 'modal-open' );\n\n\t\t// Set up the theme details view\n\t\tthis.overlay = new themes.view.Details({\n\t\t\tmodel: self.model\n\t\t});\n\n\t\tthis.overlay.render();\n\t\tthis.$overlay.html( this.overlay.el );\n\n\t\t// Bind to theme:next and theme:previous\n\t\t// triggered by the arrow keys\n\t\t//\n\t\t// Keep track of the current model so we\n\t\t// can infer an index position\n\t\tthis.listenTo( this.overlay, 'theme:next', function() {\n\t\t\t// Renders the next theme on the overlay\n\t\t\tself.next( [ self.model.cid ] );\n\n\t\t})\n\t\t.listenTo( this.overlay, 'theme:previous', function() {\n\t\t\t// Renders the previous theme on the overlay\n\t\t\tself.previous( [ self.model.cid ] );\n\t\t});\n\t},", "label_name": "CWE-352", "label": 0} {"code": " link: function(scope, element, attrs) {\n\n var width = 120;\n var height = 39;\n\n var div = $('
    A
    ').css({\n position: 'absolute',\n left: -1000,\n top: -1000,\n display: 'block',\n padding: 0,\n margin: 0,\n 'font-family': 'monospace'\n }).appendTo($('body'));\n\n var charWidth = div.width();\n var charHeight = div.height();\n\n div.remove();\n\n // compensate for internal horizontal padding\n var cssWidth = width * charWidth + 20;\n // Add an extra line for the status bar and divider\n var cssHeight = (height * charHeight) + charHeight + 2;\n\n log.debug(\"desired console size in characters, width: \", width, \" height: \", height);\n log.debug(\"console size in pixels, width: \", cssWidth, \" height: \", cssHeight);\n log.debug(\"character size in pixels, width: \", charWidth, \" height: \", charHeight);\n\n element.css({\n width: cssWidth,\n height: cssHeight,\n 'min-width': cssWidth,\n 'min-height': cssHeight\n });\n\n var authHeader = Core.getBasicAuthHeader(userDetails.username, userDetails.password);\n\n gogo.Terminal(element.get(0), width, height, authHeader);\n\n scope.$on(\"$destroy\", function(e) {\n document.onkeypress = null;\n document.onkeydown = null;\n });\n\n }", "label_name": "CWE-352", "label": 0} {"code": " $scope.initialize = function() {\n growl.success('Retrieving definition for requisition ' + $scope.foreignSource + '...');\n RequisitionsService.getForeignSourceDefinition($scope.foreignSource).then(\n function(foreignSourceDef) { // success\n $scope.foreignSourceDef = foreignSourceDef;\n // Updating pagination variables for detectors.\n $scope.filteredDetectors = $scope.foreignSourceDef.detectors;\n $scope.updateFilteredDetectors();\n // Updating pagination variables for policies.\n $scope.filteredPolicies = $scope.foreignSourceDef.policies;\n $scope.updateFilteredPolicies();\n },\n $scope.errorHandler\n );\n };", "label_name": "CWE-352", "label": 0} {"code": "function updateActionButtons() {\n if (0 !== count) {\n $('.action-menu').show();\n\n // also update labels:\n $('.mass-edit span').text(edit_selected_txt + ' (' + count + ')');\n $('.bulk-edit span').text(edit_bulk_selected_txt + ' (' + count + ')');\n $('.mass-delete span').text(delete_selected_txt + ' (' + count + ')');\n\n }\n if (0 === count) {\n $('.action-menu').hide();\n }\n}", "label_name": "CWE-352", "label": 0} {"code": "\twp.updates.updateSuccess = function( response ) {\n\t\tvar $updateMessage, name, $pluginRow, newText;\n\t\tif ( 'plugins' === pagenow || 'plugins-network' === pagenow ) {\n\t\t\t$pluginRow = $( '[data-plugin=\"' + response.plugin + '\"]' ).first();\n\t\t\t$updateMessage = $pluginRow.next().find( '.update-message' );\n\t\t\t$pluginRow.addClass( 'updated' ).removeClass( 'update' );\n\n\t\t\t// Update the version number in the row.\n\t\t\tnewText = $pluginRow.find('.plugin-version-author-uri').html().replace( response.oldVersion, response.newVersion );\n\t\t\t$pluginRow.find('.plugin-version-author-uri').html( newText );\n\n\t\t\t// Add updated class to update message parent tr\n\t\t\t$pluginRow.next().addClass( 'updated' );\n\t\t} else if ( 'plugin-install' === pagenow ) {\n\t\t\t$updateMessage = $( '.plugin-card-' + response.slug ).find( '.update-now' );\n\t\t\t$updateMessage.addClass( 'button-disabled' );\n\t\t\tname = $updateMessage.data( 'name' );\n\t\t\t$updateMessage.attr( 'aria-label', wp.updates.l10n.updatedLabel.replace( '%s', name ) );\n\t\t}\n\n\t\t$updateMessage.removeClass( 'updating-message' ).addClass( 'updated-message' );\n\t\t$updateMessage.text( wp.updates.l10n.updated );\n\t\twp.a11y.speak( wp.updates.l10n.updatedMsg );\n\n\t\twp.updates.decrementCount( 'plugin' );\n\n\t\twp.updates.updateDoneSuccessfully = true;\n\n\t\t/*\n\t\t * The lock can be released since the update was successful,\n\t\t * and any other updates can commence.\n\t\t */\n\t\twp.updates.updateLock = false;\n\n\t\t$(document).trigger( 'wp-plugin-update-success', response );\n\n\t\twp.updates.queueChecker();\n\t};", "label_name": "CWE-352", "label": 0} {"code": " $scope.save = function() {\n var form = this.fsForm;\n RequisitionsService.startTiming();\n RequisitionsService.saveForeignSourceDefinition($scope.foreignSourceDef).then(\n function() { // success\n growl.success('The definition for the requisition ' + $scope.foreignSource + ' has been saved.');\n form.$dirty = false;\n },\n $scope.errorHandler\n );\n };", "label_name": "CWE-352", "label": 0} {"code": "function permissions_load_cluster(cluster_name, callback) {\n var element_id = \"permissions_cluster_\" + cluster_name;\n $.ajax({\n type: \"GET\",\n url: \"/permissions_cluster_form/\" + cluster_name,\n timeout: pcs_timeout,\n success: function(data) {\n $(\"#\" + element_id).html(data);\n $(\"#\" + element_id + \" :checkbox\").each(function(key, checkbox) {\n permissions_fix_dependent_checkboxes(checkbox);\n });\n permissions_cluster_dirty_flag(cluster_name, false);\n if (callback) {\n callback();\n }\n },\n error: function(xhr, status, error) {\n $(\"#\" + element_id).html(\n \"Error loading permissions \" + ajax_simple_error(xhr, status, error)\n );\n if (callback) {\n callback();\n }\n }\n });\n}", "label_name": "CWE-384", "label": 1} {"code": "\t\t\t\t\tslug: $( this ).data( 'slug' )\n\t\t\t\t}\n\t\t\t};\n\n\t\t\ttarget.postMessage( JSON.stringify( job ), window.location.origin );\n\t\t});", "label_name": "CWE-352", "label": 0} {"code": " this.goto_url = function(action, query, lock)\n {\n this.redirect(this.url(action, query), lock);\n };", "label_name": "CWE-352", "label": 0} {"code": "\twp.updates.requestForCredentialsModalOpen = function() {\n\t\tvar $modal = $( '#request-filesystem-credentials-dialog' );\n\t\t$( 'body' ).addClass( 'modal-open' );\n\t\t$modal.show();\n\n\t\t$modal.find( 'input:enabled:first' ).focus();\n\t\t$modal.keydown( wp.updates.keydown );\n\t};", "label_name": "CWE-352", "label": 0} {"code": " $scope.add = function() {\n bootbox.prompt('Please enter the name for the new requisition', function(foreignSource) {\n if (foreignSource) {\n // Validate Requisition\n if (foreignSource.match(/[/\\\\?:&*'\"]/)) {\n bootbox.alert('Cannot add the requisition ' + foreignSource + ' because the following characters are invalid:
    :, /, \\\\, ?, &, *, \\', \"');\n return;\n }\n var r = $scope.requisitionsData.getRequisition(foreignSource);\n if (r) {\n bootbox.alert('Cannot add the requisition ' + foreignSource+ ' because there is already a requisition with that name');\n return;\n }\n // Create Requisition\n RequisitionsService.addRequisition(foreignSource).then(\n function(r) { // success\n growl.success('The requisition ' + r.foreignSource + ' has been created.');\n },\n $scope.errorHandler\n );\n }\n });\n };", "label_name": "CWE-352", "label": 0} {"code": " url: getPath() + \"/shutdown\",\n data: {\"parameter\":2},\n success: function success(data) {\n $(\"#spinner2\").hide();\n $(\"#DialogContent\").html(data.text);\n $(\"#DialogFinished\").removeClass(\"hidden\");\n }\n });\n });", "label_name": "CWE-352", "label": 0} {"code": "\trequestForm: function (url, params = {}) {\n\t\tapp.openUrlMethodPost(url, params);\n\t}", "label_name": "CWE-352", "label": 0} {"code": "function updateTotalBudgetedAmount(currencyId) {\n // fade info away:\n $('span.budgeted_amount[data-currency=\"' + currencyId + '\"]')\n .fadeTo(100, 0.1, function () {\n //$(this).fadeTo(500, 1.0);\n });\n\n // get new amount:\n $.get(totalBudgetedUri.replace('REPLACEME',currencyId)).done(function (data) {\n // set thing:\n $('span.budgeted_amount[data-currency=\"' + currencyId + '\"]')\n .html(data.budgeted_formatted)\n // fade back:\n .fadeTo(300, 1.0);\n\n // set bar:\n var pct = parseFloat(data.percentage);\n if (pct <= 100) {\n console.log('<100 (' + pct + ')');\n console.log($('div.budgeted_bar[data-currency=\"' + currencyId + '\"]'));\n // red bar to 0\n $('div.budgeted_bar[data-currency=\"' + currencyId + '\"] div.progress-bar-danger').width('0%');\n // orange to 0:\n $('div.budgeted_bar[data-currency=\"' + currencyId + '\"] div.progress-bar-warning').width('0%');\n // blue to the rest:\n $('div.budgeted_bar[data-currency=\"' + currencyId + '\"] div.progress-bar-info').width(pct + '%');\n } else {\n var newPct = (100 / pct) * 100;\n // red bar to new pct\n $('div.budgeted_bar[data-currency=\"' + currencyId + '\"] div.progress-bar-danger').width(newPct + '%');\n // orange to the rest:\n $('div.budgeted_bar[data-currency=\"' + currencyId + '\"] div.progress-bar-warning').width((100 - newPct) + '%');\n // blue to 0:\n $('div.budgeted_bar[data-currency=\"' + currencyId + '\"] div.progress-bar-info').width('0%');\n }\n\n\n });\n}", "label_name": "CWE-352", "label": 0} {"code": " $scope.addRequisition = function() {\n bootbox.prompt('A requisition is required, please enter the name for a new requisition', function(foreignSource) {\n if (foreignSource) {\n RequisitionsService.addRequisition(foreignSource).then(\n function() { // success\n RequisitionsService.synchronizeRequisition(foreignSource, false).then(\n function() {\n growl.success('The requisition ' + foreignSource + ' has been created and synchronized.');\n $scope.foreignSources.push(foreignSource);\n },\n $scope.errorHandler\n );\n },\n $scope.errorHandler\n );\n } else {\n window.location.href = Util.getBaseHref() + 'admin/opennms/index.jsp'; // TODO Is this the best way ?\n }\n });\n };", "label_name": "CWE-352", "label": 0} {"code": "SessionManager.prototype.logIn = function(req, user, cb) {\n var self = this;\n this._serializeUser(user, req, function(err, obj) {\n if (err) {\n return cb(err);\n }\n // TODO: Error if session isn't available here.\n if (!req.session) {\n req.session = {};\n }\n if (!req.session[self._key]) {\n req.session[self._key] = {};\n }\n req.session[self._key].user = obj;\n cb();\n });\n}", "label_name": "CWE-384", "label": 1} {"code": "\t\t\t\t\tslug: $( this ).data( 'slug' )\n\t\t\t\t}\n\t\t\t};\n\n\t\t\ttarget.postMessage( JSON.stringify( job ), window.location.origin );\n\t\t});\n\n\t} );", "label_name": "CWE-352", "label": 0} {"code": " this.changeUserSettingsIndifferent = function(attr,value){\n \t$.get(this.wwwDir+ 'user/setsettingajax/'+attr+'/'+encodeURIComponent(value)+'/(indifferent)/true');\n };", "label_name": "CWE-352", "label": 0} {"code": " var doSynchronize = function(requisition, rescanExisting) {\n RequisitionsService.startTiming();\n RequisitionsService.synchronizeRequisition(requisition.foreignSource, rescanExisting).then(\n function() { // success\n growl.success('The import operation has been started for ' + requisition.foreignSource + ' (rescanExisting? ' + rescanExisting + ')
    Use refresh to update the deployed statistics');\n requisition.setDeployed(true);\n },\n errorHandler\n );\n };", "label_name": "CWE-352", "label": 0} {"code": "\tComments.init = function(params, callback) {\n\t\tvar app = params.router,\n\t\t\tmiddleware = params.middleware,\n\t\t\tcontrollers = params.controllers;\n\t\t\t\n\t\tfs.readFile(path.resolve(__dirname, './public/templates/comments/comments.tpl'), function (err, data) {\n\t\t\tComments.template = data.toString();\n\t\t});\n\n\t\tapp.get('/comments/get/:id/:pagination?', middleware.applyCSRF, Comments.getCommentData);\n\t\tapp.post('/comments/reply', Comments.replyToComment);\n\t\tapp.post('/comments/publish', Comments.publishArticle);\n\n\t\tapp.get('/admin/blog-comments', middleware.admin.buildHeader, renderAdmin);\n\t\tapp.get('/api/admin/blog-comments', renderAdmin);\n\n\t\tcallback();\n\t};", "label_name": "CWE-352", "label": 0} {"code": "\t\t\tgoToFullForm(form) {\n\t\t\t\t//As formData contains information about both view and action removed action and directed to view\n\t\t\t\tform.find('input[name=\"action\"]').remove();\n\t\t\t\tform.append('');\n\t\t\t\t$.each(form.find('[data-validation-engine]'), function (key, data) {\n\t\t\t\t\t$(data).removeAttr('data-validation-engine');\n\t\t\t\t});\n\t\t\t\tform.addClass('not_validation');\n\t\t\t\tform.submit();\n\t\t\t},", "label_name": "CWE-352", "label": 0} {"code": " changePassword: function(newPassword) {\n var d = $q.defer(),\n loginCookie = readLoginCookie();\n\n $http({\n method: 'POST',\n url: '/SOGo/so/changePassword',\n data: {\n userName: loginCookie[0],\n password: loginCookie[1],\n newPassword: newPassword }\n }).then(d.resolve, function(response) {\n var error,\n data = response.data,\n perr = data.LDAPPasswordPolicyError;\n\n if (!perr) {\n perr = passwordPolicyConfig.PolicyPasswordSystemUnknown;\n error = _(\"Unhandled error response\");\n }\n else if (perr == passwordPolicyConfig.PolicyNoError) {\n error = l(\"Password change failed\");\n } else if (perr == passwordPolicyConfig.PolicyPasswordModNotAllowed) {\n error = l(\"Password change failed - Permission denied\");\n } else if (perr == passwordPolicyConfig.PolicyInsufficientPasswordQuality) {\n error = l(\"Password change failed - Insufficient password quality\");\n } else if (perr == passwordPolicyConfig.PolicyPasswordTooShort) {\n error = l(\"Password change failed - Password is too short\");\n } else if (perr == passwordPolicyConfig.PolicyPasswordTooYoung) {\n error = l(\"Password change failed - Password is too young\");\n } else if (perr == passwordPolicyConfig.PolicyPasswordInHistory) {\n error = l(\"Password change failed - Password is in history\");\n } else {\n error = l(\"Unhandled policy error: %{0}\").formatted(perr);\n perr = passwordPolicyConfig.PolicyPasswordUnknown;\n }\n\n d.reject(error);\n });\n return d.promise;\n }", "label_name": "CWE-352", "label": 0} {"code": " data: {config_calibre_dir: $(\"#config_calibre_dir\").val()},\n success: function success(data) {\n if ( data.change ) {\n if ( data.valid ) {\n confirmDialog(\n \"db_submit\",\n \"GeneralChangeModal\",\n 0,\n changeDbSettings\n );\n }\n else {\n $(\"#InvalidDialog\").modal('show');\n }\n } else { \t\n changeDbSettings();\n }\n }\n });\n });", "label_name": "CWE-352", "label": 0} {"code": "\twp.updates.requestForCredentialsModalCancel = function() {\n\t\t// no updateLock and no updateQueue means we already have cleared things up\n\t\tvar data, $message;\n\n\t\tif( wp.updates.updateLock === false && wp.updates.updateQueue.length === 0 ){\n\t\t\treturn;\n\t\t}\n\n\t\tdata = wp.updates.updateQueue[0].data;\n\n\t\t// remove the lock, and clear the queue\n\t\twp.updates.updateLock = false;\n\t\twp.updates.updateQueue = [];\n\n\t\twp.updates.requestForCredentialsModalClose();\n\t\tif ( 'plugins' === pagenow || 'plugins-network' === pagenow ) {\n\t\t\t$message = $( '[data-plugin=\"' + data.plugin + '\"]' ).next().find( '.update-message' );\n\t\t} else if ( 'plugin-install' === pagenow ) {\n\t\t\t$message = $( '.plugin-card-' + data.slug ).find( '.update-now' );\n\t\t}\n\n\t\t$message.removeClass( 'updating-message' );\n\t\t$message.html( $message.data( 'originaltext' ) );\n\t\twp.a11y.speak( wp.updates.l10n.updateCancel );\n\t};", "label_name": "CWE-352", "label": 0} {"code": " function update() {\n if (sending == 0) {\n sending = 1;\n sled.className = 'on';\n var r = new XMLHttpRequest();\n var send = \"\";\n while (keybuf.length > 0) {\n send += keybuf.pop();\n }\n var query = query1 + send;\n if (force) {\n query = query + \"&f=1\";\n force = 0;\n }\n r.open(\"POST\", \"hawtio-karaf-terminal/term\", true);\n r.setRequestHeader('Authorization', authHeader);\n r.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');\n r.onreadystatechange = function () {\n if (r.readyState == 4) {\n if (r.status == 200) {\n window.clearTimeout(error_timeout);\n if (r.responseText.length > 0) {\n dterm.innerHTML = r.responseText;\n rmax = 100;\n } else {\n rmax *= 2;\n if (rmax > 2000)\n rmax = 2000;\n }\n sending=0;\n sled.className = 'off';\n timeout = window.setTimeout(update, rmax);\n } else {\n debug(\"Connection error status:\" + r.status);\n }\n }\n }\n error_timeout = window.setTimeout(error, 5000);\n r.send(query);\n }\n }", "label_name": "CWE-352", "label": 0} {"code": "\twp.updates.requestForCredentialsModalClose = function() {\n\t\t$( '#request-filesystem-credentials-dialog' ).hide();\n\t\t$( 'body' ).removeClass( 'modal-open' );\n\t\twp.updates.$elToReturnFocusToFromCredentialsModal.focus();\n\t};", "label_name": "CWE-352", "label": 0} {"code": " error: function(xhr, status, error) {\n if ((status == \"timeout\") || ($.trim(error) == \"timeout\")) {\n /*\n We are not interested in timeout because:\n - it can take minutes to stop a node (resources running on it have\n to be stopped/moved and we do not need to wait for that)\n - if pcs is not able to stop a node it returns an (forceable) error\n immediatelly\n */\n return;\n }\n var message = \"Unable to stop node '\" + node + \" \" + ajax_simple_error(\n xhr, status, error\n );\n if (message.indexOf('--force') == -1) {\n alert(message);\n }\n else {\n message = message.replace(', use --force to override', '');\n if (confirm(message + \"\\n\\nDo you want to force the operation?\")) {\n node_stop(node, true);\n }\n }\n }", "label_name": "CWE-384", "label": 1} {"code": "gogo.Terminal = function(div, width, height, authHeader) {\n return new this.Terminal_ctor(div, width, height, authHeader);\n}", "label_name": "CWE-352", "label": 0} {"code": "function setup_node_links() {\n Ember.debug(\"Setup node links\");\n $(\"#node_start\").click(function() {\n node_link_action(\n \"#node_start\", get_cluster_remote_url() +\"cluster_start\", \"start\"\n );\n });\n $(\"#node_stop\").click(function() {\n var node = $.trim($(\"#node_info_header_title_name\").text());\n fade_in_out(\"#node_stop\");\n node_stop(node, false);\n });\n $(\"#node_restart\").click(function() {\n node_link_action(\n \"#node_restart\", get_cluster_remote_url() + \"node_restart\", \"restart\"\n );\n });\n $(\"#node_standby\").click(function() {\n node_link_action(\n \"#node_standby\", get_cluster_remote_url() + \"node_standby\", \"standby\"\n );\n });\n $(\"#node_unstandby\").click(function() {\n node_link_action(\n \"#node_unstandby\",\n get_cluster_remote_url() + \"node_unstandby\",\n \"unstandby\"\n );\n });\n}", "label_name": "CWE-384", "label": 1} {"code": "\twp.updates.updatePlugin = function( plugin, slug ) {\n\t\tvar $message, name,\n\t\t\t$card = $( '.plugin-card-' + slug );\n\n\t\tif ( 'plugins' === pagenow || 'plugins-network' === pagenow ) {\n\t\t\t$message = $( '[data-plugin=\"' + plugin + '\"]' ).next().find( '.update-message' );\n\t\t} else if ( 'plugin-install' === pagenow ) {\n\t\t\t$message = $card.find( '.update-now' );\n\t\t\tname = $message.data( 'name' );\n\t\t\t$message.attr( 'aria-label', wp.updates.l10n.updatingLabel.replace( '%s', name ) );\n\t\t\t// Remove previous error messages, if any.\n\t\t\t$card.removeClass( 'plugin-card-update-failed' ).find( '.notice.notice-error' ).remove();\n\t\t}\n\n\t\t$message.addClass( 'updating-message' );\n\t\tif ( $message.html() !== wp.updates.l10n.updating ){\n\t\t\t$message.data( 'originaltext', $message.html() );\n\t\t}\n\n\t\t$message.text( wp.updates.l10n.updating );\n\t\twp.a11y.speak( wp.updates.l10n.updatingMsg );\n\n\t\tif ( wp.updates.updateLock ) {\n\t\t\twp.updates.updateQueue.push( {\n\t\t\t\ttype: 'update-plugin',\n\t\t\t\tdata: {\n\t\t\t\t\tplugin: plugin,\n\t\t\t\t\tslug: slug\n\t\t\t\t}\n\t\t\t} );\n\t\t\treturn;\n\t\t}\n\n\t\twp.updates.updateLock = true;\n\n\t\tvar data = {\n\t\t\t_ajax_nonce: wp.updates.ajaxNonce,\n\t\t\tplugin: plugin,\n\t\t\tslug: slug,\n\t\t\tusername: wp.updates.filesystemCredentials.ftp.username,\n\t\t\tpassword: wp.updates.filesystemCredentials.ftp.password,\n\t\t\thostname: wp.updates.filesystemCredentials.ftp.hostname,\n\t\t\tconnection_type: wp.updates.filesystemCredentials.ftp.connectionType,\n\t\t\tpublic_key: wp.updates.filesystemCredentials.ssh.publicKey,\n\t\t\tprivate_key: wp.updates.filesystemCredentials.ssh.privateKey\n\t\t};\n\n\t\twp.ajax.post( 'update-plugin', data )\n\t\t\t.done( wp.updates.updateSuccess )\n\t\t\t.fail( wp.updates.updateError );\n\t};", "label_name": "CWE-352", "label": 0} {"code": " singleClick: function(p,c,o) {\n var s = f.get.siblings(p,o);\n f.h.off(s, o);\n f.h.on(c.current.v, o);\n f.set.clicks(c.current.v, null, null, p, o);\n },", "label_name": "CWE-352", "label": 0} {"code": "function load_agent_form(resource_id, stonith) {\n var url;\n var form;\n if (stonith) {\n form = $(\"#stonith_agent_form\");\n url = '/managec/' + Pcs.cluster_name + '/fence_device_form';\n } else {\n form = $(\"#resource_agent_form\");\n url = '/managec/' + Pcs.cluster_name + '/resource_form?version=2';\n }\n\n form.empty();\n\n var resource_obj = Pcs.resourcesContainer.get_resource_by_id(resource_id);\n if (!resource_obj || !resource_obj.get('is_primitive'))\n return;\n\n var data = {resource: resource_id};\n\n $.ajax({\n type: 'GET',\n url: url,\n data: data,\n timeout: pcs_timeout,\n success: function (data) {\n Ember.run.next(function(){form.html(data);});\n }\n });\n}", "label_name": "CWE-384", "label": 1} {"code": " $scope.refresh = function() {\n growl.success('Retrieving node ' + $scope.foreignId + ' from requisition ' + $scope.foreignSource + '...');\n RequisitionsService.getNode($scope.foreignSource, $scope.foreignId).then(\n function(node) { // success\n $scope.node = node;\n },\n $scope.errorHandler\n );\n };", "label_name": "CWE-352", "label": 0} {"code": "\t\t$.each(postData, (index, value) => {\n\t\t\tlet input = $(document.createElement('input'));\n\t\t\tinput.attr('type', 'hidden');\n\t\t\tinput.attr('name', index);\n\t\t\tinput.val(value);\n\t\t\tform.append(input);\n\t\t});", "label_name": "CWE-352", "label": 0} {"code": " $scope.reset = function() {\n bootbox.confirm('Are you sure you want to reset the foreign source definition to the default ?', function(ok) {\n if (ok) {\n RequisitionsService.startTiming();\n RequisitionsService.deleteForeignSourceDefinition($scope.foreignSource).then(\n function() { // success\n growl.success('The foreign source definition for ' + $scope.foreignSource + 'has been reseted.');\n $scope.initialize();\n },\n $scope.errorHandler\n );\n }\n });\n };", "label_name": "CWE-352", "label": 0} {"code": "\twp.updates.updateError = function( response ) {\n\t\tvar $card = $( '.plugin-card-' + response.slug ),\n\t\t\t$message,\n\t\t\t$button,\n\t\t\tname,\n\t\t\terror_message;\n\n\t\twp.updates.updateDoneSuccessfully = false;\n\n\t\tif ( response.errorCode && response.errorCode == 'unable_to_connect_to_filesystem' && wp.updates.shouldRequestFilesystemCredentials ) {\n\t\t\twp.updates.credentialError( response, 'update-plugin' );\n\t\t\treturn;\n\t\t}\n\n\t\terror_message = wp.updates.l10n.updateFailed.replace( '%s', response.error );\n\n\t\tif ( 'plugins' === pagenow || 'plugins-network' === pagenow ) {\n\t\t\t$message = $( '[data-plugin=\"' + response.plugin + '\"]' ).next().find( '.update-message' );\n\t\t\t$message.html( error_message ).removeClass( 'updating-message' );\n\t\t} else if ( 'plugin-install' === pagenow ) {\n\t\t\t$button = $card.find( '.update-now' );\n\t\t\tname = $button.data( 'name' );\n\n\t\t\t$card\n\t\t\t\t.addClass( 'plugin-card-update-failed' )\n\t\t\t\t.append( '

    ' + error_message + '

    ' );\n\n\t\t\t$button\n\t\t\t\t.attr( 'aria-label', wp.updates.l10n.updateFailedLabel.replace( '%s', name ) )\n\t\t\t\t.html( wp.updates.l10n.updateFailedShort ).removeClass( 'updating-message' );\n\n\t\t\t$card.on( 'click', '.notice.is-dismissible .notice-dismiss', function() {\n\t\t\t\t// Use same delay as the total duration of the notice fadeTo + slideUp animation.\n\t\t\t\tsetTimeout( function() {\n\t\t\t\t\t$card\n\t\t\t\t\t\t.removeClass( 'plugin-card-update-failed' )\n\t\t\t\t\t\t.find( '.column-name a' ).focus();\n\t\t\t\t}, 200 );\n\t\t\t});\n\t\t}\n\n\t\twp.a11y.speak( error_message, 'assertive' );\n\n\t\t/*\n\t\t * The lock can be released since this failure was\n\t\t * after the credentials form.\n\t\t */\n\t\twp.updates.updateLock = false;\n\n\t\t$(document).trigger( 'wp-plugin-update-error', response );\n\n\t\twp.updates.queueChecker();\n\t};", "label_name": "CWE-352", "label": 0} {"code": " success: function (data) {\n mydata = jQuery.parseJSON(data);\n $.ajax({\n type: 'GET',\n url: '/manage/get_nodes_sw_versions',\n data: {\"nodes\": nodes.join(\",\")},\n timeout: pcs_timeout,\n success: function(data) {\n versions = jQuery.parseJSON(data);\n update_create_cluster_dialog(mydata, versions);\n },\n error: function (XMLHttpRequest, textStatus, errorThrown) {\n alert(\"ERROR: Unable to contact server\");\n }\n });\n },\n error: function (XMLHttpRequest, textStatus, errorThrown) {\n alert(\"ERROR: Unable to contact server\");\n }\n });\n}", "label_name": "CWE-384", "label": 1} {"code": " $scope.refresh = function(requisition) {\n RequisitionsService.startTiming();\n RequisitionsService.updateDeployedStatsForRequisition(requisition).then(\n function() { // success\n growl.success('The deployed statistics for ' + requisition.foreignSource + ' has been updated.');\n },\n $scope.errorHandler\n );\n };", "label_name": "CWE-352", "label": 0} {"code": "function create_resource(form, update, stonith) {\n dataString = $(form).serialize();\n var resourceID = $(form).find(\"[name='name']\").val(); \n url = get_cluster_remote_url() + $(form).attr(\"action\");\n var name;\n\n if (stonith)\n name = \"fence device\";\n else\n name = \"resource\"\n\n $.ajax({\n type: \"POST\",\n url: url,\n data: dataString,\n dataType: \"json\",\n success: function(returnValue) {\n $('input.apply_changes').show();\n if (returnValue[\"error\"] == \"true\") {\n alert(returnValue[\"stderr\"]);\n } else {\n Pcs.update();\n if (!update) {\n if (stonith)\n $('#add_stonith').dialog('close');\n else\n $('#add_resource').dialog('close');\n } else {\n reload_current_resource();\n }\n }\n },\n error: function(xhr, status, error) {\n if (update) {\n alert(\n \"Unable to update \" + name + \" \"\n + ajax_simple_error(xhr, status, error)\n );\n }\n else {\n alert(\n \"Unable to add \" + name + \" \"\n + ajax_simple_error(xhr, status, error)\n );\n }\n $('input.apply_changes').show();\n }\n });\n}", "label_name": "CWE-384", "label": 1} {"code": " this.disableChatSoundAdmin = function(inst)\n {\n if (inst.prop('tagName') != 'I') {\n inst = inst.find('> i.material-icons');\n }\n\n \tif (inst.text() == 'volume_off'){\n \t\t$.get(this.wwwDir+ 'user/setsettingajax/chat_message/1');\n \t\tconfLH.new_message_sound_admin_enabled = 1;\n \t\tinst.text('volume_up');\n \t} else {\n \t\t$.get(this.wwwDir+ 'user/setsettingajax/chat_message/0');\n \t\tconfLH.new_message_sound_admin_enabled = 0;\n \t\tinst.text('volume_off');\n \t}\n \treturn false;\n };", "label_name": "CWE-352", "label": 0} {"code": "function create_group() {\n var num_nodes = 0;\n var node_names = \"\";\n $(\"#resource_list :checked\").parent().parent().each(function (index,element) {\n if (element.getAttribute(\"nodeID\")) {\n num_nodes++;\n node_names += element.getAttribute(\"nodeID\") + \" \"\n }\n });\n\n if (num_nodes == 0) {\n alert(\"You must select at least one resource to add to a group\");\n return;\n }\n\n $(\"#resources_to_add_to_group\").val(node_names);\n $(\"#add_group\").dialog({\n title: 'Create Group',\n modal: true,\n resizable: false,\n buttons: {\n Cancel: function() {\n $(this).dialog(\"close\");\n },\n \"Create Group\": function() {\n var data = $('#add_group > form').serialize();\n var url = get_cluster_remote_url() + \"add_group\";\n $.ajax({\n type: \"POST\",\n url: url,\n data: data,\n success: function() {\n Pcs.update();\n $(\"#add_group\").dialog(\"close\");\n },\n error: function (xhr, status, error) {\n alert(\n \"Error creating group \"\n + ajax_simple_error(xhr, status, error)\n );\n $(\"#add_group\").dialog(\"close\");\n }\n });\n }\n }\n });\n}", "label_name": "CWE-384", "label": 1} {"code": " data: {config_calibre_dir: $(\"#config_calibre_dir\").val(), csrf_token: $(\"input[name='csrf_token']\").val()},\n success: function success(data) {\n if ( data.change ) {\n if ( data.valid ) {\n confirmDialog(\n \"db_submit\",\n \"GeneralChangeModal\",\n 0,\n changeDbSettings\n );\n }\n else {\n $(\"#InvalidDialog\").modal('show');\n }\n } else { \t\n changeDbSettings();\n }\n }\n });\n });", "label_name": "CWE-352", "label": 0} {"code": "function genericAjaxPopupClose($layer, $event) {\n\t$popup = genericAjaxPopupFetch($layer);\n\tif(null != $popup) {\n\t\ttry {\n\t\t\tif(null != $event)\n\t\t\t\t$popup.trigger($event);\n\t\t} catch(e) { if(window.console) console.log(e); }\n\t\t\n\t\ttry {\n\t\t\t$popup.dialog('close');\n\t\t} catch(e) { if(window.console) console.log(e); }\n\t\t\n\t\treturn true;\n\t}\n\treturn false;\n}", "label_name": "CWE-352", "label": 0} {"code": " $scope.save = function() {\n var form = this.nodeForm;\n RequisitionsService.startTiming();\n RequisitionsService.saveNode($scope.node).then(\n function() { // success\n growl.success('The node ' + $scope.node.nodeLabel + ' has been saved.');\n $scope.foreignId = $scope.node.foreignId;\n form.$dirty = false;\n },\n $scope.errorHandler\n );\n };", "label_name": "CWE-352", "label": 0} {"code": "\t\t\t\t\t\tmessage: app.vtranslate('JS_LBL_ARE_YOU_SURE_YOU_WANT_TO_DELETE_FILTER')\n\t\t\t\t\t}).done((e) => {\n\t\t\t\t\t\tapp.openUrlMethodPost(thisInstance.getSelectOptionFromChosenOption(liElement).data('deleteurl'));\n\t\t\t\t\t});\n\t\t\t\t\tevent.stopPropagation();\n\t\t\t\t});", "label_name": "CWE-352", "label": 0} {"code": " $scope.addRequisition = function() {\n bootbox.prompt('A requisition is required, please enter the name for a new requisition', function(foreignSource) {\n if (foreignSource) {\n RequisitionsService.addRequisition(foreignSource).then(\n function() { // success\n RequisitionsService.synchronizeRequisition(foreignSource, false).then(\n function() {\n growl.success('The requisition ' + foreignSource + ' has been created and synchronized.');\n $scope.foreignSources.push(foreignSource);\n },\n $scope.errorHandler\n );\n },\n $scope.errorHandler\n );\n } else {\n window.location.href = Util.getBaseHref() + 'admin/opennms/index.jsp'; // TODO Is this the best way ?\n }\n });\n };", "label_name": "CWE-352", "label": 0} {"code": " $scope.delete = function(foreignSource) {\n bootbox.confirm('Are you sure you want to remove the requisition ' + foreignSource + '?', function(ok) {\n if (ok) {\n RequisitionsService.startTiming();\n RequisitionsService.deleteRequisition(foreignSource).then(\n function() { // success\n growl.success('The requisition ' + foreignSource + ' has been deleted.');\n },\n $scope.errorHandler\n );\n }\n });\n };", "label_name": "CWE-352", "label": 0} {"code": " \"Create Group\": function() {\n var data = $('#add_group > form').serialize();\n var url = get_cluster_remote_url() + \"add_group\";\n $.ajax({\n type: \"POST\",\n url: url,\n data: data,\n success: function() {\n Pcs.update();\n $(\"#add_group\").dialog(\"close\");\n },\n error: function (xhr, status, error) {\n alert(\n \"Error creating group \"\n + ajax_simple_error(xhr, status, error)\n );\n $(\"#add_group\").dialog(\"close\");\n }\n });\n }", "label_name": "CWE-384", "label": 1} {"code": "\twp.updates.decrementCount = function( upgradeType ) {\n\t\tvar count,\n\t\t\tpluginCount,\n\t\t\t$adminBarUpdateCount = $( '#wp-admin-bar-updates .ab-label' ),\n\t\t\t$dashboardNavMenuUpdateCount = $( 'a[href=\"update-core.php\"] .update-plugins' ),\n\t\t\t$pluginsMenuItem = $( '#menu-plugins' );\n\n\n\t\tcount = $adminBarUpdateCount.text();\n\t\tcount = parseInt( count, 10 ) - 1;\n\t\tif ( count < 0 || isNaN( count ) ) {\n\t\t\treturn;\n\t\t}\n\t\t$( '#wp-admin-bar-updates .ab-item' ).removeAttr( 'title' );\n\t\t$adminBarUpdateCount.text( count );\n\n\n\t\t$dashboardNavMenuUpdateCount.each( function( index, elem ) {\n\t\t\telem.className = elem.className.replace( /count-\\d+/, 'count-' + count );\n\t\t} );\n\t\t$dashboardNavMenuUpdateCount.removeAttr( 'title' );\n\t\t$dashboardNavMenuUpdateCount.find( '.update-count' ).text( count );\n\n\t\tif ( 'plugin' === upgradeType ) {\n\t\t\tpluginCount = $pluginsMenuItem.find( '.plugin-count' ).eq(0).text();\n\t\t\tpluginCount = parseInt( pluginCount, 10 ) - 1;\n\t\t\tif ( pluginCount < 0 || isNaN( pluginCount ) ) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t$pluginsMenuItem.find( '.plugin-count' ).text( pluginCount );\n\t\t\t$pluginsMenuItem.find( '.update-plugins' ).each( function( index, elem ) {\n\t\t\t\telem.className = elem.className.replace( /count-\\d+/, 'count-' + pluginCount );\n\t\t\t} );\n\n\t\t\tif (pluginCount > 0 ) {\n\t\t\t\t$( '.subsubsub .upgrade .count' ).text( '(' + pluginCount + ')' );\n\t\t\t} else {\n\t\t\t\t$( '.subsubsub .upgrade' ).remove();\n\t\t\t}\n\t\t}\n\t};", "label_name": "CWE-352", "label": 0} {"code": "rcube_webmail.prototype.managesieve_setget = function()\n{\n var id = this.filtersets_list.get_single_selection(),\n script = this.env.filtersets[id];\n\n location.href = this.env.comm_path+'&_action=plugin.managesieve-action&_act=setget&_set='+urlencode(script);\n};", "label_name": "CWE-352", "label": 0} {"code": " $scope.refresh = function(requisition) {\n RequisitionsService.startTiming();\n RequisitionsService.updateDeployedStatsForRequisition(requisition).then(\n function() { // success\n growl.success('The deployed statistics for ' + requisition.foreignSource + ' has been updated.');\n },\n $scope.errorHandler\n );\n };", "label_name": "CWE-352", "label": 0} {"code": " this.disableChatSoundUser = function(inst)\n {\n \tif (inst.find('> i').text() == 'volume_off') {\n \t\t$.get(this.wwwDir+ 'user/setsettingajax/chat_message/1');\n \t\tconfLH.new_message_sound_user_enabled = 1;\n \t\tinst.find('> i').text('volume_up');\n \t} else {\n \t\t$.get(this.wwwDir+ 'user/setsettingajax/chat_message/0');\n \t\tconfLH.new_message_sound_user_enabled = 0;\n \t\tinst.find('> i').text('volume_off');\n \t};\n\n \tif (!!window.postMessage && parent) {\n \t\tif (inst.find('> i').text() == 'volume_off') {\n \t\t\tparent.postMessage(\"lhc_ch:s:0\", '*');\n \t\t} else {\n \t\t\tparent.postMessage(\"lhc_ch:s:1\", '*');\n \t\t}\n \t};\n\n \treturn false;\n };", "label_name": "CWE-352", "label": 0} {"code": " this.disableNewChatSoundAdmin = function(inst)\n {\n if (inst.prop('tagName') != 'I') {\n inst = inst.find('> i.material-icons');\n }\n\n \tif (inst.text() == 'volume_off'){\n \t\t$.get(this.wwwDir+ 'user/setsettingajax/new_chat_sound/1');\n \t\tconfLH.new_chat_sound_enabled = 1;\n \t\tinst.text('volume_up');\n \t} else {\n \t\t$.get(this.wwwDir+ 'user/setsettingajax/new_chat_sound/0');\n \t\tconfLH.new_chat_sound_enabled = 0;\n \t\tinst.text('volume_off');\n \t}\n \treturn false;\n };", "label_name": "CWE-352", "label": 0} {"code": "\t\tregisterApproveFilterClickEvent: function () {\n\t\t\tconst thisInstance = this;\n\t\t\tconst listViewFilterBlock = this.getFilterBlock();\n\t\t\tif (listViewFilterBlock != false) {\n\t\t\t\tlistViewFilterBlock.on('mouseup', '.js-filter-approve', (event) => {\n\t\t\t\t\t//to close the dropdown\n\t\t\t\t\tthisInstance.getFilterSelectElement().data('select2').close();\n\t\t\t\t\tconst liElement = $(event.currentTarget).closest('.select2-results__option');\n\t\t\t\t\tapp.openUrlMethodPost(thisInstance.getSelectOptionFromChosenOption(liElement).data('approveurl'));\n\t\t\t\t\tevent.stopPropagation();\n\t\t\t\t});\n\t\t\t}\n\t\t},", "label_name": "CWE-352", "label": 0} {"code": " $scope.removeAllNodes = function(foreignSource) {\n bootbox.confirm('Are you sure you want to remove all the nodes from ' + foreignSource + '?', function(ok) {\n if (ok) {\n RequisitionsService.startTiming();\n RequisitionsService.removeAllNodesFromRequisition(foreignSource).then(\n function() { // success\n growl.success('All the nodes from ' + foreignSource + ' have been removed, and the requisition has been synchronized.');\n var req = $scope.requisitionsData.getRequisition(foreignSource);\n req.reset();\n },\n $scope.errorHandler\n );\n }\n });\n };", "label_name": "CWE-352", "label": 0} {"code": "function node_link_action(link_selector, url, label) {\n var node = $.trim($(\"#node_info_header_title_name\").text());\n fade_in_out(link_selector);\n $.ajax({\n type: 'POST',\n url: url,\n data: {\"name\": node},\n success: function() {\n },\n error: function (xhr, status, error) {\n alert(\n \"Unable to \" + label + \" node '\" + node + \"' \"\n + ajax_simple_error(xhr, status, error)\n );\n }\n });\n}", "label_name": "CWE-384", "label": 1} {"code": " $scope.provision = function() {\n $scope.isSaving = true;\n growl.info($sanitize('The node ' + $scope.node.nodeLabel + ' is being added to requisition ' + $scope.node.foreignSource + '. Please wait...'));\n var successMessage = $sanitize('The node ' + $scope.node.nodeLabel + ' has been added to requisition ' + $scope.node.foreignSource);\n RequisitionsService.quickAddNode($scope.node).then(\n function() { // success\n $scope.reset();\n bootbox.dialog({\n message: successMessage,\n title: 'Success',\n buttons: {\n main: {\n label: 'Ok',\n className: 'btn-secondary'\n }\n }\n });\n },\n $scope.errorHandler\n );\n };", "label_name": "CWE-352", "label": 0} {"code": " $scope.clone = function(foreignSource) {\n var availableForeignSources = [];\n angular.forEach($scope.requisitionsData.requisitions, function(r) {\n if (r.foreignSource !== foreignSource) {\n availableForeignSources.push(r.foreignSource);\n }\n });\n var modalInstance = $uibModal.open({\n backdrop: 'static',\n keyboard: false,\n controller: 'CloneForeignSourceController',\n templateUrl: cloneForeignsourceView,\n resolve: {\n foreignSource: function() { return foreignSource; },\n availableForeignSources: function() { return availableForeignSources; }\n }\n });\n modalInstance.result.then(function(targetForeignSource) {\n bootbox.confirm('This action will override the existing foreign source definition for the requisition named ' + targetForeignSource + ', using ' + foreignSource + ' as a template. Are you sure you want to continue ? This cannot be undone.', function(ok) {\n if (!ok) {\n return;\n }\n RequisitionsService.startTiming();\n RequisitionsService.cloneForeignSourceDefinition(foreignSource, targetForeignSource).then(\n function() { // success\n growl.success('The foreign source definition for ' + foreignSource + ' has been cloned to ' + targetForeignSource);\n },\n $scope.errorHandler\n );\n });\n });\n };", "label_name": "CWE-352", "label": 0} {"code": "\twp.updates.queueChecker = function() {\n\t\tif ( wp.updates.updateLock || wp.updates.updateQueue.length <= 0 ) {\n\t\t\treturn;\n\t\t}\n\n\t\tvar job = wp.updates.updateQueue.shift();\n\n\t\twp.updates.updatePlugin( job.data.plugin, job.data.slug );\n\t};", "label_name": "CWE-352", "label": 0} {"code": "\twp.updates.keydown = function( event ) {\n\t\tif ( 27 === event.keyCode ) {\n\t\t\twp.updates.requestForCredentialsModalCancel();\n\t\t} else if ( 9 === event.keyCode ) {\n\t\t\t// #upgrade button must always be the last focusable element in the dialog.\n\t\t\tif ( event.target.id === 'upgrade' && ! event.shiftKey ) {\n\t\t\t\t$( '#hostname' ).focus();\n\t\t\t\tevent.preventDefault();\n\t\t\t} else if ( event.target.id === 'hostname' && event.shiftKey ) {\n\t\t\t\t$( '#upgrade' ).focus();\n\t\t\t\tevent.preventDefault();\n\t\t\t}\n\t\t}\n\t};", "label_name": "CWE-352", "label": 0} {"code": " this.switch_task = function(task)\n {\n if (this.task === task && task != 'mail')\n return;\n\n var url = this.get_task_url(task);\n\n if (task == 'mail')\n url += '&_mbox=INBOX';\n else if (task == 'logout' && !this.env.server_error) {\n url += '&_token=' + this.env.request_token;\n this.clear_compose_data();\n }\n\n this.redirect(url);\n };", "label_name": "CWE-352", "label": 0} {"code": " $scope.deleteNode = function(node) {\n bootbox.confirm('Are you sure you want to remove the node ' + node.nodeLabel + '?', function(ok) {\n if (ok) {\n RequisitionsService.startTiming();\n RequisitionsService.deleteNode(node).then(\n function() { // success\n var index = -1;\n for(var i = 0; i < $scope.filteredNodes.length; i++) {\n if ($scope.filteredNodes[i].foreignId === node.foreignId) {\n index = i;\n }\n }\n if (index > -1) {\n $scope.filteredNodes.splice(index,1);\n }\n growl.success('The node ' + node.nodeLabel + ' has been deleted.');\n },\n $scope.errorHandler\n );\n }\n });\n };", "label_name": "CWE-352", "label": 0} {"code": " $scope.initialize = function() {\n growl.success('Retrieving definition for requisition ' + $scope.foreignSource + '...');\n RequisitionsService.getForeignSourceDefinition($scope.foreignSource).then(\n function(foreignSourceDef) { // success\n $scope.foreignSourceDef = foreignSourceDef;\n // Updating pagination variables for detectors.\n $scope.filteredDetectors = $scope.foreignSourceDef.detectors;\n $scope.updateFilteredDetectors();\n // Updating pagination variables for policies.\n $scope.filteredPolicies = $scope.foreignSourceDef.policies;\n $scope.updateFilteredPolicies();\n },\n $scope.errorHandler\n );\n };", "label_name": "CWE-352", "label": 0} {"code": " $scope.delete = function(foreignSource) {\n bootbox.confirm('Are you sure you want to remove the requisition ' + foreignSource + '?', function(ok) {\n if (ok) {\n RequisitionsService.startTiming();\n RequisitionsService.deleteRequisition(foreignSource).then(\n function() { // success\n growl.success('The requisition ' + foreignSource + ' has been deleted.');\n },\n $scope.errorHandler\n );\n }\n });\n };", "label_name": "CWE-352", "label": 0} {"code": "static void print_buttons(HttpRequest req, HttpResponse res, Service_T s) {\n if (is_readonly(req)) {\n // A read-only REMOTE_USER does not get access to these buttons\n return;\n }\n StringBuffer_append(res->outputbuffer, \"\");\n /* Start program */\n if (s->start)\n StringBuffer_append(res->outputbuffer,\n \"\", s->name);\n /* Stop program */\n if (s->stop)\n StringBuffer_append(res->outputbuffer,\n \"\", s->name);\n /* Restart program */\n if ((s->start && s->stop) || s->restart)\n StringBuffer_append(res->outputbuffer,\n \"\", s->name);\n /* (un)monitor */\n StringBuffer_append(res->outputbuffer,\n \"
    \"\n \"\"\n \"
    \"\n \"\"\n \"
    \"\n \"\"\n \"
    \"\n \"\"\n \"
    \",\n s->name,\n s->monitor ? \"unmonitor\" : \"monitor\",\n s->monitor ? \"Disable monitoring\" : \"Enable monitoring\");\n}", "label_name": "CWE-352", "label": 0} {"code": "static void handle_run(HttpRequest req, HttpResponse res) {\n const char *action = get_parameter(req, \"action\");\n if (action) {\n if (is_readonly(req)) {\n send_error(req, res, SC_FORBIDDEN, \"You do not have sufficient privileges to access this page\");\n return;\n }\n if (IS(action, \"validate\")) {\n LogInfo(\"The Monit http server woke up on user request\\n\");\n do_wakeupcall();\n } else if (IS(action, \"stop\")) {\n LogInfo(\"The Monit http server stopped on user request\\n\");\n send_error(req, res, SC_SERVICE_UNAVAILABLE, \"The Monit http server is stopped\");\n Engine_stop();\n return;\n }\n }\n LOCK(Run.mutex)\n do_runtime(req, res);\n END_LOCK;\n}", "label_name": "CWE-352", "label": 0} {"code": "void set_header(HttpResponse res, const char *name, const char *value) {\n HttpHeader h = NULL;\n\n ASSERT(res);\n ASSERT(name);\n\n NEW(h);\n h->name = Str_dup(name);\n h->value = Str_dup(value);\n if (res->headers) {\n HttpHeader n, p;\n for (n = p = res->headers; p; n = p, p = p->next) {\n if (IS(p->name, name)) {\n FREE(p->value);\n p->value = Str_dup(value);\n destroy_entry(h);\n return;\n }\n }\n n->next = h;\n } else {\n res->headers = h;\n }\n}", "label_name": "CWE-352", "label": 0} {"code": "static void doGet(HttpRequest req, HttpResponse res) {\n set_content_type(res, \"text/html\");\n if (ACTION(HOME)) {\n LOCK(Run.mutex)\n do_home(res);\n END_LOCK;\n } else if (ACTION(RUN)) {\n handle_run(req, res);\n } else if (ACTION(TEST)) {\n is_monit_running(res);\n } else if (ACTION(VIEWLOG)) {\n do_viewlog(req, res);\n } else if (ACTION(ABOUT)) {\n do_about(res);\n } else if (ACTION(FAVICON)) {\n printFavicon(res);\n } else if (ACTION(PING)) {\n do_ping(res);\n } else if (ACTION(GETID)) {\n do_getid(res);\n } else if (ACTION(STATUS)) {\n print_status(req, res, 1);\n } else if (ACTION(STATUS2)) {\n print_status(req, res, 2);\n } else if (ACTION(SUMMARY)) {\n print_summary(req, res);\n } else if (ACTION(REPORT)) {\n _printReport(req, res);\n } else if (ACTION(DOACTION)) {\n handle_do_action(req, res);\n } else {\n handle_action(req, res);\n }\n}", "label_name": "CWE-352", "label": 0} {"code": "void set_content_type(HttpResponse res, const char *mime) {\n set_header(res, \"Content-Type\", mime);\n}", "label_name": "CWE-352", "label": 0} {"code": "static void handle_action(HttpRequest req, HttpResponse res) {\n char *name = req->url;\n Service_T s = Util_getService(++name);\n if (! s) {\n send_error(req, res, SC_NOT_FOUND, \"There is no service named \\\"%s\\\"\", name ? name : \"\");\n return;\n }\n const char *action = get_parameter(req, \"action\");\n if (action) {\n if (is_readonly(req)) {\n send_error(req, res, SC_FORBIDDEN, \"You do not have sufficient privileges to access this page\");\n return;\n }\n Action_Type doaction = Util_getAction(action);\n if (doaction == Action_Ignored) {\n send_error(req, res, SC_BAD_REQUEST, \"Invalid action \\\"%s\\\"\", action);\n return;\n }\n s->doaction = doaction;\n const char *token = get_parameter(req, \"token\");\n if (token) {\n FREE(s->token);\n s->token = Str_dup(token);\n }\n LogInfo(\"'%s' %s on user request\\n\", s->name, action);\n Run.flags |= Run_ActionPending; /* set the global flag */\n do_wakeupcall();\n }\n do_service(req, res, s);\n}", "label_name": "CWE-352", "label": 0} {"code": " def test_invoice_payment_is_still_pending_for_registration_codes(self):\n \"\"\"\n test generate enrollment report\n enroll a user in a course using registration code\n whose invoice has not been paid yet\n \"\"\"\n course_registration_code = CourseRegistrationCode.objects.create(\n code='abcde',\n course_id=self.course.id.to_deprecated_string(),\n created_by=self.instructor,\n invoice=self.sale_invoice_1,\n invoice_item=self.invoice_item,\n mode_slug='honor'\n )\n\n test_user1 = UserFactory()\n self.register_with_redemption_code(test_user1, course_registration_code.code)\n\n CourseFinanceAdminRole(self.course.id).add_users(self.instructor)\n self.client.login(username=self.instructor.username, password='test')\n\n url = reverse('get_enrollment_report', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {})\n self.assertIn('The detailed enrollment report is being created.', response.content)", "label_name": "CWE-352", "label": 0} {"code": " def test_modify_access_allow_with_uname(self):\n url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'unique_student_identifier': self.other_instructor.username,\n 'rolename': 'staff',\n 'action': 'allow',\n })\n self.assertEqual(response.status_code, 200)", "label_name": "CWE-352", "label": 0} {"code": " def test_get_student_progress_url_nostudent(self):\n \"\"\" Test that the endpoint 400's when requesting an unknown email. \"\"\"\n url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 400)", "label_name": "CWE-352", "label": 0} {"code": " def test_post_only(self):\n \"\"\"\n Verify that we can't call the view when we aren't using POST.\n \"\"\"\n self.client.login(username=self.staff_user.username, password='test')\n response = self.call_add_users_to_cohorts('', method='GET')\n self.assertEqual(response.status_code, 405)", "label_name": "CWE-352", "label": 0} {"code": " def test_list_entrance_exam_instructor_tasks_all_student(self):\n \"\"\" Test list task history for entrance exam AND all student. \"\"\"\n url = reverse('list_entrance_exam_instructor_tasks', kwargs={'course_id': unicode(self.course.id)})\n response = self.client.get(url, {})\n self.assertEqual(response.status_code, 200)\n\n # check response\n tasks = json.loads(response.content)['tasks']\n self.assertEqual(len(tasks), 0)", "label_name": "CWE-352", "label": 0} {"code": "def list_course_role_members(request, course_id):\n \"\"\"\n List instructors and staff.\n Requires instructor access.\n\n rolename is one of ['instructor', 'staff', 'beta', 'ccx_coach']\n\n Returns JSON of the form {\n \"course_id\": \"some/course/id\",\n \"staff\": [\n {\n \"username\": \"staff1\",\n \"email\": \"staff1@example.org\",\n \"first_name\": \"Joe\",\n \"last_name\": \"Shmoe\",\n }\n ]\n }\n \"\"\"\n course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)\n course = get_course_with_access(\n request.user, 'instructor', course_id, depth=None\n )\n\n rolename = request.GET.get('rolename')\n\n if rolename not in ROLES:\n return HttpResponseBadRequest()\n\n def extract_user_info(user):\n \"\"\" convert user into dicts for json view \"\"\"\n return {\n 'username': user.username,\n 'email': user.email,\n 'first_name': user.first_name,\n 'last_name': user.last_name,\n }\n\n response_payload = {\n 'course_id': course_id.to_deprecated_string(),\n rolename: map(extract_user_info, list_with_level(\n course, rolename\n )),\n }\n return JsonResponse(response_payload)", "label_name": "CWE-352", "label": 0} {"code": "def test_get_delete_dataobj(test_app, client: FlaskClient, note_fixture):\n response = client.get(\"/dataobj/delete/1\")\n assert response.status_code == 302", "label_name": "CWE-352", "label": 0} {"code": " def test_list_entrance_exam_instructor_with_invalid_exam_key(self):\n \"\"\" Test list task history for entrance exam failure if course has invalid exam. \"\"\"\n url = reverse('list_entrance_exam_instructor_tasks',\n kwargs={'course_id': unicode(self.course_with_invalid_ee.id)})\n response = self.client.get(url, {\n 'unique_student_identifier': self.student.email,\n })\n self.assertEqual(response.status_code, 400)", "label_name": "CWE-352", "label": 0} {"code": " def test_course_has_entrance_exam_in_student_attempts_reset(self):\n \"\"\" Test course has entrance exam id set while resetting attempts\"\"\"\n url = reverse('reset_student_attempts_for_entrance_exam',\n kwargs={'course_id': unicode(self.course.id)})\n response = self.client.get(url, {\n 'all_students': True,\n 'delete_module': False,\n })\n self.assertEqual(response.status_code, 400)", "label_name": "CWE-352", "label": 0} {"code": " def test_show_student_extensions(self):\n self.test_change_due_date()\n url = reverse('show_student_extensions',\n kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {'student': self.user1.username})\n self.assertEqual(response.status_code, 200, response.content)\n self.assertEqual(json.loads(response.content), {\n u'data': [{u'Extended Due Date': u'2013-12-30 00:00',\n u'Unit': self.week1.display_name}],\n u'header': [u'Unit', u'Extended Due Date'],\n u'title': u'Due date extensions for %s (%s)' % (\n self.user1.profile.name, self.user1.username)})", "label_name": "CWE-352", "label": 0} {"code": " def test_list_course_role_members_staff(self):\n url = reverse('list_course_role_members', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'rolename': 'staff',\n })\n self.assertEqual(response.status_code, 200)\n\n # check response content\n expected = {\n 'course_id': self.course.id.to_deprecated_string(),\n 'staff': [\n {\n 'username': self.other_staff.username,\n 'email': self.other_staff.email,\n 'first_name': self.other_staff.first_name,\n 'last_name': self.other_staff.last_name,\n }\n ]\n }\n res_json = json.loads(response.content)\n self.assertEqual(res_json, expected)", "label_name": "CWE-352", "label": 0} {"code": " def test_reset_student_attempts_single(self):\n \"\"\" Test reset single student attempts. \"\"\"\n url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'problem_to_reset': self.problem_urlname,\n 'unique_student_identifier': self.student.email,\n })\n self.assertEqual(response.status_code, 200)\n # make sure problem attempts have been reset.\n changed_module = StudentModule.objects.get(pk=self.module_to_reset.pk)\n self.assertEqual(\n json.loads(changed_module.state)['attempts'],\n 0\n )", "label_name": "CWE-352", "label": 0} {"code": " def test_reset_nonexistent_extension(self):\n url = reverse('reset_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'student': self.user1.username,\n 'url': self.week1.location.to_deprecated_string(),\n })\n self.assertEqual(response.status_code, 400, response.content)", "label_name": "CWE-352", "label": 0} {"code": " def test_reset_date(self):\n self.test_change_due_date()\n url = reverse('reset_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'student': self.user1.username,\n 'url': self.week1.location.to_deprecated_string(),\n })\n self.assertEqual(response.status_code, 200, response.content)\n self.assertEqual(\n None,\n get_extended_due(self.course, self.week1, self.user1)\n )", "label_name": "CWE-352", "label": 0} {"code": " def test_list_course_role_members_noparams(self):\n \"\"\" Test missing all query parameters. \"\"\"\n url = reverse('list_course_role_members', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 400)", "label_name": "CWE-352", "label": 0} {"code": " def test_get_ora2_responses_success(self):\n url = reverse('export_ora2_data', kwargs={'course_id': unicode(self.course.id)})\n\n with patch('instructor_task.api.submit_export_ora2_data') as mock_submit_ora2_task:\n mock_submit_ora2_task.return_value = True\n response = self.client.get(url, {})\n success_status = \"The ORA data report is being generated.\"\n self.assertIn(success_status, response.content)", "label_name": "CWE-352", "label": 0} {"code": " def test_reset_extension_to_deleted_date(self):\n \"\"\"\n Test that we can delete a due date extension after deleting the normal\n due date, without causing an error.\n \"\"\"\n\n url = reverse('change_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'student': self.user1.username,\n 'url': self.week1.location.to_deprecated_string(),\n 'due_datetime': '12/30/2013 00:00'\n })\n self.assertEqual(response.status_code, 200, response.content)\n self.assertEqual(datetime.datetime(2013, 12, 30, 0, 0, tzinfo=utc),\n get_extended_due(self.course, self.week1, self.user1))\n\n self.week1.due = None\n self.week1 = self.store.update_item(self.week1, self.user1.id)\n # Now, week1's normal due date is deleted but the extension still exists.\n url = reverse('reset_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'student': self.user1.username,\n 'url': self.week1.location.to_deprecated_string(),\n })\n self.assertEqual(response.status_code, 200, response.content)\n self.assertEqual(\n None,\n get_extended_due(self.course, self.week1, self.user1)\n )", "label_name": "CWE-352", "label": 0} {"code": " def test_modify_access_with_inactive_user(self):\n self.other_user.is_active = False\n self.other_user.save() # pylint: disable=no-member\n url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'unique_student_identifier': self.other_user.username,\n 'rolename': 'beta',\n 'action': 'allow',\n })\n self.assertEqual(response.status_code, 200)\n expected = {\n 'unique_student_identifier': self.other_user.username,\n 'inactiveUser': True,\n }\n res_json = json.loads(response.content)\n self.assertEqual(res_json, expected)", "label_name": "CWE-352", "label": 0} {"code": " def test_certificates_features_against_status(self):\n \"\"\"\n Test certificates with status 'downloadable' should be in the response.\n \"\"\"\n url = reverse('get_issued_certificates', kwargs={'course_id': unicode(self.course.id)})\n # firstly generating downloadable certificates with 'honor' mode\n certificate_count = 3\n for __ in xrange(certificate_count):\n self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.generating)\n\n response = self.client.get(url)\n res_json = json.loads(response.content)\n self.assertIn('certificates', res_json)\n self.assertEqual(len(res_json['certificates']), 0)\n\n # Certificates with status 'downloadable' should be in response.\n self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.downloadable)\n response = self.client.get(url)\n res_json = json.loads(response.content)\n self.assertIn('certificates', res_json)\n self.assertEqual(len(res_json['certificates']), 1)", "label_name": "CWE-352", "label": 0} {"code": " def test_calculate_report_csv_success(self, report_type, instructor_api_endpoint, task_api_endpoint, extra_instructor_api_kwargs):\n kwargs = {'course_id': unicode(self.course.id)}\n kwargs.update(extra_instructor_api_kwargs)\n url = reverse(instructor_api_endpoint, kwargs=kwargs)\n success_status = \"The {report_type} report is being created.\".format(report_type=report_type)\n if report_type == 'problem responses':\n with patch(task_api_endpoint):\n response = self.client.get(url, {'problem_location': ''})\n self.assertIn(success_status, response.content)\n else:\n CourseFinanceAdminRole(self.course.id).add_users(self.instructor)\n with patch(task_api_endpoint):\n response = self.client.get(url, {})\n self.assertIn(success_status, response.content)", "label_name": "CWE-352", "label": 0} {"code": " def test_list_entrance_exam_instructor_tasks_student(self):\n \"\"\" Test list task history for entrance exam AND student. \"\"\"\n # create a re-score entrance exam task\n url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)})\n response = self.client.get(url, {\n 'unique_student_identifier': self.student.email,\n })\n self.assertEqual(response.status_code, 200)\n\n url = reverse('list_entrance_exam_instructor_tasks', kwargs={'course_id': unicode(self.course.id)})\n response = self.client.get(url, {\n 'unique_student_identifier': self.student.email,\n })\n self.assertEqual(response.status_code, 200)\n\n # check response\n tasks = json.loads(response.content)['tasks']\n self.assertEqual(len(tasks), 1)\n self.assertEqual(tasks[0]['status'], _('Complete'))", "label_name": "CWE-352", "label": 0} {"code": "def qute_settings(url):\n \"\"\"Handler for qute://settings. View/change qute configuration.\"\"\"\n if url.path() == '/set':\n return _qute_settings_set(url)\n\n src = jinja.render('settings.html', title='settings',\n configdata=configdata,\n confget=config.instance.get_str)\n return 'text/html', src", "label_name": "CWE-352", "label": 0} {"code": " def test_change_to_invalid_due_date(self):\n url = reverse('change_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'student': self.user1.username,\n 'url': self.week1.location.to_deprecated_string(),\n 'due_datetime': '01/01/2009 00:00'\n })\n self.assertEqual(response.status_code, 400, response.content)\n self.assertEqual(\n None,\n get_extended_due(self.course, self.week1, self.user1)\n )", "label_name": "CWE-352", "label": 0} {"code": " def assert_update_forum_role_membership(self, current_user, identifier, rolename, action):\n \"\"\"\n Test update forum role membership.\n Get unique_student_identifier, rolename and action and update forum role.\n \"\"\"\n url = reverse('update_forum_role_membership', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(\n url,\n {\n 'unique_student_identifier': identifier,\n 'rolename': rolename,\n 'action': action,\n }\n )\n\n # Status code should be 200.\n self.assertEqual(response.status_code, 200)\n\n user_roles = current_user.roles.filter(course_id=self.course.id).values_list(\"name\", flat=True)\n if action == 'allow':\n self.assertIn(rolename, user_roles)\n elif action == 'revoke':\n self.assertNotIn(rolename, user_roles)", "label_name": "CWE-352", "label": 0} {"code": " def test_modify_access_with_fake_user(self):\n url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'unique_student_identifier': 'GandalfTheGrey',\n 'rolename': 'staff',\n 'action': 'revoke',\n })\n self.assertEqual(response.status_code, 200)\n expected = {\n 'unique_student_identifier': 'GandalfTheGrey',\n 'userDoesNotExist': True,\n }\n res_json = json.loads(response.content)\n self.assertEqual(res_json, expected)", "label_name": "CWE-352", "label": 0} {"code": "def require_post_params(*args, **kwargs):\n \"\"\"\n Checks for required parameters or renders a 400 error.\n (decorator with arguments)\n\n Functions like 'require_query_params', but checks for\n POST parameters rather than GET parameters.\n \"\"\"\n required_params = []\n required_params += [(arg, None) for arg in args]\n required_params += [(key, kwargs[key]) for key in kwargs]\n # required_params = e.g. [('action', 'enroll or unenroll'), ['emails', None]]\n\n def decorator(func): # pylint: disable=missing-docstring\n def wrapped(*args, **kwargs): # pylint: disable=missing-docstring\n request = args[0]\n\n error_response_data = {\n 'error': 'Missing required query parameter(s)',\n 'parameters': [],\n 'info': {},\n }\n\n for (param, extra) in required_params:\n default = object()\n if request.POST.get(param, default) == default:\n error_response_data['parameters'].append(param)\n error_response_data['info'][param] = extra\n\n if len(error_response_data['parameters']) > 0:\n return JsonResponse(error_response_data, status=400)\n else:\n return func(*args, **kwargs)\n return wrapped\n return decorator", "label_name": "CWE-352", "label": 0} {"code": " def test_get_anon_ids(self):\n \"\"\"\n Test the CSV output for the anonymized user ids.\n \"\"\"\n url = reverse('get_anon_ids', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {})\n self.assertEqual(response['Content-Type'], 'text/csv')\n body = response.content.replace('\\r', '')\n self.assertTrue(body.startswith(\n '\"User ID\",\"Anonymized User ID\",\"Course Specific Anonymized User ID\"'\n '\\n\"{user_id}\",\"41\",\"42\"\\n'.format(user_id=self.students[0].id)\n ))\n self.assertTrue(\n body.endswith('\"{user_id}\",\"41\",\"42\"\\n'.format(user_id=self.students[-1].id))\n )", "label_name": "CWE-352", "label": 0} {"code": " def test_rescore_problem_all(self, act):\n \"\"\" Test rescoring for all students. \"\"\"\n url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'problem_to_reset': self.problem_urlname,\n 'all_students': True,\n })\n self.assertEqual(response.status_code, 200)\n self.assertTrue(act.called)", "label_name": "CWE-352", "label": 0} {"code": " def test_get_students_features_cohorted(self, is_cohorted):\n \"\"\"\n Test that get_students_features includes cohort info when the course is\n cohorted, and does not when the course is not cohorted.\n \"\"\"\n url = reverse('get_students_features', kwargs={'course_id': unicode(self.course.id)})\n set_course_cohort_settings(self.course.id, is_cohorted=is_cohorted)\n\n response = self.client.get(url, {})\n res_json = json.loads(response.content)\n\n self.assertEqual('cohort' in res_json['feature_names'], is_cohorted)", "label_name": "CWE-352", "label": 0} {"code": " def test_modify_access_revoke_not_allowed(self):\n \"\"\" Test revoking access that a user does not have. \"\"\"\n url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'unique_student_identifier': self.other_staff.email,\n 'rolename': 'instructor',\n 'action': 'revoke',\n })\n self.assertEqual(response.status_code, 200)", "label_name": "CWE-352", "label": 0} {"code": " def test_rescore_entrance_exam_single_student(self, act):\n \"\"\" Test re-scoring of entrance exam for single student. \"\"\"\n url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)})\n response = self.client.get(url, {\n 'unique_student_identifier': self.student.email,\n })\n self.assertEqual(response.status_code, 200)\n self.assertTrue(act.called)", "label_name": "CWE-352", "label": 0} {"code": " def test_get_ora2_responses_already_running(self):\n url = reverse('export_ora2_data', kwargs={'course_id': unicode(self.course.id)})\n\n with patch('instructor_task.api.submit_export_ora2_data') as mock_submit_ora2_task:\n mock_submit_ora2_task.side_effect = AlreadyRunningError()\n response = self.client.get(url, {})\n already_running_status = \"An ORA data report generation task is already in progress.\"\n self.assertIn(already_running_status, response.content)", "label_name": "CWE-352", "label": 0} {"code": " def test_modify_access_revoke_self(self):\n \"\"\"\n Test that an instructor cannot remove instructor privelages from themself.\n \"\"\"\n url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'unique_student_identifier': self.instructor.email,\n 'rolename': 'instructor',\n 'action': 'revoke',\n })\n self.assertEqual(response.status_code, 200)\n # check response content\n expected = {\n 'unique_student_identifier': self.instructor.username,\n 'rolename': 'instructor',\n 'action': 'revoke',\n 'removingSelfAsInstructor': True,\n }\n res_json = json.loads(response.content)\n self.assertEqual(res_json, expected)", "label_name": "CWE-352", "label": 0} {"code": " def test_list_report_downloads(self):\n url = reverse('list_report_downloads', kwargs={'course_id': self.course.id.to_deprecated_string()})\n with patch('instructor_task.models.LocalFSReportStore.links_for') as mock_links_for:\n mock_links_for.return_value = [\n ('mock_file_name_1', 'https://1.mock.url'),\n ('mock_file_name_2', 'https://2.mock.url'),\n ]\n response = self.client.get(url, {})\n\n expected_response = {\n \"downloads\": [\n {\n \"url\": \"https://1.mock.url\",\n \"link\": \"mock_file_name_1\",\n \"name\": \"mock_file_name_1\"\n },\n {\n \"url\": \"https://2.mock.url\",\n \"link\": \"mock_file_name_2\",\n \"name\": \"mock_file_name_2\"\n }\n ]\n }\n res_json = json.loads(response.content)\n self.assertEqual(res_json, expected_response)", "label_name": "CWE-352", "label": 0} {"code": " def test_entrance_exam_sttudent_delete_state(self):\n \"\"\" Test delete single student entrance exam state. \"\"\"\n url = reverse('reset_student_attempts_for_entrance_exam',\n kwargs={'course_id': unicode(self.course.id)})\n response = self.client.get(url, {\n 'unique_student_identifier': self.student.email,\n 'delete_module': True,\n })\n self.assertEqual(response.status_code, 200)\n # make sure the module has been deleted\n changed_modules = StudentModule.objects.filter(module_state_key__in=self.ee_modules)\n self.assertEqual(changed_modules.count(), 0)", "label_name": "CWE-352", "label": 0} {"code": "def test_get_delete_dataobj_not_found(test_app, client: FlaskClient):\n response = client.get(\"/dataobj/delete/1\")\n assert response.status_code == 302", "label_name": "CWE-352", "label": 0} {"code": " def test_dir(self, tmpdir):\n url = QUrl.fromLocalFile(str(tmpdir))\n req = QNetworkRequest(url)\n reply = filescheme.handler(req)\n # The URL will always use /, even on Windows - so we force this here\n # too.\n tmpdir_path = str(tmpdir).replace(os.sep, '/')\n assert reply.readAll() == filescheme.dirbrowser_html(tmpdir_path)", "label_name": "CWE-352", "label": 0} {"code": " def test_modify_access_noparams(self):\n \"\"\" Test missing all query parameters. \"\"\"\n url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 400)", "label_name": "CWE-352", "label": 0} {"code": " def test_certificates_features_csv(self):\n \"\"\"\n Test for certificate csv features.\n \"\"\"\n url = reverse('get_issued_certificates', kwargs={'course_id': unicode(self.course.id)})\n url += '?csv=true'\n # firstly generating downloadable certificates with 'honor' mode\n certificate_count = 3\n for __ in xrange(certificate_count):\n self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.downloadable)\n\n current_date = datetime.date.today().strftime(\"%B %d, %Y\")\n response = self.client.get(url)\n self.assertEqual(response['Content-Type'], 'text/csv')\n self.assertEqual(response['Content-Disposition'], 'attachment; filename={0}'.format('issued_certificates.csv'))\n self.assertEqual(\n response.content.strip(),\n '\"CourseID\",\"Certificate Type\",\"Total Certificates Issued\",\"Date Report Run\"\\r\\n\"'\n + str(self.course.id) + '\",\"honor\",\"3\",\"' + current_date + '\"'\n )", "label_name": "CWE-352", "label": 0} {"code": " def test_get_sale_records_features_json(self):\n \"\"\"\n Test that the response from get_sale_records is in json format.\n \"\"\"\n for i in range(5):\n course_registration_code = CourseRegistrationCode(\n code='sale_invoice{}'.format(i),\n course_id=self.course.id.to_deprecated_string(),\n created_by=self.instructor,\n invoice=self.sale_invoice_1,\n invoice_item=self.invoice_item,\n mode_slug='honor'\n )\n course_registration_code.save()\n\n url = reverse('get_sale_records', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {})\n res_json = json.loads(response.content)\n self.assertIn('sale', res_json)\n\n for res in res_json['sale']:\n self.validate_sale_records_response(\n res,\n course_registration_code,\n self.sale_invoice_1,\n 0,\n invoice_item=self.invoice_item\n )", "label_name": "CWE-352", "label": 0} {"code": " def wrapped(*args, **kwargs): # pylint: disable=missing-docstring\n request = args[0]\n\n error_response_data = {\n 'error': 'Missing required query parameter(s)',\n 'parameters': [],\n 'info': {},\n }\n\n for (param, extra) in required_params:\n default = object()\n if request.GET.get(param, default) == default:\n error_response_data['parameters'].append(param)\n error_response_data['info'][param] = extra\n\n if len(error_response_data['parameters']) > 0:\n return JsonResponse(error_response_data, status=400)\n else:\n return func(*args, **kwargs)", "label_name": "CWE-352", "label": 0} {"code": "def shutdown():\n task = int(request.args.get(\"parameter\").strip())\n showtext = {}\n if task in (0, 1): # valid commandos received\n # close all database connections\n calibre_db.dispose()\n ub.dispose()\n\n if task == 0:\n showtext['text'] = _(u'Server restarted, please reload page')\n else:\n showtext['text'] = _(u'Performing shutdown of server, please close window')\n # stop gevent/tornado server\n web_server.stop(task == 0)\n return json.dumps(showtext)\n\n if task == 2:\n log.warning(\"reconnecting to calibre database\")\n calibre_db.reconnect_db(config, ub.app_DB_path)\n showtext['text'] = _(u'Reconnect successful')\n return json.dumps(showtext)\n\n showtext['text'] = _(u'Unknown command')\n return json.dumps(showtext), 400", "label_name": "CWE-352", "label": 0} {"code": "def test_qute_settings_persistence(short_tmpdir, request, quteproc_new):\n \"\"\"Make sure settings from qute://settings are persistent.\"\"\"\n args = _base_args(request.config) + ['--basedir', str(short_tmpdir)]\n quteproc_new.start(args)\n quteproc_new.open_path(\n 'qute://settings/set?option=search.ignore_case&value=always')\n assert quteproc_new.get_setting('search.ignore_case') == 'always'\n\n quteproc_new.send_cmd(':quit')\n quteproc_new.wait_for_quit()\n\n quteproc_new.start(args)\n assert quteproc_new.get_setting('search.ignore_case') == 'always'", "label_name": "CWE-352", "label": 0} {"code": " def test_list_instructor_tasks_running(self, act):\n \"\"\" Test list of all running tasks. \"\"\"\n act.return_value = self.tasks\n url = reverse('list_instructor_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()})\n mock_factory = MockCompletionInfo()\n with patch('instructor.views.instructor_task_helpers.get_task_completion_info') as mock_completion_info:\n mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info\n response = self.client.get(url, {})\n self.assertEqual(response.status_code, 200)\n\n # check response\n self.assertTrue(act.called)\n expected_tasks = [ftask.to_dict() for ftask in self.tasks]\n actual_tasks = json.loads(response.content)['tasks']\n for exp_task, act_task in zip(expected_tasks, actual_tasks):\n self.assertDictEqual(exp_task, act_task)\n self.assertEqual(actual_tasks, expected_tasks)", "label_name": "CWE-352", "label": 0} {"code": " def test_list_course_role_members_beta(self):\n url = reverse('list_course_role_members', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'rolename': 'beta',\n })\n self.assertEqual(response.status_code, 200)\n\n # check response content\n expected = {\n 'course_id': self.course.id.to_deprecated_string(),\n 'beta': []\n }\n res_json = json.loads(response.content)\n self.assertEqual(res_json, expected)", "label_name": "CWE-352", "label": 0} {"code": "def reset_due_date(request, course_id):\n \"\"\"\n Rescinds a due date extension for a student on a particular unit.\n \"\"\"\n course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id))\n student = require_student_from_identifier(request.GET.get('student'))\n unit = find_unit(course, request.GET.get('url'))\n set_due_date_extension(course, unit, student, None)\n if not getattr(unit, \"due\", None):\n # It's possible the normal due date was deleted after an extension was granted:\n return JsonResponse(\n _(\"Successfully removed invalid due date extension (unit has no due date).\")\n )\n\n original_due_date_str = unit.due.strftime('%Y-%m-%d %H:%M')\n return JsonResponse(_(\n 'Successfully reset due date for student {0} for {1} '\n 'to {2}').format(student.profile.name, _display_unit(unit),\n original_due_date_str))", "label_name": "CWE-352", "label": 0} {"code": " def test_reset_entrance_exam_student_attempts_single(self):\n \"\"\" Test reset single student attempts for entrance exam. \"\"\"\n url = reverse('reset_student_attempts_for_entrance_exam',\n kwargs={'course_id': unicode(self.course.id)})\n response = self.client.get(url, {\n 'unique_student_identifier': self.student.email,\n })\n self.assertEqual(response.status_code, 200)\n # make sure problem attempts have been reset.\n changed_modules = StudentModule.objects.filter(module_state_key__in=self.ee_modules)\n for changed_module in changed_modules:\n self.assertEqual(\n json.loads(changed_module.state)['attempts'],\n 0\n )", "label_name": "CWE-352", "label": 0} {"code": " def test_show_unit_extensions(self):\n self.test_change_due_date()\n url = reverse('show_unit_extensions',\n kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {'url': self.week1.location.to_deprecated_string()})\n self.assertEqual(response.status_code, 200, response.content)\n self.assertEqual(json.loads(response.content), {\n u'data': [{u'Extended Due Date': u'2013-12-30 00:00',\n u'Full Name': self.user1.profile.name,\n u'Username': self.user1.username}],\n u'header': [u'Username', u'Full Name', u'Extended Due Date'],\n u'title': u'Users with due date extensions for %s' %\n self.week1.display_name})", "label_name": "CWE-352", "label": 0} {"code": " def test_rescore_entrance_exam_all_student_and_single(self):\n \"\"\" Test re-scoring with both all students and single student parameters. \"\"\"\n url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)})\n response = self.client.get(url, {\n 'unique_student_identifier': self.student.email,\n 'all_students': True,\n })\n self.assertEqual(response.status_code, 400)", "label_name": "CWE-352", "label": 0} {"code": "def add_security_headers(resp):\n resp.headers['Content-Security-Policy'] = \"default-src 'self' 'unsafe-inline' 'unsafe-eval';\"\n if request.endpoint == \"editbook.edit_book\":\n resp.headers['Content-Security-Policy'] += \"img-src * data:\"\n resp.headers['X-Content-Type-Options'] = 'nosniff'\n resp.headers['X-Frame-Options'] = 'SAMEORIGIN'\n resp.headers['X-XSS-Protection'] = '1; mode=block'\n resp.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n # log.debug(request.full_path)\n return resp", "label_name": "CWE-352", "label": 0} {"code": " def test_change_nonexistent_due_date(self):\n url = reverse('change_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'student': self.user1.username,\n 'url': self.week3.location.to_deprecated_string(),\n 'due_datetime': '12/30/2013 00:00'\n })\n self.assertEqual(response.status_code, 400, response.content)\n self.assertEqual(\n None,\n get_extended_due(self.course, self.week3, self.user1)\n )", "label_name": "CWE-352", "label": 0} {"code": " def test_change_due_date(self):\n url = reverse('change_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'student': self.user1.username,\n 'url': self.week1.location.to_deprecated_string(),\n 'due_datetime': '12/30/2013 00:00'\n })\n self.assertEqual(response.status_code, 200, response.content)\n self.assertEqual(datetime.datetime(2013, 12, 30, 0, 0, tzinfo=utc),\n get_extended_due(self.course, self.week1, self.user1))", "label_name": "CWE-352", "label": 0} {"code": " def test_list_instructor_tasks_problem(self, act):\n \"\"\" Test list task history for problem. \"\"\"\n act.return_value = self.tasks\n url = reverse('list_instructor_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()})\n mock_factory = MockCompletionInfo()\n with patch('instructor.views.instructor_task_helpers.get_task_completion_info') as mock_completion_info:\n mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info\n response = self.client.get(url, {\n 'problem_location_str': self.problem_urlname,\n })\n self.assertEqual(response.status_code, 200)\n\n # check response\n self.assertTrue(act.called)\n expected_tasks = [ftask.to_dict() for ftask in self.tasks]\n actual_tasks = json.loads(response.content)['tasks']\n for exp_task, act_task in zip(expected_tasks, actual_tasks):\n self.assertDictEqual(exp_task, act_task)\n self.assertEqual(actual_tasks, expected_tasks)", "label_name": "CWE-352", "label": 0} {"code": "def get_student_progress_url(request, course_id):\n \"\"\"\n Get the progress url of a student.\n Limited to staff access.\n\n Takes query paremeter unique_student_identifier and if the student exists\n returns e.g. {\n 'progress_url': '/../...'\n }\n \"\"\"\n course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)\n user = get_student_from_identifier(request.GET.get('unique_student_identifier'))\n\n progress_url = reverse('student_progress', kwargs={'course_id': course_id.to_deprecated_string(), 'student_id': user.id})\n\n response_payload = {\n 'course_id': course_id.to_deprecated_string(),\n 'progress_url': progress_url,\n }\n return JsonResponse(response_payload)", "label_name": "CWE-352", "label": 0} {"code": " def test_reset_entrance_exam_all_student_attempts(self, act):\n \"\"\" Test reset all student attempts for entrance exam. \"\"\"\n url = reverse('reset_student_attempts_for_entrance_exam',\n kwargs={'course_id': unicode(self.course.id)})\n response = self.client.get(url, {\n 'all_students': True,\n })\n self.assertEqual(response.status_code, 200)\n self.assertTrue(act.called)", "label_name": "CWE-352", "label": 0} {"code": "def list_entrance_exam_instructor_tasks(request, course_id): # pylint: disable=invalid-name\n \"\"\"\n List entrance exam related instructor tasks.\n\n Takes either of the following query parameters\n - unique_student_identifier is an email or username\n - all_students is a boolean\n \"\"\"\n course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)\n course = get_course_by_id(course_id)\n student = request.GET.get('unique_student_identifier', None)\n if student is not None:\n student = get_student_from_identifier(student)\n\n try:\n entrance_exam_key = course_id.make_usage_key_from_deprecated_string(course.entrance_exam_id)\n except InvalidKeyError:\n return HttpResponseBadRequest(_(\"Course has no valid entrance exam section.\"))\n if student:\n # Specifying for a single student's entrance exam history\n tasks = instructor_task.api.get_entrance_exam_instructor_task_history(course_id, entrance_exam_key, student)\n else:\n # Specifying for all student's entrance exam history\n tasks = instructor_task.api.get_entrance_exam_instructor_task_history(course_id, entrance_exam_key)\n\n response_payload = {\n 'tasks': map(extract_task_features, tasks),\n }\n return JsonResponse(response_payload)", "label_name": "CWE-352", "label": 0} {"code": " def test_entrance_exam_delete_state_with_staff(self):\n \"\"\" Test entrance exam delete state failure with staff access. \"\"\"\n self.client.logout()\n staff_user = StaffFactory(course_key=self.course.id)\n self.client.login(username=staff_user.username, password='test')\n url = reverse('reset_student_attempts_for_entrance_exam',\n kwargs={'course_id': unicode(self.course.id)})\n response = self.client.get(url, {\n 'unique_student_identifier': self.student.email,\n 'delete_module': True,\n })\n self.assertEqual(response.status_code, 403)", "label_name": "CWE-352", "label": 0} {"code": " def test_reset_entrance_exam_student_attempts_deletall(self):\n \"\"\" Make sure no one can delete all students state on entrance exam. \"\"\"\n url = reverse('reset_student_attempts_for_entrance_exam',\n kwargs={'course_id': unicode(self.course.id)})\n response = self.client.get(url, {\n 'all_students': True,\n 'delete_module': True,\n })\n self.assertEqual(response.status_code, 400)", "label_name": "CWE-352", "label": 0} {"code": " def test_modify_access_revoke_with_username(self):\n url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'unique_student_identifier': self.other_staff.username,\n 'rolename': 'staff',\n 'action': 'revoke',\n })\n self.assertEqual(response.status_code, 200)", "label_name": "CWE-352", "label": 0} {"code": " def test_get_student_progress_url_noparams(self):\n \"\"\" Test that the endpoint 404's without the required query params. \"\"\"\n url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 400)", "label_name": "CWE-352", "label": 0} {"code": " def test_entrance_exam_reset_student_attempts_nonsense(self):\n \"\"\" Test failure with both unique_student_identifier and all_students. \"\"\"\n url = reverse('reset_student_attempts_for_entrance_exam',\n kwargs={'course_id': unicode(self.course.id)})\n response = self.client.get(url, {\n 'unique_student_identifier': self.student.email,\n 'all_students': True,\n })\n self.assertEqual(response.status_code, 400)", "label_name": "CWE-352", "label": 0} {"code": " def test_get_students_features_teams(self, has_teams):\n \"\"\"\n Test that get_students_features includes team info when the course is\n has teams enabled, and does not when the course does not have teams enabled\n \"\"\"\n if has_teams:\n self.course = CourseFactory.create(teams_configuration={\n 'max_size': 2, 'topics': [{'topic-id': 'topic', 'name': 'Topic', 'description': 'A Topic'}]\n })\n course_instructor = InstructorFactory(course_key=self.course.id)\n self.client.login(username=course_instructor.username, password='test')\n\n url = reverse('get_students_features', kwargs={'course_id': unicode(self.course.id)})\n\n response = self.client.get(url, {})\n res_json = json.loads(response.content)\n\n self.assertEqual('team' in res_json['feature_names'], has_teams)", "label_name": "CWE-352", "label": 0} {"code": " def test_get_student_progress_url_from_uname(self):\n \"\"\" Test that progress_url is in the successful response. \"\"\"\n url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()})\n url += \"?unique_student_identifier={}\".format(\n quote(self.students[0].username.encode(\"utf-8\"))\n )\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n res_json = json.loads(response.content)\n self.assertIn('progress_url', res_json)", "label_name": "CWE-352", "label": 0} {"code": "def show_unit_extensions(request, course_id):\n \"\"\"\n Shows all of the students which have due date extensions for the given unit.\n \"\"\"\n course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id))\n unit = find_unit(course, request.GET.get('url'))\n return JsonResponse(dump_module_extensions(course, unit))", "label_name": "CWE-352", "label": 0} {"code": " def test_rescore_problem_single_from_uname(self, act):\n \"\"\" Test rescoring of a single student. \"\"\"\n url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'problem_to_reset': self.problem_urlname,\n 'unique_student_identifier': self.student.username,\n })\n self.assertEqual(response.status_code, 200)\n self.assertTrue(act.called)", "label_name": "CWE-352", "label": 0} {"code": "def rescore_problem(request, course_id):\n \"\"\"\n Starts a background process a students attempts counter. Optionally deletes student state for a problem.\n Limited to instructor access.\n\n Takes either of the following query paremeters\n - problem_to_reset is a urlname of a problem\n - unique_student_identifier is an email or username\n - all_students is a boolean\n\n all_students and unique_student_identifier cannot both be present.\n \"\"\"\n course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)\n problem_to_reset = strip_if_string(request.GET.get('problem_to_reset'))\n student_identifier = request.GET.get('unique_student_identifier', None)\n student = None\n if student_identifier is not None:\n student = get_student_from_identifier(student_identifier)\n\n all_students = request.GET.get('all_students') in ['true', 'True', True]\n\n if not (problem_to_reset and (all_students or student)):\n return HttpResponseBadRequest(\"Missing query parameters.\")\n\n if all_students and student:\n return HttpResponseBadRequest(\n \"Cannot rescore with all_students and unique_student_identifier.\"\n )\n\n try:\n module_state_key = course_id.make_usage_key_from_deprecated_string(problem_to_reset)\n except InvalidKeyError:\n return HttpResponseBadRequest(\"Unable to parse problem id\")\n\n response_payload = {}\n response_payload['problem_to_reset'] = problem_to_reset\n\n if student:\n response_payload['student'] = student_identifier\n instructor_task.api.submit_rescore_problem_for_student(request, module_state_key, student)\n response_payload['task'] = 'created'\n elif all_students:\n instructor_task.api.submit_rescore_problem_for_all_students(request, module_state_key)\n response_payload['task'] = 'created'\n else:\n return HttpResponseBadRequest()\n\n return JsonResponse(response_payload)", "label_name": "CWE-352", "label": 0} {"code": "def test_post_broken_body():\n response = client.post(\"/items/\", data={\"name\": \"Foo\", \"price\": 50.5})\n assert response.status_code == 422, response.text\n assert response.json() == {\n \"detail\": [\n {\n \"ctx\": {\n \"colno\": 1,\n \"doc\": \"name=Foo&price=50.5\",\n \"lineno\": 1,\n \"msg\": \"Expecting value\",\n \"pos\": 0,\n },\n \"loc\": [\"body\", 0],\n \"msg\": \"Expecting value: line 1 column 1 (char 0)\",\n \"type\": \"value_error.jsondecode\",\n }\n ]\n }\n with patch(\"json.loads\", side_effect=Exception):\n response = client.post(\"/items/\", json={\"test\": \"test2\"})\n assert response.status_code == 400, response.text\n assert response.json() == {\"detail\": \"There was an error parsing the body\"}", "label_name": "CWE-352", "label": 0} {"code": " def test_certificates_features_group_by_mode(self):\n \"\"\"\n Test for certificate csv features against mode. Certificates should be group by 'mode' in reponse.\n \"\"\"\n url = reverse('get_issued_certificates', kwargs={'course_id': unicode(self.course.id)})\n # firstly generating downloadable certificates with 'honor' mode\n certificate_count = 3\n for __ in xrange(certificate_count):\n self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.downloadable)\n\n response = self.client.get(url)\n res_json = json.loads(response.content)\n self.assertIn('certificates', res_json)\n self.assertEqual(len(res_json['certificates']), 1)\n\n # retrieve the first certificate from the list, there should be 3 certificates for 'honor' mode.\n certificate = res_json['certificates'][0]\n self.assertEqual(certificate.get('total_issued_certificate'), 3)\n self.assertEqual(certificate.get('mode'), 'honor')\n self.assertEqual(certificate.get('course_id'), str(self.course.id))\n\n # Now generating downloadable certificates with 'verified' mode\n for __ in xrange(certificate_count):\n self.generate_certificate(\n course_id=self.course.id,\n mode='verified',\n status=CertificateStatuses.downloadable\n )\n\n response = self.client.get(url)\n res_json = json.loads(response.content)\n self.assertIn('certificates', res_json)\n\n # total certificate count should be 2 for 'verified' mode.\n self.assertEqual(len(res_json['certificates']), 2)\n\n # retrieve the second certificate from the list\n certificate = res_json['certificates'][1]\n self.assertEqual(certificate.get('total_issued_certificate'), 3)\n self.assertEqual(certificate.get('mode'), 'verified')", "label_name": "CWE-352", "label": 0} {"code": " def test_list_email_with_no_successes(self, task_history_request):\n task_info = FakeContentTask(0, 0, 10, 'expected')\n email = FakeEmail(0)\n email_info = FakeEmailInfo(email, 0, 10)\n task_history_request.return_value = [task_info]\n url = reverse('list_email_content', kwargs={'course_id': self.course.id.to_deprecated_string()})\n with patch('instructor.views.api.CourseEmail.objects.get') as mock_email_info:\n mock_email_info.return_value = email\n response = self.client.get(url, {})\n self.assertEqual(response.status_code, 200)\n\n self.assertTrue(task_history_request.called)\n returned_info_list = json.loads(response.content)['emails']\n\n self.assertEqual(len(returned_info_list), 1)\n returned_info = returned_info_list[0]\n expected_info = email_info.to_dict()\n self.assertDictEqual(expected_info, returned_info)", "label_name": "CWE-352", "label": 0} {"code": "def get_problem_responses(request, course_id):\n \"\"\"\n Initiate generation of a CSV file containing all student answers\n to a given problem.\n\n Responds with JSON\n {\"status\": \"... status message ...\"}\n\n if initiation is successful (or generation task is already running).\n\n Responds with BadRequest if problem location is faulty.\n \"\"\"\n course_key = CourseKey.from_string(course_id)\n problem_location = request.GET.get('problem_location', '')\n\n try:\n problem_key = UsageKey.from_string(problem_location)\n # Are we dealing with an \"old-style\" problem location?\n run = problem_key.run\n if not run:\n problem_key = course_key.make_usage_key_from_deprecated_string(problem_location)\n if problem_key.course_key != course_key:\n raise InvalidKeyError(type(problem_key), problem_key)\n except InvalidKeyError:\n return JsonResponseBadRequest(_(\"Could not find problem with this location.\"))\n\n try:\n instructor_task.api.submit_calculate_problem_responses_csv(request, course_key, problem_location)\n success_status = _(\n \"The problem responses report is being created.\"\n \" To view the status of the report, see Pending Tasks below.\"\n )\n return JsonResponse({\"status\": success_status})\n except AlreadyRunningError:\n already_running_status = _(\n \"A problem responses report generation task is already in progress. \"\n \"Check the 'Pending Tasks' table for the status of the task. \"\n \"When completed, the report will be available for download in the table below.\"\n )\n return JsonResponse({\"status\": already_running_status})", "label_name": "CWE-352", "label": 0} {"code": "def change_due_date(request, course_id):\n \"\"\"\n Grants a due date extension to a student for a particular unit.\n \"\"\"\n course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id))\n student = require_student_from_identifier(request.GET.get('student'))\n unit = find_unit(course, request.GET.get('url'))\n due_date = parse_datetime(request.GET.get('due_datetime'))\n set_due_date_extension(course, unit, student, due_date)\n\n return JsonResponse(_(\n 'Successfully changed due date for student {0} for {1} '\n 'to {2}').format(student.profile.name, _display_unit(unit),\n due_date.strftime('%Y-%m-%d %H:%M')))", "label_name": "CWE-352", "label": 0} {"code": " def test_modify_access_allow(self):\n url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'unique_student_identifier': self.other_user.email,\n 'rolename': 'staff',\n 'action': 'allow',\n })\n self.assertEqual(response.status_code, 200)", "label_name": "CWE-352", "label": 0} {"code": " def test_list_background_email_tasks(self, act):\n \"\"\"Test list of background email tasks.\"\"\"\n act.return_value = self.tasks\n url = reverse('list_background_email_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()})\n mock_factory = MockCompletionInfo()\n with patch('instructor.views.instructor_task_helpers.get_task_completion_info') as mock_completion_info:\n mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info\n response = self.client.get(url, {})\n self.assertEqual(response.status_code, 200)\n\n # check response\n self.assertTrue(act.called)\n expected_tasks = [ftask.to_dict() for ftask in self.tasks]\n actual_tasks = json.loads(response.content)['tasks']\n for exp_task, act_task in zip(expected_tasks, actual_tasks):\n self.assertDictEqual(exp_task, act_task)\n self.assertEqual(actual_tasks, expected_tasks)", "label_name": "CWE-352", "label": 0} {"code": " def test_get_problem_responses_successful(self):\n \"\"\"\n Test whether get_problem_responses returns an appropriate status\n message if CSV generation was started successfully.\n \"\"\"\n url = reverse(\n 'get_problem_responses',\n kwargs={'course_id': unicode(self.course.id)}\n )\n problem_location = ''\n\n response = self.client.get(url, {'problem_location': problem_location})\n res_json = json.loads(response.content)\n self.assertIn('status', res_json)\n status = res_json['status']\n self.assertIn('is being created', status)\n self.assertNotIn('already in progress', status)", "label_name": "CWE-352", "label": 0} {"code": " def test_modify_access_bad_role(self):\n \"\"\" Test with an invalid action parameter. \"\"\"\n url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'unique_student_identifier': self.other_staff.email,\n 'rolename': 'robot-not-a-roll',\n 'action': 'revoke',\n })\n self.assertEqual(response.status_code, 400)", "label_name": "CWE-352", "label": 0} {"code": " def call_add_users_to_cohorts(self, csv_data, suffix='.csv', method='POST'):\n \"\"\"\n Call `add_users_to_cohorts` with a file generated from `csv_data`.\n \"\"\"\n # this temporary file will be removed in `self.tearDown()`\n __, file_name = tempfile.mkstemp(suffix=suffix, dir=self.tempdir)\n with open(file_name, 'w') as file_pointer:\n file_pointer.write(csv_data.encode('utf-8'))\n with open(file_name, 'r') as file_pointer:\n url = reverse('add_users_to_cohorts', kwargs={'course_id': unicode(self.course.id)})\n if method == 'POST':\n return self.client.post(url, {'uploaded-file': file_pointer})\n elif method == 'GET':\n return self.client.get(url, {'uploaded-file': file_pointer})", "label_name": "CWE-352", "label": 0} {"code": "def show_student_extensions(request, course_id):\n \"\"\"\n Shows all of the due date extensions granted to a particular student in a\n particular course.\n \"\"\"\n student = require_student_from_identifier(request.GET.get('student'))\n course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id))\n return JsonResponse(dump_student_extensions(course, student))", "label_name": "CWE-352", "label": 0} {"code": " def test_create_registration_code_without_invoice_and_order(self):\n \"\"\"\n test generate detailed enrollment report,\n used a registration codes which has been created via invoice or bulk\n purchase scenario.\n \"\"\"\n course_registration_code = CourseRegistrationCode.objects.create(\n code='abcde',\n course_id=self.course.id.to_deprecated_string(),\n created_by=self.instructor,\n mode_slug='honor'\n )\n test_user1 = UserFactory()\n self.register_with_redemption_code(test_user1, course_registration_code.code)\n\n CourseFinanceAdminRole(self.course.id).add_users(self.instructor)\n self.client.login(username=self.instructor.username, password='test')\n\n url = reverse('get_enrollment_report', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {})\n self.assertIn('The detailed enrollment report is being created.', response.content)", "label_name": "CWE-352", "label": 0} {"code": "def rescore_entrance_exam(request, course_id):\n \"\"\"\n Starts a background process a students attempts counter for entrance exam.\n Optionally deletes student state for a problem. Limited to instructor access.\n\n Takes either of the following query parameters\n - unique_student_identifier is an email or username\n - all_students is a boolean\n\n all_students and unique_student_identifier cannot both be present.\n \"\"\"\n course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)\n course = get_course_with_access(\n request.user, 'staff', course_id, depth=None\n )\n\n student_identifier = request.GET.get('unique_student_identifier', None)\n student = None\n if student_identifier is not None:\n student = get_student_from_identifier(student_identifier)\n\n all_students = request.GET.get('all_students') in ['true', 'True', True]\n\n if not course.entrance_exam_id:\n return HttpResponseBadRequest(\n _(\"Course has no entrance exam section.\")\n )\n\n if all_students and student:\n return HttpResponseBadRequest(\n _(\"Cannot rescore with all_students and unique_student_identifier.\")\n )\n\n try:\n entrance_exam_key = course_id.make_usage_key_from_deprecated_string(course.entrance_exam_id)\n except InvalidKeyError:\n return HttpResponseBadRequest(_(\"Course has no valid entrance exam section.\"))\n\n response_payload = {}\n if student:\n response_payload['student'] = student_identifier\n else:\n response_payload['student'] = _(\"All Students\")\n instructor_task.api.submit_rescore_entrance_exam_for_student(request, entrance_exam_key, student)\n response_payload['task'] = 'created'\n return JsonResponse(response_payload)", "label_name": "CWE-352", "label": 0} {"code": " def test_unicode_encode_error(self, mocker):\n url = QUrl('file:///tmp/foo')\n req = QNetworkRequest(url)\n\n err = UnicodeEncodeError('ascii', '', 0, 2, 'foo')\n mocker.patch('os.path.isdir', side_effect=err)\n\n reply = filescheme.handler(req)\n assert reply is None", "label_name": "CWE-352", "label": 0} {"code": " def _access_endpoint(self, endpoint, args, status_code, msg):\n \"\"\"\n Asserts that accessing the given `endpoint` gets a response of `status_code`.\n\n endpoint: string, endpoint for instructor dash API\n args: dict, kwargs for `reverse` call\n status_code: expected HTTP status code response\n msg: message to display if assertion fails.\n \"\"\"\n url = reverse(endpoint, kwargs={'course_id': self.course.id.to_deprecated_string()})\n if endpoint in ['send_email', 'students_update_enrollment', 'bulk_beta_modify_access']:\n response = self.client.post(url, args)\n else:\n response = self.client.get(url, args)\n self.assertEqual(\n response.status_code,\n status_code,\n msg=msg\n )", "label_name": "CWE-352", "label": 0} {"code": " def test_list_course_role_members_bad_rolename(self):\n \"\"\" Test with an invalid rolename parameter. \"\"\"\n url = reverse('list_course_role_members', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'rolename': 'robot-not-a-rolename',\n })\n self.assertEqual(response.status_code, 400)", "label_name": "CWE-352", "label": 0} {"code": " def test_rescore_problem_single(self, act):\n \"\"\" Test rescoring of a single student. \"\"\"\n url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'problem_to_reset': self.problem_urlname,\n 'unique_student_identifier': self.student.email,\n })\n self.assertEqual(response.status_code, 200)\n self.assertTrue(act.called)", "label_name": "CWE-352", "label": 0} {"code": " def test_coupon_redeem_count_in_ecommerce_section(self):\n \"\"\"\n Test that checks the redeem count in the instructor_dashboard coupon section\n \"\"\"\n # add the coupon code for the course\n coupon = Coupon(\n code='test_code', description='test_description', course_id=self.course.id,\n percentage_discount='10', created_by=self.instructor, is_active=True\n )\n coupon.save()\n\n # Coupon Redeem Count only visible for Financial Admins.\n CourseFinanceAdminRole(self.course.id).add_users(self.instructor)\n\n PaidCourseRegistration.add_to_order(self.cart, self.course.id)\n # apply the coupon code to the item in the cart\n resp = self.client.post(reverse('shoppingcart.views.use_code'), {'code': coupon.code})\n self.assertEqual(resp.status_code, 200)\n\n # URL for instructor dashboard\n instructor_dashboard = reverse('instructor_dashboard', kwargs={'course_id': self.course.id.to_deprecated_string()})\n # visit the instructor dashboard page and\n # check that the coupon redeem count should be 0\n resp = self.client.get(instructor_dashboard)\n self.assertEqual(resp.status_code, 200)\n self.assertIn('Number Redeemed', resp.content)\n self.assertIn('0', resp.content)\n\n # now make the payment of your cart items\n self.cart.purchase()\n # visit the instructor dashboard page and\n # check that the coupon redeem count should be 1\n resp = self.client.get(instructor_dashboard)\n self.assertEqual(resp.status_code, 200)\n\n self.assertIn('Number Redeemed', resp.content)\n self.assertIn('1', resp.content)", "label_name": "CWE-352", "label": 0} {"code": "def require_query_params(*args, **kwargs):\n \"\"\"\n Checks for required paremters or renders a 400 error.\n (decorator with arguments)\n\n `args` is a *list of required GET parameter names.\n `kwargs` is a **dict of required GET parameter names\n to string explanations of the parameter\n \"\"\"\n required_params = []\n required_params += [(arg, None) for arg in args]\n required_params += [(key, kwargs[key]) for key in kwargs]\n # required_params = e.g. [('action', 'enroll or unenroll'), ['emails', None]]\n\n def decorator(func): # pylint: disable=missing-docstring\n def wrapped(*args, **kwargs): # pylint: disable=missing-docstring\n request = args[0]\n\n error_response_data = {\n 'error': 'Missing required query parameter(s)',\n 'parameters': [],\n 'info': {},\n }\n\n for (param, extra) in required_params:\n default = object()\n if request.GET.get(param, default) == default:\n error_response_data['parameters'].append(param)\n error_response_data['info'][param] = extra\n\n if len(error_response_data['parameters']) > 0:\n return JsonResponse(error_response_data, status=400)\n else:\n return func(*args, **kwargs)\n return wrapped\n return decorator", "label_name": "CWE-352", "label": 0} {"code": " def test_rescore_entrance_exam_all_student(self):\n \"\"\" Test rescoring for all students. \"\"\"\n url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)})\n response = self.client.get(url, {\n 'all_students': True,\n })\n self.assertEqual(response.status_code, 200)", "label_name": "CWE-352", "label": 0} {"code": " def test_reset_student_attempts_all(self, act):\n \"\"\" Test reset all student attempts. \"\"\"\n url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'problem_to_reset': self.problem_urlname,\n 'all_students': True,\n })\n self.assertEqual(response.status_code, 200)\n self.assertTrue(act.called)", "label_name": "CWE-352", "label": 0} {"code": " def test_get_students_features(self):\n \"\"\"\n Test that some minimum of information is formatted\n correctly in the response to get_students_features.\n \"\"\"\n for student in self.students:\n student.profile.city = \"Mos Eisley {}\".format(student.id)\n student.profile.save()\n url = reverse('get_students_features', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {})\n res_json = json.loads(response.content)\n self.assertIn('students', res_json)\n for student in self.students:\n student_json = [\n x for x in res_json['students']\n if x['username'] == student.username\n ][0]\n self.assertEqual(student_json['username'], student.username)\n self.assertEqual(student_json['email'], student.email)\n self.assertEqual(student_json['city'], student.profile.city)\n self.assertEqual(student_json['country'], \"\")", "label_name": "CWE-352", "label": 0} {"code": "def handler(request):\n \"\"\"Handler for a file:// URL.\n\n Args:\n request: QNetworkRequest to answer to.\n\n Return:\n A QNetworkReply for directories, None for files.\n \"\"\"\n path = request.url().toLocalFile()\n try:\n if os.path.isdir(path):\n data = dirbrowser_html(path)\n return networkreply.FixedDataNetworkReply(\n request, data, 'text/html')\n return None\n except UnicodeEncodeError:\n return None", "label_name": "CWE-352", "label": 0} {"code": " def __init__(self):\r\n field_infos = [\r\n FieldInfo.factory(key)\r\n for key in list(request.form.keys()) + list(request.files.keys())\r\n ]\r\n # important to sort them so they will be in expected order on command line\r\n self.field_infos = list(sorted(field_infos))\r", "label_name": "CWE-352", "label": 0} {"code": " def test_get_problem_responses_already_running(self):\n \"\"\"\n Test whether get_problem_responses returns an appropriate status\n message if CSV generation is already in progress.\n \"\"\"\n url = reverse(\n 'get_problem_responses',\n kwargs={'course_id': unicode(self.course.id)}\n )\n\n with patch('instructor_task.api.submit_calculate_problem_responses_csv') as submit_task_function:\n error = AlreadyRunningError()\n submit_task_function.side_effect = error\n response = self.client.get(url, {})\n res_json = json.loads(response.content)\n self.assertIn('status', res_json)\n self.assertIn('already in progress', res_json['status'])", "label_name": "CWE-352", "label": 0} {"code": " def test_reset_student_attempts_nonsense(self):\n \"\"\" Test failure with both unique_student_identifier and all_students. \"\"\"\n url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'problem_to_reset': self.problem_urlname,\n 'unique_student_identifier': self.student.email,\n 'all_students': True,\n })\n self.assertEqual(response.status_code, 400)", "label_name": "CWE-352", "label": 0} {"code": " def test_reset_student_attempts_missingmodule(self):\n \"\"\" Test reset for non-existant problem. \"\"\"\n url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'problem_to_reset': 'robot-not-a-real-module',\n 'unique_student_identifier': self.student.email,\n })\n self.assertEqual(response.status_code, 400)", "label_name": "CWE-352", "label": 0} {"code": " def test_get_student_exam_results(self):\n \"\"\"\n Test whether get_proctored_exam_results returns an appropriate\n status message when users request a CSV file.\n \"\"\"\n url = reverse(\n 'get_proctored_exam_results',\n kwargs={'course_id': unicode(self.course.id)}\n )\n # Successful case:\n response = self.client.get(url, {})\n res_json = json.loads(response.content)\n self.assertIn('status', res_json)\n self.assertNotIn('currently being created', res_json['status'])\n # CSV generation already in progress:\n with patch('instructor_task.api.submit_proctored_exam_results_report') as submit_task_function:\n error = AlreadyRunningError()\n submit_task_function.side_effect = error\n response = self.client.get(url, {})\n res_json = json.loads(response.content)\n self.assertIn('status', res_json)\n self.assertIn('currently being created', res_json['status'])", "label_name": "CWE-352", "label": 0} {"code": " def test_get_problem_responses_invalid_location(self):\n \"\"\"\n Test whether get_problem_responses returns an appropriate status\n message when users submit an invalid problem location.\n \"\"\"\n url = reverse(\n 'get_problem_responses',\n kwargs={'course_id': unicode(self.course.id)}\n )\n problem_location = ''\n\n response = self.client.get(url, {'problem_location': problem_location})\n res_json = json.loads(response.content)\n self.assertEqual(res_json, 'Could not find problem with this location.')", "label_name": "CWE-352", "label": 0} {"code": " protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {\n\n resp.setContentType(\"application/json\");\n final PrintWriter out = resp.getWriter();\n\n HttpSession session = req.getSession(false);\n\n if (session != null) {\n Subject subject = (Subject) session.getAttribute(\"subject\");\n if (subject == null) {\n LOG.warn(\"No security subject stored in existing session, invalidating\");\n session.invalidate();\n Helpers.doForbidden(resp);\n }\n returnPrincipals(subject, out);\n return;\n }\n\n AccessControlContext acc = AccessController.getContext();\n Subject subject = Subject.getSubject(acc);\n\n if (subject == null) {\n Helpers.doForbidden(resp);\n return;\n }\n Set principals = subject.getPrincipals();\n\n String username = null;\n\n if (principals != null) {\n for (Principal principal : principals) {\n if (principal.getClass().getSimpleName().equals(\"UserPrincipal\")) {\n username = principal.getName();\n LOG.debug(\"Authorizing user {}\", username);\n }\n }\n }\n\n session = req.getSession(true);\n session.setAttribute(\"subject\", subject);\n session.setAttribute(\"user\", username);\n session.setAttribute(\"org.osgi.service.http.authentication.remote.user\", username);\n session.setAttribute(\"org.osgi.service.http.authentication.type\", HttpServletRequest.BASIC_AUTH);\n session.setAttribute(\"loginTime\", GregorianCalendar.getInstance().getTimeInMillis());\n if (timeout != null) {\n session.setMaxInactiveInterval(timeout);\n }\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Http session timeout for user {} is {} sec.\", username, session.getMaxInactiveInterval());\n }\n\n returnPrincipals(subject, out);\n }", "label_name": "CWE-352", "label": 0} {"code": " public void initWithCustomLogHandler() throws Exception {\n servlet = new AgentServlet();\n config = createMock(ServletConfig.class);\n context = createMock(ServletContext.class);\n\n HttpTestUtil.prepareServletConfigMock(config, new String[]{ConfigKey.LOGHANDLER_CLASS.getKeyValue(), CustomLogHandler.class.getName()});\n HttpTestUtil.prepareServletContextMock(context,null);\n\n expect(config.getServletContext()).andReturn(context).anyTimes();\n expect(config.getServletName()).andReturn(\"jolokia\").anyTimes();\n replay(config, context);\n\n servlet.init(config);\n servlet.destroy();\n\n assertTrue(CustomLogHandler.infoCount > 0);\n }", "label_name": "CWE-352", "label": 0} {"code": " public void accessDenied() {\n expect(backend.isRemoteAccessAllowed(\"localhost\",\"127.0.0.1\")).andReturn(false);\n replay(backend);\n\n handler.checkClientIPAccess(\"localhost\",\"127.0.0.1\");\n }", "label_name": "CWE-352", "label": 0} {"code": " private ModelAndView renameGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {\n \n String oldName = request.getParameter(\"groupName\");\n String newName = request.getParameter(\"newName\");\n \n if (StringUtils.hasText(oldName) && StringUtils.hasText(newName)) {\n m_groupRepository.renameGroup(oldName, newName);\n }\n \n return listGroups(request, response);\n }", "label_name": "CWE-352", "label": 0} {"code": " public void preflightCheck() {\n String origin = \"http://bla.com\";\n String headers =\"X-Data: Test\";\n expect(backend.isCorsAccessAllowed(origin)).andReturn(true);\n replay(backend);\n\n Map ret = handler.handleCorsPreflightRequest(origin, headers);\n assertEquals(ret.get(\"Access-Control-Allow-Origin\"),origin);\n }", "label_name": "CWE-352", "label": 0} {"code": " protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n\n HttpSession session = request.getSession(false);\n if (session == null) {\n AccessControlContext acc = AccessController.getContext();\n Subject subject = Subject.getSubject(acc);\n if (subject == null) {\n Helpers.doForbidden(response);\n return;\n }\n session = request.getSession(true);\n session.setAttribute(\"subject\", subject);\n } else {\n Subject subject = (Subject) session.getAttribute(\"subject\");\n if (subject == null) {\n session.invalidate();\n Helpers.doForbidden(response);\n return;\n }\n }\n\n String encoding = request.getHeader(\"Accept-Encoding\");\n boolean supportsGzip = (encoding != null && encoding.toLowerCase().indexOf(\"gzip\") > -1);\n SessionTerminal st = (SessionTerminal) session.getAttribute(\"terminal\");\n if (st == null || st.isClosed()) {\n st = new SessionTerminal(getCommandProcessor(), getThreadIO());\n session.setAttribute(\"terminal\", st);\n }\n String str = request.getParameter(\"k\");\n String f = request.getParameter(\"f\");\n String dump = st.handle(str, f != null && f.length() > 0);\n if (dump != null) {\n if (supportsGzip) {\n response.setHeader(\"Content-Encoding\", \"gzip\");\n response.setHeader(\"Content-Type\", \"text/html\");\n try {\n GZIPOutputStream gzos = new GZIPOutputStream(response.getOutputStream());\n gzos.write(dump.getBytes());\n gzos.close();\n } catch (IOException ie) {\n LOG.info(\"Exception writing response: \", ie);\n }\n } else {\n response.getOutputStream().write(dump.getBytes());\n }\n }\n }", "label_name": "CWE-352", "label": 0} {"code": " public void withRestrictor() throws InvalidSyntaxException, MalformedObjectNameException {\n setupRestrictor(new InnerRestrictor(true,false,true,false,true,false,true));\n assertTrue(restrictor.isHttpMethodAllowed(HttpMethod.GET));\n assertFalse(restrictor.isTypeAllowed(RequestType.EXEC));\n assertTrue(restrictor.isAttributeReadAllowed(new ObjectName(\"java.lang:type=Memory\"), \"HeapMemoryUsage\"));\n assertFalse(restrictor.isAttributeWriteAllowed(new ObjectName(\"java.lang:type=Memory\"), \"HeapMemoryUsage\"));\n assertTrue(restrictor.isOperationAllowed(new ObjectName(\"java.lang:type=Memory\"), \"gc\"));\n assertFalse(restrictor.isRemoteAccessAllowed(\"localhost\", \"127.0.0.1\"));\n assertTrue(restrictor.isCorsAccessAllowed(\"http://bla.com\"));\n }", "label_name": "CWE-352", "label": 0} {"code": " public boolean isCorsAccessAllowed(String pOrigin) {\n return restrictor.isCorsAccessAllowed(pOrigin);\n }", "label_name": "CWE-352", "label": 0} {"code": " public boolean isCorsAccessAllowed(String pOrigin) {\n return isAllowed;\n }", "label_name": "CWE-352", "label": 0} {"code": " public void preflightCheckNegative() {\n String origin = \"http://bla.com\";\n String headers =\"X-Data: Test\";\n expect(backend.isCorsAccessAllowed(origin)).andReturn(false);\n replay(backend);\n\n Map ret = handler.handleCorsPreflightRequest(origin, headers);\n assertNull(ret.get(\"Access-Control-Allow-Origin\"));\n }", "label_name": "CWE-352", "label": 0} {"code": " public void initWithAgentDiscoveryAndUrlCreationAfterGet() throws ServletException, IOException {\n checkMulticastAvailable();\n prepareStandardInitialisation(ConfigKey.DISCOVERY_ENABLED.getKeyValue(), \"true\");\n try {\n StringWriter sw = initRequestResponseMocks();\n expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);\n expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(\"text/plain\");\n String url = \"http://pirx:9876/jolokia\";\n StringBuffer buf = new StringBuffer();\n buf.append(url).append(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);\n expect(request.getRequestURL()).andReturn(buf);\n expect(request.getRequestURI()).andReturn(buf.toString());\n expect(request.getContextPath()).andReturn(\"/jolokia\");\n expect(request.getAuthType()).andReturn(\"BASIC\");\n replay(request, response);\n\n servlet.doGet(request, response);\n\n assertTrue(sw.toString().contains(\"used\"));\n\n JolokiaDiscovery discovery = new JolokiaDiscovery(\"test\",LogHandler.QUIET);\n List in = discovery.lookupAgents();\n assertTrue(in.size() > 0);\n for (JSONObject json : in) {\n if (json.get(\"url\") != null && json.get(\"url\").equals(url)) {\n assertTrue((Boolean) json.get(\"secured\"));\n return;\n }\n }\n fail(\"Failed, because no message had an URL\");\n } finally {\n servlet.destroy();\n }\n }", "label_name": "CWE-352", "label": 0} {"code": " public RechnungCostEditTablePanel(final String id)\n {\n super(id);\n feedbackPanel = new FeedbackPanel(\"feedback\");\n ajaxComponents.register(feedbackPanel);\n add(feedbackPanel);\n this.form = new Form(\"form\");\n add(form);\n rows = new RepeatingView(\"rows\");\n form.add(rows);\n }", "label_name": "CWE-352", "label": 0} {"code": " public void corsEmpty() {\n InputStream is = getClass().getResourceAsStream(\"/allow-origin3.xml\");\n PolicyRestrictor restrictor = new PolicyRestrictor(is);\n\n assertTrue(restrictor.isCorsAccessAllowed(\"http://bla.com\"));\n assertTrue(restrictor.isCorsAccessAllowed(\"http://www.jolokia.org\"));\n assertTrue(restrictor.isCorsAccessAllowed(\"http://www.consol.de\"));\n }", "label_name": "CWE-352", "label": 0} {"code": " public void setupRoutes() {\n path(controllerBasePath(), () -> {\n before(\"\", mimeType, this::setContentType);\n\n\n // change the line below to enable appropriate security\n before(\"\", mimeType, this.apiAuthenticationHelper::checkAdminUserAnd403);\n\n get(\"\", mimeType, this::show);\n\n post(\"\", mimeType, this::createOrUpdate);\n put(\"\", mimeType, this::createOrUpdate);\n\n delete(\"\", mimeType, this::deleteBackupConfig);\n });\n }", "label_name": "CWE-352", "label": 0} {"code": " public void debug() throws IOException, ServletException {\n servlet = new AgentServlet();\n initConfigMocks(new String[]{ConfigKey.DEBUG.getKeyValue(), \"true\"},null,\"No access restrictor found\",null);\n context.log(find(\"URI:\"));\n context.log(find(\"Path-Info:\"));\n context.log(find(\"Request:\"));\n context.log(find(\"time:\"));\n context.log(find(\"Response:\"));\n context.log(find(\"TestDetector\"),isA(RuntimeException.class));\n expectLastCall().anyTimes();\n replay(config, context);\n servlet.init(config);\n\n StringWriter sw = initRequestResponseMocks();\n expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);\n expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(null);\n replay(request, response);\n\n servlet.doGet(request, response);\n\n assertTrue(sw.toString().contains(\"used\"));\n servlet.destroy();\n }", "label_name": "CWE-352", "label": 0} {"code": " public void corsWildCard() {\n InputStream is = getClass().getResourceAsStream(\"/allow-origin2.xml\");\n PolicyRestrictor restrictor = new PolicyRestrictor(is);\n\n assertTrue(restrictor.isCorsAccessAllowed(\"http://bla.com\"));\n assertTrue(restrictor.isCorsAccessAllowed(\"http://www.jolokia.org\"));\n assertTrue(restrictor.isCorsAccessAllowed(\"http://www.consol.de\"));\n }", "label_name": "CWE-352", "label": 0} {"code": " public boolean isCorsAccessAllowed(String pOrigin) {\n return corsChecker.check(pOrigin);\n }", "label_name": "CWE-352", "label": 0} {"code": " private Runnable getStandardRequestSetup() {\n return new Runnable() {\n public void run() {\n expect(request.getHeader(\"Origin\")).andReturn(null);\n expect(request.getRemoteHost()).andReturn(\"localhost\");\n expect(request.getRemoteAddr()).andReturn(\"127.0.0.1\");\n expect(request.getRequestURI()).andReturn(\"/jolokia/\");\n expect(request.getParameterMap()).andReturn(null);\n }\n };\n }", "label_name": "CWE-352", "label": 0} {"code": " private void returnPrincipals(Subject subject, PrintWriter out) {\n\n Map answer = new HashMap();\n\n List principals = new ArrayList();\n\n for (Principal principal : subject.getPrincipals()) {\n Map data = new HashMap();\n data.put(\"type\", principal.getClass().getName());\n data.put(\"name\", principal.getName());\n principals.add(data);\n }\n\n List credentials = new ArrayList();\n for (Object credential : subject.getPublicCredentials()) {\n Map data = new HashMap();\n data.put(\"type\", credential.getClass().getName());\n data.put(\"credential\", credential);\n }\n\n answer.put(\"principals\", principals);\n answer.put(\"credentials\", credentials);\n\n ServletHelpers.writeObject(converters, options, out, answer);\n }", "label_name": "CWE-352", "label": 0} {"code": " public boolean check(String pArg) {\n if (patterns == null || patterns.size() == 0) {\n return true;\n }\n for (Pattern pattern : patterns) {\n if (pattern.matcher(pArg).matches()) {\n return true;\n }\n }\n return false;\n }", "label_name": "CWE-352", "label": 0} {"code": " public CorsChecker(Document pDoc) {\n NodeList corsNodes = pDoc.getElementsByTagName(\"cors\");\n if (corsNodes.getLength() > 0) {\n patterns = new ArrayList();\n for (int i = 0; i < corsNodes.getLength(); i++) {\n Node corsNode = corsNodes.item(i);\n NodeList nodes = corsNode.getChildNodes();\n for (int j = 0;j form)\n {\n form.add(csrfTokenField = new HiddenField(\"csrfToken\", Model.of(getCsrfSessionToken())));\n }", "label_name": "CWE-352", "label": 0} {"code": " private void initConfigMocks(String[] pInitParams, String[] pContextParams,String pLogRegexp, Class pExceptionClass) {\n config = createMock(ServletConfig.class);\n context = createMock(ServletContext.class);\n\n\n String[] params = pInitParams != null ? Arrays.copyOf(pInitParams,pInitParams.length + 2) : new String[2];\n params[params.length - 2] = ConfigKey.DEBUG.getKeyValue();\n params[params.length - 1] = \"true\";\n HttpTestUtil.prepareServletConfigMock(config,params);\n HttpTestUtil.prepareServletContextMock(context, pContextParams);\n\n\n expect(config.getServletContext()).andReturn(context).anyTimes();\n expect(config.getServletName()).andReturn(\"jolokia\").anyTimes();\n if (pExceptionClass != null) {\n context.log(find(pLogRegexp),isA(pExceptionClass));\n } else {\n if (pLogRegexp != null) {\n context.log(find(pLogRegexp));\n } else {\n context.log((String) anyObject());\n }\n }\n context.log((String) anyObject());\n expectLastCall().anyTimes();\n context.log(find(\"TestDetector\"),isA(RuntimeException.class));\n }", "label_name": "CWE-352", "label": 0} {"code": " public Map handleCorsPreflightRequest(String pOrigin, String pRequestHeaders) {\n Map ret = new HashMap();\n if (pOrigin != null && backendManager.isCorsAccessAllowed(pOrigin)) {\n // CORS is allowed, we set exactly the origin in the header, so there are no problems with authentication\n ret.put(\"Access-Control-Allow-Origin\",\"null\".equals(pOrigin) ? \"*\" : pOrigin);\n if (pRequestHeaders != null) {\n ret.put(\"Access-Control-Allow-Headers\",pRequestHeaders);\n }\n // Fix for CORS with authentication (#104)\n ret.put(\"Access-Control-Allow-Credentials\",\"true\");\n // Allow for one year. Changes in access.xml are reflected directly in the cors request itself\n ret.put(\"Access-Control-Allow-Max-Age\",\"\" + 3600 * 24 * 365);\n }\n return ret;\n }", "label_name": "CWE-352", "label": 0} {"code": " private ModelAndView renameGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {\n \n String oldName = request.getParameter(\"groupName\");\n String newName = request.getParameter(\"newName\");\n \n if (StringUtils.hasText(oldName) && StringUtils.hasText(newName)) {\n m_groupRepository.renameGroup(oldName, newName);\n }\n \n return listGroups(request, response);\n }", "label_name": "CWE-352", "label": 0} {"code": " public void corsAccessCheck() {\n BackendManager backendManager = new BackendManager(config,log);\n assertTrue(backendManager.isCorsAccessAllowed(\"http://bla.com\"));\n backendManager.destroy();\n }", "label_name": "CWE-352", "label": 0} {"code": " private void handle(ServletRequestHandler pReqHandler,HttpServletRequest pReq, HttpServletResponse pResp) throws IOException {\n JSONAware json = null;\n try {\n // Check access policy\n requestHandler.checkClientIPAccess(pReq.getRemoteHost(),pReq.getRemoteAddr());\n\n // Remember the agent URL upon the first request. Needed for discovery\n updateAgentUrlIfNeeded(pReq);\n\n // Dispatch for the proper HTTP request method\n json = pReqHandler.handleRequest(pReq,pResp);\n } catch (Throwable exp) {\n json = requestHandler.handleThrowable(\n exp instanceof RuntimeMBeanException ? ((RuntimeMBeanException) exp).getTargetException() : exp);\n } finally {\n setCorsHeader(pReq, pResp);\n\n String callback = pReq.getParameter(ConfigKey.CALLBACK.getKeyValue());\n String answer = json != null ?\n json.toJSONString() :\n requestHandler.handleThrowable(new Exception(\"Internal error while handling an exception\")).toJSONString();\n if (callback != null) {\n // Send a JSONP response\n sendResponse(pResp, \"text/javascript\", callback + \"(\" + answer + \");\");\n } else {\n sendResponse(pResp, getMimeType(pReq),answer);\n }\n }\n }", "label_name": "CWE-352", "label": 0} {"code": " public String extractCorsOrigin(String pOrigin) {\n if (pOrigin != null) {\n // Prevent HTTP response splitting attacks\n String origin = pOrigin.replaceAll(\"[\\\\n\\\\r]*\",\"\");\n if (backendManager.isCorsAccessAllowed(origin)) {\n return \"null\".equals(origin) ? \"*\" : origin;\n } else {\n return null;\n }\n }\n return null;\n }", "label_name": "CWE-352", "label": 0} {"code": "def add_acl_usergroup(session, acl_role_id, user_group, name)\n if (user_group == \"user\") or (user_group == \"group\")\n stdout, stderr, retval = run_cmd(\n session, PCS, \"acl\", user_group, \"create\", name.to_s, acl_role_id.to_s\n )\n if retval == 0\n return \"\"\n end\n if not /^error: (user|group) #{name.to_s} already exists$/i.match(stderr.join(\"\\n\").strip)\n return stderr.join(\"\\n\").strip\n end\n end\n stdout, stderror, retval = run_cmd(\n session, PCS, \"acl\", \"role\", \"assign\", acl_role_id.to_s, name.to_s\n )\n if retval != 0\n if stderror.empty?\n return \"Error adding #{user_group}\"\n else\n return stderror.join(\"\\n\").strip\n end\n end\n return \"\"\nend", "label_name": "CWE-384", "label": 1} {"code": "def remote_add_node(params, request, session, all=false)\n if not allowed_for_local_cluster(session, Permissions::FULL)\n return 403, 'Permission denied'\n end\n auto_start = false\n if params[:auto_start] and params[:auto_start] == \"1\"\n auto_start = true\n end\n\n if params[:new_nodename] != nil\n node = params[:new_nodename]\n if params[:new_ring1addr] != nil\n node += ',' + params[:new_ring1addr]\n end\n retval, output = add_node(session, node, all, auto_start)\n end\n\n if retval == 0\n return [200, JSON.generate([retval, get_corosync_conf()])]\n end\n\n return [400,output]\nend", "label_name": "CWE-384", "label": 1} {"code": " def get_configs_cluster(nodes, cluster_name)\n data = {\n 'cluster_name' => cluster_name,\n }\n\n $logger.debug 'Fetching configs from the cluster'\n threads = []\n node_configs = {}\n nodes.each { |node|\n threads << Thread.new {\n code, out = send_request_with_token(\n @session, node, 'get_configs', false, data\n )\n if 200 == code\n begin\n parsed = JSON::parse(out)\n if 'ok' == parsed['status'] and cluster_name == parsed['cluster_name']\n node_configs[node], _ = Cfgsync::sync_msg_to_configs(parsed)\n end\n rescue JSON::ParserError\n end\n end\n }\n }\n threads.each { |t| t.join }\n return node_configs\n end", "label_name": "CWE-384", "label": 1} {"code": "def auth(params, request, session)\n token = PCSAuth.validUser(params['username'],params['password'], true)\n # If we authorized to this machine, attempt to authorize everywhere\n node_list = []\n if token and params[\"bidirectional\"]\n params.each { |k,v|\n if k.start_with?(\"node-\")\n node_list.push(v)\n end\n }\n if node_list.length > 0\n pcs_auth(\n session, node_list, params['username'], params['password'],\n params[\"force\"] == \"1\"\n )\n end\n end\n return token\nend", "label_name": "CWE-384", "label": 1} {"code": "def add_node_attr_remote(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n retval = add_node_attr(\n session, params[\"node\"], params[\"key\"], params[\"value\"]\n )\n # retval = 2 if removing attr which doesn't exist\n if retval == 0 or retval == 2\n return [200, \"Successfully added attribute to node\"]\n else\n return [400, \"Error adding attribute to node\"]\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def add_fence_level(session, level, devices, node, remove = false)\n if not remove\n stdout, stderr, retval = run_cmd(\n session, PCS, \"stonith\", \"level\", \"add\", level, node, devices\n )\n return retval,stdout, stderr\n else\n stdout, stderr, retval = run_cmd(\n session, PCS, \"stonith\", \"level\", \"remove\", level, node, devices\n )\n return retval,stdout, stderr\n end\nend", "label_name": "CWE-384", "label": 1} {"code": " def authorize_params\n super.tap do |params|\n %w[display state scope].each do |v|\n if request.params[v]\n params[v.to_sym] = request.params[v]\n\n # to support omniauth-oauth2's auto csrf protection\n session['omniauth.state'] = params[:state] if v == 'state'\n end\n end\n\n params[:scope] ||= DEFAULT_SCOPE\n end\n end", "label_name": "CWE-352", "label": 0} {"code": "def resource_cleanup(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n stdout, stderr, retval = run_cmd(\n session, PCS, \"resource\", \"cleanup\", params[:resource]\n )\n if retval == 0\n return JSON.generate({\"success\" => \"true\"})\n else\n return JSON.generate({\"error\" => \"true\", \"stdout\" => stdout, \"stderror\" => stderr})\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def save_tokens(params, request, session)\n # pcsd runs as root thus always returns hacluster's tokens\n if not allowed_for_local_cluster(session, Permissions::FULL)\n return 403, \"Permission denied\"\n end\n\n new_tokens = {}\n\n params.each{|nodes|\n if nodes[0].start_with?\"node:\" and nodes[0].length > 5\n node = nodes[0][5..-1]\n token = nodes[1]\n new_tokens[node] = token\n end\n }\n\n tokens_cfg = Cfgsync::PcsdTokens.from_file('')\n sync_successful, sync_responses = Cfgsync::save_sync_new_tokens(\n tokens_cfg, new_tokens, get_corosync_nodes(), $cluster_name\n )\n\n if sync_successful\n return [200, JSON.generate(read_tokens())]\n else\n return [400, \"Cannot update tokenfile.\"]\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def add_acl_permission(session, acl_role_id, perm_type, xpath_id, query_id)\n stdout, stderror, retval = run_cmd(\n session, PCS, \"acl\", \"permission\", \"add\", acl_role_id.to_s, perm_type.to_s,\n xpath_id.to_s, query_id.to_s\n )\n if retval != 0\n if stderror.empty?\n return \"Error adding permission\"\n else\n return stderror.join(\"\\n\").strip\n end\n end\n return \"\"\nend", "label_name": "CWE-384", "label": 1} {"code": "def enable_cluster(session)\n stdout, stderror, retval = run_cmd(session, PCS, \"cluster\", \"enable\")\n return false if retval != 0\n return true\nend", "label_name": "CWE-384", "label": 1} {"code": "def cluster_start(params, request, session)\n if params[:name]\n code, response = send_request_with_token(\n session, params[:name], 'cluster_start', true\n )\n else\n if not allowed_for_local_cluster(session, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n $logger.info \"Starting Daemons\"\n output = `#{PCS} cluster start`\n $logger.debug output\n return output\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def resource_ungroup(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n\n unless params[:group_id]\n return [400, 'group_id has to be specified.']\n end\n \n _, stderr, retval = run_cmd(\n session, PCS, 'resource', 'ungroup', params[:group_id]\n )\n if retval != 0\n return [400, 'Unable to ungroup group ' +\n \"'#{params[:group_id]}': #{stderr.join('')}\"\n ]\n end\n return 200\nend", "label_name": "CWE-384", "label": 1} {"code": "def remove_constraint_rule_remote(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n if params[:rule_id]\n retval = remove_constraint_rule(session, params[:rule_id])\n if retval == 0\n return \"Constraint rule #{params[:rule_id]} removed\"\n else\n return [400, \"Error removing constraint rule: #{params[:rule_id]}\"]\n end\n else\n return [400, \"Bad Constraint Rule Options\"]\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def add_constraint_set_remote(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n case params[\"c_type\"]\n when \"ord\"\n retval, error = add_order_set_constraint(\n session,\n params[\"resources\"].values, params[\"force\"], !params['disable_autocorrect']\n )\n else\n return [400, \"Unknown constraint type: #{params[\"c_type\"]}\"]\n end", "label_name": "CWE-384", "label": 1} {"code": "def send_cluster_request_with_token(session, cluster_name, request, post=false, data={}, remote=true, raw_data=nil)\n $logger.info(\"SCRWT: \" + request)\n nodes = get_cluster_nodes(cluster_name)\n return send_nodes_request_with_token(\n session, nodes, request, post, data, remote, raw_data\n )\nend", "label_name": "CWE-384", "label": 1} {"code": "def cluster_status_remote(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::READ)\n return 403, 'Permission denied'\n end\n\n cluster_name = $cluster_name\n # If node is not in a cluster, return empty data\n if not cluster_name or cluster_name.empty?\n overview = {\n :cluster_name => nil,\n :error_list => [],\n :warning_list => [],\n :quorate => nil,\n :status => 'unknown',\n :node_list => [],\n :resource_list => [],\n }\n return JSON.generate(overview)\n end\n\n cluster_nodes = get_nodes().flatten\n status = cluster_status_from_nodes(session, cluster_nodes, cluster_name)\n unless status\n return 403, 'Permission denied'\n end\n return JSON.generate(status)\nend", "label_name": "CWE-384", "label": 1} {"code": "def get_avail_resource_agents(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::READ)\n return 403, 'Permission denied'\n end\n agents = getResourceAgents(session)\n return JSON.generate(agents)\nend", "label_name": "CWE-384", "label": 1} {"code": "def get_permissions_remote(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::GRANT)\n return 403, 'Permission denied'\n end\n\n pcs_config = PCSConfig.new(Cfgsync::PcsdSettings.from_file('{}').text())\n data = {\n 'user_types' => Permissions::get_user_types(),\n 'permission_types' => Permissions::get_permission_types(),\n 'permissions_dependencies' => Permissions::permissions_dependencies(),\n 'users_permissions' => pcs_config.permissions_local.to_hash(),\n }\n return [200, JSON.generate(data)]\nend", "label_name": "CWE-384", "label": 1} {"code": "def add_location_constraint_rule(\n session, resource, rule, score, force=false, autocorrect=true\n)\n cmd = [PCS, \"constraint\", \"location\", resource, \"rule\"]\n if score != ''\n if is_score(score.upcase)\n cmd << \"score=#{score.upcase}\"\n else\n cmd << \"score-attribute=#{score}\"\n end\n end\n cmd.concat(rule.shellsplit())\n cmd << '--force' if force\n cmd << '--autocorrect' if autocorrect\n stdout, stderr, retval = run_cmd(session, *cmd)\n return retval, stderr.join(' ')\nend", "label_name": "CWE-384", "label": 1} {"code": "def getAllSettings(session, cib_dom=nil)\n unless cib_dom\n cib_dom = get_cib_dom(session)\n end\n ret = {}\n if cib_dom\n cib_dom.elements.each('/cib/configuration/crm_config//nvpair') { |e|\n ret[e.attributes['name']] = e.attributes['value']\n }\n end\n return ret\nend", "label_name": "CWE-384", "label": 1} {"code": "def add_acl_role(session, name, description)\n cmd = [PCS, \"acl\", \"role\", \"create\", name.to_s]\n if description.to_s != \"\"\n cmd << \"description=#{description.to_s}\"\n end\n stdout, stderror, retval = run_cmd(session, *cmd)\n if retval != 0\n return stderror.join(\"\\n\").strip\n end\n return \"\"\nend", "label_name": "CWE-384", "label": 1} {"code": "def add_constraint_rule_remote(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n if params[\"c_type\"] == \"loc\"\n retval, error = add_location_constraint_rule(\n session,\n params[\"res_id\"], params[\"rule\"], params[\"score\"], params[\"force\"],\n !params['disable_autocorrect']\n )\n else\n return [400, \"Unknown constraint type: #{params[\"c_type\"]}\"]\n end\n\n if retval == 0\n return [200, \"Successfully added constraint\"]\n else\n return [400, \"Error adding constraint: #{error}\"]\n end\nend", "label_name": "CWE-384", "label": 1} {"code": " def self.loginByPassword(session, username, password)\n if validUser(username, password)\n session[:username] = username\n success, groups = getUsersGroups(username)\n session[:usergroups] = success ? groups : []\n return true\n end\n return false\n end", "label_name": "CWE-384", "label": 1} {"code": "def get_configs(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::FULL)\n return 403, 'Permission denied'\n end\n if not $cluster_name or $cluster_name.empty?\n return JSON.generate({'status' => 'not_in_cluster'})\n end\n if params[:cluster_name] != $cluster_name\n return JSON.generate({'status' => 'wrong_cluster_name'})\n end\n out = {\n 'status' => 'ok',\n 'cluster_name' => $cluster_name,\n 'configs' => {},\n }\n Cfgsync::get_configs_local.each { |name, cfg|\n out['configs'][cfg.class.name] = {\n 'type' => 'file',\n 'text' => cfg.text,\n }\n }\n return JSON.generate(out)\nend", "label_name": "CWE-384", "label": 1} {"code": "def config_backup(params, request, session)\n if params[:name]\n code, response = send_request_with_token(\n session, params[:name], 'config_backup', true\n )\n else\n if not allowed_for_local_cluster(session, Permissions::FULL)\n return 403, 'Permission denied'\n end\n $logger.info \"Backup node configuration\"\n stdout, stderr, retval = run_cmd(session, PCS, \"config\", \"backup\")\n if retval == 0\n $logger.info \"Backup successful\"\n return [200, stdout]\n end\n $logger.info \"Error during backup: #{stderr.join(' ').strip()}\"\n return [400, \"Unable to backup node: #{stderr.join(' ')}\"]\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def get_local_node_id()\n if ISRHEL6\n out, errout, retval = run_cmd(\n PCSAuth.getSuperuserSession, COROSYNC_CMAPCTL, \"cluster.cman\"\n )\n if retval != 0\n return \"\"\n end\n match = /cluster\\.nodename=(.*)/.match(out.join(\"\\n\"))\n if not match\n return \"\"\n end\n local_node_name = match[1]\n out, errout, retval = run_cmd(\n PCSAuth.getSuperuserSession,\n CMAN_TOOL, \"nodes\", \"-F\", \"id\", \"-n\", local_node_name\n )\n if retval != 0\n return \"\"\n end\n return out[0].strip()\n end\n out, errout, retval = run_cmd(\n PCSAuth.getSuperuserSession,\n COROSYNC_CMAPCTL, \"-g\", \"runtime.votequorum.this_node_id\"\n )\n if retval != 0\n return \"\"\n else\n return out[0].split(/ = /)[1].strip()\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def send_nodes_request_with_token(session, nodes, request, post=false, data={}, remote=true, raw_data=nil)\n out = \"\"\n code = 0\n $logger.info(\"SNRWT: \" + request)\n\n # If we're removing nodes, we don't send this to one of the nodes we're\n # removing, unless we're removing all nodes\n if request == \"/remove_nodes\"\n new_nodes = nodes.dup\n data.each {|k,v|\n if new_nodes.include? v\n new_nodes.delete v\n end\n }\n if new_nodes.length > 0\n nodes = new_nodes\n end\n end\n\n for node in nodes\n $logger.info \"SNRWT Node: #{node} Request: #{request}\"\n code, out = send_request_with_token(\n session, node, request, post, data, remote, raw_data\n )\n # try next node if:\n # - current node does not support the request (old version of pcsd?) (404)\n # - an exception or other error occurred (5xx)\n # - we don't have a token for the node (401, notoken)\n # - we didn't get a response form the node (e.g. an exception occurred)\n # - pacemaker is not running on the node\n # do not try next node if\n # - node returned 400 - it means the request cannot be processed because of\n # invalid arguments or another known issue, no node would be able to\n # process the request (e.g. removing a non-existing resource)\n # - node returned 403 - permission denied, no node should allow to process\n # the request\n log = \"SNRWT Node #{node} Request #{request}\"\n if (404 == code) or (code >= 500 and code <= 599)\n $logger.info(\"#{log}: HTTP code #{code}\")\n next\n end\n if (401 == code) or ('{\"notoken\":true}' == out)\n $logger.info(\"#{log}: Bad or missing token\")\n next\n end\n if '{\"pacemaker_not_running\":true}' == out\n $logger.info(\"#{log}: Pacemaker not running\")\n next\n end\n if '{\"noresponse\":true}' == out\n $logger.info(\"#{log}: No response\")\n next\n end\n $logger.info(\"#{log}: HTTP code #{code}\")\n break\n end\n return code, out\nend", "label_name": "CWE-384", "label": 1} {"code": "def remove_constraint_rule(session, rule_id)\n stdout, stderror, retval = run_cmd(\n session, PCS, \"constraint\", \"rule\", \"remove\", rule_id\n )\n $logger.info stdout\n return retval\nend", "label_name": "CWE-384", "label": 1} {"code": "def add_location_constraint(\n session, resource, node, score, force=false, autocorrect=true\n)\n if node == \"\"\n return \"Bad node\"\n end\n\n if score == \"\"\n nodescore = node\n else\n nodescore = node + \"=\" + score\n end\n\n cmd = [PCS, \"constraint\", \"location\", resource, \"prefers\", nodescore]\n cmd << '--force' if force\n cmd << '--autocorrect' if autocorrect\n\n stdout, stderr, retval = run_cmd(session, *cmd)\n return retval, stderr.join(' ')\nend", "label_name": "CWE-384", "label": 1} {"code": "def allowed_for_superuser(session)\n $logger.debug(\n \"permission check superuser username=#{session[:username]} groups=#{session[:groups]}\"\n )\n if SUPERUSER != session[:username]\n $logger.debug('permission denied')\n return false\n end\n $logger.debug('permission granted for superuser')\n return true\nend", "label_name": "CWE-384", "label": 1} {"code": "def add_acl_role_remote(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::GRANT)\n return 403, 'Permission denied'\n end\n retval = add_acl_role(session, params[\"name\"], params[\"description\"])\n if retval == \"\"\n return [200, \"Successfully added ACL role\"]\n else\n return [\n 400,\n retval.include?(\"cib_replace failed\") ? \"Error adding ACL role\" : retval\n ]\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def setup_cluster(params, request, session)\n if not allowed_for_superuser(session)\n return 403, 'Permission denied'\n end\n $logger.info(\"Setting up cluster: \" + params.inspect)\n nodes_rrp = params[:nodes].split(';')\n options = []\n myoptions = JSON.parse(params[:options])\n transport_udp = false\n options_udp = []\n myoptions.each { |o,v|\n if [\"wait_for_all\", \"last_man_standing\", \"auto_tie_breaker\"].include?(o)\n options << \"--\" + o + \"=1\"\n end\n\n options << \"--\" + o + \"=\" + v if [\n \"token\", \"token_coefficient\", \"join\", \"consensus\", \"miss_count_const\",\n \"fail_recv_const\", \"last_man_standing_window\",\n ].include?(o)\n\n if o == \"transport\" and v == \"udp\"\n options << \"--transport=udp\"\n transport_udp = true\n end\n if o == \"transport\" and v == \"udpu\"\n options << \"--transport=udpu\"\n transport_udp = false\n end\n\n if [\"addr0\", \"addr1\", \"mcast0\", \"mcast1\", \"mcastport0\", \"mcastport1\", \"ttl0\", \"ttl1\"].include?(o)\n options_udp << \"--\" + o + \"=\" + v\n end\n\n if [\"broadcast0\", \"broadcast1\"].include?(o)\n options_udp << \"--\" + o\n end\n\n if o == \"ipv6\"\n options << \"--ipv6\"\n end\n }\n if transport_udp\n nodes = []\n nodes_rrp.each { |node| nodes << node.split(',')[0] }\n else\n nodes = nodes_rrp\n end\n nodes_options = nodes + options\n nodes_options += options_udp if transport_udp\n stdout, stderr, retval = run_cmd(\n session, PCS, \"cluster\", \"setup\", \"--enable\", \"--start\",\n \"--name\", params[:clustername], *nodes_options\n )\n if retval != 0\n return [\n 400,\n (stdout + [''] + stderr).collect { |line| line.rstrip() }.join(\"\\n\")\n ]\n end\n return 200\nend", "label_name": "CWE-384", "label": 1} {"code": "def remote_node_available(params, request, session)\n if (not ISRHEL6 and File.exist?(Cfgsync::CorosyncConf.file_path)) or (ISRHEL6 and File.exist?(Cfgsync::ClusterConf.file_path)) or File.exist?(\"/var/lib/pacemaker/cib/cib.xml\")\n return JSON.generate({:node_available => false})\n end\n return JSON.generate({:node_available => true})\nend", "label_name": "CWE-384", "label": 1} {"code": "def remote_remove_node(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::FULL)\n return 403, 'Permission denied'\n end\n if params[:remove_nodename] != nil\n retval, output = remove_node(session, params[:remove_nodename])\n else\n return 400, \"No nodename specified\"\n end\n\n if retval == 0\n return JSON.generate([retval, get_corosync_conf()])\n end\n\n return JSON.generate([retval,output])\nend", "label_name": "CWE-384", "label": 1} {"code": "def run_auth_requests(session, nodes_to_send, nodes_to_auth, username, password, force=false, local=true)\n data = {}\n nodes_to_auth.each_with_index { |node, index|\n data[\"node-#{index}\"] = node\n }\n data['username'] = username\n data['password'] = password\n data['bidirectional'] = 1 if not local\n data['force'] = 1 if force\n\n auth_responses = {}\n threads = []\n nodes_to_send.each { |node|\n threads << Thread.new {\n code, response = send_request(session, node, 'auth', true, data)\n if 200 == code\n token = response.strip\n if '' == token\n auth_responses[node] = {'status' => 'bad_password'}\n else\n auth_responses[node] = {'status' => 'ok', 'token' => token}\n end\n else\n auth_responses[node] = {'status' => 'noresponse'}\n end\n }\n }\n threads.each { |t| t.join }\n return auth_responses\nend", "label_name": "CWE-384", "label": 1} {"code": "def update_fence_device(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n\n $logger.info \"Updating fence device\"\n $logger.info params\n param_line = getParamList(params)\n $logger.info param_line\n\n if not params[:resource_id]\n out, stderr, retval = run_cmd(\n session,\n PCS, \"stonith\", \"create\", params[:name], params[:resource_type],\n *param_line\n )\n if retval != 0\n return JSON.generate({\"error\" => \"true\", \"stderr\" => stderr, \"stdout\" => out})\n end\n return \"{}\"\n end\n\n if param_line.length != 0\n out, stderr, retval = run_cmd(\n session, PCS, \"stonith\", \"update\", params[:resource_id], *param_line\n )\n if retval != 0\n return JSON.generate({\"error\" => \"true\", \"stderr\" => stderr, \"stdout\" => out})\n end\n end\n return \"{}\"\nend", "label_name": "CWE-384", "label": 1} {"code": "def add_group(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n rg = params[\"resource_group\"]\n resources = params[\"resources\"]\n output, errout, retval = run_cmd(\n session, PCS, \"resource\", \"group\", \"add\", rg, *(resources.split(\" \"))\n )\n if retval == 0\n return 200\n else\n return 400, errout\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def get_crm_mon_dom(session)\n begin\n stdout, _, retval = run_cmd(\n session, CRM_MON, '--one-shot', '-r', '--as-xml'\n )\n if retval == 0\n return REXML::Document.new(stdout.join(\"\\n\"))\n end\n rescue\n $logger.error 'Failed to parse crm_mon.'\n end\n return nil\nend", "label_name": "CWE-384", "label": 1} {"code": "def config_restore(params, request, session)\n if params[:name]\n code, response = send_request_with_token(\n session, params[:name], 'config_restore', true,\n {:tarball => params[:tarball]}\n )\n else\n if not allowed_for_local_cluster(session, Permissions::FULL)\n return 403, 'Permission denied'\n end\n $logger.info \"Restore node configuration\"\n if params[:tarball] != nil and params[:tarball] != \"\"\n out = \"\"\n errout = \"\"\n status = Open4::popen4(PCS, \"config\", \"restore\", \"--local\") { |pid, stdin, stdout, stderr|\n stdin.print(params[:tarball])\n stdin.close()\n out = stdout.readlines()\n errout = stderr.readlines()\n }\n retval = status.exitstatus\n if retval == 0\n $logger.info \"Restore successful\"\n return \"Succeeded\"\n else\n $logger.info \"Error during restore: #{errout.join(' ').strip()}\"\n return errout.length > 0 ? errout.join(' ').strip() : \"Error\"\n end\n else\n $logger.info \"Error: Invalid tarball\"\n return \"Error: Invalid tarball\"\n end\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def fence_device_metadata(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::READ)\n return 403, 'Permission denied'\n end\n return 200 if not params[:resourcename] or params[:resourcename] == \"\"\n @fenceagent = FenceAgent.new(params[:resourcename])\n @fenceagent.required_options, @fenceagent.optional_options, @fenceagent.advanced_options, @fenceagent.info = getFenceAgentMetadata(session, params[:resourcename])\n @new_fenceagent = params[:new]\n \n erb :fenceagentform\nend", "label_name": "CWE-384", "label": 1} {"code": "def get_acls(session, cib_dom=nil)\n unless cib_dom\n cib_dom = get_cib_dom(session)\n return {} unless cib_dom\n end\n\n acls = {\n 'role' => {},\n 'group' => {},\n 'user' => {},\n 'target' => {}\n }\n\n cib_dom.elements.each('/cib/configuration/acls/*') { |e|\n type = e.name[4..-1]\n if e.name == 'acl_role'\n role_id = e.attributes['id']\n desc = e.attributes['description']\n acls[type][role_id] = {}\n acls[type][role_id]['description'] = desc ? desc : ''\n acls[type][role_id]['permissions'] = []\n e.elements.each('acl_permission') { |p|\n p_id = p.attributes['id']\n p_kind = p.attributes['kind']\n val = ''\n if p.attributes['xpath']\n val = \"xpath #{p.attributes['xpath']}\"\n elsif p.attributes['reference']\n val = \"id #{p.attributes['reference']}\"\n else\n next\n end\n acls[type][role_id]['permissions'] << \"#{p_kind} #{val} (#{p_id})\"\n }\n elsif ['acl_target', 'acl_group'].include?(e.name)\n id = e.attributes['id']\n acls[type][id] = []\n e.elements.each('role') { |r|\n acls[type][id] << r.attributes['id']\n }\n end\n }\n acls['user'] = acls['target']\n return acls\nend", "label_name": "CWE-384", "label": 1} {"code": "def resource_unclone(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n\n unless params[:resource_id]\n return [400, 'resource_id has to be specified.']\n end\n\n _, stderr, retval = run_cmd(\n session, PCS, 'resource', 'unclone', params[:resource_id]\n )\n if retval != 0\n return [400, 'Unable to unclone ' +\n \"'#{params[:resource_id]}': #{stderr.join('')}\"\n ]\n end\n return 200\nend", "label_name": "CWE-384", "label": 1} {"code": "def get_cluster_tokens(params, request, session)\n # pcsd runs as root thus always returns hacluster's tokens\n if not allowed_for_local_cluster(session, Permissions::FULL)\n return 403, \"Permission denied\"\n end\n on, off = get_nodes\n nodes = on + off\n nodes.uniq!\n return [200, JSON.generate(get_tokens_of_nodes(nodes))]\nend", "label_name": "CWE-384", "label": 1} {"code": "def getFenceAgents(session, fence_agent = nil)\n fence_agent_list = {}\n agents = Dir.glob('/usr/sbin/fence_' + '*')\n agents.each { |a|\n fa = FenceAgent.new\n fa.name = a.sub(/.*\\//,\"\")\n next if fa.name == \"fence_ack_manual\"\n\n if fence_agent and a.sub(/.*\\//,\"\") == fence_agent.sub(/.*:/,\"\")\n required_options, optional_options, advanced_options, info = getFenceAgentMetadata(session, fa.name)\n fa.required_options = required_options\n fa.optional_options = optional_options\n fa.advanced_options = advanced_options\n fa.info = info\n end\n fence_agent_list[fa.name] = fa\n }\n fence_agent_list\nend", "label_name": "CWE-384", "label": 1} {"code": "def cluster_status_gui(session, cluster_name, dont_update_config=false)\n cluster_nodes = get_cluster_nodes(cluster_name)\n status = cluster_status_from_nodes(session, cluster_nodes, cluster_name)\n unless status\n return 403, 'Permission denied'\n end\n\n new_cluster_nodes = []\n new_cluster_nodes += status[:corosync_offline] if status[:corosync_offline]\n new_cluster_nodes += status[:corosync_online] if status[:corosync_online]\n new_cluster_nodes += status[:pacemaker_offline] if status[:pacemaker_offline]\n new_cluster_nodes += status[:pacemaker_online] if status[:pacemaker_online]\n new_cluster_nodes.uniq!\n\n if new_cluster_nodes.length > 0\n config = PCSConfig.new(Cfgsync::PcsdSettings.from_file('{}').text())\n if !(dont_update_config or config.cluster_nodes_equal?(cluster_name, new_cluster_nodes))\n old_cluster_nodes = config.get_nodes(cluster_name)\n $logger.info(\"Updating node list for: #{cluster_name} #{old_cluster_nodes}->#{new_cluster_nodes}\")\n config.update_cluster(cluster_name, new_cluster_nodes)\n sync_config = Cfgsync::PcsdSettings.from_text(config.text())\n # on version conflict just go on, config will be corrected eventually\n # by displaying the cluster in the web UI\n Cfgsync::save_sync_new_version(\n sync_config, get_corosync_nodes(), $cluster_name, true\n )\n return cluster_status_gui(session, cluster_name, true)\n end\n end\n return JSON.generate(status)\nend", "label_name": "CWE-384", "label": 1} {"code": "def get_stonith_agents_avail(session)\n code, result = send_cluster_request_with_token(\n session, params[:cluster], 'get_avail_fence_agents'\n )\n return {} if 200 != code\n begin\n sa = JSON.parse(result)\n if (sa[\"noresponse\"] == true) or (sa[\"notauthorized\"] == \"true\") or (sa[\"notoken\"] == true) or (sa[\"pacemaker_not_running\"] == true)\n return {}\n else\n return sa\n end\n rescue JSON::ParserError\n return {}\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def get_sync_capabilities(params, request, session)\n return JSON.generate({\n 'syncable_configs' => Cfgsync::get_cfg_classes_by_name().keys,\n })\nend", "label_name": "CWE-384", "label": 1} {"code": " def initialize(session, configs, nodes, cluster_name, tokens={})\n @configs = configs\n @nodes = nodes\n @cluster_name = cluster_name\n @published_configs_names = @configs.collect { |cfg|\n cfg.class.name\n }\n @additional_tokens = tokens\n @session = session\n end", "label_name": "CWE-384", "label": 1} {"code": "def get_current_node_name()\n stdout, stderror, retval = run_cmd(\n PCSAuth.getSuperuserSession, CRM_NODE, \"-n\"\n )\n if retval == 0 and stdout.length > 0\n return stdout[0].chomp()\n end\n return \"\"\nend", "label_name": "CWE-384", "label": 1} {"code": "def cluster_disable(params, request, session)\n if params[:name]\n code, response = send_request_with_token(\n session, params[:name], 'cluster_disable', true\n )\n else\n if not allowed_for_local_cluster(session, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n success = disable_cluster(session)\n if not success\n return JSON.generate({\"error\" => \"true\"})\n end\n return \"Cluster Disabled\"\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def resource_master(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n\n unless params[:resource_id]\n return [400, 'resource_id has to be specified.']\n end\n _, stderr, retval = run_cmd(\n session, PCS, 'resource', 'master', params[:resource_id]\n )\n if retval != 0\n return [400, 'Unable to create master/slave resource from ' +\n \"'#{params[:resource_id]}': #{stderr.join('')}\"\n ]\n end\n return 200\nend", "label_name": "CWE-384", "label": 1} {"code": "def get_cman_version()\n begin\n stdout, stderror, retval = run_cmd(\n PCSAuth.getSuperuserSession, CMAN_TOOL, \"-V\"\n )\n rescue\n stdout = []\n end\n if retval == 0\n match = /(\\d+)\\.(\\d+)\\.(\\d+)/.match(stdout.join())\n if match\n return match[1..3].collect { | x | x.to_i }\n end\n end\n return nil\nend", "label_name": "CWE-384", "label": 1} {"code": " def protected!\n gui_request = ( # these are URLs for web pages\n request.path == '/' or\n request.path == '/manage' or\n request.path == '/permissions' or\n request.path.match('/managec/.+/main')\n )\n if request.path.start_with?('/remote/') or request.path == '/run_pcs'\n unless PCSAuth.loginByToken(session, cookies)\n halt [401, '{\"notauthorized\":\"true\"}']\n end\n else #/managec/* /manage/* /permissions\n if !gui_request and\n request.env['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest'\n then\n # Accept non GUI requests only with header\n # \"X_REQUESTED_WITH: XMLHttpRequest\". (check if they are send via AJAX).\n # This prevents CSRF attack.\n halt [401, '{\"notauthorized\":\"true\"}']\n elsif not PCSAuth.isLoggedIn(session)\n if gui_request\n session[:pre_login_path] = request.path\n redirect '/login'\n else\n halt [401, '{\"notauthorized\":\"true\"}']\n end\n end\n end\n end", "label_name": "CWE-384", "label": 1} {"code": "def add_meta_attr(session, resource, key, value)\n stdout, stderr, retval = run_cmd(\n session, PCS, \"resource\", \"meta\", resource, key.to_s + \"=\" + value.to_s\n )\n return retval\nend", "label_name": "CWE-384", "label": 1} {"code": "def add_order_constraint(\n session, resourceA, resourceB, actionA, actionB, score, symmetrical=true,\n force=false, autocorrect=true\n)\n sym = symmetrical ? \"symmetrical\" : \"nonsymmetrical\"\n if score != \"\"\n score = \"score=\" + score\n end\n command = [\n PCS, \"constraint\", \"order\", actionA, resourceA, \"then\", actionB, resourceB,\n score, sym\n ]\n command << '--force' if force\n command << '--autocorrect' if autocorrect\n stdout, stderr, retval = run_cmd(session, *command)\n return retval, stderr.join(' ')\nend", "label_name": "CWE-384", "label": 1} {"code": "def set_resource_utilization(params, reqest, session)\n unless allowed_for_local_cluster(session, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n\n unless params[:resource_id] and params[:name]\n return 400, 'resource_id and name are required'\n end\n\n res_id = params[:resource_id]\n name = params[:name]\n value = params[:value] || ''\n\n _, stderr, retval = run_cmd(\n session, PCS, 'resource', 'utilization', res_id, \"#{name}=#{value}\"\n )\n\n if retval != 0\n return [400, \"Unable to set utilization '#{name}=#{value}' for \" +\n \"resource '#{res_id}': #{stderr.join('')}\"\n ]\n end\n return 200\nend", "label_name": "CWE-384", "label": 1} {"code": "def add_fence_level_remote(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n retval, stdout, stderr = add_fence_level(\n session, params[\"level\"], params[\"devices\"], params[\"node\"], params[\"remove\"]\n )\n if retval == 0\n return [200, \"Successfully added fence level\"]\n else\n return [400, stderr]\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def get_cib(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::READ)\n return 403, 'Permission denied'\n end\n cib, stderr, retval = run_cmd(session, CIBADMIN, \"-Ql\")\n if retval != 0\n if not pacemaker_running?\n return [400, '{\"pacemaker_not_running\":true}']\n end\n return [500, \"Unable to get CIB: \" + cib.to_s + stderr.to_s]\n else\n return [200, cib]\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def remove_acl_usergroup(session, role_id, usergroup_id)\n stdout, stderror, retval = run_cmd(\n session, PCS, \"acl\", \"role\", \"unassign\", role_id.to_s, usergroup_id.to_s,\n \"--autodelete\"\n )\n if retval != 0\n if stderror.empty?\n return \"Error removing user / group\"\n else\n return stderror.join(\"\\n\").strip\n end\n end\n return \"\"\nend", "label_name": "CWE-384", "label": 1} {"code": "def get_cib_dom(session)\n begin\n stdout, _, retval = run_cmd(session, 'cibadmin', '-Q', '-l')\n if retval == 0\n return REXML::Document.new(stdout.join(\"\\n\"))\n end\n rescue\n $logger.error 'Failed to parse cib.'\n end\n return nil\nend", "label_name": "CWE-384", "label": 1} {"code": "def create_cluster(params, request, session)\n if not allowed_for_superuser(session)\n return 403, 'Permission denied'\n end\n if set_corosync_conf(params, request, session)\n cluster_start(params, request, session)\n else\n return \"Failed\"\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def get_corosync_conf_remote(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::READ)\n return 403, 'Permission denied'\n end\n return get_corosync_conf()\nend", "label_name": "CWE-384", "label": 1} {"code": "def add_order_set_constraint(\n session, resource_set_list, force=false, autocorrect=true\n)\n command = [PCS, \"constraint\", \"order\"]\n resource_set_list.each { |resource_set|\n command << \"set\"\n command.concat(resource_set)\n }\n command << '--force' if force\n command << '--autocorrect' if autocorrect\n stdout, stderr, retval = run_cmd(session, *command)\n return retval, stderr.join(' ')\nend", "label_name": "CWE-384", "label": 1} {"code": "def get_quorum_info(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::READ)\n return 403, 'Permission denied'\n end\n if ISRHEL6\n stdout_status, stderr_status, retval = run_cmd(\n PCSAuth.getSuperuserSession, CMAN_TOOL, \"status\"\n )\n stdout_nodes, stderr_nodes, retval = run_cmd(\n PCSAuth.getSuperuserSession,\n CMAN_TOOL, \"nodes\", \"-F\", \"id,type,votes,name\"\n )\n if stderr_status.length > 0\n return stderr_status.join\n elsif stderr_nodes.length > 0\n return stderr_nodes.join\n else\n return stdout_status.join + \"\\n---Votes---\\n\" + stdout_nodes.join\n end\n else\n stdout, stderr, retval = run_cmd(\n PCSAuth.getSuperuserSession, COROSYNC_QUORUMTOOL, \"-p\", \"-s\"\n )\n # retval is 0 on success if node is not in partition with quorum\n # retval is 1 on error OR on success if node has quorum\n if stderr.length > 0\n return stderr.join\n else\n return stdout.join\n end\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def get_corosync_nodes()\n stdout, stderror, retval = run_cmd(\n PCSAuth.getSuperuserSession, PCS, \"status\", \"nodes\", \"corosync\"\n )\n if retval != 0\n return []\n end\n\n stdout.each {|x| x.strip!}\n corosync_online = stdout[1].sub(/^.*Online:/,\"\").strip\n corosync_offline = stdout[2].sub(/^.*Offline:/,\"\").strip\n corosync_nodes = (corosync_online.split(/ /)) + (corosync_offline.split(/ /))\n\n return corosync_nodes\nend", "label_name": "CWE-384", "label": 1} {"code": "def need_ring1_address?()\n out, errout, retval = run_cmd(PCSAuth.getSuperuserSession, COROSYNC_CMAPCTL)\n if retval != 0\n return false\n else\n udpu_transport = false\n rrp = false\n out.each { |line|\n # support both corosync-objctl and corosync-cmapctl format\n if /^\\s*totem\\.transport(\\s+.*)?=\\s*udpu$/.match(line)\n udpu_transport = true\n elsif /^\\s*totem\\.rrp_mode(\\s+.*)?=\\s*(passive|active)$/.match(line)\n rrp = true\n end\n }\n # on rhel6 ring1 address is required regardless of transport\n # it has to be added to cluster.conf in order to set up ring1\n # in corosync by cman\n return ((ISRHEL6 and rrp) or (rrp and udpu_transport))\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def get_nodes_status()\n corosync_online = []\n corosync_offline = []\n pacemaker_online = []\n pacemaker_offline = []\n pacemaker_standby = []\n in_pacemaker = false\n stdout, stderr, retval = run_cmd(\n PCSAuth.getSuperuserSession, PCS, \"status\", \"nodes\", \"both\"\n )\n stdout.each {|l|\n l = l.chomp\n if l.start_with?(\"Pacemaker Nodes:\")\n in_pacemaker = true\n end\n if l.start_with?(\"Pacemaker Remote Nodes:\")\n break\n end\n if l.end_with?(\":\")\n next\n end\n\n title,nodes = l.split(/: /,2)\n if nodes == nil\n next\n end\n\n if title == \" Online\"\n in_pacemaker ? pacemaker_online.concat(nodes.split(/ /)) : corosync_online.concat(nodes.split(/ /))\n elsif title == \" Standby\"\n if in_pacemaker\n pacemaker_standby.concat(nodes.split(/ /))\n end\n elsif title == \" Maintenance\"\n if in_pacemaker\n pacemaker_online.concat(nodes.split(/ /))\n end\n else\n in_pacemaker ? pacemaker_offline.concat(nodes.split(/ /)) : corosync_offline.concat(nodes.split(/ /))\n end\n }\n return {\n 'corosync_online' => corosync_online,\n 'corosync_offline' => corosync_offline,\n 'pacemaker_online' => pacemaker_online,\n 'pacemaker_offline' => pacemaker_offline,\n 'pacemaker_standby' => pacemaker_standby,\n }\nend", "label_name": "CWE-384", "label": 1} {"code": "def run_cmd_options(session, options, *args)\n $logger.info(\"Running: \" + args.join(\" \"))\n start = Time.now\n out = \"\"\n errout = \"\"\n\n proc_block = proc { |pid, stdin, stdout, stderr|\n if options and options.key?('stdin')\n stdin.puts(options['stdin'])\n stdin.close()\n end\n out = stdout.readlines()\n errout = stderr.readlines()\n duration = Time.now - start\n $logger.debug(out)\n $logger.debug(errout)\n $logger.debug(\"Duration: \" + duration.to_s + \"s\")\n }\n cib_user = session[:username]\n # when running 'id -Gn' to get the groups they are not defined yet\n cib_groups = (session[:usergroups] || []).join(' ')\n $logger.info(\"CIB USER: #{cib_user}, groups: #{cib_groups}\")\n # Open4.popen4 reimplementation which sets ENV in a child process prior\n # to running an external process by exec\n status = Open4::do_popen(proc_block, :init) { |ps_read, ps_write|\n ps_read.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)\n ps_write.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)\n ENV['CIB_user'] = cib_user\n ENV['CIB_user_groups'] = cib_groups\n exec(*args)\n }\n\n retval = status.exitstatus\n $logger.info(\"Return Value: \" + retval.to_s)\n return out, errout, retval\nend", "label_name": "CWE-384", "label": 1} {"code": "def send_request_with_token(session, node, request, post=false, data={}, remote=true, raw_data=nil, timeout=30, additional_tokens={})\n token = additional_tokens[node] || get_node_token(node)\n $logger.info \"SRWT Node: #{node} Request: #{request}\"\n if not token\n $logger.error \"Unable to connect to node #{node}, no token available\"\n return 400,'{\"notoken\":true}'\n end\n cookies_data = {\n 'token' => token,\n }\n return send_request(\n session, node, request, post, data, remote, raw_data, timeout, cookies_data\n )\nend", "label_name": "CWE-384", "label": 1} {"code": " def self.loginByToken(session, cookies)\n if username = validToken(cookies[\"token\"])\n if SUPERUSER == username\n if cookies['CIB_user'] and cookies['CIB_user'].strip != ''\n session[:username] = cookies['CIB_user']\n if cookies['CIB_user_groups'] and cookies['CIB_user_groups'].strip != ''\n session[:usergroups] = cookieUserDecode(\n cookies['CIB_user_groups']\n ).split(nil)\n else\n session[:usergroups] = []\n end\n else\n session[:username] = SUPERUSER\n session[:usergroups] = []\n end\n return true\n else\n session[:username] = username\n success, groups = getUsersGroups(username)\n session[:usergroups] = success ? groups : []\n return true\n end\n end\n return false\n end", "label_name": "CWE-384", "label": 1} {"code": "def resource_stop(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n stdout, stderr, retval = run_cmd(\n session, PCS, \"resource\", \"disable\", params[:resource]\n )\n if retval == 0\n return JSON.generate({\"success\" => \"true\"})\n else\n return JSON.generate({\"error\" => \"true\", \"stdout\" => stdout, \"stderror\" => stderr})\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def remove_constraint_remote(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n if params[:constraint_id]\n retval = remove_constraint(session, params[:constraint_id])\n if retval == 0\n return \"Constraint #{params[:constraint_id]} removed\"\n else\n return [400, \"Error removing constraint: #{params[:constraint_id]}\"]\n end\n else\n return [400,\"Bad Constraint Options\"]\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def set_certs(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::FULL)\n return 403, 'Permission denied'\n end\n\n ssl_cert = (params['ssl_cert'] || '').strip\n ssl_key = (params['ssl_key'] || '').strip\n if ssl_cert.empty? and !ssl_key.empty?\n return [400, 'cannot save ssl certificate without ssl key']\n end\n if !ssl_cert.empty? and ssl_key.empty?\n return [400, 'cannot save ssl key without ssl certificate']\n end\n if !ssl_cert.empty? and !ssl_key.empty?\n ssl_errors = verify_cert_key_pair(ssl_cert, ssl_key)\n if ssl_errors and !ssl_errors.empty?\n return [400, ssl_errors.join]\n end\n begin\n write_file_lock(CRT_FILE, 0700, ssl_cert)\n write_file_lock(KEY_FILE, 0700, ssl_key)\n rescue => e\n # clean the files if we ended in the middle\n # the files will be regenerated on next pcsd start\n FileUtils.rm(CRT_FILE, {:force => true})\n FileUtils.rm(KEY_FILE, {:force => true})\n return [400, \"cannot save ssl files: #{e}\"]\n end\n end\n\n if params['cookie_secret']\n cookie_secret = params['cookie_secret'].strip\n if !cookie_secret.empty?\n begin\n write_file_lock(COOKIE_FILE, 0700, cookie_secret)\n rescue => e\n return [400, \"cannot save cookie secret: #{e}\"]\n end\n end\n end\n\n return [200, 'success']\nend", "label_name": "CWE-384", "label": 1} {"code": "def wizard_submit(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n wizard = PCSDWizard.getWizard(params[\"wizard\"])\n if wizard != nil\n return erb wizard.process_responses(params)\n else\n return \"Error finding Wizard - #{params[\"wizard\"]}\"\n end\n\nend", "label_name": "CWE-384", "label": 1} {"code": "def run_cmd(session, *args)\n options = {}\n return run_cmd_options(session, options, *args)\nend", "label_name": "CWE-384", "label": 1} {"code": "def get_node_attributes(session, cib_dom=nil)\n unless cib_dom\n cib_dom = get_cib_dom(session)\n return {} unless cib_dom\n end\n node_attrs = {}\n cib_dom.elements.each(\n '/cib/configuration/nodes/node/instance_attributes/nvpair'\n ) { |e|\n node = e.parent.parent.attributes['uname']\n node_attrs[node] ||= []\n node_attrs[node] << {\n :id => e.attributes['id'],\n :key => e.attributes['name'],\n :value => e.attributes['value']\n }\n }\n node_attrs.each { |_, val| val.sort_by! { |obj| obj[:key] }}\n return node_attrs\nend", "label_name": "CWE-384", "label": 1} {"code": "def set_configs(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::FULL)\n return 403, 'Permission denied'\n end\n return JSON.generate({'status' => 'bad_json'}) if not params['configs']\n begin\n configs_json = JSON.parse(params['configs'])\n rescue JSON::ParserError\n return JSON.generate({'status' => 'bad_json'})\n end\n has_cluster = !($cluster_name == nil or $cluster_name.empty?)\n if has_cluster and $cluster_name != configs_json['cluster_name']\n return JSON.generate({'status' => 'wrong_cluster_name'})\n end\n\n $semaphore_cfgsync.synchronize {\n force = configs_json['force']\n remote_configs, unknown_cfg_names = Cfgsync::sync_msg_to_configs(configs_json)\n local_configs = Cfgsync::get_configs_local\n\n result = {}\n unknown_cfg_names.each { |name| result[name] = 'not_supported' }\n remote_configs.each { |name, remote_cfg|\n begin\n # Save a remote config if it is a newer version than local. If the config\n # is not present on a local node, the node is beeing added to a cluster,\n # so we need to save the config as well.\n if force or not local_configs.key?(name) or remote_cfg > local_configs[name]\n local_configs[name].class.backup() if local_configs.key?(name)\n remote_cfg.save()\n result[name] = 'accepted'\n elsif remote_cfg == local_configs[name]\n # Someone wants this node to have a config that it already has.\n # So the desired state is met and the result is a success then.\n result[name] = 'accepted'\n else\n result[name] = 'rejected'\n end\n rescue => e\n $logger.error(\"Error saving config '#{name}': #{e}\")\n result[name] = 'error'\n end\n }\n return JSON.generate({'status' => 'ok', 'result' => result})\n }\nend", "label_name": "CWE-384", "label": 1} {"code": "def get_avail_fence_agents(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::READ)\n return 403, 'Permission denied'\n end\n agents = getFenceAgents(session)\n return JSON.generate(agents)\nend", "label_name": "CWE-384", "label": 1} {"code": "def add_node(session, new_nodename, all=false, auto_start=true)\n if all\n command = [PCS, \"cluster\", \"node\", \"add\", new_nodename]\n if auto_start\n command << '--start'\n command << '--enable'\n end\n out, stderror, retval = run_cmd(session, *command)\n else\n out, stderror, retval = run_cmd(\n session, PCS, \"cluster\", \"localnode\", \"add\", new_nodename\n )\n end\n $logger.info(\"Adding #{new_nodename} to pcs_settings.conf\")\n corosync_nodes = get_corosync_nodes()\n pcs_config = PCSConfig.new(Cfgsync::PcsdSettings.from_file('{}').text())\n pcs_config.update_cluster($cluster_name, corosync_nodes)\n sync_config = Cfgsync::PcsdSettings.from_text(pcs_config.text())\n # on version conflict just go on, config will be corrected eventually\n # by displaying the cluster in the web UI\n Cfgsync::save_sync_new_version(\n sync_config, corosync_nodes, $cluster_name, true\n )\n return retval, out.join(\"\\n\") + stderror.join(\"\\n\")\nend", "label_name": "CWE-384", "label": 1} {"code": "def getResourceAgents(session)\n resource_agent_list = {}\n stdout, stderr, retval = run_cmd(session, PCS, \"resource\", \"list\", \"--nodesc\")\n if retval != 0\n $logger.error(\"Error running 'pcs resource list --nodesc\")\n $logger.error(stdout + stderr)\n return {}\n end\n\n agents = stdout\n agents.each { |a|\n ra = ResourceAgent.new\n ra.name = a.chomp\n resource_agent_list[ra.name] = ra\n }\n return resource_agent_list\nend", "label_name": "CWE-384", "label": 1} {"code": "def get_cluster_properties_definition(params, request, session)\n unless allowed_for_local_cluster(session, Permissions::READ)\n return 403, 'Permission denied'\n end\n stdout, _, retval = run_cmd(\n session, PCS, 'property', 'get_cluster_properties_definition'\n )\n if retval == 0\n return [200, stdout]\n end\n return [400, '{}']\nend", "label_name": "CWE-384", "label": 1} {"code": "def set_corosync_conf(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::FULL)\n return 403, 'Permission denied'\n end\n if params[:corosync_conf] != nil and params[:corosync_conf].strip != \"\"\n Cfgsync::CorosyncConf.backup()\n Cfgsync::CorosyncConf.from_text(params[:corosync_conf]).save()\n return 200, \"Succeeded\"\n else\n $logger.info \"Invalid corosync.conf file\"\n return 400, \"Failed\"\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def update_cluster_settings(params, request, session)\n properties = params['config']\n to_update = []\n current = getAllSettings(session)\n\n # We need to be able to set cluster properties also from older version GUI.\n # This code handles proper processing of checkboxes.\n # === backward compatibility layer start ===\n params['hidden'].each { |prop, val|\n next if prop == 'hidden_input'\n unless properties.include?(prop)\n properties[prop] = val\n to_update << prop\n end\n }\n # === backward compatibility layer end ===\n\n properties.each { |prop, val|\n val.strip!\n if not current.include?(prop) and val != '' # add\n to_update << prop\n elsif current.include?(prop) and val == '' # remove\n to_update << prop\n elsif current.include?(prop) and current[prop] != val # update\n to_update << prop\n end\n }\n\n if to_update.count { |x| x.downcase == 'enable-acl' } > 0\n if not allowed_for_local_cluster(session, Permissions::GRANT)\n return 403, 'Permission denied'\n end\n end\n if to_update.count { |x| x.downcase != 'enable-acl' } > 0\n if not allowed_for_local_cluster(session, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n end\n\n if to_update.empty?\n $logger.info('No properties to update')\n else\n cmd_args = []\n to_update.each { |prop|\n cmd_args << \"#{prop.downcase}=#{properties[prop]}\"\n }\n stdout, stderr, retval = run_cmd(session, PCS, 'property', 'set', *cmd_args)\n if retval != 0\n return [400, stderr.join('').gsub(', (use --force to override)', '')]\n end\n end\n return [200, \"Update Successful\"]\nend", "label_name": "CWE-384", "label": 1} {"code": "def resource_change_group(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n\n if params[:resource_id].nil? or params[:group_id].nil?\n return [400, 'resource_id and group_id have to be specified.']\n end\n if params[:group_id].empty?\n if params[:old_group_id]\n _, stderr, retval = run_cmd(\n session, PCS, 'resource', 'group', 'remove', params[:old_group_id],\n params[:resource_id]\n )\n if retval != 0\n return [400, \"Unable to remove resource '#{params[:resource_id]}' \" +\n \"from group '#{params[:old_group_id]}': #{stderr.join('')}\"\n ]\n end\n end\n return 200\n end\n _, stderr, retval = run_cmd(\n session,\n PCS, 'resource', 'group', 'add', params[:group_id], params[:resource_id]\n )\n if retval != 0\n return [400, \"Unable to add resource '#{params[:resource_id]}' to \" +\n \"group '#{params[:group_id]}': #{stderr.join('')}\"\n ]\n end\n return 200\nend", "label_name": "CWE-384", "label": 1} {"code": "def resource_status(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::READ)\n return 403, 'Permission denied'\n end\n resource_id = params[:resource]\n @resources,@groups = getResourcesGroups(session)\n location = \"\"\n res_status = \"\"\n @resources.each {|r|\n if r.id == resource_id\n if r.failed\n res_status = \"Failed\"\n elsif !r.active\n res_status = \"Inactive\"\n else\n res_status = \"Running\"\n end\n if r.nodes.length != 0\n location = r.nodes[0].name\n break\n end\n end\n }\n status = {\"location\" => location, \"status\" => res_status}\n return JSON.generate(status)\nend", "label_name": "CWE-384", "label": 1} {"code": "def add_constraint_remote(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n case params[\"c_type\"]\n when \"loc\"\n retval, error = add_location_constraint(\n session,\n params[\"res_id\"], params[\"node_id\"], params[\"score\"], params[\"force\"],\n !params['disable_autocorrect']\n )\n when \"ord\"\n resA = params[\"res_id\"]\n resB = params[\"target_res_id\"]\n actionA = params['res_action']\n actionB = params['target_action']\n if params[\"order\"] == \"before\"\n resA, resB = resB, resA\n actionA, actionB = actionB, actionA\n end\n\n retval, error = add_order_constraint(\n session,\n resA, resB, actionA, actionB, params[\"score\"], true, params[\"force\"],\n !params['disable_autocorrect']\n )\n when \"col\"\n resA = params[\"res_id\"]\n resB = params[\"target_res_id\"]\n score = params[\"score\"]\n if params[\"colocation_type\"] == \"apart\"\n if score.length > 0 and score[0] != \"-\"\n score = \"-\" + score\n elsif score == \"\"\n score = \"-INFINITY\"\n end\n end\n\n retval, error = add_colocation_constraint(\n session,\n resA, resB, score, params[\"force\"], !params['disable_autocorrect']\n )\n else\n return [400, \"Unknown constraint type: #{params['c_type']}\"]\n end", "label_name": "CWE-384", "label": 1} {"code": "def remove_acl_remote(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::GRANT)\n return 403, 'Permission denied'\n end\n if params[\"item\"] == \"permission\"\n retval = remove_acl_permission(session, params[\"acl_perm_id\"])\n elsif params[\"item\"] == \"usergroup\"\n retval = remove_acl_usergroup(\n session, params[\"role_id\"],params[\"usergroup_id\"]\n )\n else\n retval = \"Error: Unknown removal request\"\n end\n\n if retval == \"\"\n return [200, \"Successfully removed permission from role\"]\n else\n return [400, retval]\n end\nend", "label_name": "CWE-384", "label": 1} {"code": " def self.save_sync_new_version(config, nodes, cluster_name, fetch_on_conflict, tokens={})\n if not cluster_name or cluster_name.empty?\n # we run on a standalone host, no config syncing\n config.version += 1\n config.save()\n return true, {}\n else\n # we run in a cluster so we need to sync the config\n publisher = ConfigPublisher.new(\n PCSAuth.getSuperuserSession(), [config], nodes, cluster_name, tokens\n )\n old_configs, node_responses = publisher.publish()\n if old_configs.include?(config.class.name)\n if fetch_on_conflict\n fetcher = ConfigFetcher.new(\n PCSAuth.getSuperuserSession(), [config.class], nodes, cluster_name\n )\n cfgs_to_save, _ = fetcher.fetch()\n cfgs_to_save.each { |cfg_to_save|\n cfg_to_save.save() if cfg_to_save.class == config.class\n }\n end\n return false, node_responses\n end\n return true, node_responses\n end\n end", "label_name": "CWE-384", "label": 1} {"code": "def pcsd_restart_nodes(session, nodes)\n node_response = {}\n threads = []\n nodes.each { |node|\n threads << Thread.new {\n code, response = send_request_with_token(\n session, node, '/pcsd_restart', true\n )\n node_response[node] = [code, response]\n }\n }\n threads.each { |t| t.join }\n\n node_error = []\n node_status = {}\n node_response.each { |node, response|\n if response[0] == 200\n node_status[node] = {\n 'status' => 'ok',\n 'text' => 'Success',\n }\n else\n text = response[1]\n if response[0] == 401\n text = \"Unable to authenticate, try running 'pcs cluster auth'\"\n elsif response[0] == 400\n begin\n parsed_response = JSON.parse(response[1], {:symbolize_names => true})\n if parsed_response[:noresponse]\n text = \"Unable to connect\"\n elsif parsed_response[:notoken] or parsed_response[:notauthorized]\n text = \"Unable to authenticate, try running 'pcs cluster auth'\"\n end\n rescue JSON::ParserError\n end\n end\n node_status[node] = {\n 'status' => 'error',\n 'text' => text\n }\n node_error << node\n end\n }\n return {\n 'status' => node_error.empty?() ? 'ok' : 'error',\n 'text' => node_error.empty?() ? 'Success' : \\\n \"Unable to restart pcsd on nodes: #{node_error.join(', ')}\",\n 'node_status' => node_status,\n }\nend", "label_name": "CWE-384", "label": 1} {"code": "def add_acl_remote(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::GRANT)\n return 403, 'Permission denied'\n end\n if params[\"item\"] == \"permission\"\n retval = add_acl_permission(\n session,\n params[\"role_id\"], params[\"type\"], params[\"xpath_id\"], params[\"query_id\"]\n )\n elsif (params[\"item\"] == \"user\") or (params[\"item\"] == \"group\")\n retval = add_acl_usergroup(\n session, params[\"role_id\"], params[\"item\"], params[\"usergroup\"]\n )\n else\n retval = \"Error: Unknown adding request\"\n end\n\n if retval == \"\"\n return [200, \"Successfully added permission to role\"]\n else\n return [\n 400,\n retval.include?(\"cib_replace failed\") ? \"Error adding permission\" : retval\n ]\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def node_restart(params, request, session)\n if params[:name]\n code, response = send_request_with_token(\n session, params[:name], 'node_restart', true\n )\n else\n if not allowed_for_local_cluster(session, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n $logger.info \"Restarting Node\"\n output = `/sbin/reboot`\n $logger.debug output\n return output\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def node_standby(params, request, session)\n if params[:name]\n code, response = send_request_with_token(\n session, params[:name], 'node_standby', true, {\"node\"=>params[:name]}\n )\n # data={\"node\"=>params[:name]} for backward compatibility with older versions of pcs/pcsd\n else\n if not allowed_for_local_cluster(session, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n $logger.info \"Standby Node\"\n stdout, stderr, retval = run_cmd(session, PCS, \"cluster\", \"standby\")\n return stdout\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def check_gui_status_of_nodes(session, nodes, check_mutuality=false, timeout=10)\n options = {}\n options[:check_auth_only] = '' if not check_mutuality\n threads = []\n not_authorized_nodes = []\n online_nodes = []\n offline_nodes = []\n\n nodes = nodes.uniq.sort\n nodes.each { |node|\n threads << Thread.new {\n code, response = send_request_with_token(\n session, node, 'check_auth', false, options, true, nil, timeout\n )\n if code == 200\n if check_mutuality\n begin\n parsed_response = JSON.parse(response)\n if parsed_response['node_list'] and parsed_response['node_list'].uniq.sort == nodes\n online_nodes << node\n else\n not_authorized_nodes << node\n end\n rescue\n not_authorized_nodes << node\n end\n else\n online_nodes << node\n end\n else\n begin\n parsed_response = JSON.parse(response)\n if parsed_response['notauthorized'] or parsed_response['notoken']\n not_authorized_nodes << node\n else\n offline_nodes << node\n end\n rescue JSON::ParserError\n end\n end\n }\n }\n threads.each { |t| t.join }\n return online_nodes, offline_nodes, not_authorized_nodes\nend", "label_name": "CWE-384", "label": 1} {"code": "def cluster_enable(params, request, session)\n if params[:name]\n code, response = send_request_with_token(\n session, params[:name], 'cluster_enable', true\n )\n else\n if not allowed_for_local_cluster(session, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n success = enable_cluster(session)\n if not success\n return JSON.generate({\"error\" => \"true\"})\n end\n return \"Cluster Enabled\"\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def resource_metadata(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::READ)\n return 403, 'Permission denied'\n end\n return 200 if not params[:resourcename] or params[:resourcename] == \"\"\n resource_name = params[:resourcename][params[:resourcename].rindex(':')+1..-1]\n class_provider = params[:resourcename][0,params[:resourcename].rindex(':')]\n\n @resource = ResourceAgent.new(params[:resourcename])\n if class_provider == \"ocf:heartbeat\"\n @resource.required_options, @resource.optional_options, @resource.info = getResourceMetadata(session, HEARTBEAT_AGENTS_DIR + resource_name)\n elsif class_provider == \"ocf:pacemaker\"\n @resource.required_options, @resource.optional_options, @resource.info = getResourceMetadata(session, PACEMAKER_AGENTS_DIR + resource_name)\n elsif class_provider == 'nagios'\n @resource.required_options, @resource.optional_options, @resource.info = getResourceMetadata(session, NAGIOS_METADATA_DIR + resource_name + '.xml')\n end\n @new_resource = params[:new]\n @resources, @groups = getResourcesGroups(session)\n\n erb :resourceagentform\nend", "label_name": "CWE-384", "label": 1} {"code": " def testLoginByToken\n users = []\n users << {\"username\" => \"user1\", \"token\" => \"token1\"}\n users << {\"username\" => \"user2\", \"token\" => \"token2\"}\n users << {\"username\" => SUPERUSER, \"token\" => \"tokenS\"}\n password_file = File.open($user_pass_file, File::RDWR|File::CREAT)\n password_file.truncate(0)\n password_file.rewind\n password_file.write(JSON.pretty_generate(users))\n password_file.close()\n\n session = {}\n cookies = {}\n result = PCSAuth.loginByToken(session, cookies)\n assert_equal(false, result)\n assert_equal({}, session)\n\n session = {}\n cookies = {'token' => 'tokenX'}\n result = PCSAuth.loginByToken(session, cookies)\n assert_equal(false, result)\n assert_equal({}, session)\n\n session = {}\n cookies = {'token' => 'token1'}\n result = PCSAuth.loginByToken(session, cookies)\n assert_equal(true, result)\n assert_equal(\n {:username => 'user1', :usergroups => ['group1', 'haclient']},\n session\n )\n\n session = {}\n cookies = {\n 'token' => 'token1',\n 'CIB_user' => 'userX',\n 'CIB_user_groups' => PCSAuth.cookieUserEncode('groupX')\n }\n result = PCSAuth.loginByToken(session, cookies)\n assert_equal(true, result)\n assert_equal(\n {:username => 'user1', :usergroups => ['group1', 'haclient']},\n session\n )\n\n session = {}\n cookies = {'token' => 'tokenS'}\n result = PCSAuth.loginByToken(session, cookies)\n assert_equal(true, result)\n assert_equal(\n {:username => SUPERUSER, :usergroups => []},\n session\n )\n\n session = {}\n cookies = {\n 'token' => 'tokenS',\n 'CIB_user' => 'userX',\n 'CIB_user_groups' => PCSAuth.cookieUserEncode('groupX')\n }\n result = PCSAuth.loginByToken(session, cookies)\n assert_equal(true, result)\n assert_equal(\n {:username => 'userX', :usergroups => ['groupX']},\n session\n )\n end", "label_name": "CWE-384", "label": 1} {"code": "def remove_resource(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n force = params['force']\n no_error_if_not_exists = params.include?('no_error_if_not_exists')\n errors = \"\"\n params.each { |k,v|\n if k.index(\"resid-\") == 0\n resid = k.gsub('resid-', '')\n command = [PCS, 'resource', 'delete', resid]\n command << '--force' if force\n out, errout, retval = run_cmd(session, *command)\n if retval != 0\n unless out.index(\" does not exist.\") != -1 and no_error_if_not_exists \n errors += errout.join(' ').strip + \"\\n\"\n end\n end\n end\n }\n errors.strip!\n if errors == \"\"\n return 200\n else\n $logger.info(\"Remove resource errors:\\n\"+errors)\n return [400, errors]\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def remove_acl_roles_remote(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::GRANT)\n return 403, 'Permission denied'\n end\n errors = \"\"\n params.each { |name, value|\n if name.index(\"role-\") == 0\n out, errout, retval = run_cmd(\n session, PCS, \"acl\", \"role\", \"delete\", value.to_s, \"--autodelete\"\n )\n if retval != 0\n errors += \"Unable to remove role #{value}\"\n unless errout.include?(\"cib_replace failure\")\n errors += \": #{errout.join(\" \").strip()}\"\n end\n errors += \"\\n\"\n $logger.info errors\n end\n end\n }\n if errors == \"\"\n return [200, \"Successfully removed ACL roles\"]\n else\n return [400, errors]\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def get_tokens(params, request, session)\n # pcsd runs as root thus always returns hacluster's tokens\n if not allowed_for_local_cluster(session, Permissions::FULL)\n return 403, 'Permission denied'\n end\n return [200, JSON.generate(read_tokens)]\nend", "label_name": "CWE-384", "label": 1} {"code": " def self.save_sync_new_tokens(config, new_tokens, nodes, cluster_name)\n with_new_tokens = PCSTokens.new(config.text)\n with_new_tokens.tokens.update(new_tokens)\n config_new = PcsdTokens.from_text(with_new_tokens.text)\n if not cluster_name or cluster_name.empty?\n # we run on a standalone host, no config syncing\n config_new.version += 1\n config_new.save()\n return true, {}\n end\n # we run in a cluster so we need to sync the config\n publisher = ConfigPublisher.new(\n PCSAuth.getSuperuserSession(), [config_new], nodes, cluster_name,\n new_tokens\n )\n old_configs, node_responses = publisher.publish()\n if not old_configs.include?(config_new.class.name)\n # no node had newer tokens file, we are ok, everything done\n return true, node_responses\n end\n # get tokens from all nodes and merge them\n fetcher = ConfigFetcher.new(\n PCSAuth.getSuperuserSession(), [config_new.class], nodes, cluster_name\n )\n fetched_tokens = fetcher.fetch_all()[config_new.class.name]\n config_new = Cfgsync::merge_tokens_files(config, fetched_tokens, new_tokens)\n # and try to publish again\n return Cfgsync::save_sync_new_version(\n config_new, nodes, cluster_name, true, new_tokens\n )\n end", "label_name": "CWE-384", "label": 1} {"code": "def set_sync_options(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::FULL)\n return 403, 'Permission denied'\n end\n\n options = [\n 'sync_thread_pause', 'sync_thread_resume',\n 'sync_thread_disable', 'sync_thread_enable',\n ]\n if params.keys.count { |key| options.include?(key) } != 1\n return [400, 'Exactly one option has to be specified']\n end\n\n if params['sync_thread_disable']\n if Cfgsync::ConfigSyncControl.sync_thread_disable($semaphore_cfgsync)\n return 'sync thread disabled'\n else\n return [400, 'sync thread disable error']\n end\n end\n\n if params['sync_thread_enable']\n if Cfgsync::ConfigSyncControl.sync_thread_enable()\n return 'sync thread enabled'\n else\n return [400, 'sync thread enable error']\n end\n end\n\n if params['sync_thread_resume']\n if Cfgsync::ConfigSyncControl.sync_thread_resume()\n return 'sync thread resumed'\n else\n return [400, 'sync thread resume error']\n end\n end\n\n if params['sync_thread_pause']\n if Cfgsync::ConfigSyncControl.sync_thread_pause(\n $semaphore_cfgsync, params['sync_thread_pause']\n )\n return 'sync thread paused'\n else\n return [400, 'sync thread pause error']\n end\n end\n\n return [400, 'Exactly one option has to be specified']\nend", "label_name": "CWE-384", "label": 1} {"code": " def protected!\n gui_request = ( # these are URLs for web pages\n request.path == '/' or\n request.path == '/manage' or\n request.path == '/permissions' or\n request.path.match('/managec/.+/main')\n )\n if request.path.start_with?('/remote/') or request.path == '/run_pcs'\n @auth_user = PCSAuth.loginByToken(cookies)\n unless @auth_user\n halt [401, '{\"notauthorized\":\"true\"}']\n end\n else #/managec/* /manage/* /permissions\n if !gui_request and\n request.env['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest'\n then\n # Accept non GUI requests only with header\n # \"X_REQUESTED_WITH: XMLHttpRequest\". (check if they are send via AJAX).\n # This prevents CSRF attack.\n halt [401, '{\"notauthorized\":\"true\"}']\n elsif not PCSAuth.isLoggedIn(session)\n if gui_request\n session[:pre_login_path] = request.path\n redirect '/login'\n else\n halt [401, '{\"notauthorized\":\"true\"}']\n end\n end\n end\n end", "label_name": "CWE-384", "label": 1} {"code": "def set_cluster_conf(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::FULL)\n return 403, 'Permission denied'\n end\n if params[:cluster_conf] != nil and params[:cluster_conf].strip != \"\"\n Cfgsync::ClusterConf.backup()\n Cfgsync::ClusterConf.from_text(params[:cluster_conf]).save()\n return 200, 'Updated cluster.conf...'\n else\n $logger.info \"Invalid cluster.conf file\"\n return 400, 'Failed to update cluster.conf...'\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def verify_cert_key_pair(cert, key)\n errors = []\n cert_modulus = nil\n key_modulus = nil\n\n stdout, stderr, retval = run_cmd_options(\n PCSAuth.getSuperuserSession(),\n {\n 'stdin' => cert,\n },\n '/usr/bin/openssl', 'x509', '-modulus', '-noout'\n )\n if retval != 0\n errors << \"Invalid certificate: #{stderr.join}\"\n else\n cert_modulus = stdout.join.strip\n end\n\n stdout, stderr, retval = run_cmd_options(\n PCSAuth.getSuperuserSession(),\n {\n 'stdin' => key,\n },\n '/usr/bin/openssl', 'rsa', '-modulus', '-noout'\n )\n if retval != 0\n errors << \"Invalid key: #{stderr.join}\"\n else\n key_modulus = stdout.join.strip\n end\n\n if errors.empty? and cert_modulus and key_modulus\n if cert_modulus != key_modulus\n errors << 'Certificate does not match the key'\n end\n end\n\n return errors\nend", "label_name": "CWE-384", "label": 1} {"code": "def add_colocation_constraint(\n session, resourceA, resourceB, score, force=false, autocorrect=true\n)\n if score == \"\" or score == nil\n score = \"INFINITY\"\n end\n command = [\n PCS, \"constraint\", \"colocation\", \"add\", resourceA, resourceB, score\n ]\n command << '--force' if force\n command << '--autocorrect' if autocorrect\n stdout, stderr, retval = run_cmd(session, *command)\n return retval, stderr.join(' ')\nend", "label_name": "CWE-384", "label": 1} {"code": "def get_pacemaker_version()\n begin\n stdout, stderror, retval = run_cmd(\n PCSAuth.getSuperuserSession, PACEMAKERD, \"-$\"\n )\n rescue\n stdout = []\n end\n if retval == 0\n match = /(\\d+)\\.(\\d+)\\.(\\d+)/.match(stdout.join())\n if match\n return match[1..3].collect { | x | x.to_i }\n end\n end\n return nil\nend", "label_name": "CWE-384", "label": 1} {"code": " def protected!\n if not PCSAuth.loginByToken(session, cookies) and not PCSAuth.isLoggedIn(session)\n # If we're on /managec//main we redirect\n match_expr = \"/managec/(.*)/(.*)\"\n mymatch = request.path.match(match_expr)\n on_managec_main = false\n if mymatch and mymatch.length >= 3 and mymatch[2] == \"main\"\n on_managec_main = true\n end\n\n if request.path.start_with?('/remote') or\n (request.path.match(match_expr) and not on_managec_main) or\n '/run_pcs' == request.path or\n '/clusters_overview' == request.path or\n request.path.start_with?('/permissions_')\n then\n $logger.info \"ERROR: Request without authentication\"\n halt [401, '{\"notauthorized\":\"true\"}']\n else\n session[:pre_login_path] = request.path\n redirect '/login'\n end\n end\n end", "label_name": "CWE-352", "label": 0} {"code": "def remove_constraint(session, constraint_id)\n stdout, stderror, retval = run_cmd(\n session, PCS, \"constraint\", \"remove\", constraint_id\n )\n $logger.info stdout\n return retval\nend", "label_name": "CWE-384", "label": 1} {"code": "def get_resource_agents_avail(session)\n code, result = send_cluster_request_with_token(\n session, params[:cluster], 'get_avail_resource_agents'\n )\n return {} if 200 != code\n begin\n ra = JSON.parse(result)\n if (ra[\"noresponse\"] == true) or (ra[\"notauthorized\"] == \"true\") or (ra[\"notoken\"] == true) or (ra[\"pacemaker_not_running\"] == true)\n return {}\n else\n return ra\n end\n rescue JSON::ParserError\n return {}\n end\nend", "label_name": "CWE-384", "label": 1} {"code": "def node_unstandby(params, request, session)\n if params[:name]\n code, response = send_request_with_token(\n session, params[:name], 'node_unstandby', true, {\"node\"=>params[:name]}\n )\n # data={\"node\"=>params[:name]} for backward compatibility with older versions of pcs/pcsd\n else\n if not allowed_for_local_cluster(session, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n $logger.info \"Unstandby Node\"\n stdout, stderr, retval = run_cmd(session, PCS, \"cluster\", \"unstandby\")\n return stdout\n end\nend", "label_name": "CWE-384", "label": 1} {"code": " def self.getUsersGroups(username)\n stdout, stderr, retval = run_cmd(\n getSuperuserSession, \"id\", \"-Gn\", username\n )\n if retval != 0\n $logger.info(\n \"Unable to determine groups of user '#{username}': #{stderr.join(' ').strip}\"\n )\n return [false, []]\n end\n return [true, stdout.join(' ').split(nil)]\n end", "label_name": "CWE-384", "label": 1} {"code": "function cleaner() {\n setTimeout(() => {\n if (ids.length < 1) { return; }\n ActiveRooms.forEach((element, index) => {\n element.Players.forEach((element2, index2) => {\n if (!ids.includes(element2.Id)) {\n ActiveRooms[index].Players.splice(index2, 1);\n ActiveRooms[index].Players.forEach((element3) => {\n element3.socket.emit('UserLeave', JSON.stringify({ RoomId: element.Id, UserLeaved: element2.Id }));\n });\n }\n });\n });\n ActiveRooms.forEach((element, index) => {\n if (element.Players.length === 0) {\n ActiveRooms.splice(index, 1);\n }\n });\n // ids = [];\n }, 5000);\n}", "label_name": "CWE-384", "label": 1} {"code": "export async function execRequest(routes: Routers, ctx: AppContext) {\n\tconst match = findMatchingRoute(ctx.path, routes);\n\tif (!match) throw new ErrorNotFound();\n\n\tconst endPoint = match.route.findEndPoint(ctx.request.method as HttpMethod, match.subPath.schema);\n\tif (ctx.URL && !isValidOrigin(ctx.URL.origin, baseUrl(endPoint.type), endPoint.type)) throw new ErrorNotFound(`Invalid origin: ${ctx.URL.origin}`, 'invalidOrigin');\n\n\t// This is a generic catch-all for all private end points - if we\n\t// couldn't get a valid session, we exit now. Individual end points\n\t// might have additional permission checks depending on the action.\n\tif (!match.route.isPublic(match.subPath.schema) && !ctx.joplin.owner) throw new ErrorForbidden();\n\n\treturn endPoint.handler(match.subPath, ctx);\n}", "label_name": "CWE-352", "label": 0} {"code": "function RegisterUserName(socket, Data) {\n var userName = Data.UserName.split('>').join(' ').split('<').join(' ').split('/').join(' ');\n if (userName.length > 16) userName = userName.slice(0, 16);\n if (userName.toLowerCase().includes('voc\u00ea')) userName = '~' + userName;\n ActiveRooms.forEach((element, index) => {\n if (element.Id === Data.RoomId) {\n ActiveRooms[index].Players.forEach((element2, index2) => {\n if (element2.Name.toLowerCase() === userName.toLowerCase()) {\n console.log('UserName already exists');\n return socket.emit('UserNameAlreadyExists');\n } else if (element2.Id === Data.UserId) {\n ActiveRooms[index].Players[index2].Name = userName;\n }\n socket.emit('UserNameInformation', JSON.stringify({ RoomId: element.Id, UserId: element2.Id, NickName: element2.Name }));\n });\n }\n });\n}", "label_name": "CWE-384", "label": 1} {"code": "\t\ttriggerMassAction: function (massActionUrl, type) {\n\t\t\tconst self = this.relatedListInstance;\n\t\t\tlet validationResult = self.checkListRecordSelected();\n\t\t\tif (validationResult != true) {\n\t\t\t\tlet progressIndicatorElement = $.progressIndicator(),\n\t\t\t\t\tselectedIds = self.readSelectedIds(true),\n\t\t\t\t\texcludedIds = self.readExcludedIds(true),\n\t\t\t\t\tcvId = self.getCurrentCvId(),\n\t\t\t\t\tpostData = self.getCompleteParams();\n\t\t\t\tdelete postData.mode;\n\t\t\t\tdelete postData.view;\n\t\t\t\tpostData.viewname = cvId;\n\t\t\t\tpostData.selected_ids = selectedIds;\n\t\t\t\tpostData.excluded_ids = excludedIds;\n\t\t\t\tlet actionParams = {\n\t\t\t\t\ttype: 'POST',\n\t\t\t\t\turl: massActionUrl,\n\t\t\t\t\tdata: postData\n\t\t\t\t};\n\t\t\t\tif (type === 'sendByForm') {\n\t\t\t\t\tapp.openUrlMethodPost(massActionUrl, postData);\n\t\t\t\t\tprogressIndicatorElement.progressIndicator({ mode: 'hide' });\n\t\t\t\t} else {\n\t\t\t\t\tAppConnector.request(actionParams)\n\t\t\t\t\t\t.done(function (responseData) {\n\t\t\t\t\t\t\tprogressIndicatorElement.progressIndicator({ mode: 'hide' });\n\t\t\t\t\t\t\tif (responseData && responseData.result !== null) {\n\t\t\t\t\t\t\t\tif (responseData.result.notify) {\n\t\t\t\t\t\t\t\t\tVtiger_Helper_Js.showMessage(responseData.result.notify);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (responseData.result.reloadList) {\n\t\t\t\t\t\t\t\t\tVtiger_Detail_Js.reloadRelatedList();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (responseData.result.processStop) {\n\t\t\t\t\t\t\t\t\tprogressIndicatorElement.progressIndicator({ mode: 'hide' });\n\t\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.fail(function (error, err) {\n\t\t\t\t\t\t\tprogressIndicatorElement.progressIndicator({ mode: 'hide' });\n\t\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tself.noRecordSelectedAlert();\n\t\t\t}\n\t\t},", "label_name": "CWE-352", "label": 0}