Authentication with a second manager - authentication

I created a second manager for my second database.
In this base, i create a table which it contains my users.
The problem is the symfony don't load users from this database.
here is an extract of my config.yml :
Doctrine Configuration
doctrine:
dbal:
default_connection: default
connections:
default:
driver: pdo_mysql
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
seconddb:
driver: pdo_mysql
host: "xx.xx.xx.xx"
port: "3306"
dbname: "acme_test"
user: "acmegamestest"
password: "mypassword"
charset: UTF8
# if using pdo_sqlite as your database driver:
# 1. add the path in parameters.yml
# e.g. database_path: "%kernel.root_dir%/data/data.db3"
# 2. Uncomment database_path in parameters.yml.dist
# 3. Uncomment next line:
# path: "%database_path%"
orm:
default_entity_manager: default
auto_generate_proxy_classes: "%kernel.debug%"
#naming_strategy: doctrine.orm.naming_strategy.underscore
entity_managers:
default:
connection: default
mappings:
acmeAdminBundle: ~
acmeBlogBundle: ~
gedmo_translatable:
type: annotation
alias: GedmoTranslatable
prefix: Gedmo\Translatable\Entity
is_bundle: false
# make sure vendor library location is correct
dir: "%kernel.root_dir%/../vendor/gedmo/doctrine-extensions/lib/Gedmo/Translatable/Entity"
seconddb:
connection: seconddb
mappings:
acmeJoueurBundle: ~
and here is an extract of my security.yml :
encoders:
FOS\UserBundle\Model\UserInterface: sha512
Acme\JoueurBundle\Entity\Players:
algorithm: sha512
encode_as_base64: false
providers:
seconddb:
entity:
class: Acme\JoueurBundle\Entity\Players
property: username
manager_name: seconddb
fos_userbundle:
id: fos_user.user_provider.username
firewalls:
administration:
pattern: ^/admin
provider: fos_userbundle
context: administration
form_login:
#csrf_provider: security.csrf.token_manager
login_path : fos_user_security_login
check_path : fos_user_security_check
failure_path : null
default_target_path : /admin
logout:
path : fos_user_security_logout
target : /connexion
anonymous: true
frontend:
pattern: ^/
provider: acme_joueurbundle
context: frontend
form_login:
#csrf_provider: form.csrf_provider
login_path : acme_players_login
check_path : acme_players_check
failure_path : null
default_target_path : acme_players_userprofile
logout:
path : acme_players_logout
target : acme_players_login
anonymous: true
and my entity implements "AdvancedUserInterface, \Serializable"
with this function :
//////////////////////////liaison pour symfony////////////////////////////
public function getRoles()
{
return array('ROLE_PLAYERS');
}
public function getSalt(){
return $this->salt;
}
public function eraseCredentials(){
}
public function isAccountNonExpired()
{
return true;
}
public function isCredentialsNonExpired()
{
return true;
}
public function isAccountNonLocked()
{
return !$this->banned;
}
public function isEnabled()
{
return $this->active;
}
/** #see \Serializable::serialize() */
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
$this->active
// see section on salt below
// $this->salt,
));
}
/** #see \Serializable::unserialize() */
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->password,
$this->active
// see section on salt below
// $this->salt
) = unserialize($serialized);
}
/////////////////////////////////////////////////////////////////////////////
However when i trying to connect, i get this errors in dump function :
and in the section Doctrine i get this :
Is what you know the solution?
Hope you can help me.
Thanks

EDIT
So, the error comes from this piece of code in the user authentication provider :
try {
$user = $this->retrieveUser($username, $token);
} catch (UsernameNotFoundException $e) {
if ($this->hideUserNotFoundExceptions) {
throw new BadCredentialsException('Bad credentials.', 0, $e);
}
$e->setUsername($username);
throw $e;
}
The method retrieveUser failed and it throws bad crendentials exception. This explains why there is no connection since it has not yet been called.
Before asking you for the code of your provider, let's look at your security.yml because you create a provider called seconddb and in your firewall frontend you try to call a provider acme_joueurbundle who propably doesn't exist.
So, your security.yml should look like this:
# app/config/security.yml
[...]
providers:
seconddb:
entity:
class: Acme\JoueurBundle\Entity\Players
property: username
manager_name: seconddb
fos_userbundle:
id: fos_user.user_provider.username
firewalls:
administration:
provider: fos_userbundle
[...]
frontend:
provider: seconddb
[...]

