cakephp redirection error after login return HTTP/1.1 302 in the logs - cakephp

I have implemented cakephp redirect() function on successfull login into my application .
But the redirection is not working for some reasons and it is instead getting redirected to the same url , while in the APACHE logs , I can see HTTP 302 response for that redirected URL .
My code is something as under :
if(isset($_REQUEST['submit']) && $_REQUEST['submit']=='Log In')
{
/*Entire validation logic goes here*/
if(isset($famUserInfo['user_type']) && $famUserInfo['user_type'] == USER_TYPE_ADVERTISER)
{
$redirectTo = !empty($returnto)?$returnto:'/homepageadv?login=1';
}
else if(isset($adminUserInfo['user_type']) && $adminUserInfo['user_type'] == USER_TYPE_ADMIN)
{
/* My control flow comes till here successfully */
$this->redirect("/opstool/zoneprobabilityindex");
die;
}
else
{
$redirectTo = !empty($returnto)?$returnto:'/homepage?login=1';
}
$this->redirect($redirectTo);
die;
}
When I check in the APACHE logs , I noticed like these :
127.0.0.1 - - [14/Oct/2011:19:24:34 +0530] "POST /login?returnto= HTTP/1.1" 302 5
127.0.0.1 - - [14/Oct/2011:19:24:34 +0530] "GET /opstool/zoneprobabilityindex HTTP/1.1" 302 12
127.0.0.1 - - [14/Oct/2011:19:24:34 +0530] "GET /login?returnto= HTTP/1.1" 200 6057
http://localhost:9001/login?returnto= is my login page url and this where it's returning to.
My .htaccess contents is inside /app folder and is as follows :
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^$ webroot/ [L]
RewriteRule (.*) webroot/$1 [L]
</IfModule>
Please help. I am struck on this.

Related

Multiple Request with Flask API and Reactjs

Below is the request that I did. Everything works except when I try the put /stats-batch which shows this error. I don't know what is the options that is being displayed, I only noticed it today.
The /stats-batch also just prints hello when access
27.0.0.1 - - [25/May/2021 16:20:46] "OPTIONS /user HTTP/1.1" 200 -
127.0.0.1 - - [25/May/2021 16:20:46] "POST /user HTTP/1.1" 200 -
127.0.0.1 - - [25/May/2021 16:20:48] "OPTIONS /product HTTP/1.1" 200 -
127.0.0.1 - - [25/May/2021 16:20:48] "GET /product HTTP/1.1" 200 -
127.0.0.1 - - [25/May/2021 16:20:48] "OPTIONS /new-batch HTTP/1.1" 200 -
127.0.0.1 - - [25/May/2021 16:20:48] "GET /new-batch HTTP/1.1" 200 -
127.0.0.1 - - [25/May/2021 16:21:21] "OPTIONS /new-batch HTTP/1.1" 200 -
oks
127.0.0.1 - - [25/May/2021 16:21:21] "PUT /new-batch HTTP/1.1" 200 -
127.0.0.1 - - [25/May/2021 16:21:21] "GET /new-batch HTTP/1.1" 200 -
127.0.0.1 - - [25/May/2021 16:21:43] "OPTIONS /stats-batch HTTP/1.1" 200 -
127.0.0.1 - - [25/May/2021 16:21:44] "PUT /stats-batch HTTP/1.1" 500 -
Traceback (most recent call last):
File "C:\Users\USER\Desktop\Allen\santeh\env\Lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
.......
.......
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\Lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type function is not JSON serializable
I call this functions with a button click using axios like this. config has the authorization header just like all the other request
const startBatch = async () => {
const status = 'start'
await axios
.put('http://127.0.0.1:5000/stats-batch', status, config)
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
})
}
The console shows the error that No Access-Control-Allow-Origin header is present on the requested resource.
I also have flask_cors installed and the other axios request is working. I don't know what cause this error if its the backend or the frontend.
I see an issue; "/new-batch" endpoint is throwing 500 exceptions, which could be related to "Object of type function is not JSON serializable".
Based on the description / Error "No Access-Control-Allow-Origin header is present on the requested resource" message what I understand is
CORS configuration has been missed for PUT VERB.
Because you wrote that rest of the endpoints work without issues, only PUT on this specific "/new-batch" endpoint fails.
Options: In CORS, a preflight request is sent with the OPTIONS method so that the server can respond if it is acceptable to send the request.
URL: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS

