Esempio n. 1
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')
    })
Esempio n. 2
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
        })
Esempio n. 3
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)
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
Esempio n. 5
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
Esempio n. 6
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)
def video(post_data):
    """
    Creates JWT Twlio Room token
    Request:
        appointmentId: string
        hcpToken: string?
        patientToken: string?
    Response:
        token: videoId
        id: AppointmentId
        date: number
        duration: number
        doctor: DoctorId
        patient: PatientId
        subject: string
    """
    auth_token = post_data.get('token')
    if auth_token:
        pid, _ = Auth.decode_auth_token(auth_token)

        appointment_id = post_data.get('appointmentId')
        appointments_output = appointmentsdb.document(
            str(appointment_id)).get().to_dict()
        if not (pid == appointments_output['patient']
                or pid == appointments_output['doctor']):
            response_object = {
                "Success": False,
                "message": "ID not in appointment, unable to access room"
            }
            return response_object, 401

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

        token = twilio.access_token(pid)
        token.add_grant(VideoGrant(room=str(appointment_id)))
        token.add_grant(ChatGrant(service_sid=conversation.chat_service_sid))

        response_object = {
            "accessToken": token.to_jwt().decode(),
            "id": appointments_output['id'],
            "date": appointments_output['date'],
            "duration": appointments_output['duration'],
            "doctor": appointments_output['doctor'],
            "patient": appointments_output['patient'],
            "subject": appointments_output['subject'],
            "notes": appointments_output['notes']
        }
        return response_object, 200
    else:
        response_object = {
            'Success': False,
            'message': 'Failed to verify role'
        }
        return response_object, 401
Esempio n. 8
0
def login():
    username = request.get_json(force=True).get('username')
    room = request.get_json(force=True).get('room')
    if not username:
        abort(401)

    conversation = get_chatroom(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=room))
    token.add_grant(ChatGrant(service_sid=conversation.chat_service_sid))

    return {
        'token': token.to_jwt().decode(),
        'conversation_sid': conversation.sid
    }
Esempio n. 9
0
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'))
Esempio n. 10
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'))
Esempio n. 11
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'))
    token.add_grant(ChatGrant(service_sid=twilio_chat_service_sid))

    return {'token': token.to_jwt().decode()}
def getToken():
    identity = request.query.get('identity')

    if identity == '':
        response.status = 400
        return 'getToken requires an Identity to be provided'

    # 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(service_sid=service_sid)
    token.add_grant(chat_grant)
    return (token.to_jwt())
Esempio n. 13
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'])
Esempio n. 14
0
def login():
    payload = request.get_json(force=True)
    username = payload.get('username')
    if not username:
        abort(401)

    # create the user (if it does not exist yet)
    participant_role_sid = None
    for role in twilio_client.conversations.roles.list():
        if role.friendly_name == 'participant':
            participant_role_sid = role.sid
    try:
        twilio_client.conversations.users.create(identity=username,
                                                 role_sid=participant_role_sid)
    except TwilioRestException as exc:
        if exc.status != 409:
            raise

    # add the user to all the conversations
    conversations = twilio_client.conversations.conversations.list()
    for conversation in conversations:
        try:
            conversation.participants.create(identity=username)
        except TwilioRestException as exc:
            if exc.status != 409:
                raise

    # generate an access token
    twilio_account_sid = os.environ.get('TWILIO_ACCOUNT_SID')
    twilio_api_key_sid = os.environ.get('TWILIO_API_KEY_SID')
    twilio_api_key_secret = os.environ.get('TWILIO_API_KEY_SECRET')
    service_sid = conversations[0].chat_service_sid
    token = AccessToken(twilio_account_sid,
                        twilio_api_key_sid,
                        twilio_api_key_secret,
                        identity=username)
    token.add_grant(ChatGrant(service_sid=service_sid))

    # send a response
    return {
        'chatrooms': [[conversation.friendly_name, conversation.sid]
                      for conversation in conversations],
        'token':
        token.to_jwt().decode(),
    }
def get_chat_token(username):
    logger.info('Generating Chat token for {}'.format(username))

    # This call is simply to ensure the service exists, though it is not needed to generate token
    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)

    return token.to_jwt()
