Redirect to sub-domain with route parameter in laravel - subdomain

How can I show for example this route "example.com/parameter" to this "parameter.example.com" for site visitors .
the back-end of site is laravel 5.3 and web server is Apache.
I want to use parameter in laravel controller.

You can set up a subdomain route like this:
Route::group(['domain' => '{parameter}.example.com'], function () {
Route::get('/', 'UserController#showByParameter');
});
then in your controller you can do
public function showByParameter($parameter)
{
$user = \App\User::whereParameter($parameter)->firstOrFail();
return view('users.show', compact('user'));
}

Related

How to redirect to a client callback page after a successful authentication via Identityserver4?

I am creating a login server using Identityserver4. I am using ASP.net core 3.1 for functionality, and angular 9 project for serving static files for login/registeration screens. The angular project is being served from within the .netcore project's wwwroot folder.
My flow goes like this
javascript client calls OIDC user manager's signInRedirect() method with following configurations
This sends a call to my Login method to render the angular's login component. Once the user fills in credentials, a second call is sent to my Login method return this.http.post('Account/Login', {UserName, Password, ReturnUrl}, {headers, responseType:'text'});
On successfull login, I do a return Redirect(model.returnUrl);
[HttpGet]
public IActionResult Login(string returnUrl)
{
return Redirect("/login?ReturnUrl=" + WebUtility.UrlEncode(returnUrl));
}
[HttpPost]
public IActionResult Login([FromBody]LoginViewModel model)
{
if (ModelState.IsValid)
{
var user = _userManager.FindByNameAsync(model.UserName).Result;
var result = _signInManager.PasswordSignInAsync(model.UserName, model.Password, false, false).Result;
if(result.Succeeded)
{
return Redirect(model.ReturnUrl);
}
return Ok(new Error { ErrorMessage = "Invalid credentials" });
}
return Ok(new Error { ErrorMessage = "Some error" });
}
In my network tab, I can see that the return Url which is a call to IdentityServer's authorization endpoint /connect/authorize/callbackis successfull.
It has also made a second call to the actual javascript client in point 1 with the authentication successfull.
However, the problem arises here. This request is returning the HTML as string of the JS clients callback.html instead of actually redirecting to that URL(http://localhost:5003/callback.html)
I don't even have any way to access the URL of the returned HTML, otherwise I would have done a window.location.href. How do I capture the URL of the callback page in angular and redirect to it ?
I would need a few more details to remedy this particular situation. However, I did want to offer my expertise in the form of explaining how this is supposed to work. I have an NPM library imng-auth0-oidc that does this very thing, except that it uses NGRX.
Your callback.html should be a static (non-Angular) HTML page. You can find a copy here callback.html. The purpose of this page is to receive the OAUTH2 response and store the token in localStorage, then redirect the response to your Angular application. Once the application is loaded, you'll now have access to your token that is waiting in localStorage.
-Isaac

Laravel 5.4: attach custom service provider to a controller

I created a service provider named AdminServiceProvider
namespace App\Providers;
use Modules\Orders\Models\Orders;
use Illuminate\Support\ServiceProvider;
use View;
class AdminServiceProvider extends ServiceProvider
{
public function boot()
{
$comments = Orders::get_new_comments();
View::share('comments', $comments);
}
public function register()
{
}
}
Registered the provider
App\Providers\AdminServiceProvider::class,
Now I try to attach it to the controller
namespace App\Http\Controllers\admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Providers\AdminServiceProvider;
class AdminController extends Controller
{
public $lang;
public function __construct()
{
}
public function index(){
return view('admin/dashboard');
}
}
Now I get this error message
Undefined variable: comments
This is the first time I try to use a custom service provider and don't know exactly how it works I'm sure there's something missing Hope you can help. Thanks in advance.
[UPDATE]
removed use App\Providers\AdminServiceProvider; from the controller
php artisan clear-compiled solved the problem but I want to attach it to some controllers not all controllers as the $comments are sent to all contollers in my app. So how to attach the service provider to specific controllers not all of them?
For the undefined variable run: php artisan clear-compiled will solve it
If you want to share a variable in some of your views you can create a middleware and assign it to the views you want to share the data with:
First create a middleware: php artisan make:middleware someName
Then in the handle function you add your view sharing logic:
$comments = Orders::get_new_comments();
view()->share('comments',$comments);
return $next($request);
Then register your middleware under the $routeMiddleware array and
give it an alias.
Then attach it to your routes like:
Route::group(['middleware'=> 'yourMiddlewwareName'], function(){
//your routes
});
If you have all your admin views in one directory (views\admin for example) you can use view composer in AdminServiceProvider:
public function boot()
{
view()->composer('admin.*', function($view){
$view->with('comments', Orders::get_new_comments());
});
}
It will attach comments variable to each view in your views\admin directory.
You can also attach a variable to some specific views or folders like this:
view()->composer(['admin.posts.*', 'admin.pages.index'], function($view){
$view->with('comments', Orders::get_new_comments());
});

Yii Site gets 404 error

I programmed an own yii-site called myScript_Formular.php,which has been put in
E:\xampp\htdocs\MyProject_Yii2.0\views\site. All other sites are in this folder,too!Furthermore,I added following code in SiteController:
public function actionScript() //A new method, programmed by Thomas Kipp
{
$model = new myScriptForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
return $this->render('myScript', ['model' => $model]);
}
else
{
return $this->render('myScript_Formular', ['model' => $model]);
}
}
If I try to get this page in yii2.0 in order to put in following url:
http://localhost/MyProject_Yii2.0/web/index.php?r=site%2FmyScript_Formular
I just get error:Not Found (#404)
What the hell is that? I controlled the name of the file thousands of times,it's correct and available in folder site.What should I do?
To be a little bit more precise I try to give you an official answer. The 404 error you got means that the url manager cannot resolve the url you provided to a route. The route in your case consists of a controller (site) and an action (script). You access your view through the action, therfore the url must form a valid route which identifies the controller and the action.
You should really read up on routing here: Yii2 routing

Trying to call action from cshtml fails with routing error?

I'm trying to call an action on a controller in an MVC project from a view and I get the following error:
This can happen when a controller uses RouteAttribute for routing, but no action on that controller matches the request
I've read some people have removed the attribute routing to get this to work but that seems a bit extreme. Does anyone know where to start with this one?
//Calling in view like so
#Html.Action("Edit", new { datablockId = 227 })
//THe controller
[RoutePrefix("CustomData")]
public class CustomDataController : Controller, ICustomDataController
{
[Route("Edit")]
[HttpGet]
public ActionResult Edit(int datablockId)
{
return this.PartialView(new CustomDataEditViewModel() { DataRows = Data, DataBlockId = datablockId });
}
}
Try routing the action to that particular controller explicitly like this:
#Html.Action("Edit", "CustomData" ,new { datablockId = 227 })
Html action accepts aditional parameters that might fix your routing issue, those parameters are: Html.Action("Action", "Controller", Parameters)

passing json data of webapi method from controller to view

I have data in my apicontroller in following way-
public class OutletPOCController : ApiController
{
OutletPOCContext db = new OutletPOCContext();
[System.Web.Http.ActionName("GetTabText")]
public TabTextModel GetTabText(int bizId)
{
var outlet = db.Info.Where(t => t.BizId == bizId).SingleOrDefault();
return new TabTextModel
{
HomeTab = outlet.BizHomeTabText,
AboutTab = outlet.BizAboutTabText,
TimingsTab = outlet.BizTimingsTabText,
};
}
And now i want to retrieve this data into my view. How shall i create view for this controller and pass the above data? What will be my action method? I am new to webapi and json. Any help is appreciable! Thanks in advance!
The API controller dosent really have views in the sense that you create a cshtml page that takes care of how you display your data. The purpose of the ApiController is simply to return data in the format that you want to consume it.
Basically the API exposes raw data to the web, you consume it in some way, and then display it..
I use something similar to this to load data dynamically into a web page.
Just a simple web api that returns data to the client.
public class APIController : ApiController
{
[HttpGet]
[HttpPost] // allow both post and get requests
public IEnumerable<String> GetData()
{
return new List<string>() { "test1", "test2" };
}
}
When you browse to the API method above it returns this xml data
<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>test1</string>
<string>test2</string>
</ArrayOfstring>
Which I get using Jquery and do what I please with (http://api.jquery.com/jQuery.get/):
$.get("/api/GetData", function(data) {
alert("Data Loaded: " + data);
});
Examples of XML parsing with JS/Jquery:
http://tech.pro/tutorial/877/xml-parsing-with-jquery
http://www.kawa.net/works/js/jkl/parsexml-e.html
If you are simply looking to get data into a regular view and work with it there without going through javascript I wouldent use a webapi, but instead get the data in the controller and send it to the view for displaying (ASP MVC4 - Pass List to view via view model).
You can also check out the ViewBag container for passing random odd data to the view http://goo.gl/03JTR
On the off chance you really do want to render your data in a view, check this out: Web API - Rendering Razor view by default?