Twilio - generate 6 digit random numbers - python

Im planning to integrate twilio for two factor authentication in my Django application.
Now, I have installed twilio python module and sent some random messages to my number.
The next step is for me to send some random 6 digit numbers that's done in banking application or google two factor authentication.
How can I generate these numbers in my DJango application?

In addition to Matthias' answer (I upvoted his answer);
Django provides a shortcut function for this purpose:
from django.utils.crypto import get_random_string
get_random_string(length=6, allowed_chars='1234567890')
Which is more readable and memorable.
And also if you are really concerned about randomness of this string, you may want to use random module from pycrypto because standard library implementations of random function in programming languages are not "random" enough for cryptographic and security related issues.

You can use random.choice to determine each digit. choice will give you one element from the given sequence.
The code could look like this:
import random
pin = ''.join(random.choice('0123456789') for _ in range(6))

you could also do
import random
random.SystemRandom().randint(100000,999999)

Twilio developer evangelist here.
There have been some great answers to help you generate a random 6 digit string, however I just wanted to add one more suggestion.
Authy is part of Twilio and provides Two Factor Authentication as a service. It supports sending codes by SMS (which goes via Twilio), generating codes in the Authy application and even two factor authentication without copying a code from an app/sms to your login screen with Authy OneTouch. You can implement your entire 2FA flow with just 3 API calls.
There is a tutorial on how to use Authy with Flask, which I'm sure you could translate to Django.
Let me know if this helps at all.

rand(1000, 9999); == 4 digit
rand(100000, 999999); == 6 digit
$client = $this->_initTwilioClient();
$fromNo = $this->_helperPot->getTwilioPhone();
$code = rand(1000, 9999);
try {
$result = $client->messages->create(
$toNo,
[
'from' => $this->_helperPot->getTwilioPhone(),
'body' => "Verification code: $code"
]
);
$output = [];
$output['status'] = "success";
$output['code'] = $code;
return $output;
} catch (\Exception $e) {
$output = [];
$output['status'] = "failure";
$output['message'] = $e->getMessage();
return $output;
}

Related

Is it possible to inject python code in Kwargs and how could I prevent this user input

I'm at the moment in the middle of writing my Bachelor thesis and for it creating a database system with Postgres and Flask.
To ensure the safety of my data, I was working on a file to prevent SQL injections, since a user should be able to submit a string via Http request. Since most of my functions which I use to analyze the Http request use Kwargs and a dict based on JSON in the request I was wondering if it is possible to inject python code into those kwargs.
And If so If there are ways to prevent that.
To make it easier to understand what I mean, here are some example requests and code:
def calc_sum(a, b):
c = a + b
return c
#app.route(/<target:string>/<value:string>)
def handle_request(target,value):
if target == 'calc_sum':
cmd = json.loads(value)
calc_sum(**cmd)
example Request:
Normal : localhost:5000/calc_sum/{"a":1, "b":2}
Injected : localhost:5000/calc_sum/{"a":1, "b:2 ): print("ham") def new_sum(a=1, b=2):return a+b":2 }
Since I'm not near my work, where all my code is I'm unable to test it out. And to be honest that my code example would work. But I hope this can convey what I meant.
I hope you can help me, or at least nudge me in the right direction. I've searched for it, but all I can find are tutorials on "who to use kwargs".
Best regards.
Yes you, but not in URL, try to use arguments like these localhost:5000/calc_sum?func=a+b&a=1&b=2
and to get these arguments you need to do this in flask
#app.route(/<target:string>)
def handle_request(target):
if target == 'calc_sum':
func= request.args.get('func')
a = request.args.get('a')
b = request.args.get('b')
result = exec(func)
exec is used to execute python code in strings

how to validate values in array and do actions python whatsapp framework

