How to intercept and redirect each request on owncloud - redirect

I' struggling with a simple problem on owncloud 7.0
I'm creation an app that have to check a condition and redirect to a page to validate something. My target is to disable service usage until a condition is ok.
In the nominal scenario, user log in, system redirect user to the validation page if condition is not verified. So I use postLogin hook.
But if user try to change page without validating, I have to catch him and redirect it back to the validation page.
I have tried Middleware (owncloud interceptor), but they are not global, so second scenario fails.
Now I'm working with app loading and do something like
$app = new MyApp();
$c = $app->getContainer();
if ( $c->isLoggedIn() ) {
$requestedPath = path($_SERVER['REQUEST_URI']);
$redirectPath = $c->getServer()->getURLGenerator()->linkToRoute('myapp.page.validate');
$refererPath = path($_SERVER['HTTP_REFERER']);
if ( $requestedPath !== $redirectPath && $redirectPath !== $refererPath ) {
$location = $c->getServer()->getRouter()->generate('myapp.page.validate');
header('Location: ' . $location);
exit();
}
}
function path($url) {
$urlArray = parse_url($url);
return $urlArray['path'];
}
It works fine for the first case, but I go into several redirections in the second case.
I think it must exist a better solution. Somebody has an idea ?
PS: I have exposed my case on IRC channel without success to interest someone :)

You might be able to do this using appinfo/app.php if you've registered your app as type authentication in appinfo/info.xml. This should basically look like the following code, however this obviously needs further tuning for your use-case.
info.xml:
<?xml version="1.0"?>
<info>
<id>appname</id>
<name>Appname</name>
<description>Lorem Ipsum.</description>
<licence>AGPL</licence>
<author>Your Name</author>
<require>6.0.3</require>
<types>
<authentication/>
</types>
</info>
app.php:
<?php
namespace OCA\appname\AppInfo;
use \OCP\User;
/**
* Implement your code here
* #return bool
*/
function conditionMatch() {
return true;
}
// Intercept all requests which have not already been matched
if ($_SESSION['alreadyMatched'] !== true) {
if(conditionMatch()) {
$_SESSION['alreadyMatched'] = true;
} else {
// The session has not met the condition - enter your code here
exit();
}
}

Related

Using Symfony Form component standalone with security-csrf - error on submission

