def register(): if current_user.is_authenticated: return redirect(url_for('users.home')) #set up the phone verification api twilioApi = AuthyApiClient(current_app.config['AUTHY_API_KEY']) form = RegistrationForm() if form.validate_on_submit(): session['phone_number'] = form.phone.data try: twilioApi.phones.verification_start(form.phone.data, '+254', via='sms') except Exception as e: print(e) hashed_password = bcrypt.generate_password_hash( form.password.data).decode('utf-8') #create new user user = User(username=form.username.data.capitalize(), email=form.email.data.lower(), phone=form.phone.data, password=hashed_password) #create session and commit db.session.add(user) db.session.commit() return redirect(url_for("users.verify_phone")) return render_template("register.html", form=form, title='Register')
def __init__(self, user): self.user = user self.errors = {} self.client = AuthyApiClient(api_key=AUTHY_KEY, api_uri=AUTHY_API_URL) self.force_verification = True
def verify_phone(): #logout the user first to prevent redirecting to dashboard logout_user() form = PhoneVerificationForm() if form.validate_on_submit(): code = form.verification_code.data phone_number = session.get('phone_number') twilioApi = AuthyApiClient(current_app.config['AUTHY_API_KEY']) try: verification = twilioApi.phones.verification_check( phone_number, '+254', code) if verification.ok(): #phone successfully verified flash("You can now log in with your account", "success") return redirect(url_for('users.index')) else: flash("The code you entered is not correct.Try again", "danger") return redirect(url_for('users.verify_phone')) except Exception as e: return redirect(url_for('users.index')) return render_template('verify_phone.html', title='Phone verification', form=form)
def verify_phone(request): authy_api = AuthyApiClient('bRswEbgitGVmzXWTvhnbEvuJkE21rJj1') phone_number = User.objects.get(username=request.user).phone verification_code = request.POST.get("verify_phone") check = authy_api.phones.verification_check(phone_number, 91, verification_code) print(phone_number) error_text = "" print(verification_code) if not check.ok(): req = authy_api.phones.verification_start(phone_number, 91, via='sms', locale='en') print(req.content) print(check.ok()) elif check.ok(): request.user.is_user_verified = True request.user.save() return redirect('users:normal_user') if verification_code != " " and not check.ok(): error_text = "OTP not sent. Change the number!" return render(request, 'users/normal_user.html', {'error_text': error_text}) return render(request, 'accounts/verify_phone.html', {'phone_number': phone_number})
class ApiClientTest(unittest.TestCase): def setUp(self): self.api = AuthyApiClient(test_helper.API_KEY, test_helper.API_URL) def test_tokens(self): self.assertIsInstance(self.api.tokens, Tokens) def test_users(self): self.assertIsInstance(self.api.users, Users) def test_version(self): if six.PY3: self.assertRegex(self.api.version(), '\d.\d*') else: import re self.assertTrue(re.compile(r'\d.\d*').search(self.api.version()))
def verify(request): authy_api = AuthyApiClient('kGMhLpEz8fxhoryGsqCoLQ8VBpVpHquk') verification = authy_api.tokens.verify('116415031', '4076094') if verification.ok(): return HttpResponse("OK") else: return HttpResponse("Wrong")
def check_2fa(self, code): authy_api = AuthyApiClient(current_app.config['AUTHY_KEY']) check = authy_api.tokens.verify(self.authy_user_id, code) if check.ok(): return True else: return False
def authy_verify(self, to_number, country_code): authy_api = AuthyApiClient(self.authy_api_key) request = authy_api.phones.verification_start(to_number, country_code, via='sms', locale='en') print(request.content)
def auth(key, email, phone, area_code): authy_api = AuthyApiClient(key) user = authy_api.users.create(email, phone, area_code) if user.ok(): print('user id is {}'.format(user.id)) else: print('error occurred!')
def check_push_status(uuid): authy_api = AuthyApiClient(app.config['AUTHY_API_KEY']) resp = authy_api.one_touch.get_approval_status(uuid) if resp.ok(): return resp.content['approval_request']['status'] else: return "pending"
def verify_phone_check(phone_number, token): if phone_number is not None: authy_api = AuthyApiClient(app.config['TWILIO_VERIFY_SECRET_KEY']) verification = authy_api.phones.verification_check( phone_number, '1', token ) return verification
def verify_phone_start(phone_number, method): if phone_number is not None: authy_api = AuthyApiClient(app.config['TWILIO_VERIFY_SECRET_KEY']) verification = authy_api.phones.verification_start( phone_number, '1', method ) return True
def send_sms_with_callback_token(user, **kwargs): """ Sends a SMS to user.mobile via Twilio. Passes silently without sending in test environment. """ base_string = kwargs.get('mobile_message', api_settings.PASSWORDLESS_MOBILE_MESSAGE) try: if api_settings.PASSWORDLESS_MOBILE_NOREPLY_NUMBER: # We need a sending number to send properly if api_settings.PASSWORDLESS_TEST_SUPPRESSION is True: # we assume success to prevent spamming SMS during testing. return True #from twilio.rest import Client from authy.api import AuthyApiClient authy_api = AuthyApiClient(api_settings.TWILIO_API_KEY) phone_verification = authy_api.phones.verification_start( phone_number=getattr( user, api_settings.PASSWORDLESS_USER_MOBILE_FIELD_NAME), country_code=54, via='sms', locale='es') #twilio_client = Client(os.environ['TWILIO_ACCOUNT_SID'], os.environ['TWILIO_AUTH_TOKEN']) #twilio_client.messages.create( # body=base_string % mobile_token.key, # to=getattr(user, api_settings.PASSWORDLESS_USER_MOBILE_FIELD_NAME), # from_=api_settings.PASSWORDLESS_MOBILE_NOREPLY_NUMBER #) return True else: log.debug( "Failed to send token sms. Missing PASSWORDLESS_MOBILE_NOREPLY_NUMBER." ) return False except ImportError: log.debug("Couldn't import Twilio client. Is twilio installed?") return False except KeyError: log.debug( "Couldn't send SMS." "Did you set your Twilio account tokens and specify a PASSWORDLESS_MOBILE_NOREPLY_NUMBER?" ) except Exception as e: log.debug( "Failed to send token SMS to user: %d. " "Possibly no mobile number on user object or the twilio package isn't set up yet. " "Number entered was %s" % (user.id, getattr(user, api_settings.PASSWORDLESS_USER_MOBILE_FIELD_NAME))) log.debug(e) return False
def check_confirmation_code(self, code): authy_api = AuthyApiClient(current_app.config['AUTHY_KEY']) check = authy_api.phones.verification_check(self.phone, self.country_code, code) if check.ok(): self.phone_number_confirmed = True db.session.add(self) return True else: return False
def register_authy_user(email, country_code, phone_number): authy_api = AuthyApiClient(app.config['AUTHY_API_KEY']) user = authy_api.users.create(email, phone_number, country_code) if user.ok(): _save_user(email, country_code, phone_number, user.id) return user.id else: flash("Error registering user with Authy: '{}'".format(user.errors()), "error")
def verify_authy_token(authy_id, token): authy_api = AuthyApiClient(app.config['AUTHY_API_KEY']) try: verification = authy_api.tokens.verify(authy_id, token) except Exception as e: flash("Error validating token: {}".format(e), "error") return False return verification.ok()
def delete_user(authy_id): """Unregister a user from Authy push notifications. :param authy_id: the Authy ID for the user. :returns True if successful or False otherwise. """ authy_api = AuthyApiClient(current_app.config['AUTHY_PRODUCTION_API_KEY']) resp = authy_api.users.delete(authy_id) return resp.ok()
def check_token(self, token): """ returns True iff token is a valid authy.com two-factor token for the given user """ authy_api = AuthyApiClient(settings.AUTHY_API_KEY) verification = authy_api.tokens.verify(self.authy_id, token) return verification.ok()
def create_authy_user(self): authy_api = AuthyApiClient(current_app.config['AUTHY_KEY']) user = authy_api.users.create(self.email, self.phone, self.country_code) if user.ok(): self.authy_user_id = user.id db.session.add(self) return True else: print(user.errors()) return False
def send_voice_token(authy_id, locale): authy_api = AuthyApiClient(app.config['AUTHY_API_KEY']) call = authy_api.users.request_call(authy_id, { 'force': True, 'locale': locale }) if call.ok(): return (True, None) else: return (False, call.errors()['message'])
def send_sms_token(authy_id, locale): authy_api = AuthyApiClient(app.config['AUTHY_API_KEY']) sms = authy_api.users.request_sms(authy_id, { 'force': True, 'locale': locale }) if sms.ok(): return (True, None) else: return (False, sms.errors()['message'])
def send_sms_token(authy_id, locale): """ Send an SMS token Returns a tuple of (success: Boolean, message: String) """ authy_api = AuthyApiClient(app.config['AUTHY_API_KEY']) # TODO - send SMS # https://github.com/twilio/authy-python#sending-sms-2fa-tokens # API reference: https://www.twilio.com/docs/authy/api/one-time-passwords#request-a-one-time-password return (False, "TODO - implement this")
def send_push_auth(authy_id): """ Starts a push authentication Returns a tuple of (push_uuid: String, errors: String) """ authy_api = AuthyApiClient(app.config['AUTHY_API_KEY']) # TODO start push auth # https://github.com/twilio/authy-python#send-approval-request # API reference: https://www.twilio.com/docs/authy/api/push-authentications#create-an-approval-request return (None, "TODO - implement this")
def check_push_notification_status(uuid): """Check if a push notification has been handled. :param uuid: the ID of the push notification. :returns 'approved', 'pending' or 'error' """ authy_api = AuthyApiClient(current_app.config['AUTHY_PRODUCTION_API_KEY']) resp = authy_api.one_touch.get_approval_status(uuid) if not resp.ok(): return 'error' return resp.content['approval_request']['status']
def register_authy_user(email, country_code, phone_number): """ Register the user with Authy. Returns the Authy ID. """ authy_api = AuthyApiClient(app.config['AUTHY_API_KEY']) # TODO - register Authy user # https://github.com/twilio/authy-python#users # API reference: https://www.twilio.com/docs/authy/api/users#enabling-new-user return "TODO - authy ID"
def verify(self, token=None): authy_api = AuthyApiClient(settings.ACCOUNT_SECURITY_API_KEY) verification = authy_api.phones.verification_check( self.phone, self.country_code, token) if verification.ok(): self.verified = True self.save() return True, None # verified, error_msg else: return False, verification.errors()
def verify_authy_token(authy_id, token): """ Check the token Returns success boolean """ authy_api = AuthyApiClient(app.config['AUTHY_API_KEY']) # TODO - check token # https://github.com/twilio/authy-python#verifying-tokens # API reference: https://www.twilio.com/docs/authy/api/one-time-passwords#verify-a-one-time-password return False # TODO
class ApiClientTest(unittest.TestCase): def setUp(self): self.api = AuthyApiClient(test_helper.API_KEY, test_helper.API_URL) def test_tokens(self): self.assertIsInstance(self.api.tokens, Tokens) def test_users(self): self.assertIsInstance(self.api.users, Users) def test_version(self): self.assertRegexpMatches(self.api.version(), '\d.\d*')
class ApiClientTest(unittest.TestCase): def setUp(self): self.api = AuthyApiClient("bf12974d70818a08199d17d5e2bae630", "http://sandbox-api.authy.com") def test_tokens(self): self.assertIsInstance(self.api.tokens, Tokens) def test_users(self): self.assertIsInstance(self.api.users, Users) def test_version(self): self.assertRegexpMatches(self.api.version(), '\d.\d*')
def getOpt(request): if request.method == 'POST': email = '*****@*****.**' phone = '15041536955' country = '+86' authy_api = AuthyApiClient('kGMhLpEz8fxhoryGsqCoLQ8VBpVpHquk') authy_user = authy_api.users.create(email, phone, country) if authy_user.ok(): print(authy_user.id) sms = authy_api.users.request_sms(authy_user.id) print(sms.content) return HttpResponse(sms) else: return HttpResponse("Failed")
def setUp(self): self.api = AuthyApiClient("bf12974d70818a08199d17d5e2bae630", "http://sandbox-api.authy.com")
def setUp(self): self.api = AuthyApiClient(test_helper.API_KEY, test_helper.API_URL)