Can't call a function to create a object on #route function even tough it works on python interpreter

I'm creating a database for a school project and doing the backend between it and the app.(I'm using Flask and SQLAlchemy for it)
So the problem is that i can't call a function User(entrances), the function User() is a construction function used to create and object ,well it's what it looks like for me at least. But the function itself works when i do it in the interpreter.
WHY can i do it in my interpreter and can't do it on the flask tiny web framework???
here's the github link:BackEndRepository
Before taking a look at the samples here's the output form the interpreter that works:
Interperter
here's the code for my route:
from app import app,db
from models import User
from flask import render_template,Flask,request,redirect,url_for
#app.route('/index')
def index():
return "Hello, World!"
#app.route('/teste')
def teste():
users = db.session.query(User).all()
return u"<br>".join([u"{0}: {1}".format(user.name, user.email) for user in users])
#app.route('/teste2')
def teste2():
teste=User(name='susan',email='susan#example.com')
#u = User(name=request.args.get('1'), email=request.args.get('2'))
return teste
And here is the code for my model:
from app import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
def __init__(self,name,email):
self.name = name
self.email= email
def __repr__(self):
return '<User {0} {1}>'.format(self.name,self.email)
so i run in my terminal "flask run" and get the error in response:(theese is all the log i had after doing what i explained)
#Arthur:~/Public/ProjetoBackEnd(Original)$ flask run
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [21/Nov/2018 14:24:41] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [21/Nov/2018 14:24:41] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [21/Nov/2018 14:24:46] "GET /index HTTP/1.1" 200 -
127.0.0.1 - - [21/Nov/2018 14:24:46] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [21/Nov/2018 14:24:52] "GET /teste HTTP/1.1" 200 -
127.0.0.1 - - [21/Nov/2018 14:24:53] "GET /favicon.ico HTTP/1.1" 404 -
[2018-11-21 14:24:57,004] ERROR in app: Exception on /teste2 [GET]
Traceback (most recent call last):
File "/home/arthur/.local/lib/python2.7/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/home/arthur/.local/lib/python2.7/site-packages/flask/app.py", line 1816, in full_dispatch_request
return self.finalize_request(rv)
File "/home/arthur/.local/lib/python2.7/site-packages/flask/app.py", line 1831, in finalize_request
response = self.make_response(rv)
File "/home/arthur/.local/lib/python2.7/site-packages/flask/app.py", line 1982, in make_response
reraise(TypeError, new_error, sys.exc_info()[2])
File "/home/arthur/.local/lib/python2.7/site-packages/flask/app.py", line 1974, in make_response
rv = self.response_class.force_type(rv, request.environ)
File "/home/arthur/.local/lib/python2.7/site-packages/werkzeug/wrappers.py", line 921, in force_type
response = BaseResponse(*_run_wsgi_app(response, environ))
File "/home/arthur/.local/lib/python2.7/site-packages/werkzeug/test.py", line 923, in run_wsgi_app
app_rv = app(environ, start_response)
TypeError: 'User' object is not callable
The view function did not return a valid response. The return type must be a string, tuple, Response instance, or WSGI callable, but it was a User.
127.0.0.1 - - [21/Nov/2018 14:24:57] "GET /teste2 HTTP/1.1" 500 -
127.0.0.1 - - [21/Nov/2018 14:24:57] "GET /favicon.ico HTTP/1.1" 404 -
JUST highlighting the part that's bugging me out the most here:
TypeError: 'User' object is not callable
The problem is here:
#app.route('/teste2')
def teste2():
teste=User(name='susan',email='susan#example.com')
#u = User(name=request.args.get('1'), email=request.args.get('2'))
return teste
You are returning teste which is a User. That's not a valid return type here as the error tells you:
The return type must be a string, tuple, Response instance, or WSGI callable, but it was a User.
It's fine to return a string for example, so this should work:
#app.route('/teste2')
def teste2():
teste=User(name='susan',email='susan#example.com')
#u = User(name=request.args.get('1'), email=request.args.get('2'))
return teste.name

