Slim Framework and Auth0 - slim

Not worked with PHP for close on 10 years now, so very out of touch. I have a a project I am working on that requires a web front end with secure authentication. There is no need for API's at all.
Auth0 meets the requirements from an authentication point of view, and provides a lot of options.
What I cant find is how to integrate this with Slim Framework, can anyone point me in the right direction?
Background on the app, I am collating information from multiple API sources into a database and want to display this out and add some more functionality. Currently most of this is displayed on Grafana dashboards around the office, but there are some new requirements for this which cant be solved with dashboards.
Slim looks like the right tool for me, I need something that allows me to create pages quite easily where I will be in effect displaying a few graphs but mostly tables and forms to interact with the data. If Slim is not the right fit, happy to look elsewhere.
Thanks

According to the official Auth0 documentation I would try a setup in Slim 3 like this:
Installation
composer require auth0/auth0-php
Container Setup
Add a new container factory entry:
use Auth0\SDK\Auth0;
use Psr\Container\ContainerInterface as Container;
//...
$container[Auth0::class] = function (Container $container) {
return new Auth0([
'domain' => 'YOUR_DOMAIN',
'client_id' => 'YOUR_CLIENT_ID',
'client_secret' => 'YOUR_CLIENT_SECRET',
'redirect_uri' => 'https://YOUR_APP/callback',
'audience' => 'https://YOUR_DOMAIN/userinfo',
'scope' => 'openid profile',
'persist_id_token' => true,
'persist_access_token' => true,
'persist_refresh_token' => true,
]);
};
Usage
The user's information is stored in the session. Each time you call getUser(), it retrieves the information from the session.
use Auth0\SDK\Auth0;
$auth0 = $container->get(Auth0::class);
$userInfo = $auth0->getUser();
if (!$userInfo) {
// We have no user info
// redirect to Login
} else {
// User is authenticated
// Say hello to $userInfo['name']
// print logout button
}
Note: Don't use the container directly. In reality it's better to use dependency injection.

"but mostly tables and forms to interact with the data"
aside from your graphs to be displayed if the above is the main requirement then I would also recommend you look at Yii Framework (a PHP framework)
In particular looking at Gii - a code generator that builds, exceptionally quickly, CRUD forms and tables...

Related

Backpack with Multi tenancy

i am creating an ERP system with multi tenant with different db and has sub-domain for tenants.
i am using the stancl\tenancy for the multi tenant package
I have a main domain for creating and adding companies
Normally, when i load users in my tenant's sub-domains ex.(foo.maindomain.com), it is only showing the users table in the tenant's db. But with the backpack dashboard in permission manager it is showing the Users in the main database instead of the user in the tenant's own database.
Is there someone who has experience this and can help me with this problem?
your help will be much appreciated, Thank you in advance
The docs for that tenancy package show that they use a various middlewares that set the tenant for the application. Based on your question, Ill assume you're using the Subdomain identification middleware in your app.
The issue is most likely that your Backpack permissions routes are not using this middleware.
If we look at Backpack's docs, they say this about the permissions routes:
If you need to modify how this works in a project:
create a routes/backpack/permissionmanager.php file; the package will see that, and load your routes file, instead of the one in the package;
To fix the issue, create a file at allin.com/routes/backpack/permissionmanager.php copy the contents from vendor/backpack/permissionmanager/src/routes/backpack/permissionmanager.php, paste that in the new file and add the middleware needed for the tenancy app, which should look something like:
Route::group([
'namespace' => 'Backpack\PermissionManager\app\Http\Controllers',
'prefix' => config('backpack.base.route_prefix', 'admin'),
'middleware' => ['web', InitializeTenancyBySubdomain::class, backpack_middleware()],
], function () {
Route::crud('permission', 'PermissionCrudController');
Route::crud('role', 'RoleCrudController');
Route::crud('user', 'UserCrudController');
});

Zend Framework 2 Doctrine ORM Authentication

