Create a Service for the User Provider - silex

I created a custom user class with a custom userProvider based on following link
I'm unable to create a Service for the User Provider.
$app->setParameter(
'webservice_user_provider.class',
'Tac\WebserviceUserBundle\Security\User\WebserviceUserProvider'
);
$app->setDefinition(
'webservice_user_provider',
new Definition('%webservice_user_provider.class%')
);
Fatal error: Call to undefined method Silex\Application::setParameter() in http://content.api.com/Users/davyd/Sites/content_api/src/boot.php on line 119

Silex is not the Symfony2 framework, so Symfony2's documentation does not apply.
Have a look at http://silex.sensiolabs.org/doc/services.html for documentation on how to define services in Silex.
$app['some_service'] = $app->share(function () {
return new Service();
});

Related

CosmosClient Singleton and Global.asax

I'm trying to create a CosmosClient instance for use in an ASP.Net MVC application. Microsoft recommends creating a singleton instance of the client. I've figured out I need something in Application_Start in Global.asax but that's it so far. Can anyone please give me an step by step idiots guide on how to do this as I am new to ASP.Net?
I have the following code running in a console app which creates the instance but I don't know how to translate this to an ASP Web App.
public async Task<bool> setupInitialiseClientAsync() // Use to create and also initialise Cosmos client
{
List<(string, string)> containersToInitialize = new List<(string, string)> { (databaseId, containerId) };
this.cosmosClient = await CosmosClient.CreateAndInitializeAsync(PrimaryConnectionString, containersToInitialize);
this.container = cosmosClient.GetContainer(databaseId, containerId);
return true;
}
Thanks.

Google Spreadsheet API - Accessing a spreadsheet created with service account

I created a service provider in my laravel app which connects with the google spreadsheet API, and I am able to create new spreadsheets, edit existing ones (with the right sharing permissions of course) and so on.
The problem is that I supplied my service account's json credentials key, hence the spreadsheets that are being created are owned by this cryptic mail address, so after the creation - I get an ID and when I'm trying to access the spreadsheet it gives me this 'request access' page, and when i'm trying to request access to my own email (I defined myself as an 'owner' of the project as well), I get these delivery status notifications via mail -
Your message wasn't delivered to
xxxxxx#yyyyyy-1x3x71x4x27x4.iam.gserviceaccount.com because the domain
admanager-1x3x71x4x27x4.iam.gserviceaccount.com couldn't be found.
Check for typos or unnecessary spaces and try again.
Obviously it's trying to send an email from me (xxxx#gmail.com) to my service account email, to request an access to this specific spreadsheet, and of course this address doesn't really exist. I feel like I'm doing something wrong from the very first place..
GoogleServiceProvider.php -
class GoogleServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* #return void
*/
public function register()
{
$this->app->singleton('google_spreadsheet_client', function ($app) {
// we will instantiate the Google Spread Sheet Client once in this function
$client = new Google_Client();
$client->setApplicationName('xxxxx');
$client->setScopes(Google_Service_Sheets::SPREADSHEETS);
$client->setAuthConfig('xxxxxx-1xyxyxyxyxyxy-221ca2fc3123.json');
$google_service_sheets = new Google_Service_Sheets($client);
return $google_service_sheets;
});
}
SpreadsheetController.php
class SpreadsheetsController extends Controller {
public function create() {
$service = resolve('google_spreadsheet_client');
$spreadsheet = new \Google_Service_Sheets_Spreadsheet([
'properties' => [
'title' => 'test'
]
]);
$spreadsheet = $service->spreadsheets->create($spreadsheet, [
'fields' => 'spreadsheetId'
]);
printf("Spreadsheet ID: %s\n", $spreadsheet->spreadsheetId);
}
}
And as I said - I do get a response with a string that looks like an actual spreadsheet ID, but can't access it with my own email for some reason..

How to integrate waffle NegotiateSecurityFilter spring-security with sparkjava embedded jetty?

Our application is using sparkjava http://sparkjava.com/ as the REST framework. The jetty server is embedded in the application (sparkjava default). We are also using spring for dependency injection.
For providing AD authentication, we need to integrate the waffle's NegotiateSecurityFilter.
As per waffle documentation and several online resources including stackoverflow, a DelegatingFilterProxy is required with the name springSecurityFilterChain.
But since we are not using spring MVC, I have to add it as follows:
ServletContextHandler sparkContext = new ServletContextHandler(ServletContextHandler.SESSIONS);
sparkContext.addFilter(new FilterHolder( new DelegatingFilterProxy( "springSecurityFilterChain" ) ),"/*", EnumSet.allOf( DispatcherType.class ));
And since a ContextLoaderListener does not already exist, need to add in the following manner:
sparkContext.addEventListener( new ContextLoaderListener() );
But it gives the error "Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader" at time of server startup.
Please let me know a solution in this scenario if you have successfully integrated spring-security DelegatingFilterProxy with embedded jetty and sparkjava (without using spring MVC).
This is how I achieved it finally:
In the main method where I have access to the sparkContext:
ServletContextHandler sparkContext = new ServletContextHandler(ServletContextHandler.SESSIONS);
sparkContext.setContextPath("/");
sparkContext.addServlet(DefaultServlet.class, "/*");
addSPNEGOFilter(sparkContext);
And the implementing methods are as:
private void addSPNEGOFilter(ServletContextHandler sparkContext) {
final ServletHandler handler = new ServletHandler();
final FilterHolder fh = handler.addFilterWithMapping(NegotiateSecurityFilter.class, <SPNEGO_FILTER_PATH>,
EnumSet.allOf(DispatcherType.class));
setNegotiateFilterParams(fh);
sparkContext.addFilter(fh, <SPNEGO_FILTER_PATH>, EnumSet.allOf(DispatcherType.class));
}
Add the following properties to the holder:
private static void setNegotiateFilterParams(final FilterHolder fh) {
fh.setInitParameter("principalFormat", "fqn");
fh.setInitParameter("roleFormat", "both");
fh.setInitParameter("allowGuestLogin", "false");
fh.setInitParameter("impersonate", "false");
fh.setInitParameter("securityFilterProviders",
"waffle.servlet.spi.NegotiateSecurityFilterProvider");
fh.setInitParameter("waffle.servlet.spi.NegotiateSecurityFilterProvider/protocols", "Negotiate");
}

