예제 #1
0
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)
예제 #2
0
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
예제 #4
0
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
            })
예제 #5
0
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
        })
예제 #6
0
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
        })
예제 #7
0
    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()
예제 #8
0
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)
예제 #9
0
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 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)
예제 #11
0
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')
    })
예제 #12
0
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)
예제 #13
0
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')
예제 #14
0
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
예제 #15
0
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
    }
예제 #16
0
    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)
예제 #17
0
파일: app.py 프로젝트: astaninger/GenMatch
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))
예제 #18
0
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()
예제 #19
0
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.
예제 #20
0
def amazon_token(country_code, worker_id):
    _, identity = get_caller_identity(country_code, worker_id)
    token = AccessToken(TWILIO_ACCOUNT_SID,
                        TWILIO_API_KEY,
                        TWILIO_API_SECRET,
                        identity=identity)
    grant = VoiceGrant(outgoing_application_sid=AMAZON_TWIML_APP_SID)
    token.add_grant(grant)

    return jsonify({"token": token.to_jwt()})
예제 #21
0
def generateToken(identity):

    # Create access token with credentials
    token = AccessToken(account_sid, api_key, api_secret, identity=identity)

    if chat_service:
        chat_grant = ChatGrant(service_sid=chat_service)
        token.add_grant(chat_grant)
    # Return token info as JSON
    return jsonify(identity=identity, token=token.to_jwt().decode('utf-8'))
예제 #22
0
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()
예제 #23
0
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}
예제 #24
0
def login():
    username = request.get_json(force=True).get('username')
    if not username:
        abort(401)
    token = AccessToken(app.config["TWILIO_ACCOUNT_SID"],
                        app.config["TWILIO_API_KEY_SID"],
                        app.config["TWILIO_API_KEY_SECRET"],
                        identity=username)
    token.add_grant(VideoGrant(room='My Room'))
    return {'token': token.to_jwt().decode()}
예제 #25
0
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'))
예제 #26
0
    def test_video_grant(self):
        scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret')
        scat.add_grant(VideoGrant(room='CP123'))

        token = scat.to_jwt()
        assert_is_not_none(token)
        decoded_token = AccessToken.from_jwt(token, 'secret')
        self._validate_claims(decoded_token.payload)
        assert_equal(1, len(decoded_token.payload['grants']))
        assert_equal({'room': 'CP123'},
                     decoded_token.payload['grants']['video'])
예제 #27
0
def videologin(request, room_name):

    identity = request.GET.get('identity', fake.user_name())
    token = AccessToken(twilio_account_sid,
                        twilio_api_key_sid,
                        twilio_api_key_secret,
                        identity=identity)
    token.add_grant(VideoGrant(room=room_name))
    data = {'identity': token.identity, 'token': token.to_jwt().decode()}
    response = {'identity': identity, 'token': token.to_jwt().decode()}
    return JsonResponse(response)
예제 #28
0
 def token(self, request, pk=None):
     user = CustomUser.objects.get(pk=pk)
     token = AccessToken(account_sid,
                         api_key,
                         api_key_secret,
                         identity='user' + str(user.id))
     voice_grant = VoiceGrant(outgoing_application_sid=app_sid,
                              push_credential_sid=push_credential_sid,
                              incoming_allow=True)
     token.add_grant(voice_grant)
     return HttpResponse(token.to_jwt().decode('utf-8'), )
예제 #29
0
def connect_video():
    username = request.get_json(force=True).get('username')
    if not username:
        abort(401)
    #Initaitve connection by getting the access key
    token = AccessToken(Config.TWILIO_ACCOUNT_SID,
                        Config.TWILIO_API_KEY,
                        Config.TWILIO_SECRET_KEY,
                        identity=username)
    token.add_grant(VideoGrant(room='Private Video Call'))
    return {'token': token.to_jwt().decode()}
예제 #30
0
    def test_conversations_grant(self):
        scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret')
        scat.add_grant(ConversationsGrant(configuration_profile_sid='CP123'))

        token = scat.to_jwt()
        assert_is_not_none(token)
        decoded_token = AccessToken.from_jwt(token, 'secret')
        self._validate_claims(decoded_token.payload)
        assert_equal(1, len(decoded_token.payload['grants']))
        assert_equal({'configuration_profile_sid': 'CP123'},
                     decoded_token.payload['grants']['rtc'])
