How to hide the Models section in Swagger UI? - swagger-ui

I use Swagger UI to display API documentation. By default, it displays the "Models" section at the bottom:
How to hide it?

To hide the "Models" section, add defaultModelsExpandDepth: -1 to the Swagger UI configuration code in your index.html.
Note the option name uses plural Model*s* not Model.
// index.html
<script>
window.onload = function() {
// Begin Swagger UI call region
const ui = SwaggerUIBundle({
url: "https://petstore.swagger.io/v2/swagger.json",
dom_id: '#swagger-ui',
defaultModelsExpandDepth: -1, // <-------
Swagger UI also has many other configuration options that control API documentation rendering.

For .Net Core 3.0 just Add c.DefaultModelsExpandDepth(-1); on your Startup.cs
// Startup.cs
app.UseSwaggerUI(c =>
{
c.DefaultModelsExpandDepth(-1); // Disable swagger schemas at bottom
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Your API V1");
});

In Docket bean just add
new
Docket(DocumentationType.SWAGGER_2).ignoredParameterTypes(YourClass.class,YourAnother.class)
I hope its helpful

If using Django add this inside your settings.py:
SWAGGER_SETTINGS = {
'DEFAULT_MODEL_DEPTH':-1
}

Although not the exact results you are looking for but i find it perfect to just disable the properties of the model you don't want via:
<?php
// src/AppBundle/Entity/User.php
use ApiPlatform\Core\Annotation\ApiResource;
use Symfony\Component\Serializer\Annotation\Groups;
...
* #ApiResource(
* attributes={
* "normalization_context"={"groups"={"api"}},
* "denormalization_context"={"groups"={"api"}}
* },
...
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
* #Groups({"api","user:read"})
*/
protected $id;
/**
* #var \DateTime
*/
private $disabledProperty;
This way you will get a model just with the props you exposed via the group api.
Hope this helps someone :)

Related

How to edit $request-url in middleware in Laravel 5.8 before it hits route API

I'm developing an API. I want to edit the incoming $request->url so it hits different routes based on the authorization. It should work for any kind of request (POST, GET , DELETE etc...).
By now I 've come this far. The middleware get hit, but $request->server->set('REQUEST_URI','http://...'); doesn 't have any effect. The incoming $request url stays at it is. This is the simplified middleware code of the class RedirectToUrl:
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
use Illuminate\Http\Request;
class RedirectToUrl
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(Request $request, Closure $next)
{
if($request->user()->role()->first()->role === "admin"){
$request->server->set('REQUEST_URI','http://rest-api-with-session-httponly:8888/api/admin');
}elseif($request->user()->role()->first()->role === "basic"){
$request->server->set('REQUEST_URI','http://rest-api-with-session-httponly:8888/api/basic');
}else{
$request->server->set('REQUEST_URI','http://rest-api-with-session-httponly:8888/api/basic');
}
return $next($request);
}
}
I`ve put the middleware RedirectToUrl::class at the end of the middleware priority:
protected $middlewarePriority = [
\App\Http\Middleware\AddAuthHeader::class,
\Illuminate\Auth\Middleware\Authenticate::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\Authenticate::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
\App\Http\Middleware\CheckRole::class,
\App\Http\Middleware\RedirectToUrl::class,
];
Any hint appreciated.
Thx!

Fluent Validation, MVC: Triggering Client-Side RuleSet Validation on Button Click

Context
In a view, I've created one form for my view model. I've separated the form over multiple sections using the Twitter Bootstrap Wizard plugin. The user can access the next section by clicking a "Next" button. Each section has a Fluent Validation RuleSet defined for the model properties on that section. The rules I've defined in each RuleSet are compatible with Fluent Validaiton's client-side validation.
Question
Upon clicking the next button, what's the best way:
To get the validation state for only the current section's RuleSet on the client-side with Fluent Validation?
To get Fluent Validation to display client-side validation for only the current section's RuleSet?
What I've Tried
I've read the Fluent Validation start guide and this question. While they demonstrate how to achieve what I'm looking for on the server-side, they don't seem to address my client-side questions. I bold "seem" because I'm reasonably new to Fluent Validation and MVC, so, I may have misunderstood the links' content.
You can use commands from the jQuery validation library, which Fluent Validation uses.
In an element in your form, define an attribute that will help you recognise a validation group. For example
#Html.EditorFor(model => model.GroupA_TextA, new { htmlAttributes = new { #class = "form-control", data_validation_group = "GroupA" }})
Use the .settings.ignore syntax from the jQuery validation library to control which groups to validate.
I've made a class that exposes functionality to validate a group in, and the entirety of, a Fluent Validation validated form. I've included the TypeScript and transpiled JavaScript below.
TypeScript
/**
* For validating a form when Fluent Validation is used for model valdiation.
*/
interface IFluentValidationFormValidator {
/**
* The form to validate.
*/
form: JQuery<HTMLElement>;
/**
* The name of the validation group to validate.
*/
group: string;
/**
* Validate the entire form.
*/
validate(): boolean;
/**
* Validate a validation group in the form.
* #param group The name of the validation group to validate.
*/
validateGroup(): boolean;
}
/**
*
*/
class StandardFluentValidationFormValidator implements IFluentValidationFormValidator {
/**
* #inheritdoc
*/
form: JQuery<HTMLElement>;
/**
* #inheritdoc
*/
group: string;
/**
* #inheritdoc
*/
validate(): boolean {
const formValidator = this.form.validate();
formValidator.form();
return formValidator.valid();
}
/**
* #inheritdoc
*/
validateGroup(): boolean {
// The form validator.
const formValidator = this.form.validate();
// Perform standard validation on form if the validation group is undefined.
if (this.group === undefined) {
formValidator.form();
return formValidator.valid();
}
// Current group validation settings.
const initialValidateIgnoreSetting = formValidator.settings.ignore;
// Ignore all elements but the group.
formValidator.settings.ignore += `,:not([data-validation-group=${this.group}])`;
// Valdiate the form.
formValidator.form();
// Reset group validation settings.
formValidator.settings.ignore = initialValidateIgnoreSetting;
// Return the validation state.
return formValidator.valid();
}
}
JavaScript
"use strict";
var StandardFluentValidationFormValidator = (function () {
function StandardFluentValidationFormValidator() {
}
StandardFluentValidationFormValidator.prototype.validate = function () {
var formValidator = this.form.validate();
formValidator.form();
return formValidator.valid();
};
StandardFluentValidationFormValidator.prototype.validateGroup = function () {
var formValidator = this.form.validate();
if (this.group === undefined) {
formValidator.form();
return formValidator.valid();
}
var initialValidateIgnoreSetting = formValidator.settings.ignore;
formValidator.settings.ignore += ",:not([data-validation-group=" + this.group + "])";
formValidator.form();
formValidator.settings.ignore = initialValidateIgnoreSetting;
return formValidator.valid();
};
return StandardFluentValidationFormValidator;
}());

Middleware in laravel does not works properly

I am trying to apply middleware on my routes like this:
Route::get('twitterlogin','TwitterController#gettwitterlogin');
Route::post('twitterlogin','TwitterController#posttwitterlogin');
Route::group(['middleware'=>'auth'],function()
{
Route::get('twitternewsfeed','TwitterController#gettwitternewsfeed');
Route::post('postimage','TwitterController#postimage');
Route::post('posttweet','TwitterController#posttweet');
Route::get('twitterlogout','TwitterController#gettwitterlogout');
Route::post('editprofilepic','TwitterController#posteditprofilepic');
Route::post('searchuser','TwitterController#postsearchuser');
Route::post('edittweet{id}','TwitterController#postedittweet');
Route::get('deletetweet{id}','TwitterController#getdeletetweet');
Route::post('editprofile','TwitterController#posteditprofile');
Route::get('userprofile{email}','TwitterController#getuserprofile');
});
And when i am trying to submit my login form it does not bring me on next page. It again opens the login page....what is the exact problem in this? My authenticate middleware is as follows....
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class Authenticate
{
/**
* The Guard implementation.
*
* #var Guard
*/
protected $auth;
/**
* Create a new middleware instance.
*
* #param Guard $auth
* #return void
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('twitterlogin');
}
}
return $next($request);
}
}
I assume you are using the Route::post('twitterlogin','TwitterController#posttwitterlogin') route to perform your login operation - please ensure that you're logging the user in with Laravel's Auth correctly and redirecting the user to the appropriate route in the posttwitterlogin method
I feel you also may also be using a different table to store user data - in which case, kindly ensure that you have your auth.php config file setup appropriately
In case you're using a custom authentication mechanism for some reason, you'll need to replace $this->auth->guest() in your middleware with the appropriate alternative check for the user not being logged-in
For eg: if you're setting a Session variable called is_authenticated to true with \Session::put('is_authenticated', true) upon successfully logging in, you'll check for it with if(\Session::get('is_authenticated') === true) in your Middleware instead of relying on the Laravel Auth method if ($this->auth->guest())

Language choser

I want to make a Language chooser in Laravel 5.1, but i know how I can make it, but I want that it remembers the selected language (so if I visit the page again, that I have still the samen language). But how can I do it? And have I need to store it in the DB?
Better explained here:
So if a visitor joins the site for the first time, then the language will be "English" and then he can choose his language that he/she want's. If the same person leaves and joins at another time, then the language would be the same as the person selected earlier.
I’ve written a blog post about this, see Detect and change language on the fly with Laravel for details but basically you need a Middleware to attribute a default locale:
/**
*
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (Session::has('locale')) {
$locale = Session::get('locale', Config::get('app.locale'));
} else {
$locale = substr($request->server('HTTP_ACCEPT_LANGUAGE'), 0, 2);
if ($locale != 'fr' && $locale != 'en') {
$locale = 'en';
}
}
App::setLocale($locale);
return $next($request);
}
And a method (along with a form) to store a language change:
/**
* Change session locale
* #param Request $request
* #return Response
*/
public function changeLocale(Request $request)
{
$this->validate($request, ['locale' => 'required|in:fr,en']);
\Session::put('locale', $request->locale);
return redirect()->back();
}

How do I send the same header with every response in zf2?

I would like to send the header "X-Content-Type-Options: nosniff" back with every response in my zend framework 2 application. How can I do that without explicitly coding it in every single controller method?
You can modify the response object via the bootstrap:
Module.php
/**
* On bootstrap event
*
* #param \Zend\Mvc\MvcEvent $e
*/
public function onBootstrap(MvcEvent $e)
{
$headers = $e->getResponse()->getHeaders();
$headers->addHeaderLine('X-Content-Type-Options: nosniff');
}

Resources