I am newbie learning python, I need a little help in whatsapp framework in github but that's python programming where my knowledge is limited. here you can see two things:
message.text ( here is stored the whatsapp message, so i can create commands)
message.conversation (here you can get the groupid or phone number of the sender)
the example code:
# modules/hi_module.py
from app.mac import mac, signals
#signals.message_received.connect
def handle(message):
if message.text == "hi":
mac.send_message("Hello", message.conversation)
# Can also send media
#mac.send_image("path/to/image.png", message.conversation)
#mac.send_video("path/to/video.mp4", message.conversation)
i want to limit my commands like that "hi" to work only in three groups allowed by me, i am thinking in an array where this is stored. So i am thinking in an idea like that
groupIds = { "group": "123456789#whatsapp.net", "group": "123458754#whatsapp.net",}
if "hi" in message.text:
validategroup()
#do something
else:
#print("you are not allowed to do this command")
def validategroup:
if groupIds in message.conversation:
validation = true
else:
validation = false
I am stuck at this part, I don't know how to code correctly the method and how to return and allow command or deny. please help me to learn
I think you can not do like this
if groupIds in message.conversation:
As groupIds is dic and you can not find complete dic. you should use the value of the key to find in message.conversation.
One more I want to check is message.conversation get string or list..?
Thanks
Your BOOLEAN values must begin with a Capital Letter ( i.e. True or False ).

Create own IVR that will access Database

I'm currently interning with a company and have been tasked with researching some methods of using telephony. The goal is to provide our clients with the ability to call in and through an IVR-prompted questions, get information back. The information will be from our database.
I have successfully done this using Twilio and a small python app. It does exactly what I'm looking to do, except the cost factor can be a bit high, especially if we have 30,000+ clients calling for minutes on end.
My goal is to find a way to replicate what I've done with Twilio, but on our own server. I've found options like Asterisk and IncrediblePBX, but because my limited knowledge of Linux, every error I run into results in scouring the internet for answers. Ultimately, I'm not sure if I'm heading in the right direction.
This is an example of what I'd like to accomplish:
Client calls into number. They're directed to provide an account number, (possibly their phone number) At that point it will take this information and talk to a database. Gathering this information it will relay back to the client the status of their account etc.
Questions:
I was hoping to use Google Voice to route calls similar to Twilio, is this possible? Alternatively, could my company switch to a VoIP and do the same thing?
If I move away from Twilio, can Asterisk perform the necessary tasks? Receiving calls and running the app to gather database information.
Current code for Twilio, in Python:
from flask import Flask, request, redirect
import twilio.twiml
import json
from urllib.request import urlopen
app = Flask(__name__)
callers = {
"+": "Nicholas",
}
#app.route("/", methods=['GET', 'POST'])
def initial():
# Get the caller's phone number from the incoming Twilio request
from_number = request.values.get('From', None)
resp = twilio.twiml.Response()
# if the caller is someone we know:
if from_number in callers:
# Greet the caller by name
caller = callers[from_number]
else:
caller = ""
resp = twilio.twiml.Response()
resp.say("Hello " + caller)
resp.say("Thank you for calling.")
your_number = list(from_number)
del your_number[0]
del your_number[0]
resp.say("You are calling from: ")
x = 0
while x < len(your_number):
resp.say(your_number[x])
x += 1
print("Please enter the neighborhood I.D. you're looking for.")
with resp.gather(numDigits=1, action="/handle-first", method="POST") as g:
g.say("Please enter the neighborhood I.D. you're looking for.")
return str(resp)
#app.route("/handle-first", methods=['GET', 'POST'])
def handle_key():
digit_pressed = request.values.get('Digits', '')
resp = twilio.twiml.Response()
url = 'http://localhost/...'
response = urlopen(url)
data = json.loads(response.readall().decode('utf-8'))
current = data['rows'][0]['Neighborhood']
print(current)
resp.say("You have chosen " + current + "as your neighborhood.")
with resp.gather(numDigits=1, action="/handle-second", method="POST") as h:
h.say("Press 1 to choose another Neighborhood?")
return str(resp)
#app.route("/handle-second", methods=['GET', 'POST'])
def handle_key2():
digit_pressed = request.values.get('Digits', '')
resp = twilio.twiml.Response()
if digit_pressed == "1":
return redirect("/")
else:
resp.say("Thank you for calling. Good-bye.")
return str(resp)
if __name__ == "__main__":
app.run(debug=True)
Asterisk is fundamentally different than Twilio, I can honestly say they are somewhat opposites. The track you are seeking to follow is that of Asterisk dialplan with a combination of AGI. AGI is the Asterisk Gateway Interface, and will enable you a way to interact with Asterisk via a simple scripting mechanism. The API is fairly simple and there is a whole range of ready made libraries you can use. Let's put it this way, when it comes to AGI, just pick your poison - PHP, Python, JAVA, Ruby - all are available.
My personal favorite, and many in the Asterisk world as well, is PHP - with an LGPL component called PHP-AGI. It's fairly old and has been around for years, but works well with all versions of Asterisk. If you wish to walk on the bleeding edge and require stronger call control, you can go with ARI (Asterisk REST interface), however, judging from your requirement - that's an overkill.
You can read a bit about AGI development with PHP at this link:
https://www.packtpub.com/books/content/asterisk-gateway-interface-scripting-php
(Shameful plug - I wrote the book)
In addition, you can refer to the following presentation for additional information (again, my own presentation) - It's a little old, but still valid in terms of concept and usage:
http://osdc.org.il/2006/html/Asterisk_AGI_Programming.ppt
Good luck
Yes, asterisk can do all task you can program. It even have api for access raw stream.
However no, you can't use SAME code.
For google voice check chan_motif code.
For db access use dialplan+realtime or func_odbc or fastagi/agi interface.
You are probably looking for an open source IVR solution. The only one I am aware of is OpenVBX.
I am in no way affiliate with them or Twilio.