예제 #31
0
    def test_conversations_grant(self):
        scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret')
        scat.add_grant(ConversationsGrant(configuration_profile_sid='CP123'))

        token = scat.to_jwt()
        assert_is_not_none(token)
        decoded_token = AccessToken.from_jwt(token, 'secret')
        self._validate_claims(decoded_token.payload)
        assert_equal(1, len(decoded_token.payload['grants']))
        assert_equal({
            'configuration_profile_sid': 'CP123'
        }, decoded_token.payload['grants']['rtc'])
예제 #32
0
    def test_grants(self):
        scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret')
        scat.add_grant(VideoGrant())
        scat.add_grant(IpMessagingGrant())

        token = scat.to_jwt()
        assert_is_not_none(token)
        decoded_token = AccessToken.from_jwt(token, 'secret')
        self._validate_claims(decoded_token.payload)
        assert_equal(2, len(decoded_token.payload['grants']))
        assert_equal({}, decoded_token.payload['grants']['video'])
        assert_equal({}, decoded_token.payload['grants']['ip_messaging'])
예제 #33
0
    def test_video_grant(self):
        scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret')
        scat.add_grant(VideoGrant(room='RM123'))

        token = scat.to_jwt()
        assert_is_not_none(token)
        decoded_token = AccessToken.from_jwt(token, 'secret')
        self._validate_claims(decoded_token.payload)
        assert_equal(1, len(decoded_token.payload['grants']))
        assert_equal({
            'room': 'RM123'
        }, decoded_token.payload['grants']['video'])
예제 #34
0
    def test_chat_grant(self):
        scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret')
        scat.add_grant(ChatGrant(service_sid='IS123', push_credential_sid='CR123'))

        token = scat.to_jwt()
        assert_is_not_none(token)
        decoded_token = AccessToken.from_jwt(token, 'secret')
        self._validate_claims(decoded_token.payload)
        assert_equal(1, len(decoded_token.payload['grants']))
        assert_equal({
            'service_sid': 'IS123',
            'push_credential_sid': 'CR123'
        }, decoded_token.payload['grants']['chat'])
예제 #35
0
    def test_sync_grant(self):
        scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret')
        scat.identity = "bender"
        scat.add_grant(SyncGrant(service_sid='IS123', endpoint_id='blahblahendpoint'))

        token = scat.to_jwt()
        assert_is_not_none(token)
        decoded_token = AccessToken.from_jwt(token, 'secret')
        self._validate_claims(decoded_token.payload)
        assert_equal(2, len(decoded_token.payload['grants']))
        assert_equal("bender", decoded_token.payload['grants']['identity'])
        assert_equal({
            'service_sid': 'IS123',
            'endpoint_id': 'blahblahendpoint'
        }, decoded_token.payload['grants']['data_sync'])
예제 #36
0
    def test_programmable_voice_grant_incoming(self):
        grant = VoiceGrant(
            incoming_allow=True
        )

        scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret')
        scat.add_grant(grant)

        token = scat.to_jwt()
        assert_is_not_none(token)
        decoded_token = AccessToken.from_jwt(token, 'secret')
        self._validate_claims(decoded_token.payload)
        assert_equal(1, len(decoded_token.payload['grants']))
        assert_equal({
            'incoming': {
                'allow': True
            }
        }, decoded_token.payload['grants']['voice'])
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']

    # Create an Access Token
    token = AccessToken(account_sid, api_key, api_secret)

    # Set the Identity of this token
    token.identity = fake.user_name()

    # Grant access to Twilio Video
    grant = VideoGrant()
    grant.configuration_profile_sid = os.environ['TWILIO_CONFIGURATION_SID']
    token.add_grant(grant)

    # Return token info as JSON
    return jsonify(identity=token.identity, token=token.to_jwt())
