im trying to build an auth api for my react using lumen/laravel , each time i want to test it out with postman i get the following error HTTP 405 Method Not Allowed .
my routes :
$router->group(['prefix' => 'patient'], function () use ($router) {
$router->post('register',[PatientAuthController::class,'register'] );
$router->post('login', [PatientAuthController::class,'login'] );
});
CorsMiddlware :
class CorsMiddleWare
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
//Intercepts OPTIONS requests
if ($request->isMethod('OPTIONS')) {
$response = response('', 200);
} else {
// Pass the request to the next middleware
$response = $next($request);
}
// Adds headers to the response
$response->header('Access-Control-Allow-Methods', 'HEAD, GET, POST, PUT, PATCH, DELETE');
$response->header('Access-Control-Allow-Headers', $request->header('Access-Control-Request-Headers'));
$response->header('Access-Control-Allow-Origin', '*');
$response->header('Access-Control-Expose-Headers', 'Location');
// Sends it
return $response;
}
PatientAuthController :
protected $patient;
protected $utilityService;
public function __construct()
{
$this->middleware("auth:patient",['except'=>['login','register']]);
$this->patient = new Patient;
$this->utilityService = new UtilityService;
}
public function register(PatientRegisterRequest $request)
{
$password_hash = $this->utilityService->hash_password($request->password);
$this->patient->createPatient($request,$password_hash);
$success_message = "registration completed successfully";
return $this->utilityService->is200Response($success_message);
}
/**
* Get a JWT via given credentials.
*
* #param Request $request
* #return Response
*/
public function login(LoginRequest $request)
{
$credentials = $request->only(['email', 'password']);
if (! $token = Auth::guard('patient')->attempt($credentials)) {
$responseMessage = "invalid username or password";
return $this->utilityService->is422Response($responseMessage);
}
return $this->respondWithToken($token);
}
.htaccess :
Options -MultiViews -Indexes
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
i have registred the middlware in app.php , but tho i still face this problem .
Related
I need to implement subdomain for api routes, but I'm getting 404 error
I have APP_URL set to http://example.com
I've configured subdomain in RouteServiceProvider
protected function mapApiRoutes()
{
Route::domain('api.example.com')
->prefix('/api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
}
I see that problem is in Illuminate\Routing\Matching\HostValidator when it calls $request->getHost() it returns 'example.com', not 'api.example.com'. If i change APP_URL to http://api.example.com it works well.
class HostValidator implements ValidatorInterface
{
/**
* Validate a given rule against a route and request.
*
* #param \Illuminate\Routing\Route $route
* #param \Illuminate\Http\Request $request
* #return bool
*/
public function matches(Route $route, Request $request)
{
$hostRegex = $route->getCompiled()->getHostRegex();
$host = $request->getHost();
if (is_null($hostRegex)) {
return true;
}
return preg_match($hostRegex, $request->getHost());
}
}
Looks like i missed some configuration, but I haven't found any additional configuration requirements in laravel docs.
"laravel/framework": "^7.12"
ADDITIONAL: so currently i can see that laravel redirects api.example.com to example.com, so that's why I'm getting host validation error.
The next question is - Why it does redirect? =)
I don't think it will help somebody, but the answer was in one middleware which I've found in project. It was redirecting all invalid hosts (non APP_URL) to APP_URL:
if (auth()->user() == null && $request->getSchemeAndHttpHost() != $this->config->get('app.url')) {
$additional = '';
if ($request->input()) {
$additional .= '?' . http_build_query($request->input());
}
return redirect()->secure($this->config->get('app.url') . $request->getPathInfo() . $additional);
}
return $next($request);
my project works locally (dev) like a charm, but in production, where I did set inside the .env file APP_URL as https://myurl, generated links are in http, so I get the mixed content problem. How to force ssl? App is behind Haproxy, which terminates SSL connection, inside a LXC container. Here's my TrustedProxies middleware:
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* #var array
*/
protected $proxies = [
'*'
];
/**
* The headers that should be used to detect proxies.
*
* #var int
*/
protected $headers = Request::HEADER_X_FORWARDED_ALL;
}
any help?
Thanks
You can try this:
File: App/Providers/AppServiceProvider
public function boot()
{
\URL::forceSchema('https'); // Force HTTPS
}
Be sure on your .env files:
APP_URL = "https://"
Last step : File .htaccess
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
I want specific htaccess file for specific route.
For example, i want to allow all ips to home route of my site but prevent access specific ips to just payment route or specific routes.
Please help me with this problem.
you can use three solution:
laravel middleware
code Source
here:
namespace App\Http\Middleware;
use Closure;
use Symfony\Component\HttpFoundation\IpUtils;
class RedirectInvalidIPs
{
protected $ips = [
'65.202.143.122',
'148.185.163.203'
];
protected $ipRanges = [
'10.11.3.1',
];
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
foreach ($request->getClientIps() as $ip) {
if (! $this->isValidIp($ip) && ! $this->isValidIpRange($ip)) {
return redirect('/');
}
}
return $next($request);
}
protected function isValidIp($ip)
{
return in_array($ip, $this->ips);
}
protected function isValidIpRange($ip)
{
return IpUtils::checkIp($ip, $this->ipRanges);
}
}
.htaccess
code Source
here:
Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REQUEST_URI} /thisdirectoryandallcontents
RewriteCond %{REMOTE_ADDR} !=111.111.111.111
RewriteRule ^.*$ /maintenance.php [R=302,L]
Nginx allow and deny IP
CloudFlare
How do I control IP access to my site?
You should use middleware for access control, the .htaccess 'can' technically be used for this, but it is highly recommended not to.
Rough example of possible logic to filter based on ip, that can be put in the handle function of newly created middleware:
if (!in_array($request->ip, ['127.0.0.1', '::1'])) {
abort(403);
}
return $next($request);
I've installed on my server new Codeigniter installation and I would like to be able to pass to the default controller (welcome) GET parameters.
For example:
http://www.myserver.com/1234
and I would like the default index function on the welcome controller will get '1234' as GET parameter, but I cant make it to work any idea?
here is my controller code:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* #see http://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
$this->load->view('welcome_message');
// echo get parameter here = 1234
}
}
And my .htaccess code:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
Your controller should be like this
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* #see http://codeigniter.com/user_guide/general/urls.html
*/
public function index($number)
{
//$this->load->view('welcome_message');
echo get parameter here = 1234
}
}
In your config.php you can enable query strings:
$config['enable_query_strings'] = TRUE;
The access to the method using this url:
http://www.myserver.com/?id=1234
I think that should work.
On your route.php file
// Would leave as your default controller
$route['default_controller'] = 'welcome';
// But add get query route here
$route['number='] = 'welcome/index';
You need to have ? at the start of the query get and then after that any other url query use &.
And then on controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index()
{
$this->load->helper('url');
echo anchor('?number=1234', 'Home', array('target' => '_blank'));
// http://www.example.com/index.php/?number=1234
echo '</br>';
echo $this->input->get('number');
$this->load->view('welcome_message');
}
}
When refresh page you should be able to see the anchor link which you can click on then will open new page and should display the numbers.
You also may come up with error disallowed uri
Then go to config and use ?&=
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-?&=';
You could alt use uri segments
<?php echo $this->uri->segment(1);?>
Use remap function
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function _remap($method, $params = array())
{
if (method_exists($this, $method))
return call_user_func_array(array($this, $method), $params);
else
return call_user_func_array(array($this, 'index'), $params);
}
public function index($number)
{
//$this->load->view('welcome_message');
echo get parameter here = 1234
}
}
I got a NotFoundHttpException when accessing to POST:http://localhost:8000/auth/register. This error appears when I updating AuthController validator and create methods. With default AuthController there is no error but datas not stored in database
AuthController
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
}
protected function create(array $data)
{
return User::create([
'lastname' => $data['lastname'],
'firstname' => $data['firstname'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
protected function validator(array $data)
{
return Validator::make($data, [
'firstname' => 'required|max:255',
'lastname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:8',
]);
}
}
Routes
Route::post('auth/register', 'Auth\AuthController#postRegister');
User model
namespace App;
use Illuminate\Auth\Authenticatable;
use Jenssegers\Mongodb\Model as Eloquent;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Eloquent implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
protected $collection = 'users_collection';
protected $fillable = ['firstname', 'lastname', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
public function websites(){
return $this->hasMany('App\Website');
}
}
Route list
http://pastebin.com/Xq24AQLK
Htaccess
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
as I mentioned in my comment out there, and according to your comment mentioning that the user actually gets registered in the database, so to debug the problem, let's take a look at the source code of postRegister method:
/**
* Handle a registration request for the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postRegister(Request $request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
Auth::login($this->create($request->all()));
return redirect($this->redirectPath());
}
As we can see, after the registration, the method redirects to the redirction path returned by redirectPath, let's take a look at its source code as well:
/**
* Get the post register / login redirect path.
*
* #return string
*/
public function redirectPath()
{
if (property_exists($this, 'redirectPath')) {
return $this->redirectPath;
}
return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home';
}
As we can see, if the 'redirectTo' attribute is not specified, the method by default redirects to '/home', so you have two possible solutions:
specify a route for /home and get done with it quickly
specify the 'redirectTo' or redirectPath attribute in the AuthController as follows:
In the AuthController.php
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectPath = '/myspecifiedroute';
...
...
i have a $redirectTo property in my AuthController, overriding the default redirect after successful login:
class AuthController extends Controller {
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
public $redirectTo = '/';
protected $loginPath = '/account/login';
...
I'm not really sure if it's $redirectTo or $redirectPath (at least according to the docs, i couldn't find this one in my project)
Further Reading
#hamza-ouaghad answer is the right answer for my problem. But I got another problem : my datas was not store in my database. When using laravel-mongodb and you need an unique field in your data model (like an email), you have to create a migration like :
Schema::create('users_collection', function($collection) {
$collection->unique('email');
});