CakePHP controller , Url not found on server

I write a controller in CakePhp-2.9 named API to access outside.
Controller Code:
class APIController extends AppController
{
var $name = 'API';
var $cache_dir = 'img/cache';
var $cache_width = 400;
public $msgs = array();
public function beforeFilter()
{
parent::beforeFilter();
$this->Auth->allow('ecall_request','ecall_callback','testlog','ecall_request_test','ecall_callback_test');
}
public function ecall_request()
{
Cache::write("test_request".time(),$this->request->data);
if($this->request->is('post'))
{
// my code here
}
}
}
And i tested "http://localhost/dentech/api/ecall_request" on POSTMAN successfully, But when i upload it on server at https://dentech.com/api/ecall_request it does not access and gives 404 error.
htaccess code is:
<IfModule mod_rewrite.c>
RewriteEngine on
# Uncomment if you have a .well-known directory in the root folder, e.g. for the Let's Encrypt challenge
# https://tools.ietf.org/html/rfc5785
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
#RewriteRule ^(\.well-known/.*)$ $1 [L]
RewriteRule ^$ app/webroot/ [L]
RewriteRule (.*) app/webroot/$1 [L]
Updated from comments: The reason for the 404-error is that the controller name in the URL has to be in uppercase characters. Instead of
https://dentech.com/api/ecall_request
You need to use
https://dentech.com/API/ecall_request
The fact that it works on localhost but not on the server is the difference in the operating system. Windows (often used locally) is not case-sensitive, while Linux (usually the servers OS) is case-sensitive.

how caching via nginx result of prerender.io