I have a question regarding symfony/form using as a standalone component and security-csrf running with PHP build-in server. I hardly remember having such issue with the Symfony framework.
When setting symfony/form as a standalone component I tried this code for both v4.2 and v5.1 https://github.com/xmgcoyi/standalone-forms/tree/4.2+twig. A rewrite of webmozart's example mentioned here https://symfony.com/doc/current/components/form.html
The csrf token is generated with twig-bridge, but when submitting the form - on calling$form->isValid() - invalid csrf error appears.
By default csrf protection is enabled, setting to false - the form submits.
Tried CSRF component with both setups with NativeSessionTokenStorage and SessionTokenStorage + Session of HttpFoundation.
Could you give any hint on what I'm doing wrong and where to look at?
P.S.
Code samples with csrf error on submission:
https://github.com/xmgcoyi/standalone-forms/tree/4.2+twig
https://github.com/liorchamla/pratique-symfony-form/tree/06-protection-csrf
UPD
The apps above work well, the problem was in browser storage filled with garbage.
Setting to false in $formFactory->createBuilder(FormType::class, null, ['csrf_protection' => false]) submits the form
This is a bit of a guess but the 4.2 linked repo has:
$csrfManager = new CsrfTokenManager($csrfGenerator, $csrfStorage);
$csrfTokenManager = new CsrfTokenManager();
Two token managers. One is used in the twig form engine and one is used in the form factory extension. Does not seem like a reasonable thing to do.
Here is an updated 5.1 working example. I stripped it down even more from your linked repo. But the only thing that I really changed was the token manager.
# index.php
require_once '../vendor/autoload.php';
$app = new App();
$app->run();
final class App
{
public function run()
{
$csrfGenerator = new UriSafeTokenGenerator();
$csrfStorage = new NativeSessionTokenStorage();
$csrfManager = new CsrfTokenManager($csrfGenerator, $csrfStorage);
$twig = new Environment(new FilesystemLoader([
'../templates',
'../vendor/symfony/twig-bridge/Resources/views/Form',
]));
$formEngine = new TwigRendererEngine(['form_div_layout.html.twig'], $twig);
$twig->addRuntimeLoader(new FactoryRuntimeLoader([
FormRenderer::class => function () use ($formEngine,$csrfManager) {
return new FormRenderer($formEngine, $csrfManager);
},
]));
$twig->addExtension(new TranslationExtension());
$twig->addExtension(new FormExtension());
$formFactory = Forms::createFormFactoryBuilder()
->addExtension(new CsrfExtension($csrfManager))
//->addExtension(new ValidatorExtension($validator))
->getFormFactory();
$form = $formFactory->createBuilder()
->add('firstName', TextType::class)
->getForm();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$form->submit($_POST[$form->getName()]); // form
if ($form->isValid()) {
dump('form is valid');
}
}
echo $twig->render('index.html.twig', [
'form' => $form->createView(),
]);
}
}
The composer.json is simply:
{
"require": {
"symfony/form": "^5.1",
"symfony/twig-bridge": "^5.1",
"symfony/translation": "^5.1",
"symfony/security-csrf": "^5.1"
},
"require-dev": {
"symfony/var-dumper": "^5.1"
}
}
If you still have trouble then I would suggest tracking down where the sessions are stored and then verifying the that csrf token is being properly stored. It should look something like:
_csrf|a:1:{s:4:"form";s:43:"9v1tUNe3J3eYVOmEPwVdz5_iISfzBg8Qa9pLMV8tSN4";}
This was actually kind of an interesting exercise in using the twig system for standalone forms. Thanks.

Disable redirect in fetch request using React native

