Login with SESSION and header()! - php-5.5

I'm trying to be redirected to my index.php Homepage after login but it does not work and I am not getting any error.
At the beginning of my index.php script i have the following code to redirect the user to the login.php Page:
<?php
if (!isset($_SESSION['username'])) {
include 'login.php';
die();
}
?>
From my loginController.php the user should be redirected to the index.php Homepage. index.php and loginController.php are located in the same folder.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
if(isset($_POST['username'], $_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
if(!empty($username) && !empty($password)){
try{
include 'models/login.php'; //This is another login.php else in the included one in index.php
$login = new Login($username, $password);
//echo "your query was successful :) ";
session_start();
$_SESSION['username'] = $username;
header('Location: index.php');
}
catch(Exception $exc){
echo $exc->getMessage();
}
} }
?>
I want to mention that my query is seccessful

Related

Yii2-curl oAuth2 with zoho

I am working on Yii2. I have a URL which on hitting a browser is redirected to my redirect URI.
URL
https://accounts.zoho.com/oauth/v2/auth?scope=ZohoBugTracker.projects.ALL,ZohoBugTracker.bugs.ALL&client_id=1000&response_type=code&access_type=offline&redirect_uri=http://11.111.111.111:7000/api/oauth/zoho_auth
When I hit the above URL it will redirect to my redirect URI while giving a code
Redirect URI
After hitting the above URL the redirect URI is http://11.111.111.111:7000/api/oauth/zoho_auth?code=1000&location=us&accounts-server=https%3A%2F%2Faccounts.zoho.com
Redirect URI Response
{"Message":"No HTTP resource was found that matches the request URI 'http://11.111.111.111:7000/api/oauth/zoho_auth?code=1000&location=us&accounts-server=https:%2F%2Faccounts.zoho.com'."}
How to get the code from the above response?
Update 1
As per suggestion given. I tried to send a GET request using linslin. Below is my code
public static function authToken()
{
$curl = new curl\Curl();
$response = $curl->setGetParams([
'scope' => 'ZohoBugTracker.projects.ALL,ZohoBugTracker.bugs.ALL',
'client_id' => '1000',
'response_type' => 'code',
'access_type' => 'offline',
'redirect_uri' => 'http://11.111.111.111:7000/api/oauth/zoho_auth',
])
->get('https://accounts.zoho.com/oauth/v2/auth');
echo $response;
exit();
}
And then called this function inside a function through which I am actually creating bugs using zoho API
Testing my API via POSTMAN
http://localhost:225/inventory-web/api/web/v1/installation/email?ref_no=28373340485858U&customer_id=37030315933&site_snap_name=28373340485858U_1530958224_site_9.jpg&flag=1
My email function is written inside a API controller. So, it will first hit the issueSetup($param1,$param2)
public function actionEmail()
{
.
.
.
.
Installations::setupEmail($param1, $param2, $param3);
.
.
.
}
The above function setupEmail($param1,$param2,$param3) is inside my controller.
public static function setupEmail($ref_no, $customer_id, $install_id)
{
.
.
.
.
.
list(params.....)= Installations::issueSetup($param1,$param2);
.
.
.
.
}
issuSetup funciton
public static function issueSetup($param1,$param2)
{
.
.
.
.
$token = Installations::authToken();
exit();
.
.
.
.
}
After hitting the API the I am getting no response in POSTMAN just the empty window
Any help would be highly appreciated.
Its working quite fine when you enable SSL and check the response code / response header to redirect to the userAuth form on Zuhu:
$curl = new \linslin\yii2\curl\Curl();
/** #var Curl $response */
$curl->setGetParams([
'scope' => 'ZohoBugTracker.projects.ALL,ZohoBugTracker.bugs.ALL',
'client_id' => '1000',
'response_type' => 'code',
'access_type' => 'offline',
'redirect_uri' => 'http://11.111.111.111:7000/api/oauth/zoho_auth',
])->setOption(CURLOPT_SSL_VERIFYPEER, true)
->setOption(CURLOPT_SSL_VERIFYHOST, false)
->setOption(CURLOPT_CAINFO, 'C:/Ampps/apache/conf/ssl_crt/cacert.pem')
->get('https://accounts.zoho.com/oauth/v2/auth');
$responseHeaders = $curl->responseHeaders;
if ($curl->responseCode === 302 && isset($responseHeaders['Location'])) {
header("location: ".$responseHeaders['Location']);
die();
}
Have you tried this to get Error
if ($curl->errorCode === null) {
echo $response;
} else {
echo '<pre>';print_r($curl->errorCode);
}

Sentinel for laravel 5 - Cannot Logout - session persists

Laravel 5.1
Sentinel 2
Here is my logout() in controller:
public function logout()
{
$user = Sentinel::getUser();
Sentinel::logout($user, true);
return redirect('/shopadmin/login');
}
Here is how I login:
public function login(Request $request)
{
if (Sentinel::guest()):
$email = $request->get('email');
$pass = $request->get('password');
$credentials = [
'email' => $email,
'password' => $pass,
];
// $role = Sentinel::findRoleByName('admin');
$user = Sentinel::findById(1);
$user = Sentinel::findUserById(1);
if($user = Sentinel::authenticateAndRemember($user, $credentials)):
return redirect('/shopadmin');
else:
return view('backend.login');
endif;
else:
return redirect('/shopadmin');
endif;
}
And I also have this in my __contruct
public function __construct()
{
$this->layout = view('layouts.backend');
$user = Sentinel::check();
view()->share('user',$user);
}
No middleware
My problem is after logout runs, user should get redirected to login page, but instead it forwards me to the dashboard and Sentinel::getUser(); still shows active user.
with following:
**#persistableKey: "user_id"
#persistableRelationship: "persistences"**
Is there a different way to log out? I cannon flush entire session because I am keeping some non-user variables.
Technically, logout() should destroy all cookies and sessions related to user? correct? Then why in the Functional-Uniformly-Coded-Kernel my user is still logged in?!
Thanks for help!

Zend framework 2 - csrf regenerates on refresh

I am having a problem with the Zend Framework 2 formElement csrf.
It works fine until I submit an invalid form, hit the same page then refresh the page. A "notTheSame" validation error occurs on the field and the message "The form submitted did not originate from the expected site"
appears. And that is correct, because if I check the value of the csrf field, it is different from the one before submission.
The form was working fine before I decided to add the csrf field.
I am creating my csrf field as follow:
class SignupForm extends Form
{
public function __construct()
{
parent::__construct('signup');
$this->setAttribute('method', 'post')
->setHydrator(new ClassMethodsHydrator(false))
->setInputFilter(new InputFilter());
$this->add(array(
'type' => 'Zend\Form\Element\Csrf',
'name' => 'csrf',
'options' => array(
)
));
// I also add a couple of fieldsets after this
And in the view file :
<?php
$form = $this->form;
$form->setAttribute('action', $this->url('needfunding', array('action' => 'register')));
$form->setAttribute('class', "signup-form start");
$form->prepare();
echo $this->form()->openTag($form);
$applicant = $form->get('applicant');
?>
<?php $this->FormErrors($form); ?>
<?php echo $this->formRow($form->get('csrf')); ?>
(FormErrors is a view helper that retrieves the form messages and styles them)
In my controller :
public function signupAction()
{
$form = new SignupForm();
/* some unrelated code [...] */
$request = $this->getRequest();
if ($request->isPost()) {
$category_group_id = $request->getPost()->category_group;
$selected_categories = array();
foreach ($categories as $c) {
$selected_categories[$c->getId()]=html_entity_decode($c->getName());
}
$form->get('category')->setValueOptions($selected_categories);
$form->setData($request->getPost());
if ($form->isValid()) {
/* some unrelated code [...] */
return $this->redirect()->toRoute('signupconfirmation');
}
else {
}
}
return array('form' => $form, 'categories' => $ordered_categories);
}
I guess my question is, why is my csrf regenerated once I'm back on my form page because the form wasn't valid ?
PS: I could not find my solution in this post Zend Framework 2 CSRF Protection
I had experienced a similar problem.
In my case I was using a login form with an Zend\Authentication\Validator\Authentication validation.
The validator was destroying the session on each validation attempt, because it was using a Zend\Authentication\AuthenticationService with the default Zend\Authentication\Storage\Session storage.
Because the csrf value is stored in session, using the validator caused destroyal of the csrf value, so it had to be recreated on each login form POST attempt.
So, my advice is: try to check whether the session does not get destroyed during the refresh (it should not). This reference might help: http://framework.zend.com/manual/2.2/en/modules/zend.session.config.html

How to Access Application Config from View in Zend Framework 2 (zf2)?

I wanted to access the application config from a view. How can I achieve that in ZF 2?
Actually you shouldn't need to access application config inside a view. In MVC, views just responsible for displaying/rendering data (output) and shouldn't contain any business or application logic.
If you really want to do that you can simply pass to view in your controller something like this:
<?php
namespace YourModule\Controller;
use Zend\View\Model\ViewModel;
// ...
public function anyAction()
{
$config = $this->getServiceLocator()->get('config');
$viewModel = new ViewModel();
$viewModel->setVariables(array('config' => $config ));
return $viewModel;
}
// ...
?>
So in your view.phtml file;
<div class="foo">
...
<?php echo $this->config; ?>
...
</div>
You should create a view helper.
Config.php
<?php
namespace Application\View\Helper;
class Config extends \Zend\View\Helper\AbstractHelper
{
public function __construct($config)
{
$this->key = $config;
}
public function __invoke()
{
return $this->config;
}
}
Module.php or theme.config.php
return array(
'helpers' => array(
'factories' => array(
'config' => function ($sm) {
return new \Application\View\Helper\Config(
$sm->getServiceLocator()->get('Application\Config')->get('config')
);
},
)
),
);
Then you can use config variables in any view.
echo $this->config()->Section->key;
I created the module with controller plugin and view helper for reading a config in controllers and views. GitHub link __ Composer link
After installation via composer you can use it easily.
echo $this->configHelp('key_from_config'); //read specific key from config
$config = $this->configHelp(); //return config object Zend\Config\Config
echo $config->key_from_config;

symfony - nestedSet and rendering of parent/child nodes

I have created a model using the doctrine nestedSet behaviour in Symfony1.4, as I'm trying to create a basic cms, with heiracrchial pages.
I have a couple of pages, with parent and child nodes
Parent_1
Child_1
Child_2
Parent_2
Child_3
My problem comes with rendering these items in terms of a navigation header. (<ul><li> etc)
What would be the easiest/best way to do this?
I'd like the root nodes to have URLs such as /parent_1 and subsequent child nodes, be parent_1/child_1
Thanks
I wrote a recursive function that will draw the tree starting from any node. Specifying the root node will draw the entire tree. It is used in my cart plug-in, and you can view a demo of the completed UI here.
I have pasted the function below, but modified it from my implementation to make it more clear.
<?php
//Render a nested set. Recurses for all descendants of that node. Can be used to draw entire tree, when specifying root id.
//Secondary parameter ($node) is used for performance boost, internally in function.
public static function display_node($id, $node = null) {
$isRoot = false;
if ($node == null) {
$node = Doctrine_Core::getTable('YOURNESTEDTABLENAME')->findOneById($id)->getNode();
if ($node->isRoot()) {
$isRoot = true;
}
}
$record = $node->getRecord();
if (!$isRoot) {
echo "<li class='tree_item' id='list_". $record->getId() . "'>";
echo "<div class='listitem' id='listitem_".$record->getId()."'>";
echo $record->getName();
echo "<div style='clear:both'></div>";
echo "</div>";
if ($node->hasChildren()) {
echo "<ol>";
foreach ($node->getChildren() as $child) {
self::display_node($child->getId(), $child->getNode());
}
echo "</ol>";
}
}
else {
if ($node->hasChildren()) {
echo "<ol class='sortable'>";
echo "<li class='tree_item root_item' style='position: relative;' id='list_". $record->getId() . "'>";
foreach ($node->getChildren() as $child) {
self::display_node($child->getId(), $child->getNode());
}
echo "</ol>";
}
}
}
?>
You can also easily modify the code to add URLs as you wish.
Hopefully this helps. Let me know if you require clarification.
I hate to echo view element anywhere other than templates, so here's my version.
//actions:
public function executeShow(sfWebRequest $request)
{
$this->tree = Doctrine::getTable('Model')->getMenuTree();
}
//lib:
class ModelTable extends Doctrine_Table
{
/**
* Gets tree element in one query
*/
public function getMenuTree()
{
$q = $this->createQuery('g')
->orderBy('g.root_id')
->addOrderBy('g.lft')
->where('g.root_id NOT NULL');
return $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY_HIERARCHY);
}
}
//template:
<?php function echoNode($tree, $parent=null) { ?>
<ul>
<?php foreach ($tree as $node): ?>
<li data-id='<?php echo $node['id'] ?>'>
<?php echo $node['name'] ?>
<?php if (count($node['__children']) > 0): ?>
<?php echo echoNode($node['__children'], $node) ?>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
<?php } ?>
<?php echo echoNode($tree) ?>
Now, if you need a part of tree, you can either do in an action or better yet, write a separate model method for that.

Resources