Esempio n. 16
0
    def make_messaging_token(self, user_id, uuid):
        try:
            identity = str(user_id)

            # Create access token with credentials
            token = AccessToken(self._account_sid,
                                self._api_key,
                                self._api_secret,
                                identity=identity)

            # Create an Chat grant and add to token
            chat_grant = ChatGrant(
                service_sid=self._chat_service_sid,
                push_credential_sid=self._push_credential_sid)
            token.add_grant(chat_grant)

            return token.to_jwt().decode('utf-8')
        except Exception as ex:
            logging.error('make_messaging_token failed, {}'.format(ex))
            raise APIInternalServicesError('make_messaging_token failed')
Esempio n. 17
0
def token(request):
    if request.method == 'POST':
        body = json.loads(request.body)
        username = body['username']
        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(account_sid,
                            api_sid,
                            api_secret,
                            identity=username)
        token.add_grant(VideoGrant(room='My Room'))
        token.add_grant(ChatGrant(service_sid=conversation.chat_service_sid))

        return JsonResponse({'token': token.to_jwt().decode('utf-8')})
Esempio n. 18
0
def token(request):
    identity = request.user.username
    device_id = request.GET.get('device', 'default')

    account_sid = 'AC9aad7718f64dfb7e31c8dabb56c1e308'
    api_key = 'SKb5e2d2a54657675a6d11c483bb5ca90a'
    api_secret = '6Mlikb507Fb6STGFrkyKUAb0BjuWaMl3'
    chat_service_sid = 'ISa9d87f39b3c14f75b2a40a805e70cd5f'

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

    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)
Esempio n. 19
0
def token(request):
    """"""
    identity = request.GET.get("identity", request.user.username)
    device_id = request.GET.get("device", "default")

    account_sid = settings.TWILIO_ACCOUNT_SID
    api_key = settings.TWILIO_API_KEY_SID
    api_secret = settings.TWILIO_API_KEY_SECRET
    chat_service_sid = settings.TWILIO_CHAT_SERVER_SID

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

    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)
Esempio n. 20
0
def token(request):
    from_user_id = request.GET.get('from_user_id', None)
    to_user_id = request.GET.get('to_user_id', None)
    device_id = request.GET.get('device', 'default')  # unique device ID
    from_user_name = User.objects.get(id=from_user_id).first_name
    to_user_name = User.objects.get(id=to_user_id).first_name

    room_id = min(from_user_id, to_user_id) + "--" + \
        max(from_user_id, to_user_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=from_user_name)

    # Create a unique endpoint ID for the device
    endpoint = "MyDjangoChatRoom:{0}:{1}".format(room_id, device_id)

    if chat_service_sid:
        chat_grant = ChatGrant(endpoint_id=endpoint,
                               service_sid=chat_service_sid)
        token.add_grant(chat_grant)

    response = {
        'from_user_name': from_user_name,
        'to_user_name': to_user_name,
        'identity': room_id,
        'token': token.to_jwt().decode('utf-8')
    }

    print("Response: ", response)

    return JsonResponse(response)
Esempio n. 21
0
def generate_video_token():

    # current_user = get_jwt_identity()

    # required for all twilio access tokens
    account_sid = os.getenv('TWILIO_ACCOUNT_SID')
    api_key = os.getenv('TWILIO_API_KEY')
    api_secret = os.getenv('TWILIO_API_SECRET')
    service_id = os.getenv('TWILIO_SERVICE_ID')

    identity = request.json.get('identity')

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

    # Return token info as JSON
    return jsonify({'token': token.to_jwt().decode()})
Esempio n. 22
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())
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())
import os
from twilio.jwt.access_token import AccessToken
from twilio.jwt.access_token.grants import ChatGrant

# required for all twilio access tokens
# To set up environmental variables, see http://twil.io/secure
account_sid = os.environ['TWILIO_ACCOUNT_SID']
api_key = os.environ['TWILIO_API_KEY']
api_secret = os.environ['TWILIO_API_KEY_SECRET']

# required for Chat grants
service_sid = 'ISxxxxxxxxxxxx'
identity = '*****@*****.**'

# 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(service_sid=service_sid)
token.add_grant(chat_grant)

# Return token info as JSON
print(token.to_jwt())
Esempio n. 25
0
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())
from twilio.jwt.access_token.grants import ChatGrant

endpoint = 'https://some.endpoint'
service_sid = 'ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'

grant = ChatGrant(endpoint_id=endpoint,
                  service_sid=service_sid,
                  push_credential_sid='CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')