I have a controller, ShareController, and a method, view:
class ShareController extends AppController
{
public function beforeFilter(Event $event)
{
}
public function index()
{
}
public function view($id)
{
die('here');
}
}
And I have a route:
Router::defaultRouteClass(DashedRoute::class);
Router::extensions(['json', 'xml']);
Router::scope('/', function (RouteBuilder $routes) {
$routes->connect('/forsale/:id', ['controller' => 'Share', 'action' => 'view'])
->setPatterns(['id' => '\d+'])
->setPass(['id']);;
$routes->fallbacks(DashedRoute::class);
});
Router::prefix('sitecontrol', function ($routes) {
$routes->connect('/', ['controller' => 'Admins', 'action' => 'login']);
$routes->connect('/dashboard', ['controller'=>'Admins','action'=>'dashboard']);
$routes->connect('/logout', ['controller'=>'Admins','action'=>'logout']);
$routes->fallbacks('InflectedRoute');
});
/**
* Load all plugin routes. See the Plugin documentation on
* how to customize the loading of plugin routes.
*/
Plugin::routes();
When I visit http://thewebsite/forsale/197 I get redirected to: http://thewebsite/users/login?redirect=%2Fforsale%2F197
What could be causing this redirect? I am expecting to see "here".
Thanks
You are redirected to login page because of Authentication module. As you have not allowed view action for non logged in user, you need to bypass auth for view action. Please modify beforefilter function as following:
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Auth->allow('view');
}
Related
I'm new to Laravel and trying to load a JSON file into my project (which will then be used for a search function).
NEW EDIT *** It is giving me an error of "undefined constant "data""
For my Controller.php I have:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SiteController extends Controller
{
public function index() {
$results = file_get_contents("http://ftp.ebi.ac.uk/pub/databases/genenames/hgnc/json/locus_groups/protein-coding_gene.json");
$data = json_decode($results, true);
dd($data);
}
}
And for my new edited route per response below web.php I have: (still has the laravel given code in here as well).
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Controller;
Route::get('/', function () {
return view('welcome');
});
Route::get(“data”, [SiteController::class, “index”]);
In your web.php you need import your controller file:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Controller;
// in laravel 8 and 9 your need to do this with all your controllers
use App\Http\Controllers\SiteController;
Route::get('/', function () {
return view('welcome');
});
Route::get(“data”, [SiteController::class, “index”]);
I have a react admin application with a customRoutes, as well as resources (say /users). One of my custom route is a private page (say /private), which I protect with the useAuthenticated() hook:
export default () => {
useAuthenticated();
return (<Card>
<Title title="Private Page" />
<CardContent>
This is a private page.
</CardContent>
</Card>)
}
When I browse this private page and I'm not authenticated, I'm entering an authentication process as it should be (I'm using OIDC). This process is triggered by the checkAuth() method of the authProvider. But when the process is completed, I'm redirected to the /users resource and not the /private page. Is there a way to tell the authProvider that I want to be redirected to the private page?
Thanks - C
I have not done this myself, but I imagine you can use your redirect path as an argument in the useAuthenticated() call. https://marmelab.com/react-admin/Authentication.html#useauthenticated-hook
export default () => {
useAuthenticated({ redirectPath: '/privatepage' });
return (
<Card>
<Title title="Private Page" />
<CardContent>
This is a private page.
</CardContent>
</Card>
)
}
From there you should be able to use that arg/parameter in your checkAuth method.
tl;dr In your login().then() aspect, do a redirect('/myDefaultUrl')
I had the same challenge as you, I think. After looking into the ReactAdmin code a bit I was unable to find a way to do it in any 'official' way. I did see something quite interesting in the useAuthProvider() hook.
The AuthProvider object maintained by RA seems to have a variable with a couple properties initialized with some defaults.
import { useContext } from 'react';
import { AuthProvider } from '../types';
import AuthContext from './AuthContext';
export const defaultAuthParams = {
loginUrl: '/login',
afterLoginUrl: '/',
};
/**
* Get the authProvider stored in the context
*/
const useAuthProvider = (): AuthProvider => useContext(AuthContext);
export default useAuthProvider;
Specifically the afterLoginUrl property looked interesting. I attempted to override that property in my authProvider but didn't have any luck.
What I ended up doing was this. In my invocation of the login (from useLogin()), when the authProvider.login resolves, I return back the user along with their profile (I use Cognito so it is a CognitoUser instance). In my user I have configured an attribute for where the user should go after login. I then simply use the redirect hook (from useRedirect) to then direct the user to that URL.
Here is my login from my AuthProvider:
const authProvider = {
login: (params) => {
if (params instanceof CognitoUser) {
return params;
}
if (params.error) {
return Promise.reject(params.error);
}
return new Promise((resolve, reject) => {
Auth.signIn(params.username,params.password).then(cognitoUser => {
if (cognitoUser.challengeName === 'NEW_PASSWORD_REQUIRED') {
reject({ code: 'NewPasswordRequired', cognitoUser: cognitoUser })
} else {
setAndStoreUserProfile(cognitoUser);
resolve(cognitoUser);
}
}, function(err) {
reject(err);
});
});
},
....
Then in my Login form, I do this:
raLogin(formData)
.then((cognitoUser) => {
console.log("User logged in. Result:", cognitoUser);
clearTransitionState();
redirect('/profile');
})
.catch(error => {
if (error.code && error.code === 'PasswordResetRequiredException') {
transition(PHASE.RESET_ACCOUNT, {username: formData.username });
} else if (error.code && error.code === 'NewPasswordRequired') {
transition(PHASE.NEW_PASSWORD, { cognitoUser: error.cognitoUser });
} else {
processAuthError(error);
}
});
Actually, i'm new to laravel. I'm trying to make Authenticating Users manually I have a problem that there's no middleware work anyone know what's the problem
it should redirect to the homepage but it doesn't ...
here's for login
public function __construct(){
$this->middleware('auth')->except(['index','show' ]);
}
and that for posts
public function __constructor(){
$this->middleware('guest')->except(['destroy' ]);
}
You should add your middleware in app/Http/Kernel.php and this file have examples,then add the middleware in route like this Route::group(['middleware' => 'your middleware's name'], function () {....}
Laravel POST return type?
I'm setting up an API alpha version using basic auth single sign on.
Cant debug with postman/js because its not returning JSON but redirecting me instead. From what Ive read AJAX calls shouldnt be redirected? Do I have errors in the configuration?
Routes:
Route::post('/test1', 'tradesCtrl#test1']);
//Route::post('/test1', ['middleware' => 'auth.basic.once', 'uses' => 'tradesCtrl#test1']);
AJAX call:
$.post(
"http://localhost:8000/test1",
{
p1:"100a",
p2:80
},
function(data, status,jqXHR){
console.log(data);
});
Controller (this will echo HTTP (!):
public function test1(Request $request)
{
if($request->ajax()) {
echo "AJAX!";
} else {
echo "HTTP!";
}
}
Allow cross domain for now in App.php
// allow origin
header('Access-Control-Allow-Origin: *');
Kernel.php disable csrf protection by commeting out
app\Http\Middleware\VerifyCsrfToken::class
If I try to insert validation for parameters
public function test1(Request $request)
{
$this->validate($request, [
'p1' => 'Integer',
'p2' => 'Integer'
]);
echo "Serving stuff";
}
This immediately return in a 404 page not found when failing validation, probably a redirect to something else that's not working??
Currently I'm using php and nusoap and wanted to convert it to Laravel.
When creating the soap calls I use data out of a mysql database.
So I think I would need a model (to get my data) and a controller (to create request).
EDIT:
<?php
namespace App\Http\Controllers;
use Artisaninweb\SoapWrapper\Facades\SoapWrapper;
class SoapController extends Controller {
public function demo()
{
// Add a new service to the wrapper
SoapWrapper::add(function ($service) {
$service
->name('currency')
->wsdl('path/to/wsdl')
->trace(true);
->options(['user' => 'username', 'pass' => 'password']);
});
// Using the added service
SoapWrapper::service('currency', function ($service) {
var_dump($service->getFunctions());
var_dump($service->call('Otherfunction'));
});
}
}
from laravel-soap I couldn't find a tutorial on how to send login parameters prior to any other request. In the example 'using the added service' I see the login credentials but it doesn't work.
This is how I got soap to work in Laravel 5.1
clean install laravel 5.1
install artisaninweb/laravel-soap
create a controller SoapController.php
<?php
namespace App\Http\Controllers;
use Artisaninweb\SoapWrapper\Facades\SoapWrapper;
class SoapController extends Controller {
public function demo()
{
// Add a new service to the wrapper
SoapWrapper::add(function ($service) {
$service
->name('currency')
->wsdl('path/to/wsdl')
->trace(true);
});
$data = [
'user' => 'username',
'pass' => 'password',
];
// Using the added service
SoapWrapper::service('currency', function ($service) use ($data) {
var_dump($service->call('Login', [$data]));
var_dump($service->call('Otherfunction'));
});
}
}
Create a route in your routes.php
Route::get('/demo', ['as' => 'demo', 'uses' => 'SoapController#demo']);
If requered you can also use the model extension as described here