What does exactly Dependency Injection in Symfony2 do?

I registered my services.yml file like below :
services:
PMI.form.users_tasks:
class: PMI\UserBundle\Form\UsersTasksType
arguments:
EntityManager: "#doctrine.orm.default_entity_manager"
I can list it by php app/console container:debug, so that mean my service is registered properly.
In my UsersTasksType class I have like below :
class UsersTasksType extends AbstractType
{
protected $ur;
public function __construct(EntityManager $ur )
{
$this->setUr($ur);
}
// Get and setters
}
Does Dependency Injection mean that I don't have to pass the EntityManager to the class constructor anymore? Or what ?
Because when I have to run the code below :
$form = $this->createForm(new UsersTasksType(), $entity);
I get this error:
Catchable Fatal Error: Argument 1 passed to PMI\UserBundle\Form\UsersTasksType::__construct() must be an instance of Doctrine\ORM\EntityManager, none given, called in C:\wamp\www\PMI_sf2\src\PMI\UserBundle\Controller\UsersTasksController.php on line 74 and defined in C:\wamp\www\PMI_sf2\src\PMI\UserBundle\Form\UsersTasksType.php line 19
And I have to do something below :
$em = $this->container->get('doctrine.orm.entity_manager');
$form = $this->createForm(new UsersTasksType($em), $entity);
So what would be the whole purpose of Dependency Injection ?
Dependency Injection basically gives one service (in this case, your UserTasksType) access to another service (in this case, your the entity manager).
arguments:
EntityManager: "#doctrine.orm.default_entity_manager"
These two lines tell Symfony to expect the entity manager service to be passed into the constructor when you instantiate a new UserTasksType object, which effectively gives your UserTasksType access to the entity manager.
If you aren't using the entity manager in your UserTasksType, there is no need to inject it in the constructor and you could get rid of the two lines above and the __construct() / setUr() methods in your UserTasksType.
A better example to help you understand DIC might be that you have a service that is written specifically to send emails (Swiftmail, for e.g.) and you need to inject it into another service so that service can send emails.
By adding
arguments: [ #mailer ]
to your service definition, your services constructor will expect your mailer service
__construct ($mailer)
{
$this->mailer = $mailer;
}
which will give it access to send emails
someFunction()
{
//do something useful, then send an email using the swift mailer service
$this->mailer->sendEmail();
}
Check out the latest Symfony docs for more of an explanation.
http://symfony.com/doc/current/book/service_container.html

Need to Authenticate the Users using Twitter, Google, Facebook Apis through oauth plugin?

First i briefly want to know how you can use oauth works. What we need to pass in this plugin and what this plugin will return. Do we have to customize the plugin for different php frameworks. I have seen that their is a different extension of oauth for different framework, why is that?
I need to authenticate the users using social networks in yii framework and I have integrated eouath extension of yii to use oauth and have made an action to use access the ads service of google user like this
public function actionGoogleAds() {
Yii::import('ext.eoauth.*');
$ui = new EOAuthUserIdentity(
array(
//Set the "scope" to the service you want to use
'scope'=>'https://sandbox.google.com/apis/ads/publisher/',
'provider'=>array(
'request'=>'https://www.google.com/accounts/OAuthGetRequestToken',
'authorize'=>'https://www.google.com/accounts/OAuthAuthorizeToken',
'access'=>'https://www.google.com/accounts/OAuthGetAccessToken',
)
)
);
if ($ui->authenticate()) {
$user=Yii::app()->user;
$user->login($ui);
$this->redirect($user->returnUrl);
}
else throw new CHttpException(401, $ui->error);
}
If I want to use other services like linkedin, facebook, twitter just to sign up the user should I just change the scope and parameters or also have to make some changes elsewhere. How do I store user information in my own database?
In simple case you may use the table "identities" with fields "*external_id*" and "provider". Every OAuth provider must give unique user identificator (uqiue only for that provider). To make it unique on your site you may use pair with provider predefined name (constant). And any other additional fields (if a provider gives it).
In the same table you should store identity data of internal authorization, with provider name 'custom' (for ex.). To store password and other data use a separate table, and PK from this table would be your "*external_id*". Universal scheme.
And PHP, something like this:
class UserIdentity extends CUserIdentity
{
protected $extUserID;
public function __construct($extUserID)
{
$this->extUserID = $extUserID;
}
...
public function authenticate()
{
...
//After search $this->extUserID as PK in users table (built-in authorization)
...
$identity = Identities::model()->findByAttributes(array(
'ext_id' => $this->extUserID,
'service' => 'forum',
));
if(!count($identity))
{
$identity = new Identities;
$identity->ext_id = $this->extUserID;
$identity->service = 'forum';
$identity->username = $userData['username'];
$identity->save();
}
$this->setState('id', $identity->id);
...
}
}

Resources