I'm trying to crawl a web using React Native which has no API. It's written in PHP.
To log an user, a POST request must be sent. The response returns a cookie with a PHPSessid cookie which I must capture to use in subsequent requests.
I would like to capture the cookie value, buy the POST response is a 302 and the redirection is followed automatically, so I can't see the cookie. In node I was able to do it with redirect:manual, but it does not work in react native.
The cookie is sent automatically in subsequent requests, buy I'm trying to manage cookies by hand with react-native-cookie and I'd like to know if it's possible.
Do you know a way to stop the redirection?
I've been checking the code and what I did was the following:
Clear all cookies
Launch an empty login request
Capture the PHPSessID coookie
Launch a login request with that PHPSessID
After that, the subsequent fetch requests would have automatically a PHPSessID cookie with a valid logged in user, so we can use the site with simple fetchs
Here is some code, but the important thing is that you do a first empty login request, capture the PHPSessid and launch the real login request with that PHPSessid.
This would be the main function:
import Cookie from 'react-native-cookie';
// I think this is used only to clear the cookies
function login(user, pass){
// clear all cookies for all domains
// We need to start withouth authorization token
Cookie.clear();
const makeLoginRequest = (sessid) =>
makeLoginRequestForUserAndPass(user,pass,sessid);
return makeInitialRequest()
.then(getSessionIDFromResponse)
.then(makeLoginRequest)
.then(checkIfLoggedAndGetSessionID);
}
The initial request is a request to the login script. Note that I used GET because it worked with my site, perhaps an empty post would be necessary:
function makeInitialRequest() {
const INIT_PATH = '/index.php?r=site/login';
const INIT_URL = site + INIT_PATH;
const request = new Request(INIT_URL, options....);
return fetch(request);
}
We have the session ID in the response. I used a simple regex to extract it. Note that we are not logged in; PHP has created a session and that's what we have here:
function getSessionIDFromResponse(response) {
return getPHPSessIdFromCookie(response.headers.get('set-cookie'));
}
function getPHPSessIdFromCookie(header) {
const regex = /PHPSESSID=(\w*)/;
const match = regex.exec(header);
return match ? match[1] : '';
}
Now the login request. Note that I can't stop redirection here, but I't have to do it because we can have PHPSessid later. Redirection must be set to manual in POST request:
function makeLoginRequestForUserAndPass(user, pass, sessid) {
const request = buildLoginRequest(user, pass, sessid);
return fetch(request);
}
// This is where we build the real login request
function buildLoginRequest(user, pass, sessid) {
const LOGIN_PATH = '/index.php?r=site/login';
const LOGIN_URL = site + LOGIN_PATH;
const fields = [
{name: 'LoginForm[username]', value: user},
{name: 'LoginForm[password]', value: pass},
etc...
];
const data = translateFieldsToURLEncodedData(fields);
const headers = {
'Content-type': 'application/x-www-form-urlencoded',
Cookie: `PHPSESSID=${sessid}`, // HERE is where you put the data
};
const options = { method: 'POST',
headers: headers,
mode: 'cors',
cache: 'default',
agent: proxy,
body: data,
redirect: 'manual' // VERY IMPORTANT: if you don't do it, the cookie is lost
};
return new Request(LOGIN_URL, options);
}
// Simple utility function
function translateFieldsToURLEncodedData(fields){
let pairs = fields.map( (field) => {
return encodeURIComponent(field.name) + '=' + encodeURIComponent(field.value);
});
return pairs.join('&');
}
This is the last part. To see if I was logged in I checked if the response had text belonging to login error's page. I also got the PHPSessid (I think it changed after login, not sure, it was a year ago) but I don't know if I used it, I believe it was included automatically in subsequent requests. I think this part could be simplified an improved:
function checkIfLoggedAndGetSessionID(response) {
return (
checkIfLoggedOK(response)
.then(() => getSessionIDFromResponse(response))
);
}
function checkIfLoggedOK(response){
return getTextFromResponse(response)
.then(throwErrorIfNotLogedOk);
}
function getTextFromResponse(response) {
return response.text();
}
function throwErrorIfNotLogedOk(page) {
if(isErrorPage(page)) throw new Error("Login failed");
}
function isErrorPage(text) {
const ERROR_MESSAGE = 'Something that appears in login failed page of your site';
let n = text.search(ERROR_MESSAGE);
return n !== -1;
}
Hope this can be useful.

Google Analytics OAuth2: How to solve error: "redirect_uri_mismatch"?

