def generateToken(identity): # Get credentials from environment variables account_sid = settings.TWILIO_ACCT_SID chat_service_sid = settings.TWILIO_CHAT_SID sync_service_sid = settings.TWILIO_SYNC_SID api_sid = settings.TWILIO_API_SID api_secret = settings.TWILIO_API_SECRET # Create access token with credentials token = AccessToken(account_sid, api_sid, api_secret, identity=identity) # Create a Sync grant and add to token if sync_service_sid: sync_grant = SyncGrant(service_sid=sync_service_sid) token.add_grant(sync_grant) # Create a Chat grant and add to token if chat_service_sid: chat_grant = ChatGrant(service_sid=chat_service_sid) token.add_grant(chat_grant) # Return token info as JSON return JsonResponse({ 'identity': identity, 'token': token.to_jwt().decode('utf-8') })
def twilio_api_chat(): from twilio.jwt.access_token import AccessToken from twilio.jwt.access_token.grants import ChatGrant from twilio.rest import Client service_sid = 'IScb01dd8aeded43f1961957e46cfcf717' identity = request.args.get('identity') # required for all twilio access tokens account_sid = 'AC1ab30057b0be6eaaa144ff94b773c882' auth_token = '6ec8894a7733967f155c26d39feadf3a' client = Client(account_sid, auth_token) ACCOUNT_SID = account_sid API_KEY_SID = 'SK08e688a95ac12a599a36deb2aec64a68' API_KEY_SECRET = 'akrwxUmAompQjVNnpExLgOkMAf2m45iC' token = AccessToken(ACCOUNT_SID, API_KEY_SID, API_KEY_SECRET, identity=identity) # Create an Chat grant and add to token chat_grant = ChatGrant(service_sid=service_sid) token.add_grant(chat_grant) print(token.to_jwt().decode('utf-8')) return ujson.dumps({ 'token': token.to_jwt(), 'identity': identity })
def twilio_api_video(): from twilio.jwt.access_token import AccessToken from twilio.jwt.access_token.grants import VideoGrant from twilio.rest import Client name = request.args.get('name') room = request.args.get('room') ACCOUNT_SID = 'AC0899dfbac4d4374a162ad3f494a29cb9' API_KEY_SID = 'SK0d73ceea012fd7a740cfea97b091b11f' API_KEY_SECRET = '9c2gxH04Fd2RNV9EePMYW1XmeNP1ehOm' # Create an Access Token token = AccessToken(ACCOUNT_SID, API_KEY_SID, API_KEY_SECRET, identity=name) # Grant access to Video grant = VideoGrant(room=room) token.add_grant(grant) print(token.to_jwt()) return ujson.dumps({ 'token': token.to_jwt(), 'name': name, 'room': room })
def token(): user_id = request.args.get('user') if not user_id: return "Invalid user" platform = request.args.get('platform') if not platform: return "Invalid platform" account_sid = os.environ.get("ACCOUNT_SID", ACCOUNT_SID) api_key = os.environ.get("API_KEY", API_KEY) api_key_secret = os.environ.get("API_KEY_SECRET", API_KEY_SECRET) user_identity = 'agent_' + user_id if platform == 'android': push_credential = os.environ.get("ANDROID_PUSH_CREDENTIAL_SID", ANDROID_PUSH_CREDENTIAL_SID) else: push_credential = os.environ.get("IOS_PUSH_CREDENTIAL_SID", IOS_PUSH_CREDENTIAL_SID) grant = VoiceGrant( push_credential_sid=push_credential ) token = AccessToken(account_sid, api_key, api_key_secret, user_identity) token.add_grant(grant) return str(token)
def get_user_twilio_token(self, user_id, context): try: user_id = user_id.value # print("get_user_twilio_token", user_id) TWILIO_ACCOUNT_SID = 'AC0cb509ad66d21f69f2fd6e4b566e2449' TWILIO_API_KEY_SID = 'SK6ea1006b0adabde2957b9077e0a25679' TWILIO_API_KEY_SECRET = 'AP6uPE2wJoVACZlWG2CSnDBI40MRaYfM' # Create an Access Token token = AccessToken(TWILIO_ACCOUNT_SID, TWILIO_API_KEY_SID, TWILIO_API_KEY_SECRET) # Set the Identity of this token token.identity = user_id # Grant access to Video grant = VideoGrant(room='AwesomeRoom') token.add_grant(grant) # Serialize the token as a JWT jwt = token.to_jwt().decode('utf-8') print(jwt) print(user_id) print(token.payload["exp"]) return main_pb2.JWTToken(id=main_pb2.UUID(value=str(user_id)), expiry_time=token.payload["exp"], jwt=jwt) except Exception as e: print("Error in get_user", e) traceback.print_exc(file=sys.stdout)
def createToken(request): content = request.GET # get the identity from the request, or make one up identity = request.user.username # get credentials for environment variables account_sid = os.environ['TWILIO_ACCOUNT_SID'] api_key = os.environ['TWILIO_API_KEY'] api_secret = os.environ['TWILIO_API_SECRET'] chat_service_sid = os.environ.get('TWILIO_CHAT_SERVICE_SID', None) # Create access token with credentials token = AccessToken(account_sid, api_key, api_secret, identity=identity) # Create an Chat grant and add to token if chat_service_sid: chat_grant = ChatGrant(service_sid=chat_service_sid) token.add_grant(chat_grant) # Return token info as JSON return JsonResponse(data={ "identity": identity, "token": token.to_jwt().decode('utf-8') }, safe=False)
def token(request): identity = request.GET.get('identity', fake.user_name()) device_id = request.GET.get('device', 'default') # unique device ID account_sid = settings.TWILIO_ACCOUNT_SID api_key = settings.TWILIO_API_KEY api_secret = settings.TWILIO_API_SECRET chat_service_sid = settings.TWILIO_CHAT_SERVICE_SID token = AccessToken(account_sid, api_key, api_secret, identity=identity) # Create a unique endpoint ID for the device endpoint = "MyDjangoChatRoom:{0}:{1}".format(identity, device_id) if chat_service_sid: chat_grant = ChatGrant(endpoint_id=endpoint, service_sid=chat_service_sid) token.add_grant(chat_grant) response = { 'identity': identity, 'token': token.to_jwt().decode('utf-8') } return JsonResponse(response)
def create_access_token(): id_user_hash = get_jwt_identity() id_user = db.session.query(Users.id_user).filter( Users.id_user_hash == id_user_hash ).first() if id_user: account_sid = current_app.config["TWILIO_ACCOUNT_SID"] api_sid = current_app.config["TWILIO_API_SID"] api_secret = current_app.config["TWILIO_API_SECRET"] chat_sid = current_app.config["TWILIO_CHAT_SID"] token = AccessToken( account_sid, api_sid, api_secret, identity=id_user_hash, ttl=7200) chat_grant = ChatGrant(service_sid=chat_sid) token.add_grant(chat_grant) return jsonify({ "token": token.to_jwt().decode("utf-8") }), 200 else: return jsonify({ "message": "Invalid credential" }), 401
def token(): # get credentials for environment variables account_sid = os.environ['TWILIO_ACCOUNT_SID'] api_key = os.environ['TWILIO_API_KEY'] api_secret = os.environ['TWILIO_API_SECRET'] sync_service_sid = os.environ['TWILIO_SYNC_SERVICE_SID'] chat_service_sid = os.environ['TWILIO_CHAT_SERVICE_SID'] # create a randomly generated username for the client identity = fake.user_name() # Create access token with credentials token = AccessToken(account_sid, api_key, api_secret, identity=identity) # Create a Sync grant and add to token if sync_service_sid: sync_grant = SyncGrant(service_sid=sync_service_sid) token.add_grant(sync_grant) # Create a Video grant and add to token video_grant = VideoGrant() token.add_grant(video_grant) # Create an Chat grant and add to token if chat_service_sid: chat_grant = IpMessagingGrant(service_sid=chat_service_sid) token.add_grant(chat_grant) # Return token info as JSON return jsonify(identity=identity, token=token.to_jwt().decode('utf-8'))
def login(): username = request.get_json(force=True).get('username') if not username: abort(401) conversation = get_chatroom(os.environ.get('CHATROOM', 'My Room')) conversation_sid = '' if conversation: try: conversation.participants.create(identity=username) except TwilioRestException as ex: # do not error if the user is already in the conversation if ex.status != 409: raise conversation_sid = conversation.sid token = AccessToken(twilio_account_sid, twilio_api_key_sid, twilio_api_key_secret, identity=username) token.add_grant(VideoGrant(room='My Room')) if conversation: token.add_grant( IpMessagingGrant(service_sid=conversation.chat_service_sid)) return { 'token': token.to_jwt().decode(), 'conversation_sid': conversation_sid }
def generateToken(identity): # get credentials for environment variables account_sid = os.environ['TWILIO_ACCOUNT_SID'] api_key = os.environ['TWILIO_API_KEY'] api_secret = os.environ['TWILIO_API_SECRET'] sync_service_sid = os.environ.get('TWILIO_SYNC_SERVICE_SID', 'default') chat_service_sid = os.environ.get('TWILIO_CHAT_SERVICE_SID', None) # Create access token with credentials token = AccessToken(account_sid, api_key, api_secret, identity=identity) # Create a Sync grant and add to token if sync_service_sid: sync_grant = SyncGrant(service_sid=sync_service_sid) token.add_grant(sync_grant) # Create a Video grant and add to token video_grant = VideoGrant() token.add_grant(video_grant) # Create an Chat grant and add to token if chat_service_sid: chat_grant = ChatGrant(service_sid=chat_service_sid) token.add_grant(chat_grant) # Return token info as JSON return jsonify(identity=identity, token=token.to_jwt().decode('utf-8'))
def token(): client_name = request.values.get('client') platform = request.values.get('platform') account_sid = os.environ.get("ACCOUNT_SID", ACCOUNT_SID) api_key = os.environ.get("API_KEY", API_KEY) api_key_secret = os.environ.get("API_KEY_SECRET", API_KEY_SECRET) app_sid = os.environ.get("APP_SID", APP_SID) if platform == 'iosdev': push_credential_sid = os.environ.get("PUSH_CREDENTIAL_SID_IOS", PUSH_CREDENTIAL_SID_IOS_DEV) elif platform == 'iosprod': push_credential_sid = os.environ.get("PUSH_CREDENTIAL_SID_IOS", PUSH_CREDENTIAL_SID_IOS_PROD) else: push_credential_sid = os.environ.get("PUSH_CREDENTIAL_SID_ANDROID", PUSH_CREDENTIAL_SID_ANDROID) if client_name: IDENTITY =client_name grant = VoiceGrant( push_credential_sid=push_credential_sid, outgoing_application_sid=app_sid ) token = AccessToken(account_sid, api_key, api_key_secret, IDENTITY) token.add_grant(grant) k = {'accessToken': str(token)} return json.dumps(k)
def generate_token(username, roomname): token = AccessToken(twilio_account_sid, twilio_api_key_sid, twilio_api_key_secret, identity=username) token.add_grant(VideoGrant(room=roomname)) return token.to_jwt().decode()
def get_chat_token(username): logger.info(f'Generating Chat token for {username}') # This call is simply to ensure the service exists service = get_service() token = AccessToken(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_API_KEY, settings.TWILIO_API_SECRET, identity=username) sync_grant = SyncGrant(service_sid='default') token.add_grant(sync_grant) chat_grant = ChatGrant(service_sid=service.sid) token.add_grant(chat_grant) # Expire token in three minutes expiration = 180 jwt_token = token.to_jwt(ttl=expiration).decode("utf-8") # Cache the token, set to expire after the token expires cache.set(f'tokens:chat:{username}', jwt_token, expiration) return jwt_token
def token(): client_name = request.values.get('client') platform = request.values.get('platform') account_sid = os.environ.get('ACCOUNT_SID', ACCOUNT_SID) api_key = os.environ.get('API_KEY', API_KEY) api_key_secret = os.environ.get('API_KEY_SECRET', API_KEY_SECRET) app_sid = os.environ.get('APP_SID', APP_SID) if platform == 'ios': push_credential_sid = os.environ.get('PUSH_CREDENTIAL_SID_IOS', PUSH_CREDENTIAL_SID_IOS) else: push_credential_sid = \ os.environ.get('PUSH_CREDENTIAL_SID_ANDROID', PUSH_CREDENTIAL_SID_ANDROID) if client_name: IDENTITY = client_name grant = VoiceGrant(push_credential_sid=push_credential_sid, outgoing_application_sid=app_sid) token = AccessToken(account_sid, api_key, api_key_secret, IDENTITY) token.add_grant(grant) return str(token)
def on_room_entry_request(data): user_id = (models.DB.session.query( models.CurrentConnections.user).filter_by( sid=flask.request.sid).first()) models.DB.session.add(models.EnteredRooms(user_id, data["roomId"])) models.DB.session.commit() socketio.emit("room entry accepted", room=flask.request.sid) flask_socketio.join_room(str(data["roomId"])) print("room entry accepted") emit_room_history(flask.request.sid) username = models.DB.session.query( models.AuthUser.username).filter_by(id=user_id).first()[0] if data['roomId'] not in roomTokens.keys(): token = AccessToken(twilio_account_sid, twilio_api_key_sid, twilio_api_key_secret, identity=username) roomTokens[data['roomId']] = token token.add_grant(VideoGrant(room=data['roomId'])) socketio.emit( "token", { 'tokens': token.to_jwt().decode(), 'room': str(data['roomId']), 'username': username }) else: token = roomTokens[data['roomId']] token.identity = username socketio.emit( "token", { 'tokens': token.to_jwt().decode(), 'room': str(data['roomId']), 'username': username })
def generate_voice_access_token(self, from_number: str, identity_postfix=None, ttl=60 * 60): """Generates a token required to make voice calls from the browser. """ # identity is used by twilio to identify the user uniqueness at browser(or any endpoints). identity = from_number if identity_postfix: identity = '_'.join( [identity, self.safe_identity(identity_postfix)]) # Create access token with credentials token = AccessToken(self.account_sid, self.api_key, self.api_secret, identity=identity, ttl=ttl) # Create a Voice grant and add to token voice_grant = VoiceGrant( outgoing_application_sid=self.application_sid, incoming_allow=True, # Allow incoming calls ) token.add_grant(voice_grant) return token.to_jwt()
def get_twilio_jwt(identity, room): token = AccessToken(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_API_KEY, settings.TWILIO_API_SECRET, identity=identity) token.add_grant(VideoGrant(room=room)) return token.to_jwt().decode('utf-8')
def test_region(self): scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret', region='foo') token = scat.to_jwt() decoded_token = AccessToken.from_jwt(token, 'secret') assert_equal(decoded_token.headers['twr'], 'foo')
def token(): token = AccessToken( os.environ['TWILIO_ACCOUNT_SID'], os.environ['TWILIO_API_KEY_SID'], os.environ['TWILIO_API_KEY_SECRET'], grants=[SyncGrant(os.environ['TWILIO_SYNC_SERVICE_SID'])], identity=uuid.uuid4().hex) return {'token': token.to_jwt().decode()}
def test_empty_grants(self): scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret') token = str(scat) assert_is_not_none(token) payload = decode(token, 'secret') self._validate_claims(payload) assert_equal({}, payload['grants'])
def test_empty_grants(self): scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret') token = scat.to_jwt() assert_is_not_none(token) decoded_token = AccessToken.from_jwt(token, 'secret') self._validate_claims(decoded_token.payload) assert_equal({}, decoded_token.payload['grants'])
def test_nbf(self): now = int(time.mktime(datetime.now().timetuple())) scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret', nbf=now) token = scat.to_jwt() assert_is_not_none(token) decoded_token = AccessToken.from_jwt(token, 'secret') self._validate_claims(decoded_token.payload) assert_equal(now, decoded_token.nbf)
def video(): identity = random_user() scat = AccessToken(app.config['TWILIO_ACCOUNT_SID'], \ app.config['TWILIO_API_KEY'], app.config['TWILIO_API_SECRET'], identity=identity) scat.add_grant(VideoGrant(room="Room1")) token = scat.to_jwt() value = str(token) value2 = value[2:-1] return jsonify(dict(identity=identity, token=value2))
def create_token(identity): token = AccessToken(account_sid, api_key, api_secret) token.identity = identity # Create a Video grant and add to token video_grant = VideoGrant(room='441') token.add_grant(video_grant) # Return token info as JSON # return {"identity":identity, "token":token.to_jwt()} return token.to_jwt()
def video_access_token(roomId: str, username: str) -> str: token = AccessToken(twilio_account_sid, twilio_api_key_sid, twilio_api_key_secret, identity=username, ttl=3600) token.add_grant(VideoGrant(room=roomId)) return token.to_jwt( ) # This str() is done to work with (slightly) older flask/python version.
def test_nbf(self): now = int(time.mktime(datetime.now().timetuple())) scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret', nbf=now) token = str(scat) assert_is_not_none(token) payload = decode(token, 'secret') self._validate_claims(payload) assert_equal(now, payload['nbf'])
def get_twilio_token(username, classroom_name): token = AccessToken( settings.TWILIO_ACCOUNT_SID, settings.TWILIO_API_KEY_SID, settings.TWILIO_API_KEY_SECRET, identity=username, ) token.add_grant(VideoGrant(room=classroom_name)) return token.to_jwt().decode()
def login(): username = request.get_json(force=True).get('username') if not username: abort(401) token = AccessToken(twilio_account_sid, twilio_api_key_sid, twilio_api_key_secret, identity=username) token.add_grant(VideoGrant(room='My Room')) return {'token': token.to_jwt().decode(), 'name': username}
def token(): # get the userid from the incoming request identity = request.values.get('identity', None) # Create access token with credentials token = AccessToken(twilio_account_sid, twilio_api_key, twilio_api_secret, identity=identity) # Create a Sync grant and add to token sync_grant = SyncGrant(service_sid=twilio_sync_service_id) token.add_grant(sync_grant) # Return token info as JSON return jsonify(identity=identity, token=token.to_jwt().decode('utf-8'))