예제 #1
0
    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'])
예제 #2
0
    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)
예제 #3
0
    def test_identity(self):
        scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret', identity='*****@*****.**')
        token = scat.to_jwt()

        assert_is_not_none(token)
        decoded_token = AccessToken.from_jwt(token, 'secret')
        self._validate_claims(decoded_token.payload)
        assert_equal({
            'identity': '*****@*****.**'
        }, decoded_token.payload['grants'])
예제 #4
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'])
예제 #5
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'])
예제 #6
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'])
예제 #7
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'])
예제 #8
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'])
예제 #9
0
    def test_pass_grants_in_constructor(self):
        grants = [
            VideoGrant(),
            IpMessagingGrant()
        ]
        scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret', grants=grants)

        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'])
예제 #10
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'])
예제 #11
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())
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())
예제 #13
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'])
예제 #14
0
    def generate_voice_access_token(self,
                                    from_number: str,
                                    identity: str,
                                    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 = self.safe_identity(identity)

        # 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 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())
예제 #16
0
def generateToken(identity):
    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)
    token = AccessToken(account_sid, api_key, api_secret, identity=identity)
    # we sync here, according to tutorial. not too sure what it does
    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, we basically add chat services for the user
    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())
예제 #17
0
def token(request):
    identity = request.GET.get('identity', fake.user_name())
    device_id = request.GET.get('device', 'default')

    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)
예제 #18
0
def serve_room():
    room = request.args.get("room", None)
    other_gp = request.args.get("other_gp", True)
    if room is None:
        return "Invalid room", 400

    identity = str(uuid1())

    account_sid = os.getenv("TWILIO_ACCOUNT_SID")
    api_key = os.getenv("TWILIO_API_KEY")
    api_secret = os.getenv("TWILIO_API_SECRET")

    # 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=room)
    token.add_grant(video_grant)

    # Return token info as JSON
    token_str = token.to_jwt().decode("utf-8")
    return render_template("room.html",
                           token=token_str,
                           is_grandparent=other_gp)
예제 #19
0
def login():
    username = request.get_json(force=True).get('username')
    if not username:
        abort(401)

    conversation = get_chatroom('My Room')
    try:
        conversation.participants.create(identity=username)
    except TwilioRestException as exc:
        # do not error if the user is already in the conversation
        if exc.status != 409:
            raise

    token = AccessToken(twilio_account_sid,
                        twilio_api_key_sid,
                        twilio_api_key_secret,
                        identity=username)
    token.add_grant(VideoGrant(room='My Room'))
    token.add_grant(ChatGrant(service_sid=conversation.chat_service_sid))

    return {
        'token': token.to_jwt().decode(),
        'conversation_sid': conversation.sid
    }
예제 #20
0
def login():
    print(
        "******************************************************************kjhaugyf"
    )
    # username = request.form.get('username')
    username = request.get_json(force=True).get('username')
    # username = request.form.get('username')
    if not username:
        abort(401)

    twilio_account_sid = app.config.get('TWILIO_ACCOUNT_SID')
    twilio_api_key_sid = app.config.get('TWILIO_API_KEY_SID')
    twilio_api_key_secret = app.config.get('TWILIO_API_KEY_SECRET')

    token = AccessToken(twilio_account_sid,
                        twilio_api_key_sid,
                        twilio_api_key_secret,
                        identity=username)
    token.add_grant(VideoGrant(room='My Room'))
    my_token = token.to_jwt().decode()
    print(my_token)
    token_dict = {'token': my_token}
    print(jsonify(token_dict))
    return jsonify(token_dict)
예제 #21
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'])
예제 #22
0
def token():
  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)
  push_credential_sid = os.environ.get("PUSH_CREDENTIAL_SID", PUSH_CREDENTIAL_SID)
  app_sid = os.environ.get("APP_SID", APP_SID)

  grant = VoiceGrant(
    push_credential_sid=push_credential_sid,
    outgoing_application_sid=app_sid
  )

  # identity = request.values["identity"] \
  #         if request.values and request.values["identity"] else IDENTITY

  # Generate a random user name
  identity = alphanumeric_only.sub('', fake.user_name())

  token = AccessToken(account_sid, api_key, api_key_secret, identity=identity)
  token.add_grant(grant)

  print("identity is "+identity)

  return jsonify(identity=identity, token=token.to_jwt())
예제 #23
0
파일: views.py 프로젝트: mudit1804/EduDevs
def token(request):
    curruser = request.user
    uname = curruser.username
    identity = request.GET.get('identity', uname)
    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 = "MiniSlackChat:{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)
