Session management in Zend Framework 2 - session

Trying to do site with administration on Zend Framework 2, set the authorization at mysite / admin / login. How to deny access if the authorization is not completed all the way after mysite / admin / ...?
In ZF1 for this I used «BaseController», but ZF2 want to check session in class Module.
class Module
{
public function onBootstrap($e)
{
$app = $e->getApplication();
$sm = $app->getServiceManager();
$config = $sm->get('Configuration');
// DB Adapter
$adapter = $sm->get('Zend\Db\Adapter\Adapter');
GlobalAdapterFeature::setStaticAdapter($adapter);
// Session
$sessionConfig = new SessionConfig();
$sessionConfig->setOptions($config['session']);
$sessionManager = new SessionManager($sessionConfig, null, null);
Container::setDefaultManager($sessionManager);
$sessionManager->start();
}
}
Tell me whether I want to do? And in which direction to look?

Try to use Zendframe Work 2 EventManager.

Related

Sabre Integration for CalDAV

I'm working on a web-based scheduling application that needs to integrate iCloud Calendar into it. Unlike Google Calendar and Microsoft Outlook, I came to know that iCloud doesn't provide any APIs for integration. So, I came to know about Sabre CalDAV.
But instead of progressing, I got stuck into its comprehensive documentation. Does anyone have proper documentation or could help me out with authenticating: Sabre\DAV\Auth\Backend\Apache(https://sabre.io/dav/caldav/) for Authentication.
Also, I need to CalDAV plugin but it may require authentication first.
Please find below as my server.php code:
<?php
use
Sabre\DAV,
Sabre\CalDAV,
Sabre\DAVACL;
$pdo = new \PDO('sqlite:data/db.sqlite');
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
//Mapping PHP errors to exceptions
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
// Files we need
require_once 'vendor/autoload.php';
// Backends
$authBackend = new DAV\Auth\Backend\PDO($pdo);
$principalBackend = new DAVACL\PrincipalBackend\PDO($pdo);
$calendarBackend = new CalDAV\Backend\PDO($pdo);
// Directory tree
$tree = array(
new DAVACL\PrincipalCollection($principalBackend),
new CalDAV\CalendarRoot($principalBackend, $calendarBackend)
);
// The object tree needs in turn to be passed to the server class
$server = new DAV\Server($tree);
// You are highly encouraged to set your WebDAV server base url. Without it,
// SabreDAV will guess, but the guess is not always correct. Putting the
// server on the root of the domain will improve compatibility.
$server->setBaseUri('/sabre/server.php');
// Authentication plugin
$authPlugin = new DAV\Auth\Plugin($authBackend,'SabreDAV');
$server->addPlugin($authPlugin);
// CalDAV plugin
$caldavPlugin = new CalDAV\Plugin();
$server->addPlugin($caldavPlugin);
// CardDAV plugin
$carddavPlugin = new CardDAV\Plugin();
$server->addPlugin($carddavPlugin);
// ACL plugin
$aclPlugin = new DAVACL\Plugin();
$server->addPlugin($aclPlugin);
// Support for html frontend
$browser = new DAV\Browser\Plugin();
$server->addPlugin($browser);
// And off we go!
$server->exec();

How to implement versioning for Token endpoint in Web API 2

I have a Asp.Net Web API 2 using Token based authentication (OAuth2).
I have implemented Web API versioning using aspnet-api-versioning.
So now I have three different versions of my API. It's really great, I can now change V3 without affecting the current API.
But the /token endpoint is not versioned because it is not in my controller. It's in the Providers.
I searched but couldn't find anything helpful.
We can register more than one token endpoint in the Startup.Auth.cs
So here's what I did:
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(TokenExpirationInDays),
AllowInsecureHttp = true, //Allow HTTP to send username password.
};
app.UseOAuthBearerTokens(OAuthOptions);
OAuthOptionsV3 = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/api/V3/Accounts/Token"),
Provider = new ApplicationOAuthProvider2(PublicClientId),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(TokenExpirationInDays),
AllowInsecureHttp = true, //Allow HTTP to send username password.
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptionsV3);
So now I have different token endpoint for each version.
I'm not familiar with this particular setup, but this looks like middleware. There isn't quite enough information here to provide you with a specific answer, but your goals should be achievable in one of a few ways:
Option 1 - Use the Conventions API
If you authorization endpoint is actually a controller (though I think it is not), you can use the Conventions API like so:
services.AddApiVersioning(options =>
{
options.Conventions.Controller<OAuthController>().IsApiVersionNeutral();
}
Conventions was specifically meant to deal with a scenario where a controller might be externally defined and you don't have any control over the source code.
Option 2 - Use a Custom Convention
Middleware could create actions dynamically. As long as actions are actually produced, then you can use a custom IControllerConvention. You would be passed the ControllerModel which contains the actions you need to version. Assuming this is the correct behavior, you'd be looking for matching actions in the source model and then you can apply it to the controller conventions with something like:
public class MyConventions : IControllerConvention
{
public bool Apply(IControllerConventionBuilder controller, ControllerModel controllerModel)
{
var method = // TODO: resolve the target method from controllerModel
if (method == null)
{
return false;
}
controller.Action(method).IsApiVersionNeutral();
return false;
}
}
Option 3 - In Middleware
If this is pure middleware, API versioning isn't directly supported there. You can, however, support versioning on your own if the pipeline is composed properly. Specifically, API Versioning must come before other parts of middleware that need it. This usually happens automatically, but if you need to control registration, you need to change your setup to handle it manually like this:
services.AddApiVersioning(options => options.RegisterMiddleware = false);
// ... inside application setup
services.UseApiVersioning();
The API Versioning middleware doesn't really do much of anything special. It merely adds a pipeline feature. As long as that's before your other middleware, it will be available downstream like this:
var feature = context.Features.Get<IApiVersioningFeature>();
// the raw, unparsed API version, if any
var rawApiVersion = feature.RawApiVersion;
// the parse API version; will be null if no version is specified
// or the value cannot be parsed
var apiVersion = feature.ApiVersion;
// TODO: enforce versioning policies within the middleware
Option 4 - Use the API Explorer
If none of the previous approaches will work for you, you can leverage the API Explorer extensions for API Versioning to build your configuration (as above) from discovered APIs. This would have the advantage of not being hardcoded or require changes every time you release a new version.
Your application startup configuration would change to something like this:
public void Configure(IApplicationBuilder app, IApiVersionDescriptionProvider provider)
{
foreach (var description in provider.ApiVersionDescriptions)
{
var options = new OAuthAuthorizationServerOptions()
{
TokenEndpointPath = new PathString($"/api/{description.GroupName}/Accounts/Token"),
Provider = new ApplicationOAuthProvider2(PublicClientId),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(TokenExpirationInDays),
AllowInsecureHttp = true,
};
app.UseOAuthBearerTokens(options);
}
}

QuickBooks API "Failed to open required file"

I'm integrating QuickBooks API in my newly created laravel app. But I'm always stuck with an error of Failed to open required file. I've been searching for the same problem but none of them works. Is there anyone who have tried to integrate QuickBooks API to their laravel app ? Can you guide me on how do it ?
QuickBooks_Loader::load(): Failed opening required 'C:\wamp64\www\...\vendor\consolibyte\quickbooks/QuickBooks\Driver\.php' (include_path='.;C:\php\pear;C:\wamp64\www\...\vendor\consolibyte\quickbooks')
this is how I set up my qbo env variables.
QB_DSN= mysqli://root:#localhost:3306/omni_qbo
QB_TOKEN=AB11573209674XW53cTKF8xf5lY8vva2A4C8aMliPMWgWGUOl7
QB_OAUTH_CONSUMER_KEY= ABsW9nlMQEpjnzYNvl5ySx1FSqpaibMuJEe1DS0xMMt8bKpQoZ
QB_CONSUMER_SECRET=SxbO5CUvclrWWTFTnVCB1ZWvwk8TjqM67shCv3VP
QB_OAUTH_URL=http://localhost:8000/qbo/oauth
QB_SUCCESS_URL=http://localhost:8000/qbo/success
QB_SANDBOX=true
QB_USERNAME=DO_NOT_CHANGE_ME
QB_TENANT=12345
This is the controller sample code I copied from the link . I just followed the steps on how to integrate quickbooks api to laravel but still not working.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class QuickBookController extends Controller
{
private $IntuitAnywhere;
private $context;
private $realm;
public function __construct(){
if (!\QuickBooks_Utilities::initialized(env('QBO_DSN'))) {
// Initialize creates the neccessary database schema for queueing up requests and logging
\QuickBooks_Utilities::initialize(env('QBO_DSN'));
}
$this->IntuitAnywhere = new \QuickBooks_IPP_IntuitAnywhere(env('QBO_DSN'), env('QBO_ENCRYPTION_KEY'), env('QBO_OAUTH_CONSUMER_KEY'), env('QBO_CONSUMER_SECRET'), env('QBO_OAUTH_URL'), env('QBO_SUCCESS_URL'));
}
public function qboConnect(){
if ($this->IntuitAnywhere->check(env('QBO_USERNAME'), env('QBO_TENANT')) && $this->IntuitAnywhere->test(env('QBO_USERNAME'), env('QBO_TENANT'))) {
// Set up the IPP instance
$IPP = new \QuickBooks_IPP(env('QBO_DSN'));
// Get our OAuth credentials from the database
$creds = $this->IntuitAnywhere->load(env('QBO_USERNAME'), env('QBO_TENANT'));
// Tell the framework to load some data from the OAuth store
$IPP->authMode(
\QuickBooks_IPP::AUTHMODE_OAUTH,
env('QBO_USERNAME'),
$creds);
if (env('QBO_SANDBOX')) {
// Turn on sandbox mode/URLs
$IPP->sandbox(true);
}
// This is our current realm
$this->realm = $creds['qb_realm'];
// Load the OAuth information from the database
$this->context = $IPP->context();
return true;
} else {
return false;
}
}
public function qboOauth(){
if ($this->IntuitAnywhere->handle(env('QBO_USERNAME'), env('QBO_TENANT')))
{
; // The user has been connected, and will be redirected to QBO_SUCCESS_URL automatically.
}
else
{
// If this happens, something went wrong with the OAuth handshake
die('Oh no, something bad happened: ' . $this->IntuitAnywhere->errorNumber() . ': ' . $this->IntuitAnywhere->errorMessage());
}
}
public function qboSuccess(){
return view('qbo_success');
}
public function qboDisconnect(){
$this->IntuitAnywhere->disconnect(env('QBO_USERNAME'), env('QBO_TENANT'),true);
return redirect()->intended("/yourpath");// afer disconnect redirect where you want
}

Your credentials do not allow access to this resource [code] => 220

I am using twitter login for magento i configure everything but when get the user informations the give the following error.Your credentials do not allow access to this resource [code] => 220. if some body face this type of problem then help me and thanks in advance.
my code is
$CONSUMER_KEY='xxxxxxxxxxxxxxxxx';
$CONSUMER_SECRET='xxxxxxxxxxxxxxxxxxxxxx';
$OAUTH_CALLBACK='http://demo004.fmeaddons.com';
session_start();
$twitteroauth = new TwitterOAuth($CONSUMER_KEY, $CONSUMER_SECRET);
$request_token = $twitteroauth->getRequestToken($OAUTH_CALLBACK);
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
if($twitteroauth->http_code==200){
$url = $twitteroauth->getAuthorizeURL($request_token['oauth_token']);
echo $url;
$twitteroauth = new TwitterOAuth($CONSUMER_KEY, $CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$access_token = $twitteroauth->getAccessToken($_GET['oauth_verifier']); $_SESSION['access_token'] = $access_token;
$user_info = $twitteroauth->get('account/verify_credentials');
print_r($user_info);
} else {
die('Something wrong happened.');
}
Make sure your keys were created with the correct permissions. You can check this in the "Keys and tokens" section of your Twitter developer dashboard:

Dynamic site, access session in global

Hello i am currently developing a kind of wiki system for my school, this system uses sub domains to find what course the wiki belongs to. example math1.wiki.com will be the course Math 1.
Now all these wikis use the same database and are given a wiki id, to find what data to load.
Here is the code i use to find the wiki id.
Global.asax
protected void Session_Start()
{
var database = new DataContext();
IWikiRepository rep = new WikiRepository(database);
IWikiService service = new WikiService(rep);
var domain = HttpContext.Current.Request.Url.Authority;
var port = "";
if (domain.Contains(':'))
{
var tmp = domain.Split(':');
domain = tmp[0];
port = tmp[1];
}
var split = domain.Split('.');
var subdomain = split[0];
// if (subdomain == "localhost")
// subdomain = "wiki1";
var wiki = service.GetSite(subdomain);
if (wiki == null)
{
Response.StatusCode = 404;
return;
}
Session["CurrentWiki"] = wiki;
}
This is all fine, but i want to make the mvc system send a 404 request if no wiki was found for the subdomain. But this can not only be done in session_start() as it only runs once per session i have therefor tryed using Application_BeginRequest, but sadly do i not have access to the sessions in the method.
Do any one know how i can implement this?
why can't you just make a custom function that you call at the start of the main page to determine if the wiki exists and if not, redirect/error page/whatever. If it's a custom function, you can just recall it when necessary.

Resources