Related

Deploying Synapse Workspace with Managed Vnet Enabled (Bicep), but cannot assign private endpoints in UI

Situation:
I am deploying a Synapse workspace instance in Bicep with Managed Virtual Network Enabled.
I can see the Managed Vnet Is enabled from the UI:
However, when I enter the workspace my integration runtimes are not enabled for virtual network access and I cannot create managed private endpoints.
I'm writing the following code for the bicep deployment:
resource synapse_workspace 'Microsoft.Synapse/workspaces#2021-06-01' = {
name: synapse_workspace_name
location: location
tags: {
Workload: '####'
Environment: envName
Classification: 'Confidential'
Criticality: 'Low'
}
identity: {
type: 'SystemAssigned'
}
properties: {
// Git Repo
workspaceRepositoryConfiguration: {
accountName: '#####'
collaborationBranch: 'main'
projectName: '####'
repositoryName: '#############'
rootFolder: '/synapse/syn-data-${envName}'
tenantId: '####################'
type: 'WorkspaceVSTSConfiguration'
}
defaultDataLakeStorage: {
resourceId: storage_account_id
createManagedPrivateEndpoint: true
accountUrl: ###################
filesystem: ################
}
encryption: {
cmk: {
kekIdentity: {
useSystemAssignedIdentity: true
}
key: {
name: 'default'
keyVaultUrl: '#########################'
}
}
}
managedVirtualNetwork: 'default'
connectivityEndpoints: {
web: 'https://web.azuresynapse.net?workspace=%2fsubscriptions%######################
dev: 'https://##############.dev.azuresynapse.net'
sqlOnDemand: '################-ondemand.sql.azuresynapse.net'
sql: '################.sql.azuresynapse.net'
}
managedResourceGroupName: guid('synapseworkspace-managed-resource-group-${envName}')
sqlAdministratorLogin: 'sqladminuser'
privateEndpointConnections: []
managedVirtualNetworkSettings: {
preventDataExfiltration: true
allowedAadTenantIdsForLinking: []
}
publicNetworkAccess: 'Disabled'
cspWorkspaceAdminProperties: {
initialWorkspaceAdminObjectId: '#########################'
}
trustedServiceBypassEnabled: false
}
}
I get no errors in the deployment regarding the virtual network or any associated settings, but I still get the default integration runtime set to "Public" and not "Managed Virtual Network".
Is this a limitation in Bicep or am I missing some parameter?
Any help would be great
Joao

Codeception seeInDatabase() not working as expected

I have problems getting codeceptions seeInDatabase() to work. This is my Cest:
public function testContactMailCheckbox(AcceptanceTester $I) {
$I->scrollTo("#adminMailSettingsForm", 0, -200);
$I->seeInDatabase("pib_users", [
"user_email" => "admin-cest#example.org",
"user_receive_contact_notification" => 0
]);
$I->click("//label[#for='contactMailNotification']", "#adminMailSettingsForm");
$I->waitForJS("return $.active == 0;",10);
$I->wait(100);
$I->seeInDatabase("pib_users", [
"user_email" => "admin-cest#example.org",
"user_receive_contact_notification" => 1
]);
}
The first seeInDatabase() passes, everything is fine. I can verify that this seeInDatabase-Assertion works correctly, by changing the default-data in my database dump. When I change the default data to "user_receive_contact_notification" => 1, the first seeInDatabase fails, which means it is working correctly.
I use $I->wait(100) to verify, that there are no synchronisation-issues. During this timespan I can check via phpMyAdmin, that the row was indeed updated correctly. That means the test should pass.
Here is my Db-config:
actor: AcceptanceTester
modules:
enabled:
- WebDriver:
url: 'http://pib.local/'
window_size: false # disabled in ChromeDriver
port: 5555
browser: chrome
capabilities:
chromeOptions:
args: ["--headless", "--no-sandbox", "--disable-gpu", "--window-size=1920,1080"]
- \Helper\Acceptance
- Sequence
- \Helper\DbHelper
config:
\Helper\DbHelper:
user: "root"
password: ""
dsn: "mysql:host=localhost;dbname=pib"
cleanup: true
dump: 'tests/database_dump_tests.sql'
populate: true
reconnect: true
step_decorators: ~
My DbHelper contains only a single function:
class DbHelper extends \Codeception\Module\Db
{
public function putInDatabase($table, $data, $insertOnlyIfNotExisting = true) {
// if ignoreDuplicateError is true, only execute insert when not existing already
if($this->countInDatabase($table, $data) == 0 | !$insertOnlyIfNotExisting) {
$this->_insertInDatabase($table, $data);
}
}
}
This might be related to this question. I don't use Laravel though, so just using the seeRecord()-helper isn't going to help me.

