Laravel 5.8 LDAP Authentication not working - LdapRecord Package - ldap

I'm trying to implements an LDAP authentication in an application for my company. I'm using Laravel 5.8 and the LdapRecord package
I have succeed to connect the application with the LDAP server test see Successfully connected and my to authenticate with openldap to online server its also Successfully. but when i want to do the authentication with active directory to my app it not working , Why who can help me?
Here is my code :
The .env
LDAP_LOGGING=true
LDAP_CONNECTION=default
LDAP_HOST=server
LDAP_PORT=389
LDAP_BASE_DN="dc=mydomain,dc=local"
LDAP_TIMEOUT=5
LDAP_SSL=false
LDAP_TLS=false
The ldap.php
return [
'default' => env('LDAP_CONNECTION', 'default'),
'connections' => [
'default' => [
'hosts' => [env('LDAP_HOST', 'server')],
'username' => env('LDAP_USERNAME', ''),
'password' => env('LDAP_PASSWORD', ''),
'port' => env('LDAP_PORT', 389),
'base_dn' => env('LDAP_BASE_DN', 'dc=mydomain,dc=local'),
'timeout' => env('LDAP_TIMEOUT', 5),
'use_ssl' => env('LDAP_SSL', false),
'use_tls' => env('LDAP_TLS', false),
],
],
'logging' => env('LDAP_LOGGING', true),
'cache' => [
'enabled' => env('LDAP_CACHE', false),
'driver' => env('CACHE_DRIVER', 'file'),
],
];
The auth.php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'ldap',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
'providers' => [
'users' => [
'driver' => 'eloquent' ,
'model' => App \ User :: class,
],
'ldap' => [
'driver' => 'ldap',
'model' => LdapRecord\Models\ActiveDirectory\User::class,
// 'model' => LdapRecord\Models\OpenLDAP\User::class,
'database' => [
'model' => App\User::class,
'sync_passwords' => false,
'sync_attributes' => [
'name' => 'cn',
'email' => 'mail',
],
],
]
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
'password_timeout' => 10800,
];
The user.php model
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use LdapRecord\Laravel\Auth\LdapAuthenticatable;
use LdapRecord\Laravel\Auth\AuthenticatesWithLdap;
class User extends Authenticatable implements LdapAuthenticatable
{
use Notifiable, AuthenticatesWithLdap, HasLdapUser ;
protected $fillable = [
'name',
'email',
'password',
];
protected $hidden = [
'password', 'remember_token' ,
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
The LoginController
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
protected function credentials(Request $request)
{
return [
'uid' => $request->get('username'),
'password' => $request->get('password'),
];
}
public function username()
{
return 'username';
}
}
Is there anyone who has already used this package and can help me on my code ? thank you in advance :)

Related

Why yii 2 mailer not send email?

My yii 2 web config
'components' => [
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.send-box.ru',
'username' => 'sendbox#jobgis.ru',
'password' => 'password',
'port' => '587',
'encryption' => 'tls',
],
],
My yii 2 controller for send mail
public function actionSpam(){
Yii::$app->mailer->compose()
->setFrom('sendbox#jobgis.ru')
->setTo('jetananas#yandex.ru')
->setSubject('Тема сообщения')
->setTextBody('Текст сообщения')
->setHtmlBody('<b>текст сообщения в формате HTML</b>')
->send();
}
Why mail not sending?
Why mailer not display errors?

cakephp 3.8.13 add admad/cakephp-jwt-auth

This question is asked many times in the stack overflow but I tried every accepted solution.
I'm new to cake PHP and I was assigned to add JWT in our application. Previously the team used the default cake sessions. In order to integrate, I used admad/cakephp-jwt-auth. So In the AppController
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Recurring');
$this->loadComponent('Auth', [
'storage' => 'Memory',
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'user_name',
'password' => 'password',
],
'contain' => ['Roles']
],
'ADmad/JwtAuth.Jwt' => [
'parameter' => 'token',
'userModel' => 'CbEmployees',
'fields' => [
'username' => 'id'
],
'queryDatasource' => true
]
],
'unauthorizedRedirect' => false,
'checkAuthIn' => 'Controller.initialize'
]);
}
I have to use CbEmployees which is our user model.
Then in my custom controller, I add my login function
public function login()
{
$user = $this->Auth->identify();
if (!$user) {
$data = "Invalid login details";
} else {
$tokenId = base64_encode(32);
$issuedAt = time();
$key = Security::salt();
$data = JWT::encode(
[
'alg' => 'HS256',
'id' => $user['id'],
'sub' => $user['id'],
'iat' => time(),
'exp' => time() + 86400,
],
$key
);
}
$this->ApiResponse([
"data" => $data
]);
}
Then I call this function using postman with body
{
"username": "developer",
"password": "dev2020"
}
I always get the response as Invalid login details. So the suggested solution is to check the password data type and length. The password is varchar(255). Another solution is to check the password in the entity. In the entity I have
protected function _setPassword($password)
{
if (strlen($password) > 0) {
return Security::hash($password, 'sha1', true);
// return (new DefaultPasswordHasher)->hash($password);
}
}
I specifically asked why the team is using Security::hash($password, 'sha1', true); due to migration from cake 2 to cake 3 they have to use the same.
Why I'm getting always Invalid login details? What I'm doing wrong here? I can log in the using the same credentials when I'm using the application.