예제 #38
0
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']
    service_sid = os.environ['TWILIO_SYNC_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)

    # Create a Sync grant and add to token
    sync_grant = SyncGrant(service_sid=service_sid)
    token.add_grant(sync_grant)

    # Return token info as JSON
    return jsonify(identity=identity, token=token.to_jwt())
예제 #39
0
    def test_task_router_grant(self):
        grant = TaskRouterGrant(
            workspace_sid='WS123',
            worker_sid='WK123',
            role='worker'
        )

        scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret')
        scat.add_grant(grant)

        token = scat.to_jwt()
        assert_is_not_none(token)
        decoded_token = AccessToken.from_jwt(token, 'secret')
        self._validate_claims(decoded_token.payload)
        assert_equal(1, len(decoded_token.payload['grants']))
        assert_equal({
            'workspace_sid': 'WS123',
            'worker_sid': 'WK123',
            'role': 'worker'
        }, decoded_token.payload['grants']['task_router'])
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']
    service_sid = os.environ['TWILIO_CHAT_SERVICE_SID']

    # create a randomly generated username for the client
    identity = fake.user_name()

    # Create a unique endpoint ID for the
    device_id = request.args.get('device')
    endpoint = "TwilioChatDemo:{0}:{1}".format(identity, device_id)

    # Create access token with credentials
    token = AccessToken(account_sid, api_key, api_secret, identity=identity)

    # Create a Chat grant and add to token
    chat_grant = ChatGrant(endpoint_id=endpoint, service_sid=service_sid)
    token.add_grant(chat_grant)

    # Return token info as JSON
    return jsonify(identity=identity, token=token.to_jwt())
예제 #41
0
    def test_programmable_voice_grant(self):
        grant = VoiceGrant(
            outgoing_application_sid='AP123',
            outgoing_application_params={
                'foo': 'bar'
            }
        )

        scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret')
        scat.add_grant(grant)

        token = scat.to_jwt()
        assert_is_not_none(token)
        decoded_token = AccessToken.from_jwt(token, 'secret')
        self._validate_claims(decoded_token.payload)
        assert_equal(1, len(decoded_token.payload['grants']))
        assert_equal({
            'outgoing': {
                'application_sid': 'AP123',
                'params': {
                    'foo': 'bar'
                }
            }
        }, decoded_token.payload['grants']['voice'])
예제 #42
0
 def test_add_grant_validates_grant(self):
     scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret')
     scat.add_grant(VideoGrant())
     self.assertRaises(ValueError, scat.add_grant, 'GrantRootAccess')
from twilio.jwt.access_token import AccessToken
from twilio.jwt.access_token.grants import VideoGrant

# Required for all Twilio Access Tokens
account_sid = 'ACxxxxxxxxxxxx'
api_key = 'SKxxxxxxxxxxxx'
api_secret = 'xxxxxxxxxxxxxx'

# required for Video grant
identity = 'user'

# Create Access Token with credentials
token = AccessToken(account_sid, api_key, api_secret, identity=identity)

# Create a Video grant and add to token
video_grant = VideoGrant(room='cool room')
token.add_grant(video_grant)

# Return token info as JSON
print(token.to_jwt())
from twilio.jwt.access_token import AccessToken, IpMessagingGrant

# required for all twilio access tokens
account_sid = 'ACxxxxxxxxxxxx'
api_key = 'SKxxxxxxxxxxxx'
api_secret = 'xxxxxxxxxxxxxx'

# required for IP messaging grants
ipm_service_sid = 'ISxxxxxxxxxxxx'
identity = '*****@*****.**'
device_id = 'someiosdevice'
endpoint_id = "HipFlowSlackDockRC:{0}:{1}".format(identity, device_id)

# Create access token with credentials
token = AccessToken(account_sid, api_key, api_secret, identity)

# Create an IP Messaging grant and add to token
ipm_grant = IpMessagingGrant(
        endpoint_id=endpoint_id,
        service_sid=ipm_service_sid)
token.add_grant(ipm_grant)

# Return token info as JSON
print(token.to_jwt())
예제 #45
0
from twilio.jwt.access_token import AccessToken, VoiceGrant

# required for all twilio access tokens
account_sid = 'ACxxxxxxxxxxxx'
api_key = 'SKxxxxxxxxxxxx'
api_secret = 'xxxxxxxxxxxxxx'

# required for Voice grant
outgoing_application_sid = 'APxxxxxxxxxxxxx'
identity = 'user'

# Create access token with credentials
token = AccessToken(account_sid, api_key, api_secret, identity)

# Create a Voice grant and add to token
voice_grant = VoiceGrant(
    outgoing_application_sid=outgoing_application_sid
)
token.add_grant(voice_grant)

# Return token info as JSON
print(token.to_jwt())
from twilio.jwt.access_token import AccessToken
from twilio.jwt.access_token.grants import ChatGrant

# required for all twilio access tokens
account_sid = 'ACxxxxxxxxxxxx'
api_key = 'SKxxxxxxxxxxxx'
api_secret = 'xxxxxxxxxxxxxx'

# required for Chat grants
service_sid = 'ISxxxxxxxxxxxx'
identity = '*****@*****.**'
device_id = 'someiosdevice'
endpoint_id = "HipFlowSlackDockRC:{0}:{1}".format(identity, device_id)

# Create access token with credentials
token = AccessToken(account_sid, api_key, api_secret, identity=identity)

# Create an Chat grant and add to token
chat_grant = ChatGrant(endpoint_id=endpoint_id, service_sid=service_sid)
token.add_grant(chat_grant)

# Return token info as JSON
print(token.to_jwt())