Laravel Voyager LdapRecord SSO - laravel

I would like to use Voyager with an SSO connection.
I am trying to use LdapRecord to do this.
But the user models are different and I can't merge them.
Any ideas on how to use Voyager and LdapRecord together ?

With Windows IIS, i enable Windows authentication for my site.
So, we can use $_SERVER['AUTH_USER']
namespace App\Http\Controllers\Common;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Commun\FunctionController;
use App\Models\User;
class ConnexionController extends Controller
{
/**
*
* #return array
*/
public static function ConnexionSSO()
{
$authenticate = array(
'state' => false,
'message' => "You can't be authenticated."
);
$not_autorised = "";
$ident = "";
$agident = 0;
$name = "";
$surname = "";
$email = "";
if (App::environment() == 'local') {
$ident = 'IDENT_LOCAL';
$name = 'IDENT';
$surname = 'FOR_LOCAL';
$authenticate = [
'state' => true,
'message' => "You have been authenticated."
];
$agident = 1;
} else if (isset($_SERVER['AUTH_USER']) && $_SERVER['AUTH_USER'] != '') {
$ident = $_SERVER['AUTH_USER'];
if (Str::contains($ident , '\\')) {
$ident = explode('\\', $ident );
$ident = $ident [1];
}
$user = FunctionController::DataAgentIdentifiant($ident);
$name = $user['nom'];
$surname = $user['prenom'];
$email = $user['mail'];
$select = "PS #nom='".$name." ".$surname."'";
$dataUser = collect(DB::connection('sqlsrv')
->select($select))
->first();
$agident = $dataUser->AgIdent;
$authenticate = [
'state' => true,
'message' => "You have been authenticated."
];
}
return array(
'authenticate' => $authenticate,
'not_autorised' => $not_autorised,
'ident' => $ident,
'agident' => $agident,
'name' => $name,
'surname' => $surname,
'email' => $email
);
}
}

Related

I need to retrieve the last "order" and pass it to a mail