Relation two database and make join yii2

Can you help me. How to relate it and make a join
. i get error has no relation named "project".
i using ActiveRecord with my code :
$posts = MaKantor::find()
->leftJoin('project.track', '`track`.`id_office` = `m_kantor`.`kantor_id`')
->with('project.track')->where(['collecting_id' => $model->collecting_id])
->all();
and config
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=project',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
'db2' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=db_master',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
When you use with('relationName') in query, relation function needs to be defined in MaKantor model.
For example :
public function getProject()
{
return $this->hasOne(Project::className(), ['id' => 'project_id']);
}

Laravel 5.5 BroadcastException with Pusher

I have create the chat application in laravel with Brodecast+Vue so when trying to my test broadcast class its getting error "BroadcastException in PusherBroadcaster.php (line 106)" I have double checked all configurations and api authentications are correct. but getting error and pusher debug console do not display and request.
driver :
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => 'ap1',
'encrypted' => true
],
],
event :
public $message;
public $user;
public function __construct($message, User $user)
{
$this->message = $message;
$this->user = $user;
}
test function :
public function test()
{
$user = User::find(Auth::id());
event(new ChatEvent('Hello pusher', $user));
return response('done');
}
i think you need to make encrypted = false.
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => 'ap1',
'encrypted' => false
],
],

FOSRestBundle post many to one relation

I would like to know how to properly post data when Entity has another ManyToOne relation in FOSRestBundle.
User entity has locale (locale_id):
/**
* #ORM\ManyToOne(targetEntity="Locale")
* #ORM\JoinColumn(name="locale_id", referencedColumnName="id")
*/
private $locale;
I was hoping that passing something like:
{
"user":{
"firstName":"John",
"emailAddress":"somewhere#somehow.com",
"lastName":"Doe",
"sex":"1",
"locale":{
"id":"1"
}
}
}
will work, but it does not pass the validation and Symfony throws:
{"code":400,"message":"Validation Failed","errors":{"children":{"firstName":[],"lastName":[],"emailAddress":[],"sex":[],"locale":{"errors":["This value is not valid."]}}}}
As you can see, locale is still wrong.
Does anyone know how can I post it properly?
EDIT
Here is how the form looks like:
<?php
namespace Software\Bundle\Form\Type;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
/**
* Class UserType
* #package Software\Bundle\Form\Type
*/
class UserType extends AbstractFormType
{
public function buildForm(FormBuilderInterface $builder, array $option)
{
$builder
->add('firstName', 'text', [
'label' => 'word.first_name',
'required' => true
])
->add('lastName', 'text', [
'label' => 'word.last_name',
'required' => true
])
->add('emailAddress', 'email', [
'label' => 'word.email_address',
'required' => true
])
->add('sex', 'choice', [
'label' => 'word.sex',
'choices' => [
'0' => 'word.male',
'1' => 'word.female'
],
'required' => true,
'empty_value' => 'word.select',
'empty_data' => null
])
->add('locale', 'entity', [
'label' => 'word.locale',
'required' => false,
'property' => 'code',
'class' => 'SoftwareBundle:Locale',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('l')
->orderBy('l.code', 'ASC');
},
'placeholder' => 'word.select',
'empty_data' => null
])
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults([
'translation_domain' => 'general',
'data_class' => 'Software\Bundle\Entity\User',
'attr' => ['novalidate' => 'novalidate'],
'csrf_protection' => false
]);
}
public function getName()
{
return 'user';
}
}
EDIT 2
And the controller:
public function postAction(Request $request)
{
$form = $this->createForm(new UserType(), new User());
$form->handleRequest($request);
if($form->isValid())
{
die('are you valid or not??');
}
return $this->view($form, 400);
}
Try without the "1" and only with 1 , otherwise it can be interpreted as string.
Edit :
{
"user":{
"firstName":"John",
"emailAddress":"somewhere#somehow.com",
"lastName":"Doe",
"sex":"1",
"locale": 1
}
}
}