def token(request): identity = request.GET.get('identity', request.user.username) 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) print(endpoint) if chat_service_sid: chat_grant = ChatGrant(endpoint_id=endpoint, service_sid=chat_service_sid) grant = VideoGrant(room=None) token.add_grant(chat_grant) token.add_grant(grant) response = {'identity': identity, 'token': token.to_jwt().decode('utf-8')} return JsonResponse(response)
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 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
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 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 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 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 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 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 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 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(): 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 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 __init__(self, user, room): # Create access token with credentials self.token = AccessToken(account_sid, api_key, api_secret, identity=user) # Create a Video grant and add to token video_grant = VideoGrant(room=room) self.token.add_grant(video_grant)
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 = request.values.get('identity') or 'identity' # Grant access to Video grant = VideoGrant() grant.room = request.values.get('room') token.add_grant(grant) # Return token return token.to_jwt()
def token(): # Get credentials for environment variables account_sid = 'ACbce0865b277c75152da6fc469b650463' api_key = 'SK2e4b45c9cb8835c6ad1a614c3346b209' api_secret = 'l6GKan4KkOKCmiktZDTmhahRY7q2aTPz' # Create an Access Token token = AccessToken(account_sid, api_key, api_secret) # Set the Identity of this token token.identity = request.values.get('identity') or 'identity' # Grant access to Video grant = VideoGrant() grant.room = request.values.get('room') token.add_grant(grant) # Return token return token.to_jwt()
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 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 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())
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 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()}
def token(): # Get credentials for environment variables account_sid = "ACa9489e89bea2fd6a143b64def1cf01f7" api_key = "SKe3a14561d59837544e4079f95e9b6616" api_secret = "4mxMGKNUjD80RhIZ1xGxtaP6ABCnIlUD" # Create an Access Token token = AccessToken(account_sid, api_key, api_secret) # Set the Identity of this token token.identity = request.values.get('identity') or 'identity' # Grant access to Video grant = VideoGrant() grant.room = request.values.get('room') token.add_grant(grant) # Return token return token.to_jwt()
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()}
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'])
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)
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'])
def token(room_name): # get credentials for environment variables account_sid = os.getenv("TWILIO_ACCOUNT_SID") api_key = os.getenv("TWILIO_API_KEY") api_secret = os.getenv("TWILIO_API_SECRET") # Create an Access Token token = AccessToken(account_sid, api_key, api_secret) # Set the Identity of this token print(_request_ctx_stack.top.current_user['sub']) token.identity = _request_ctx_stack.top.current_user['sub'] # Grant access to Video grant = VideoGrant() grant.room = room_name token.add_grant(grant) # Return token info as JSON return jsonify(identity=token.identity, token=token.to_jwt().decode('UTF-8'))
def login(request): json_body = json.loads(request.body) username = json_body["username"] if not username: return HttpResponse('Unauthorized', status=401) token = AccessToken(twilio_account_sid, twilio_api_key_sid, twilio_api_key_secret, identity=username) token.add_grant(VideoGrant(room='My Room')) return JsonResponse({'token': token.to_jwt().decode()})
def start_call(request): user_name = json.loads(request.body.decode("utf-8")).get('user_name') room_name = json.loads(request.body.decode("utf-8")).get('room_name') token = AccessToken(twilio_account_sid, twilio_api_key_sid, twilio_api_key_secret, identity=user_name) token.add_grant(VideoGrant(room=room_name)) # token.add_grant(VideoGrant(room=username_caller + '_' + username_callee)) return JsonResponse({'token': token.to_jwt().decode()})
def login(): username = request.get_json(force=True).get('identity') if not username: abort(401) roomname = request.get_json(force=True).get('room') if not roomname: abort(401) token = AccessToken(twilio_account_sid, twilio_api_key_sid, twilio_api_key_secret, identity=username) video_grant = VideoGrant(room=roomname) token.add_grant(video_grant) return {'token': token.to_jwt().decode()}
def get_token(identity, room): # 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 time_stamp = time.time() token.identity = identity + str(time_stamp) # Grant access to Video grant = VideoGrant() grant.room = room token.add_grant(grant) # Return token return token.to_jwt().decode('utf-8')