Web2py ticket invalid links - python

I started playing around with web2py the other day for a new project. I really like the structure and the whole concept which feels like a breath of fresh air after spending a few years with PHP frameworks.
The only thing (currently) that is bothering me is the ticketing system. Each time I make a misstake a page with a link to a ticket is presented. I guess I could live with that if the link worked. It currently points to an admin page with http as protocol instead of https. I've done a bit of reading and the forced https for admin seems to be a security measure, but this makes debugging a pain.
Whats the standard solution here? Alter the error page, allow http for admin och use logs for debugging?
Best regards
Fredrik

I was in the same boat as you, I did not like the default mechanism. Luckily, customized exception handling with web2py is very straightforward. Take a look at routes.py in the root of your web2py directory. I've added the following to mine:
routes_onerror = [('application_name/*','/application_name/error/index')]
This routes any exceptions to my error handler controller (application_name/controllers/error.py) in which I defined my def index as:
def index():
if request.vars.code == '400':
return(dict(app=request.application,
ticket=None,
traceback="A 400 error was raised, this is controller/method path not found",
code=None,
layer=None,
wasEmailed=False))
elif request.vars.code == '404':
return(dict(app=request.application,
ticket=None,
traceback="A 404 error was raised, this is bad.",
code=None,
layer=None,
wasEmailed=False))
else:
fH = file('applications/%s/errors/%s' % (request.application,request.vars.ticket.split("/")[1]))
e = cPickle.load(fH)
fH.close()
__sendEmail(request.application,e['layer'],e['traceback'],e['code'])
return(dict(app=request.application,
ticket=request.vars.ticket,
traceback=e['traceback'],
code=e['code'],
layer=e['layer'],
wasEmailed=True))
As you can see for non-400 and 404 errors, I'm emailing the traceback to myself and then invoking the corresponding views/error/index.html. In production, this view gives a generic "I'm sorry an error has occurred, developers have been emailed". On my development server, it displays the formatted traceback.

Normally, I just use http://127.0.0.1/ (if you are local or over ssh) or edit/navigate using https://...
So, you will logon the admin app the first time, but always will the show the tickets after.

Related

authorisation failure in Pyramid (Python)

So I'm trying to port some old Pylons code to Pyramid, and I'd like to be able to improve on the Auth setup - specifically support better RBAC, and Pyramid has good support for this.
However, I'd like to offer unauthorised users better info when they try illegal pages:
"Sorry, in order to view [page] you ([user]) need [group] privileges - please contact [admin]"
However I don't see how that's practical in Pyramid - I can do stuff in the forbidden_view_config page, however I can't easily find all the info needed from the page which was attempted - is it possible to get the exception or similar with the actual reason why permission was not granted?
The request object itself should have all the bits you need.
Specifically, security-related pieces lists some of the request attributes that you can retrieve. Also the request.exception attribute will be available when an exception is raised. There are several URL-related pieces available to get the "page", including application_url.

how can I make an outbound SIP call using Twilio?