I need to retrieve the last "order" created on the mySql database and pass it to a mail in order to be able to print a receipt, but it does not matter what i try, in the mail view it's always undefined. any tips for a newbie?
this is the controller that and sends the mail
public function token(Request $request)
{
$gateway = new \Braintree\Gateway([
'environment' => 'sandbox',
'merchantId' => 'jgvy755pfvwdcjzx',
'publicKey' => 'qqpm93srfgwtx6dp',
'privateKey' => 'd13ce21a7642606db73b12bb1300d3fd'
]);
$clientToken = $gateway->clientToken()->generate();
if ($request->input('nonce') != null) {
$request->validate([
'name' => 'required',
'last_name' => 'required',
'phone' => 'required',
'address' => 'required',
'email' => 'email:rfc',
]);
//# Storo l'ordine
$name = $request->input('name');
$last_name = $request->input('last_name');
$address = $request->input('address');
$phone = $request->input('phone');
$email = $request->input('email');
$arr_id = $request->input('arr_id');
$arr_quant = $request->input('arr_quant');
$delivery_fee = $request->input('delivery_fee');
//# Recupero tutti i piatti dell'ordine per calcolarne il totale
$dishes = Dish::findMany($arr_id);
$arrayLength = count($arr_id);
$amount = 0;
for ($i = 0; $i < $arrayLength; $i++) {
$amount += $dishes[$i]->price * $arr_quant[$i];
}
$amount += $delivery_fee;
//#
$newOrder = new Order();
$newOrder->status = 1;
$newOrder->address = $address;
$newOrder->user_name = $name;
$newOrder->user_surname = $last_name;
$newOrder->phone = $phone;
$newOrder->email = $email;
$newOrder->total = $amount;
$newOrder->save();
// // storo l'array di IDs
// Ciclo una volta per ogni piatto contenuto nell'ordine, salvo la relazione e la sua quantità
for ($i = 0; $i < $arrayLength; $i++) {
$dish_id = $arr_id[$i];
// Scrive nella tabella pivot dopo aver creato la relazione
$newOrder->dishes()->attach([$dish_id => ['quantity' => $arr_quant[$i]]]);
//
}
//#
var_dump($request->input('nonce'));
$nonceFromTheClient = $request->input('nonce');
$gateway->transaction()->sale([
'amount' => $amount,
'paymentMethodNonce' => $nonceFromTheClient,
'options' => [
'submitForSettlement' => True
]
]);
Mail::to($email)->send(new PaymentConfirmationMail());
return view('orders.success');
}
return view('orders.braintree', ['token' => $clientToken]);
}
public function success(Request $request)
{
return view('orders.success');
}
}
this is the mail
class PaymentConfirmationMail extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('mails.payment_confirmation_mail');
}
}
Your Mail class isn't being told anything about the new order - you need to pass it to it :
Mail::to($email)->send(new PaymentConfirmationMail($newOrder));
then in your Mail class you need to be prepared to receive it :
protected $newOrder;
public function __construct(Order $newOrder) {
$this->newOrder = $newOrder
}
And also then pass the newOrder to the view :
public function build() {
$newOrder = $this->newOrder;
return $this->view('mails.payment_confirmation_mail')->with(compact('newOrder);
}
It should then be usable in your view with {{ $newOrder->something }}.

delete_cookie('name') not working codeigniter 4

I am trying to delete the cookie i create when user logs in but somehow delete_cookie() function is not deleting the cookie i made. I checked the documentation and everything but i cannot get it to work
Here is my code
public function __construct()
{
helper('cookie');
}
public function login() {
$data = [];
$session = session();
$model = new AdminModel();
$username = $this->request->getPost('username');
$password = $this->request->getPost('password');
$remember = $this->request->getPost('agree');
$rules = [
'username' => 'required',
'password' => 'required',
];
if(!$this->validate($rules)) {
$data['validation'] = $this->validator;
} else {
$admin = $model->where('username', $username)->where('password', $password)->first();
if($admin) {
$session->set('uid', $admin['id']);
if($remember) {
set_cookie([
'name' => 'id',
'value' => $admin['id'],
'expire' => '3600',
'httponly' => false
]);
}
} else {
$session->setFlashdata('msg', 'Incorrect Username or Password');
return redirect()->to('admin/login');
}
}
return view('admin/login', $data);
}
public function logout() {
$session = session();
$session->destroy();
delete_cookie('id');
return redirect()->to('admin/login')->withCookies();
}
Edit:
I fixed it. I had to redirect with withCookies();
use this Library
use Config\Services;
Services::response()->deleteCookie('id');
refer this link
https://codeigniter.com/user_guide/libraries/cookies.html

Laravel 7 cognito used in web and apps

I want to build laravel 7 with aws cognito and use this package aws-sdk-php-laravel.
This project will be made for the web & apps.
so how the laravel handle login from apps then apps get API from web with same token from cognito?
This is my first time use cognito, usually use auth-jwt.
After many tries without package
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class CognitoController extends Controller
{
private $key;
private $secret;
private $region;
private $version;
private $client_id;
private $client_secret;
private $user_pool_id;
private $aws;
private $client;
public function __construct()
{
$this->key = 'xxxxxx';
$this->secret = 'xxxxxx';
$this->region = 'xxxxxx';
$this->version = 'latest';
$this->client_id = 'xxxxxx';
$this->client_secret = 'xxxxxx';
$this->user_pool_id = 'xxxxxx';
$config = [
'credentials' => [
'key' => $this->key,
'secret' => $this->secret,
],
'region' => $this->region,
'version' => $this->version,
'app_client_id' => $this->client_id,
'app_client_secret' => $this->client_secret,
'user_pool_id' => $this->user_pool_id,
];
$this->aws = new \Aws\Sdk($config);
$this->client = $this->aws->createCognitoIdentityProvider();
}
public function login()
{
$username = 'guest';
$password = 'password';
$result = $this->client->adminInitiateAuth([
'AuthFlow' => 'ADMIN_NO_SRP_AUTH',
'AuthParameters' => [
'USERNAME' => $username,
'PASSWORD' => $password,
'SECRET_HASH' => $this->secretHash($username),
],
'ClientId' => $this->client_id,
'UserPoolId' => $this->user_pool_id,
]);
$access_token = $result->get('AuthenticationResult')['AccessToken'];
echo '<pre>';
print_r( $result );
echo '<br/>';
print_r( $access_token );
echo '</pre>';
}
public function register()
{
$username = 'guest';
$password = 'password';
$email = 'guest#email.com';
$phone_number = '+819000000000';
$result = $this->client->signUp([
'ClientId' => $this->client_id,
'Password' => $password,
'SecretHash' => $this->secretHash($username),
'UserAttributes' => [
[
'Name' => 'phone_number',
'Value' => $phone_number,
],
[
'Name' => 'email',
'Value' => $email,
]
],
'Username' => $username
]);
echo '<pre>';
print_r( $result );
echo '</pre>';
}
public function register_confirm()
{
$username = 'guest';
$confirmationCode = '123456'; // from email verification code
$result = $this->client->confirmSignUp([
'ClientId' => $this->client_id,
'Username' => $username,
'SecretHash' => $this->secretHash($username),
'ConfirmationCode' => $confirmationCode,
]);
echo '<pre>';
print_r( $result );
echo '</pre>';
}
public function list()
{
$search = ['UserPoolId' => $this->user_pool_id];
$users = $this->client->listUsers($search)->toArray();
echo '<pre>';
print_r( $users );
echo '</pre>';
}
private function secretHash($username) {
$clientId = $this->client_id;
$clientSecret = $this->client_secret;
$s = hash_hmac('sha256', $username . $clientId, $clientSecret, true);
return base64_encode($s);
}
}
token from auth cognito is it the same as the token when use JWTAuth?
Laravel Socialite doesn't have a cognito platform yet
You can configure AWS Cognito for OAuth and use one of the Laravel Oauth plugin to connect and authenticate with Cognito. I hope you will be storing user credentials in AWS Cognito User Pool.
Complete documentation (High Level) of AWS Cognito - https://www.slideshare.net/awsugkochi/acdkochi19-enterprise-grade-security-for-web-and-mobile-applications-on-aws
Documentation of AWS Cognito architecture for OAuth configuration - https://aws.amazon.com/blogs/mobile/understanding-amazon-cognito-user-pool-oauth-2-0-grants/
Documentation of Laravel Socialite to connect with AWS Cognito over OAuth and get authentication.

Laravel Mqtt's subscription doesn't end

I receive an Mqtt message from Laravel and try to do some action, but if you subscribe, you only get one message and it takes about a minute to delay.
I referred to this at https://github.com/salmanzafar949/MQTT-Laravel.
Implementing Mqtttt motion was made by creating a separate controller.
My code is
<?php
namespace App\Http\Controllers;
use Salman\Mqtt\MqttClass\Mqtt;
use Illuminate\Http\Request;
class MqttController extends Controller{
public $token = "";
public function SendMsgViaMqtt(Request $request)
{
$mqtt = new Mqtt();
//$client_id = Auth::user()->id;/
$topic = $request->topic;
$token = $request->token;
$message = $request->message;
$output = $mqtt->ConnectAndPublish("test", $message, "");
if ($output === true)
{
if($token == "none" || !$token){
return "End";
}else{
$this->SubscribetoTopic($token);
}
}else{
return "Failed";
}
}
public function SubscribetoTopic($token)
{
$topic = 'test';
$this->token = $token;
$message = [];
$mqtt = new Mqtt();
$client_id = "";
$mqtt->ConnectAndSubscribe($topic, function($topic, $msg){
if($msg == "end"){
$message = [
'title' => '魚が釣れました',
'body' => '釣竿を確認してください',
'click_action' => 'Url'
];
}else if($msg == "no"){
$message = [
'title' => '測定できません',
'body' => '波が強すぎると測れません',
'click_action' => 'Url'
];
}else{
return "end";
}
return $this->sendCrul($this->token, $message);
}, "");
}
public function sendCrul($token, $message){
define('SERVER_API_KEY', 'APIKEY');
$tokens = $token;
$header = [
'Authorization: Key=' . SERVER_API_KEY,
'Content-Type: Application/json'
];
$payload = [
'to' => $tokens,
'notification' => $message
];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://fcm.googleapis.com/fcm/send",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode( $payload ),
CURLOPT_HTTPHEADER => $header
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if($err){
echo "cURL Error #:". $err;
}else{
return $response;
}
// return "ok";
}
}
If you're in trouble like me, let me know how.

Creating laravel service class

My Uptime.php
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.uptimerobot.com/v2/getMonitors",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "Your Api Key",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: application/x-www-form-urlencoded"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
$data = json_decode($response);
$custom_uptime = ($data->monitors[0]->custom_uptime_ratio);
$uptime = explode("-",$custom_uptime);
}
?>
ApiCommand.php
public function handle()
{
//include(app_path() . '/Includes/Uptime.php')
$this->showMonitors();
}
public function showMonitors(UptimeRobotAPI $uptime_api)
{
$monitors = $uptime_api->getMonitors();
return $monitors;
}
Hello everyone. I just want to ask how can I turn this to a service class? Do I need to use service providers or service containers? Thanks in advance.
Someone convert it to service class and here was my command looks like.
In your terminal, require the guzzle package as you will use it as an HTTP client: composer require guzzlehttp/guzzle
Then you can make a class for your UptimeRobotAPI at app/Services/UptimeRobotAPI.php:
<?php
namespace App\Services;
use GuzzleHttp\Client;
class UptimeRobotAPI
{
protected $url;
protected $http;
protected $headers;
public function __construct(Client $client)
{
$this->url = 'https://api.uptimerobot.com/v2/';
$this->http = $client;
$this->headers = [
'cache-control' => 'no-cache',
'content-type' => 'application/x-www-form-urlencoded',
];
}
private function getResponse(string $uri = null)
{
$full_path = $this->url;
$full_path .= $uri;
$request = $this->http->get($full_path, [
'headers' => $this->headers,
'timeout' => 30,
'connect_timeout' => true,
'http_errors' => true,
]);
$response = $request ? $request->getBody()->getContents() : null;
$status = $request ? $request->getStatusCode() : 500;
if ($response && $status === 200 && $response !== 'null') {
return (object) json_decode($response);
}
return null;
}
private function postResponse(string $uri = null, array $post_params = [])
{
$full_path = $this->url;
$full_path .= $uri;
$request = $this->http->post($full_path, [
'headers' => $this->headers,
'timeout' => 30,
'connect_timeout' => true,
'http_errors' => true,
'form_params' => $post_params,
]);
$response = $request ? $request->getBody()->getContents() : null;
$status = $request ? $request->getStatusCode() : 500;
if ($response && $status === 200 && $response !== 'null') {
return (object) json_decode($response);
}
return null;
}
public function getMonitors()
{
return $this->getResponse('getMonitors');
}
}
You can then add more functions beneath, I created getMonitors() as an example.
To use this in a controller, you can simply dependency inject it into your controller methods:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Services\Promises\UptimeRobotAPI;
class ExampleController extends Controller
{
public function showMonitors(UptimeRobotAPI $uptime_api)
{
$monitors = $uptime_api->getMonitors();
return view('monitors.index')->with(compact('monitors'));
}
}
This is just an example, this does not handle any errors or timeouts that can occur, this is simply for you to understand and extend. I don't know what you want to do with it, but I can't code your whole project, this will definitely answer your question though. :)

Resources