Why does this program hang? Google App Engine and Python

This program is supposed to compute a numeric palindrome, when data is input via a web form. It did run properly on localhost environment using just python and the web.py framework. But since then, I ported it to the google app engine, using webapp2 framework, so that I can launch this on a public server. When I refactored code for this new framework, something got off in the lines of code dealing with the computation. Hoping someone can help solve this.
Below is the class that handles getting the input from browser. I've tested and it seems to get that input fine. Then it sends it to compute_palintip, which is supposed to solve the palindrome (final amount). It is hanging here.
class result(webapp2.RequestHandler):
def post(self):
form = self.request.get_all('entries', default_value = None)
if form[0]:
if form[1]:
orig_dollar_amount = cgi.escape(form[0])
tip_percent = cgi.escape(form[1])
final_amount = compute_palintip(float(orig_dollar_amount),
float(tip_percent))
actual_tip_percent = final_amount - orig_dollar_amount
actual_tip_percent = actual_tip_percent*100/orig_dollar_amount
This is the compute_palintip code and its helper function:
def compute_palintip(orig_dollar_amount, tip_percent):
orig_amount_cents = orig_dollar_amount*100
final_amount = orig_amount_cents*(1.0 + tip_percent/100.0)
while(is_palindrome(final_amount) == False):
final_amount += 1
final_amount = final_amount/100
final_amount = round(final_amount, 2)
return final_amount
def is_palindrome(num):
num_str = str(num)
num_str_len = len(num_str)
for i in range(num_str_len):
if num_str[i] != num_str[num_str_len-i-1]:
return False
return True
A few notes:
I had to convert the input into floats in order to send them to the compute_palintip function.
Couldn't convert to ints because they do not allow decimal places (cents are needed for these inputs related to restaurant dollar amounts).
I also have to use the float type I'm pretty sure, because neither Strings nor Ints will be able to operate with the formulas which are also floats. Python wants them all the same.
However, it seems that the math is now wonky since the floats and ints got mixed up, and it is not terminating.
The math was written by a colleague, whereas I was writing the UI type stuff, which is why I'm not really able to debug it at this point, so I am hoping someone else can spot a solution I'm not seeing. Thanks.
Perhaps you can set some logging to see the flow of the program. When dealing in floats, be consistent in your arithmetic, and use decimals after each number:
orig_dollar_amount*100.0
final_amount/100.0
final_amount += 1.0
actual_tip_percent*100.0/orig_dollar_amount
Also, you failed to cast orig_dollar_amount to a float
What are the numbers you've input? There are cases where is_palindrome never returns True. e.g. 1234567890. It will go through the entire string, and return False for every test.
I solved the issues, thanks for the help everyone. The decimal places had to be exact, and I had to be sure in each place of choosing whether to use ints / floats / strings, etc. in order to get the proper outcome. Line by line debugging, testing various examples, and correcting the flaws one by one was the only way to go.
The prototype app of this code is up and running at http://third-fire-595.appspot.com/ , by the way, for anyone interested in playing with it. please feel free to test out some combinations and let me know any feedback.