We have site with frontend on angular that need to render for search bots and other application like skype, which can make preview of page.
We use nginx, which setup for proxing requests from bots to prerender, which installed on our server. But in that case prerendering one of page takes about 15 seconds.
So, question is how setup caching result of prerender?
I have already try:
put settings for caching into frontend.conf
proxy_cache_path /var/lib/nginx/cache levels=1:2 keys_zone=STATIC:10m max_size=1G;
proxy_temp_path /var/lib/nginx/proxy 1 2;
server {
location #prerender {
.....................
proxy_cache STATIC;
proxy_cache_valid 1d;
if ($prerender = 1) {
rewrite .* /$scheme://$host:$server_port$request_uri? break;
proxy_pass http://10.0.2.2:3000;
}}}
Where 10.0.2.2 server with working prerender.io
And I tried doing this through another nginx, which setup like cache-proxy. In frotnend.conf I comment all caching settings and put them into other nginx. But I still have the same problem, page rendering takes 15sec, and nginx don't make any caching.
UDP.
I tried another configuration of nginx, but still have problem.
Schema looks like
web-browser(http://myapp.local) > |AppServer(frontend) is a virtual Server|(proxy_pass) > to > |nginx with proxy cache| > to > |prerender|
proxy-cache.conf
proxy_cache_path /var/lib/nginx/cache levels=1:2 keys_zone=STATIC:10m max_size=1G;
proxy_temp_path /var/lib/nginx/proxy 1 2;
server {
..............................
location / {
proxy_cache STATIC;
proxy_ignore_headers Cache-Control;
proxy_ignore_headers X-Accel-Expires;
proxy_ignore_headers Expires;
proxy_cache_methods GET;
proxy_cache_valid any 1d; # 200
#proxy_cache_key $host$uri$is_args$args;
proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
proxy_pass http://127.0.0.1:3000;
}}
And I configure logging for cache. When I make a request to the server in log I get this:
GET /http://myweb.local:80/ HTTP/1.0 "302" 20 "-" "10.0.2.2" "skype" "-" "MISS" "127.0.0.1:3000" "0.388" "0.389"
GET /http://myweb.local:80/en/ HTTP/1.0 "200" 14685 "-" "10.0.2.2" "skype" "-" "MISS" "127.0.0.1:3000" "1.261" "1.263"
GET /http://myweb.local:80/ HTTP/1.0 "302" 20 "-" "10.0.2.2" "skype" "-" "HIT" "-" "-" "0.001"
GET /http://myweb.local:80/en/ HTTP/1.0 "200" 14689 "-" "10.0.2.2" "skype" "-" "MISS" "127.0.0.1:3000" "1.249" "1.251"
In log of prerender:
2016-06-15T14:05:57.880Z getting http://myweb.local:80/en/
2016-06-15T14:05:59.131Z got 200 in 1251ms for http://myweb.local:80/en/
2016-06-15T14:06:00.332Z getting http://myweb.local:80/en/
2016-06-15T14:06:01.885Z got 200 in 1553ms for http://myweb.local:80/en/
I resolve this problem. It need to add another ignore of headers proxy_ignore_headers Set-Cookie; . So configuration for cache prerender via nginx will be:
proxy_cache_path /var/lib/nginx/cache levels=1:2 keys_zone=STATIC:10m inactive=24h max_size=2g;
server {
.......................
location / {
try_files $uri #prerender;
}
location #prerender {
set $prerender 0;
.......................
proxy_cache STATIC;
proxy_cache_valid any 1d;
proxy_ignore_headers Cache-Control;
proxy_ignore_headers X-Accel-Expires;
proxy_ignore_headers Set-Cookie;
proxy_ignore_headers Expires;
proxy_cache_key $host$uri$is_args$args;
proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
if ($prerender = 1) {
rewrite .* /$scheme://$host:$server_port$request_uri? break;
proxy_pass http://10.0.2.2:3000;
}
It is fairly easy to add caching to the prerender server itself, s3 and memory cache works out of the box.
If you need need nginx to handle the caching, I think you get a better chance at an answer if you put it in the question title.

Routes and Path in CakePHP

i am currently dvelpping a website for a friend and i have a strange issue.
Let me first say i am rather a non experienced developper and I cant seem to find a solution:
I've localized my websites in different languages you can watch it here:
http://parfum-poudre.fr/en (in English) it works fine
but if you go to http://parfum-poudre.fr/en/ the paths are messed up and some pics don't appear...
for example there is a professional sapce on this website but then if you go back on the public space i have the same issue...
anyone ha s anything to say about that ?
Thanks
Have added your images, scripts and styles using normal HTML tag in layout file?
This can be one issue.
You can add images,scripts and styles to your layout file using
<?php
echo $this -> Html -> css('style');
echo $this -> Html -> script('jquery');
echo $this -> fetch('css');
echo $this -> fetch('script');
?>
<?php echo $this->Html->image('logo2.png', array('url' => '/ProjectName/','alt'=>'Logo')); ?>
Add this to your app_helper.php
class AppHelper extends Helper {
function url($url = null, $full = false) {
$routerUrl = Router::url($url, $full);
if (!preg_match('/\\.(rss|html|js|css|jpeg|jpg|gif|png|xml?)$/', strtolower($routerUrl)) && substr($routerUrl, -1) != '/') {
$routerUrl .= '/';
}
return $routerUrl;
}
}
The AppHelper stuff goes in the app_helper.php file located in HTDOCS/PROJECT/APP folder (APP ROOT). If the file doesn't exits, create one.
And edit your .htaccess to
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule ^(.*)$ http://domain.com/$1/ [L,R=301]
The .htaccess code goes in the .htaccess file in HTDOCS/PROJECT/APP/WEBROOT folder (APP ROOT/WEBROOT). Just replace the original contents and make sure you change domain.com to whatever your domain is.

Resources