I am using a Galaxy 8S android phone with the Samsung SIP settings. I have successfully registered a (Twilio) SIP account on the phone. I want to make an outbound call to an international PSTN Number NOT to another sip address.
My SIP doman, on Twilio, points to my heroku app.
The code is:
#application.route("/makesip", methods=['GET', 'POST'])
def makesip():
to_number=request.values.get('To', None),
client = Client(ACCOUNT_SID, AUTH_TOKEN)
call = client.calls.create(to=to_number, from_="+1415792xxxx", url="https://myapp.herokuapp.com/sipout", method="POST")
return call.sid
#return "OK"
#application.route("/sipout", methods=['GET', 'POST'])
def sipout():
response = VoiceResponse()
to_number = request.values.get('To', None)
dial = Dial(caller_id='+1415792xxxx')
dial.number(to_number)
response.append(dial)
return str(response)
When I make the call from my cell phone it hangs up almost immediately and says "Server Error try again later". The Twilio error log says:
We don't support dialing out to global twilio domains (domainname.sip.twilio.com). Only regional (domainname.sip.us1.twilio.com) ones are supported.
I think that I am making a very fundamental error here but I simply cannot identify it. Can anybody help please? Should I, for example, set the "from_" parameter as "sip:my_sip_address.domainname.sip.us1.twilio.com"?
I'm not a heroku expert, but your code looks similar enough to the php I have running which works fine for this.
In your phone settings is your SIP server set as user#domainname.sip.twilio.com or as user#domainname.sip.us1.twilio.com? It should be the latter. I seem to remember getting caught out by something like this when I was trying to get things working
EDIT
Just had another play with mine and I figured it out. You have to dial the number from your phone as phonenumber#yourdomain.sip.twilio.com, then twilio will return to as sip:phonenumber#yourdomain.sip.twilio.com
You need to change this line of your code to strip out just the number
to_number=request.values.get('To', None),
My php line is substr(strtok($to, '#'), 4); so whatever your equivalent of that is.
What I think is probably happening is that the "To" that is hitting your Heroku app is in the format "sip:+12312123123#yoursipdomain.sip.twilio.com;user=phone" and you're trying to inject that directly into the "dial" verb.
What you actually want is to strip it down to the bare number in E.194 format (with the leading +).
I'd suggest starting by testing using a quick TwiML Bin as per the Twilio SIP Registration docs, rather than your Heroku app.
TwiML Bins are basically static TwiML but with a tiny bit of intelligence in special tags. It's like the Twilio equivalent of Mail Merge, if you've ever used that in Microsoft Word.
(Twilio recently updated the SIP Registration docs. They're much better now.)
Use a TwiML Bin for initial testing otherwise you risk spending time fixing an otherwise working Heroku app because the problem is your phone/account.
Go to "Twilio Docs > API Reference > Twilio Voice API > SIP Registration".
Scroll down to "Using Enhanced TwiML Bin Templates to Call a mobile/landline on the Public Telephone Network" and follow that.
See if that works.
If it doesn't, my suspicion is your Samsung is actually spitting out something daft due to something dial plan related. (Dial plan is the conversion of +12345645642 into a SIP URI. You might find it's doing something like +012345645642 instead.)
If it does work, great. If you want to get your Heroku app working, compare the working response body to the one your Heroku app is spitting out. Post both, and we'll figure out what's going wrong.
Just to check, you are specifying a region in your Domain and Registration Server settings on the Samsung, yeah? The "yoursipdomain.sip.us1.twilio.com" that miknik talked about?

Uber Rides/Python - How to configure Oauth w. Apache