I'm developing my first real project with ZF2 and Doctrine ORM. And I cannot find any good example of user authentication through doctrine orm authentication adapter. Now I'm using standard Zend Db Adapter authentication. In addition, I use
$adapter->setIdentityColumn(filter_var($request->getPost('useremail'),FILTER_VALIDATE_EMAIL) ? 'useremail' : 'userlogin');
in my login controller to login either via email and login.
But I want to perform all job through doctrine ORM. Could someone show me a similar example with doctrine.authentication.orm_default and storing user identity data in session/storage to access in any controller or module.php? Is it possible to use two fields - userlogin or email for login?
Thank you in advance for your help.
Updated: I kept seaching and as a result this and this helped me so much
One problem, that i haven't solved yet. How can I check user status (activated or not) with doctrine adapter?
Like
$authAdapter = new AuthAdapter($dbAdapter,'user','username','password','MD5(?) AND status = 1');
You can use credential_callable option (Doctrine Module doc.). It can be any callable (PHP Manual), for example with closure:
'credential_callable' => function(User $user, $passwordGiven) {
return md5($passwordGiven) == $user->getPassword() && $user->isActive();
},
or with static class method:
'credential_callable' => 'Application\User\UserService::verifyUser'
What about an external module idea? If you are OK with that you can take a look at https://github.com/ZF-Commons/ZfcUser and https://github.com/SocalNick/ScnSocialAuth or the whole modules repositories http://modules.zendframework.com/?query=user. Even if you don't install just download and see what other people do stuff.

Using Everyauth/Express and Multiple Configurations?

I'm successfully using Node.js + Express + Everyauth ( https://github.com/abelmartin/Express-And-Everyauth/blob/master/app.js ) to login to Facebook, Twitter, etc. from my application.
The problem I'm trying to wrap my head around is that Everyauth seems to be "configure and forget." I set up a single everyauth object and configure it to act as middleware for express, and then forget about it. For example, if I want to create a mobile Facebook login I do:
var app = express.createServer();
everyauth.facebook
.appId('AAAA')
.appSecret('BBBB')
.entryPath('/login/facebook')
.callbackPath('/callback/facebook')
.mobile(true); // mobile!
app.use(everyauth.middleware());
everyauth.helpExpress(app);
app.listen(8000);
Here's the problem:
Both mobile and non-mobile clients will connect to my server, and I don't know which is connecting until the connection is made. Even worse, I need to support multiple Facebook app IDs (and, again, I don't know which one I will want to use until the client connects and I partially parse the input). Because everyauth is a singleton which in configured once, I cannot see how to make these changes to the configuration based upon the request that is made.
What it seems like is that I need to create some sort of middleware which acts before the everyauth middleware to configure the everyauth object, such that everyauth subsequently uses the correct appId/appSecret/mobile parameters. I have no clue how to go about this...
Suggestions?
Here's the best idea I have so far, though it seems terrible:
Create an everyauth object for every possible configuration using a different entryPath for each...
Apparently I jumped the gun and wrote this before my morning cup of coffee, because I answered my own question, and it was quite easy to implement. Basically I just had to create my own custom express middleware to switch the everyauth configuration before the everyauth gets its grubby paws on the request, so...
var configureEveryauth = function()
{
return function configure(req, res, next) {
// make some changes to the everyauth object as needed....
next();
};
}
and now my setup becomes:
var app = express.createServer();
everyauth.facebook
.entryPath('/login/facebook')
.callbackPath('/callback/facebook');
app.use(configureEveryauth());
app.use(everyauth.middleware());
everyauth.helpExpress(app);
app.listen(8000);
Notice that I don't even bother fully configuring the everyauth Facebook object during the startup, since I know that the middleware will fill in the missing params.

how to keep track of currently logged user in zend framework

I am a new user for zend framework. For my applications I need to keep track of currently logged in user, to do this I know I have to use zend_Auth and zend_Acl, but I don't know how to do that.
Well then the documentation would be the first place for you.
Zend_Auth: http://framework.zend.com/manual/en/zend.auth.html
Zend_Acl: http://framework.zend.com/manual/en/zend.acl.html
To get an easier access you could try this great tutorial series on youtube: http://www.youtube.com/watch?v=UmtGClgImpo which covers every step from auth to acl.
To keep track of something you can use Zend_Registry, e.g.
Zend_Registry::set ( 'role', 'guests' );
and use the auth instance, e.g.
if(Zend_Auth::getInstance()->hasIdentity()){
Zend_Registry::set('role', Zend_Auth::getInstance()->getStorage()
->read()->role);
}else{
Zend_Registry::set('role', 'guests');
}
But this all is described very well in the tutorial.
Good Luck!

Can I integrate a Zend-Framework powered web application into a wordpress site?