There is no extension able to load the

I integrating of bundles FOSRestBundle,JMSSerializerBundle and NelmioApiDocBundle, I modified the files config.yml and routing.yml but I find this problem
code config.yml:
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services.yml }
- { resource: "#UserBundle/Resources/config/services.yml" }
# Put parameters here that don't need to change on each machine where the app is deployed
# http://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
locale: fr
framework:
#esi: ~
translator: ~
secret: "%secret%"
router:
resource: "%kernel.root_dir%/config/routing.yml"
strict_requirements: ~
form: ~
csrf_protection: ~
validation: { enable_annotations: true }
#serializer: { enable_annotations: true }
templating:
engines: ['twig']
default_locale: "%locale%"
trusted_hosts: ~
trusted_proxies: ~
session:
# handler_id set to null will use default session handler from php.ini
handler_id: ~
fragments: ~
http_method_override: true
# Twig Configuration
twig:
debug: "%kernel.debug%"
strict_variables: "%kernel.debug%"
# Doctrine Configuration
doctrine:
dbal:
driver: pdo_mysql
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
# if using pdo_sqlite as your database driver:
# 1. add the path in parameters.yml
# e.g. database_path: "%kernel.root_dir%/data/data.db3"
# 2. Uncomment database_path in parameters.yml.dist
# 3. Uncomment next line:
# path: "%database_path%"
orm:
auto_generate_proxy_classes: "%kernel.debug%"
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
# Swiftmailer Configuration
swiftmailer:
transport: "%mailer_transport%"
host: "%mailer_host%"
username: "%mailer_user%"
password: "%mailer_password%"
spool: { type: memory }
fos_user:
db_driver: orm # other valid values are 'mongodb', 'couchdb' and 'propel'
firewall_name: main
user_class: test\UserBundle\Entity\User
fos_rest:
view:
view_response_listener: 'force'
formats:
json: true
format_listener:
rules:
- { path: '^/api', priorities: ['json'], fallback_format: json, prefer_extension: true }
- { path: '^/', stop: true }
nelmio_cors:
paths:
'^/api/':
allow_credentials: true
allow_origin: ['*']
allow_headers: ['*']
allow_methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']
max_age: 3600
code routing.yml:
user:
resource: "#UserBundle/Resources/config/routing.yml"
prefix: /
med:
resource: "#MedBundle/Resources/config/routing.yml"
prefix: /
app:
resource: "#AppBundle/Controller/"
type: annotation
fos_user:
resource: "#FOSUserBundle/Resources/config/routing/all.xml"
NelmioApiDocBundle:
resource: "#NelmioApiDocBundle/Resources/config/routing.yml"
prefix: /api/doc
app_api:
resource: "#MedBundle/Resources/config/routing_rest.yml"
type: rest
prefix: /api
code routing_rest.yml:
api_app:
resource: MedBundle\Controller\Api\AppController
type: rest
code AppController.php:
<?php
namespace test\MedBundle\Controller\Api;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\RestBundle\Controller\Annotations\RouteResource;
/**
* #RouteResource("User")
*/
Class AppController extends Controller {
public function getAction() {
$em = $this->getDoctrine()->getManager();
$test = $em->getRepository('MedBundle:Apps')->findAll();
return array("test" => $test);
}
public function postAction(Request $request){
return $request->request->all();
}
}
Now I find this problem when it can test API
What is the solution and thank you
You don't have any configuration for assetic in your config.yml file. I assume you don't have the AsseticBundle installed on your app. Since Symfony 2.8, Assetic is no longer included by default in the Symfony Standard Edition. You need to install it yourself:
First require the bundle with composer:
composer require symfony/assetic-bundle
Enable the bundle in the AppKernel.php file
class AppKernel extends Kernel
{
// ...
public function registerBundles()
{
$bundles = array(
// ...
new Symfony\Bundle\AsseticBundle\AsseticBundle(),
);
// ...
}
}
add the following minimal configuration to your config.yml file to enable Assetic
# app/config/config.yml
assetic:
debug: '%kernel.debug%'
use_controller: '%kernel.debug%'
filters:
cssrewrite: ~