I'm new to this so I apologize in advance. I am actually an AppleScript developer and would merely like to use Uber Rides.py into a script, and I have virtually no knowledge in Python. (Just looking for an 'easy' way to initiate a Uber ride within a more complex script using Homebridge and Siri).
I've built the py app but I don't know to get the Oauth code after using the authorization_code_grant.py script.
I will be the only user of this app (it's just for testing at home) so I'm not that worried about Auth but I understand it's a mandatory uber process. There's no frontend to the app (it's just the script running and responding to Siri requests via Homebridge) and no web page for the user to authenticate. The user will be myself so I just need a way to "get" the Oauth code that I then will use as part of the CLI/Python command within the Applescript.
I have two main issues:
Can someone give me a step by step on how to grab the code sent by Uber once the user has logged in and clicked on the authorized button? I seem to understand I should configure my Apache server to "receive" the code but I don't know how to? (If it helps I have set up an Horuku account but I'm not sure I need this considering Apache runs on my Mac, I just don't know how to configure it…)
When I try to use the authorization_code py (with the URI set to http://localhost:7000 but, to my knowledge, nothing runs on port 7000 at the moment, hence question 1) it generates the error below
Error:
>mediacenter$ python example/authorization_code_grant.py
Login and grant access by going to:
login.uber.com/oauth/authorize?scope=profile+request+history&state=MgnYJ18l7DxqbSYxkSfjrbGCL8BQAMg0&redirect_uri=https%3A%2F%2Foauthswift.herokuapp.com%2Fcallback%2Fsiriuber&response_type=code&client_id=3Wk7zJbSLVCFCQ69UZvQJCZ_aBfHJBDu
>Copy the URL you are redirected to and paste here:
oauth-callback/siriuber?state=MgnYJ18l7DxqbSYxkSfjrbGCL8BQAMg0&code=dK1ETADCaHcZCAbXnYKOSapetgexgj
Failed to request access token: UNAUTHORIZED.
[ErrorDetails: 401 UNAUTHORIZED invalid_client]
Traceback (most recent call last):
File "example/authorization_code_grant.py", line 150, in
hello_user(api_client)
File "example/authorization_code_grant.py", line 122, in hello_user
response = api_client.get_user_profile()
AttributeError: 'NoneType' object has no attribute 'get_user_profile'
I hope it kind of makes sense. I know I should spend some time getting to learn a "real" language but AS is (most of the time) perfect to bring different things together quickly and doing what I want!
Thanks in advance,
JC
Same person from GitHub. After digging around, I came up with this.
Basically there is probably a configuration issue in either your example/config.yaml or in your app dashboard. Make sure you configured both of those correctly. the example/config.yaml setup should be exactly like this with the three values replaced. Make sure your redirect URL is the same as the one in your dashboard under "Authorizations" redirect URLs.
Did you install from source? As in did you clone it from the GitHub repo? Or did you install it using pip?
Hope this helps.

How to properly deal with errors on live django site?

Let's say I have a try and catch and there is an exception ... What is the proper way to deal with those exceptions/errors on a live production (django) site?
So I have
try:
create_response = wepay.call('/account/create',
{'name': name, 'description': desc})
self.wepay_account_id = create_response['account_id']
self.save()
except WePay.WePayError as e:
..... (what do I put here?
You can set up e-mail error reporting through Django: https://docs.djangoproject.com/en/dev/howto/error-reporting/
Or you can use a service like Rollbar (has a free account) to track error occurances.
Or you could use self-hosted Greylog (like suggested in comments), here's a good guide for django: http://www.caktusgroup.com/blog/2013/09/18/central-logging-django-graylog2-and-graypy/
Respond with (optionally a redirect to) a appropriate page explaining the problem to the user and if possible, provide a solution. Serving a 500 to your users in production is something you want to avoid, so catching the exception is a good idea.
So:
except WePay.WePayError as e:
return render_to_response('wepay_error_page.html')
or:
except WePay.WePayError as e:
return HttpResponseRedirect('/errors/wepay/') # Note: better use urlresolvers
(note this particular code will only work if it's in a view)
Then (optionally), make sure you get a copy of the error, by for example sending yourself an email.
A suggestion for this particular case (if I interpret the code succesfully) may be to notify yourself, and repond with a page explaining to the user their payment went wrong. Tell them this might occur because of their actions (maybe they cancelled their payment), and provide contact details for when users think it was not their fault.
Django by default mails (when mail is properly configured) all 500 errors to settings.ADMINS, but these only occur on uncaught exceptions, so in this particular question services like Rollbar or a central logging solution will only work if you re-raise the exception (will result in a 500) or send the error to one of these manually in the catch block.
I would recommend the above solution of redirecting over to a page that explains WePay error, combined with using django-wepay app available on pypi that features logging of all errors, and optionally all calls.

urllib2.urlopen fails in deployed app

I wonder if there is something restrictive about the app engine proxy that serves url fetch requests that just changed today. For example, this url http://www.google.com/ig/calculator?q=1eur=?usd was working without a hitch until a few hours ago. This is the error I'm getting now
http://www.google.com/ig/calculator?q=1eur=?usd returned an error: HTTP Error 503: Service Unavailable
Note that in the SDK (who uses my local internet connection) the code below works. Also 'curl http://www.google.com/ig/calculator?q=1eur=?usd' works, so I don't think that it's google restricting that the request doesn't come from an end user browser (ie. no vainilla user agent). It's probably something that has changed a few hours ago in app engine infrastructure.
url = 'http://www.google.com/ig/calculator?q=1eur=?usd'
request = urllib2.Request(url = url, data = None)
try:
response = urllib2.urlopen(request)
except urllib2.URLError, e:
raise Exception("%s returned an error: %s" % (url, e))
As noted in the comments, it's very likely you are seeing being throttled. iGoogle hosts a number of private (but not secret) APIs for use by Google-authored gadgets that run on the page (the weather API is another widely-used example). However, they're not really intended for consumption by non-Google gadgets or applications, and their implementation can (and does) change without notice.
Furthermore, iGoogle is a deprecated product. I would expect that those utility APIs will go away simultaneously with the iGoogle shutdown (Nov 1, 2013). If you don't want your application to break when iGoogle goes away, I'd advise finding a different source for this information.

Categories

Resources