I have a project in which I want to be able to call wp_list_pages() on a page that also uses the Zend Framework to power some complex interfaces manages custom data outside of wordpress.
This page should also redirect the user to the wordpress login screen if they're not already logged in with the appropriate level of authorization.
How would this work at a high level, i.e. do I need to edit the wordpress bootstrap file to conditionally implement the custom interface based on a specific URL or something, but still include certain files to be able to call wp_list_pages() on that custom interface?
I've developed a couple of WordPress plugins, and I've found it's really easy to extend. Haven't worked with Zend though.
You should check the WordPress plugin api. Mostly the part about actions, filters and hooks: http://codex.wordpress.org/Plugin_API
You can even override some functions (not sure if wp_list_pages() is overridable).
It's pretty well documented, and there's a large developer community behind it on IRC, forums, etc.
Thanks Fernando.
I just read this thread which suggests that you can use Zend in any script by just including:
require_once('Zend/Loader.php');
Zend_Loader::registerAutoload();
So given that all I need to use Zend for is on one page, can I just include that code in a custom template file that I assign to the appropriate page in the navigation? If I used javascript to submit the form via XHR, the requested URL would take the form '/controller/action' - but Zend wouldn't know the controller directory.
Could I put Zend code into the wordpress bootstrap, i.e. the above code plus the frontController configuration, and then use Zend wherever however?
So I've created a page in Wordpress and a custom template for that page, in which I've placed the following Zend Framework code:
require_once('Zend/Loader.php');
Zend_Loader::registerAutoload();
$db = Zend_Db::factory('Pdo_Mysql', array(
'host' => 'localhost',
'username' => 'username',
'password' => 'password',
'dbname' => 'dbname'
));
Zend_Db_Table::setDefaultAdapter($db);
class Users extends Zend_Db_Table_Abstract {
protected $_name = 'wp_users';
}
$users = new Users();
$users = $users->fetchAll()->toArray();
print_r($users[0]['user_login']);
This all works fine, so it's clearly possible to use Zend in conjuction with Wordpress at least to some extent.
It's becoming apparant that the problem is about who controls the URL rewriting, or the routing, or the bootstrapping (not sure of the correct terminology). If I were to put the end of the above code, starting $users = new Users();, into a controller as follows:
class UsersController extends Zend_Controller_Action {
function getUserAction() {
$this->_helper->viewRenderer->setNoRender();
$users = new Users();
$users = $users->fetchAll()->toArray();
echo $users[0]['user_login'];
}
}
How would I then call that function? My intention would be to call it from javascript via an XHR request in response to an event on the page, but requesting the URL 'index.php/Users/getUser/' returns 'No input file selected'. Trying to access the URL http://www.domain.com/Users/getUser/ produces a Wordpress 404 page.
Is there a way around this? It doesn't just apply to wordpress, of course - I expect it applies to any existing application that rewrites/routes requests via a bootstrap.
I guess you could do that, just import the framework into the one page you need it for. I don't know how Zend works, but check the paths as to where to put your directories so that Zend finds them.As I said I guess you could do that, just experiment and tell us how it went!
Beware of name conflicts for functions and/or variables, this shouldn't be much of a problem coming from such popular products as WordPress and Zend though... (which should be theoretically well coded)
I guess you could do that, just import the framework into the one page you need it for. I don't know how Zend works, but check the paths as to where to put your directories so that Zend finds them.As I said I guess you could do that, just experiment and tell us how it went!
Beware of name conflicts for functions and/or variables, this shouldn't be much of a problem coming from such popular products as WordPress and Zend though... (which should be theoretically well coded)
I've built a plugin for wordpress that has a similar goal to yours, more modeled on CodeIgniter though. Not knowing Zend terribly well, I think this should help:
Make a file named routes.php in your plugins directory with the following code:
add_action( 'init', 'add_custom_urls' );
function add_custom_urls(){
global $wp, $wp_rewrite;
$wp_rewrite->add_rule( '(.*)$', 'index.php?&cPath=$matches[1]', 'top' );
$wp->add_query_var( 'cPath' );
}
Be sure to activate both plugins in your admin. These two files will allow you to catch the url before Wordpress tries to figure out what to do with it. You can use regular expressions to have finer control over which pages to catch. You may have to delete the record in your _options db table where option_name = 'rewrite_rules' before this works.
Next, make another plugin with the following code:
add_action( 'template_redirect', 'bootstrap' );
function bootstrap(){
global $cPath;
echo( "cPath : $cPath" );
if( $cPath ){
dosomethingwith( $cPath );
}
}
Put all your code in the dosomethingwith() function. You'll need to figure out if the url requested can me mapped to a zend controller, etc. http://www.domain.com/Users/getUser/ would give you $cPath = Users/getUser/ If successful, you'll also probably want to die(), so once it is completed Wordpress won't try and take over again.