Swagger defination, how to specify that a file is returned?

I want to download a file from the server, and I define the swagger file as follows:
swagger: '2.0'
################################################################################
# API Information
################################################################################
info:
version: v0
title: XXX REST API
host: api.xxx.io
basePath: /v0
schemes:
- http
- https
produces:
- application/json
################################################################################
# Security
################################################################################
################################################################################
# Parameters
################################################################################
parameters:
productId:
name: productId
in: path
description: The product identifier
type: string
required: true
################################################################################
# Paths
################################################################################
paths:
/products:
get:
description: Get the list of products
operationId: getProducts
responses:
200:
description: OK
schema:
type: array
items:
$ref: '#/definitions/Product'
/resources/{productId}:
parameters:
- $ref: '#/parameters/productId'
get:
description: Get resources of a product
operationId: getResourcesByProductId
produces:
- application/octet-stream
responses:
200:
description: OK
schema:
type: file
################################################################################
# Definitions
################################################################################
definitions:
Product:
type: object
required:
- id
properties:
id:
type: string
name:
type: string
category:
type: array
items:
type: string
description:
type: string
price:
type: number
thumbnailUri:
type: string
previewUris:
type: array
items:
type: string
resources:
type: array
items:
$ref: '#ResourceMeta'
And the api is as follows:
#javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringCodegen", date = "2016-10-24T17:56:03.446+08:00")
#Controller
public class ResourcesApiController implements ResourcesApi {
public ResponseEntity<File> getResourcesByProductId(
#ApiParam(value = "The product identifier",required=true ) #PathVariable("productId") String productId
) {
// do some magic!
return new ResponseEntity<File>(HttpStatus.OK);
}
}
My controller is as follows:
#Controller
public class ResourceController implements ResourcesApi {
private final Logger logger = Logger.getLogger(ResourceController.class);
// #RequestMapping(value="/resources/{productId}", method= RequestMethod.GET)
public ResponseEntity<File> getResourcesByProductId(#ApiParam(value = "The product identifier", required = true) #PathVariable("productId") String productId) {
String path = "resources" + File.separator + productId;
File file = new File(path);
FileSystemResource fileSystemResource = new FileSystemResource(file);
InputStreamResource inputStreamResource = null;
try {
inputStreamResource = new InputStreamResource(fileSystemResource.getInputStream());
} catch (IOException e) {
logger.error(e.toString());
}
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));
return ResponseEntity
.ok()
.headers(headers)
.contentLength(file.length())
.body(file);
}
}
However, when I run the application, it return a file but only contains the metadata of the file instead of its content. How can I make it return the file content? Thanks!
Use the InputStreamResource to return the file contents:
return new ResponseEntity(inputStreamResource, headers, HttpStatus.OK);

Logstash can't communicate with elasticsearch through readonly rest elasticsearch plugin.

I am trying to connect logstash with elasticsearch through authentication but this configuration gives me the following error : [401] Forbidden by ReadonlyREST ES plugin {:class=>"Elasticsearch::Transport::Transport::Errors::Unauthorized", :level=>:error}
Configuration files are given below:
[Elasticsearch conf file]
http.cors.enabled: true
http.cors.allow-origin: /https?:\/\/localhost(:[0-9]+)?/
readonlyrest:
enable: true
response_if_req_forbidden: Forbidden by ReadonlyREST ES plugin
access_control_rules:
- name: "Logstash can write and create its own indices"
auth_key: logstash:logstash
type: allow
actions: ["indices:data/read/*","indices:data/write/*","indices:admin/template/*","indices:admin/create"]
indices: ["logstash-*", "<no_index>"]
- name: Kibana Server (we trust this server side component, full access granted via HTTP authentication)
auth_key: admin:pass3
type: allow
- name: Developer (reads only logstash indices, but can create new charts/dashboards)
auth_key: dev:dev
type: allow
kibana_access: ro+
indices: ["<no-index>", ".kibana*", "logstash*", "default"]
[logstash conf file]
input {
file {
path =>"/var/log/site.log"
start_position => beginning
}
}
filter {
grok {
match => { "message" => "%{COMBINEDAPACHELOG}"}
}
geoip {
source => "clientip"
}
}
output {
elasticsearch {
user => "logstash"
password => "logstash"
}
}
Mention output in logstash config file like below :-
output {
elasticsearch {
hosts => ["localhost:9200"]
user => ["logstash"]
password => ["logstash"]
}