Signing requests in Python for OAuth

currently I'm interfacing the Twitter API using the OAuth protocol and writing the code in Python. As most of the users out there, I think the toughest part of the specs is dealing with signatures.
After wandering around the web in search for a solution, I decided to go for my custom code, so as to have a better understanding of what is going on.
For the sake of other users, I'm posting here a very simple and short implementation of the SHA1 signature specs in Python:
import hmac
from hashlib import sha1
from urllib import quote, urlencode
from base64 import b64encode
from urlparse import urlparse
def sign_request_sha1(url,method,data,secret=""):
pu = urlparse(urlparse(url).geturl())
normUrl = "%s://%s%s%s" % (
pu.scheme,
pu.hostname,
"" if not pu.port or {"http":80,"https":443}[pu.scheme] == pu.port else ":%d" % pu.port,
pu.path,
)
names = data.keys()
names.sort()
sig = "%s&%s&%s" % (
method.upper(),
quote(normUrl,''),
quote("&".join(["%s=%s" % (k,quote(data[k].encode('utf-8'),'')) for k in names]),''),
)
key = "%s&%s" % (quote(CONSUMER_SECRET.encode('utf-8'),''),secret)
return b64encode(hmac.new(key,sig,sha1).digest())
The input parameters to the function are:
url: the url you are going to call for the specific OAuth request.
method: this must be "GET" or "POST" depending on how you're going to issue your request.
data: a dictionary containing all the parameters of the requests, including any custom argument but excluding the "oauth_signature" one (for obvious reasons).
secret: a secret token you received in the initial phase of the protocol.
I tested it with Twitter and it seems to work but I'd like to receive some comments about mistakes, improvements and so on.
Lastly, here you find a piece of code calling the code for the initial "request token" phase:
from random import getrandbits
from base64 import b64encode
from time import time
def twitter_request_token(req,callback,errback):
req_url="http://twitter.com:80/oauth/request_token"
data = { \
"oauth_consumer_key" : CONSUMER_KEY,
"oauth_nonce" : b64encode("%0x" % getrandbits(256))[:32],
"oauth_timestamp" : str(int(time())),
"oauth_signature_method" : "HMAC-SHA1",
"oauth_version" : "1.0",
"oauth_callback" : "http://localhost:8080/",
}
data["oauth_signature"] = sign_request_sha1(req_url,"GET",data)
Thank you.
My knee-jerk reaction to this is If You're Typing The Letters A-E-S Into Your Code, You're Doing It Wrong. Or, as redditor khafra recently reminded us of the Sicilian's version:
Haha.. you fool! You fell victim to one of the classic blunders. The most famous is: Never get involved in a land war in Asia. But only slightly less famous is this: Never attempt to roll your own crypto when there's a well-tested library that'll do it better!
I mean, I get it. The first time I looked at it, oauth.py didn't impress me either. There's been a lot of work on it since and it's looking better, but there still appear to be no tests, so I don't know. Anyway, tests or no tests, it's been reviewed and used by more people than your code has.
But that's just me being uptight on the subject of crypto code reuse and doesn't really help you in figuring out the protocol machinery. It looks okay to me, but I haven't had my head in the OAuth spec too much lately.
Just use some more lines for that pu.port business; having a conditional if expression, an or expression, and the {}[] construct all in one line is really hard to read.
If you really want code review by people who are familiar with the protocol, you're probably better off asking the mailing list. And if you can offer them an alternate API that will make the code in their repository more appealing to new users, that'll be good for everyone.

Categories

Resources