예제 #24
0
def get_room(encounter_name=None, guest_code=None):
    twilio_account_sid = "AC70b39fd03e3485b309ad8a70a1bb225f"
    twilio_api_key_sid = "SKeae44b74f2c50d1d0d87845ffe0084ca"
    twilio_api_key_secret = "mwf41jZu62hfb5KVWilUFPPDUSRRH7mL"

    #either encounter_name or guest_code must be passed
    if not encounter_name and not guest_code:
        frappe.throw("Must provide encounter name or guest code")

    #check if it is a guest patient
    user = frappe.session.user
    if not user or user == 'Guest':
        #check guest's permission code for encounter
        appointment_name = frappe.db.get_value("Patient Appointment",
                                               {"tele_code": guest_code},
                                               "name")
        if not guest_code or not appointment_name:
            frappe.throw(_("Access Denied"), frappe.AuthenticationError)

        else:
            encounter_list = frappe.db.get_values(
                "Patient Encounter", {'appointment': appointment_name},
                "*",
                as_dict=True)
            if not encounter_list:
                frappe.throw("Must wait for medic to start consultation.")
            encounter = encounter_list[0]
            #twilio
            identity = encounter.patient_name
            #make sure room_id is the same for user and non-user
            room_id = encounter.name + encounter.patient + encounter.practitioner
            token = AccessToken(twilio_account_sid,
                                twilio_api_key_sid,
                                twilio_api_key_secret,
                                identity=identity)
            token.add_grant(VideoGrant(room=room_id))
            return {"id": room_id, "accessToken": token.to_jwt().decode()}
    else:
        #check valid encounter
        if not encounter_name or not frappe.db.get_value(
                "Patient Encounter", {"name": encounter_name}):
            frappe.throw(_("Access Denied"))

        status = frappe.db.get_value("Patient Encounter",
                                     {"name": encounter_name}, "docstatus")
        if status == 1 or status == 2:
            frappe.throw(_("Access Denied"))

        patient = frappe.db.get_value("Patient Encounter",
                                      {"name": encounter_name}, "patient")
        practitioner = frappe.db.get_value("Patient Encounter",
                                           {"name": encounter_name},
                                           "practitioner")

        if user == 'Administrator' or validate_encounter_practitioner(
                encounter_name):
            #twilio
            first_name = frappe.db.get_value("Healthcare Practitioner",
                                             {"user_id": user}, "first_name")
            last_name = frappe.db.get_value("Healthcare Practitioner",
                                            {"user_id": user}, "last_name")
            identity = user
            if first_name:
                identity = first_name
            if last_name:
                identity = identity + ' ' + last_name

            #make sure room_id is the same for user and non-user
            room_id = encounter_name + patient + practitioner
            token = AccessToken(twilio_account_sid,
                                twilio_api_key_sid,
                                twilio_api_key_secret,
                                identity=identity)
            token.add_grant(VideoGrant(room=room_id))
            return {"id": room_id, "accessToken": token.to_jwt().decode()}

    frappe.throw(_("Access Denied"))
예제 #25
0
 def test_headers(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.assertEqual(decoded_token.headers['cty'], 'twilio-fpa;v=1')
예제 #26
0
 def test_headers(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.assertEqual(decoded_token.headers['cty'], 'twilio-fpa;v=1')
예제 #27
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')
예제 #28
0
def generateToken():
#    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)
#    push_credential_sid = os.environ.get("PUSH_CREDENTIAL_SID", PUSH_CREDENTIAL_SID)
#    app_sid = os.environ.get("APP_SID", APP_SID)
#    sync_service_sid = os.environ.get("SYNC_SERVICE_SID", SYNC_SERVICE_SID)
#    auth_token = os.environ.get("AUTH_TOKEN", AUTH_TOKEN)
    account_sid         = os.environ['TWILIO_ACCOUNT_SID']
    api_key             = os.environ['TWILIO_API_KEY']
    api_key_secret      = os.environ['TWILIO_API_KEY_SECRET']
    push_credential_sid = os.environ['TWILIO_PUSH_CREDENTIAL_SID']
    app_sid             = os.environ['TWILIO_TWIML_APP_SID']
    sync_service_sid    = os.environ['TWILIO_SYNC_SERVICE_SID']
    auth_token          = os.environ['TWILIO_AUTH_TOKEN']
    
    identity = request.values.get('id')
    
    if identity[0] == ' ':
        identity = "+" + identity[1:]
    
    identity = getIdentity(identity)
    print(identity)

    token = AccessToken(account_sid, api_key, api_key_secret, identity=identity)

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

    # 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)

#    client = Client(account_sid, auth_token)
#    data = json.dumps({'board':{
#                      'date_updated': str(datetime.now()),
#                      'status': "none",
#                      }})
#    documents = client.preview \
#                        .sync \
#                            .services(sync_service_sid) \
#                                .documents \
#                                    .list()
#    isMatch = False
#    for document in documents:
#        print(document.unique_name)
#        print(document.data)
#        did_delete = client.preview \
#                            .sync \
#                                .services(sync_service_sid) \
#                                    .documents(document.unique_name) \
#                                        .delete()
#        print("Delete: ",did_delete)
#        if document.unique_name == identity:
#            isMatch = True
#            print("Fetch")
#            document = client.preview.sync.services(sync_service_sid).documents(identity).fetch()
#            print(document.unique_name)#
#    if not isMatch:
#        print ("Create")
#        document = client.preview.sync.services(sync_service_sid).documents.create(unique_name=identity, data=data)
#        print(document.unique_name)
#    else:
#        print("Already created.")

    return jsonify(identity=identity, token=token.to_jwt())
예제 #29
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())
예제 #30
0
 def test_empty_region(self):
     scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret')
     token = scat.to_jwt()
     decoded_token = AccessToken.from_jwt(token, 'secret')
     self.assertRaises(KeyError, lambda: decoded_token.headers['twr'])