I'm trying to get this example to work: https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/web-php#enable
The error I'm getting is "Error: redirect_uri_mismatch" .
In order to install the google api resources, I used composer with this command:
php composer.phar require google/apiclient:^2.0.0#RC
This installed the "vendor" folder in my root site folder. My index.php and oauth2callback.php files are located in the "public_html" folder.
Here's a screenshot of my error when going to my site:
The weird thing is that if I navigate to the link above that's included in the error message "Visit ...... to update the authorized..", I get this error message: " The OAuth Client Does Not Exist "
If I click on my only available Client ID, I can navigate to see the URI's which I'll screenshot below as well:
As you can see, under Authorized Javascript origins, I have http://localhost listed, and under authorized redirect URIs, I have my live site followed by the "oauthc2callback.php" file extension.
I don't understand how to get rid of the error I'm getting. I've tried replacing the URI's and putting in different JavaScript origins.
Also, for some reason on that last screenshot, it says that I don't have permission to edit this OAuth client, but I can make edits.
The code I have for index.php:
<?php
// Load the Google API PHP Client Library.
require_once '../vendor/autoload.php';
// Start a session to persist credentials.
session_start();
// Create the client object and set the authorization configuration
// from the client_secretes.json you downloaded from the developer console.
$client = new Google_Client();
$client->setAuthConfigFile('../config/client_secrets.json');
$client->addScope('https://www.googleapis.com/auth/analytics.readonly');
// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// Set the access token on the client.
$client->setAccessToken($_SESSION['access_token']);
// Create an authorized analytics service object.
$analytics = new Google_Service_Analytics($client);
// Get the first view (profile) id for the authorized user.
$profile = getFirstProfileId($analytics);
// Get the results from the Core Reporting API and print the results.
$results = getResults($analytics, $profile);
printResults($results);
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
function getFirstprofileId(&$analytics) {
// Get the user's first view (profile) ID.
// Get the list of accounts for the authorized user.
$accounts = $analytics->management_accounts->listManagementAccounts();
if (count($accounts->getItems()) > 0) {
$items = $accounts->getItems();
$firstAccountId = $items[0]->getId();
// Get the list of properties for the authorized user.
$properties = $analytics->management_webproperties
->listManagementWebproperties($firstAccountId);
if (count($properties->getItems()) > 0) {
$items = $properties->getItems();
$firstPropertyId = $items[0]->getId();
// Get the list of views (profiles) for the authorized user.
$profiles = $analytics->management_profiles
->listManagementProfiles($firstAccountId, $firstPropertyId);
if (count($profiles->getItems()) > 0) {
$items = $profiles->getItems();
// Return the first view (profile) ID.
return $items[0]->getId();
} else {
throw new Exception('No views (profiles) found for this user.');
}
} else {
throw new Exception('No properties found for this user.');
}
} else {
throw new Exception('No accounts found for this user.');
}
}
function getResults(&$analytics, $profileId) {
// Calls the Core Reporting API and queries for the number of sessions
// for the last seven days.
return $analytics->data_ga->get(
'ga:' . $profileId,
'7daysAgo',
'today',
'ga:sessions');
}
function printResults(&$results) {
// Parses the response from the Core Reporting API and prints
// the profile name and total sessions.
if (count($results->getRows()) > 0) {
// Get the profile name.
$profileName = $results->getProfileInfo()->getProfileName();
// Get the entry for the first entry in the first row.
$rows = $results->getRows();
$sessions = $rows[0][0];
// Print the results.
print "<p>First view (profile) found: $profileName</p>";
print "<p>Total sessions: $sessions</p>";
} else {
print "<p>No results found.</p>";
}
}
The code I have for "oauth2callback.php":
<?php
require_once '../vendor/autoload.php';
// Start a session to persist credentials.
session_start();
// Create the client object and set the authorization configuration
// from the client_secrets.json you downloaded from the Developers Console.
$client = new Google_Client();
$client->setAuthConfigFile('../config/client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
$client->addScope('https://www.googleapis.com/auth/analytics.readonly');
// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
All of this code was taken from the first website example, except with a few minor additions to make it match my system.
Anyone know how I can get rid of this error? What am I doing wrong?
Remember, as far as Google is concerned, "your" server is hostile until you name it "friendly", you must explicitly whitelist every possible source of an OAuth call TO Google.
Google is a clubbouncer, a big, ugly, unmovable bouncer with a a guest list saying to your application: "I will only deal with your request if your exact name OR id is on the list"
Have you tried including, not only localhost, but all other possible origins?
You must list every possible variation of url "root", including explicit IPs.
http://www.example.com
http://example.com
https://example.com
https://www.example.com
http://222.111.0.111
...
dont forget to include
https://accounts.google.com:443
The redirect Uri in the request MUST be exactly the same as one Uri you stored.
I see a / at the end of the stored one you missed in your request.
just copy the request URI on which error is occurring from error screen and paste it to OAuth credentials "Authorised redirect URIs"
now run the app.
this works for me. Hope I answered your query.

Yii REST POST is not working in POSTMAN but in Framework

how could i post the form to the rest api action. Or how can i test the rest api for creating a record in the db with all the field values. Should we add create aq queryStringUrl. if its comming from a POST form action its fine. But this yii rest api should also work when called on a android device. I have used $_Request on post of the form , will the same work else where. if i wanna test the same in POSTMAN how can i do it. http://localhost/basic/web/site/create?fname=deepika&uname=deeps&email=deep#gmail.com&pwd=deepika&pwd_confirm=deepika&gender=female says 404 in postman. But works in the yii controller url This is the action i have created.
public function actionCreate()
{
$params=$_REQUEST;
//echo $params;
$model= new UsersForm();
if(isset($params['fname']))
$fname=$params['fname'];
if(isset($params['uname']))
$uname=$params['uname'];
if(isset($params['email']))
$email=$params['email'];
if(isset($params['pwd']))
$pwd=$params['pwd'];
if(isset($params['gender']))
$gender=$params['gender'];
if($fname == "" || $uname == "" || $email == "" || $pwd == "" || $gender == ""){
$this->setHeader(400);
echo "<pre>".json_encode(array('status'=>0,'error_code'=>400,'errors'=>"Something went wrong"),JSON_PRETTY_PRINT)."</pre>";
}else{
$model->fname = $fname;
$model->uname = $uname;
$model->email = $email;
$model->pwd = $pwd;
$model->pwd_confirm = $pwd;
$model->gender = $gender;
if($model->save()){
if($model->status == 0){
$mailSent = Yii::$app->mailer->compose()
->setFrom("noreply#gmail.com")
->setTo($model->email)
->setSubject("Proceed by Verification")
->setTextBody('Plain text content')
->setHtmlBody('<b>HTML content</b>')
->send();
// VarDumper::dump($mailSent, 10, true);die();
}
$this->setHeader(200);
echo "<pre>".json_encode(array('status'=>1,'success_code' => 200,'verification_mail'=>$mailSent,'message'=>'Registered Successfully'),JSON_PRETTY_PRINT)."</pre>";
}else{
$this->setHeader(400);
echo "<pre>".json_encode(array('status'=>0,'error_code'=>400,'errors'=>$model->errors),JSON_PRETTY_PRINT)."</pre>";
}
}
// VarDumper::dump($params, 10, true);die();
}
Without code examples its hard to say what goes wrong in your app. I think first of all if you creat new item by GET method, its not REST. In REST API cretion of new item goes by POST method (I say nothing about URL appearance). When I was realized REST in some project, I create simple methods at the backend application and then on frontend (JavaScript app) create simple method for send request to API URLs, and when I preparing headers to send, and then depending of url I set method to headers GET, POST, or PUT (no DELETE because we not deletin items throgh API). So it may be little bit confusing... But I believe when you will get things about REST you will resolve your problem.

Zend Framework: How to redirect to original url after login?

I'm trying to implement a login system that will be smart enough to redirect a user back to the page they were on before they decided (or were forced to) go to the login page.
I know this seems like a similar question to this one, and this one, but they do not address both of my scenarios.
There are two scenarios here:
User specifically decides to go to login page:
<a href="<?php echo $this->url(array(
'controller'=>'auth',
'action'=>'login'), 'default', true); ?>">Log In</a>
User is redirected because they tried to access protected content:
if (!Zend_Auth::getInstance()->hasIdentity()) {
$this->_helper->redirector('login', 'auth');
}
How can I implement a solution for this without displaying the "redirect to" url in the address bar?
Save the destination URL in the session. I guess you have some kind of access pre-dispatch plug-in. Do it there. And then, in the login form handler, check for the destination URL in the session, and redirect to it after a successful authentication.
Sample code from my project:
class Your_Application_Plugin_Access extends Zend_Controller_Plugin_Abstract {
public function preDispatch(Zend_Controller_Request_Abstract $request) {
foreach (self::current_roles() as $role) {
if (
Zend_Registry::get('bootstrap')->siteacl->is_allowed(
$role,
new Site_Action_UriPath($request->getPathInfo())
)
) return; // Allowed
}
$this->not_allowed($request);
}
private function not_allowed(Zend_Controller_Request_Abstract $request) {
$destination_url = $request->getPathInfo();
// If the user is authenticted, but the page is denied for his role, show 403
// else,
// save $destination_url to session
// redirect to login page, with $destination_url saved:
$request
->setPathInfo('/login')
->setModuleName('default')
->setControllerName('login')
->setActionName('index')
->setDispatched(false);
}
...
}
Here, current_roles() always contains 'guest', which is unauthenticated user, for which Zend_Auth::hasIdentity() is false.