예제 #1
0
def get(handler, parameters, url_parameters, ids_parameters):
    """GET method"""
    query = handler.session.query(Tournament)
    guild_id = None
    for key, values in url_parameters.items():
        if key in vars(Tournament):
            for value in values:
                if key == "server_id":
                    guild_id = value
                query.where(getattr(Tournament, key) == hash_str(value))
    results = query.all()
    token = handler.session.query(Token).where(
        Token.session_token == hash_str(handler.session_token)).first()
    if not token:
        handler.logger.debug("Unauthorized")
        handler.send_error(401, "Unauthorized.")
        return
    headers = {'Authorization': 'Bot ' + constants.TOKEN}
    try:
        r = requests.get(API_ENDPOINT + '/guilds/' + guild_id + '/members/' +
                         token.discord_user_id,
                         headers=headers)
        r.raise_for_status()
    except requests.exceptions.HTTPError:
        handler.logger.exception("Couldn't get the data from Discord API.")
        handler.logger.debug(r.text)
        handler.send_error(500, "Couldn't get the data from Discord API.")
        return
    member = json.loads(r.text)
    try:
        r = requests.get(API_ENDPOINT + '/guilds/' + guild_id, headers=headers)
        r.raise_for_status()
    except requests.exceptions.HTTPError:
        handler.logger.exception("Couldn't get the data from Discord API.")
        handler.logger.debug(r.text)
        handler.send_error(500, "Couldn't get the data from Discord API.")
        return
    guild = json.loads(r.text)
    tournaments = []
    for tournament in results:
        if token.discord_user_id == guild[
                "owner_id"] or tournament.admin_role_id in member["roles"]:
            brackets = handler.session.query(Bracket).where(
                Bracket.tournament_id == tournament.id).all()
            tournament.brackets = brackets
            tournaments.append(tournament)
    if not tournaments:
        handler.logger.debug("Unauthorized")
        handler.send_error(401, "Unauthorized.")
        return
    etag = handler.get_etag(tournaments)
    if not etag:
        handler.send_error(304)
        return
    handler.send_object(tournaments, etag)
예제 #2
0
def post(handler, parameters, url_parameters, ids_parameters):
    """POST method"""
    token = handler.session.query(Token).where(
        Token.session_token == hash_str(handler.session_token)).first()
    if not token:
        handler.logger.debug("Invalid token")
        handler.send_json(401, "This token doesn't exist.")
        return
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    data = {
        'client_id': constants.CLIENT_ID,
        'client_secret': constants.CLIENT_SECRET,
        'token': token.access_token
    }
    try:
        r = requests.post(OAUTH2_ENDPOINT + '/token/revoke',
                          headers=headers,
                          data=data)
        r.raise_for_status()
    except requests.exceptions.HTTPError:
        handler.logger.exception("Couldn't post the data to Discord API.")
        handler.logger.debug(r.text)
        handler.send_error(500, "Couldn't post the data to Discord API.")
        return
    handler.session.delete(token)
    handler.send_json("{}")
예제 #3
0
def get(handler, parameters, url_parameters, ids_parameters):
	"""GET method"""
	token = handler.session.query(Token).where(Token.session_token == hash_str(handler.session_token)).first()
	if not token:
		handler.logger.debug("Unauthorized")
		handler.send_error(401, "Unauthorized.")
		return
	headers = {
		'Authorization': 'Bearer ' + token.access_token
	}
	try:
		r = requests.get(API_ENDPOINT + '/users/@me/guilds', headers=headers)
		r.raise_for_status()
	except requests.exceptions.HTTPError:
		handler.logger.exception("Couldn't get the data from Discord API.")
		handler.logger.debug(r.text)
		handler.send_error(500, "Couldn't get the data from Discord API.")
		return
	user_guilds = json.loads(r.text)
	bot_guilds = []
	headers = {
		'Authorization': 'Bot ' + constants.TOKEN
	}
	last_id = None
	while True:
		try:
			if last_id:
				r = requests.get(API_ENDPOINT + '/users/@me/guilds?after=' + last_id, headers=headers)
			else:
				r = requests.get(API_ENDPOINT + '/users/@me/guilds', headers=headers)
			r.raise_for_status()
		except requests.exceptions.HTTPError:
			handler.logger.exception("Couldn't get the data from Discord API.")
			handler.logger.debug(r.text)
			handler.send_error(500, "Couldn't get the data from Discord API.")
			return
		tmp_guilds = json.loads(r.text)
		if not tmp_guilds:
			break
		last_id = tmp_guilds[-1]["id"]
		bot_guilds += tmp_guilds
		if len(tmp_guilds) < 100:
			break
	common_guilds = [e for e in user_guilds for e2 in bot_guilds if e['id'] == e2['id']]
	etag = handler.get_etag(common_guilds)
	if not etag:
		handler.send_error(304)
		return
	handler.send_object(common_guilds, etag)
예제 #4
0
def do_endpoint(method, handler, endpoint, parameters):
    """Parse url parameters and ready up the search of the endpoint"""
    token = handler.session.query(Token).where(Token.session_token == hash_str(handler.session_token)).first()
    if token:
        if int(token.expiry_date) < int(time.time()):
            handler.session.delete(token)
            logging.info("Token expired")
            handler.send_error(403, "Not connected")
            return
        elif token.access_token:
            handler.refresh_token(token)
    elif endpoint != "/api/v1/discord/tokens":
        logging.info("No token")
        handler.send_error(403, "Not connected")
        return
    parsed_url = parse.urlparse(endpoint.strip("/"))
    if not find_endpoint(method, handler, parameters, parse.parse_qs(parsed_url.query), [], "routes", parsed_url.path):
        handler.send_error(404, "The resource at the location specified doesn't exist")
        print("404 error")
예제 #5
0
def store_token(handler, data):
    token = None
    session_token = handler.session_token
    if session_token:
        token = handler.session.query(Token).where(
            Token.session_token == hash_str(session_token)).first()
    if not token:
        token = Token()
        token.discord_user_id = get_user_id(handler, data)
        if not token.discord_user_id:
            return None
        session_token = str(uuid.uuid4())
        token.session_token = session_token
        token.expiry_date = str(int(time.time()) + 2592000)
        handler.session.add(token)
    token.access_token = data["access_token"]
    token.token_type = data["token_type"]
    token.access_token_expiry_date = str(int(time.time()) + data["expires_in"])
    token.refresh_token = data["refresh_token"]
    token.scope = data["scope"]
    handler.session.update(token)
    return session_token
예제 #6
0
def get(handler, parameters, url_parameters, ids_parameters):
    """GET method"""
    token = handler.session.query(Token).where(Token.session_token == hash_str(handler.session_token)).first()
    if not token:
        handler.logger.debug("Unauthorized")
        handler.send_error(401, "Unauthorized.")
        return
    headers = {
        'Authorization': 'Bearer ' + token.access_token
    }
    try:
        r = requests.get(API_ENDPOINT + '/users/@me', headers=headers)
        r.raise_for_status()
    except requests.exceptions.HTTPError:
        handler.logger.exception("Couldn't get the data from Discord API.")
        handler.logger.debug(r.text)
        handler.send_error(500, "Couldn't get the data from Discord API.")
        return
    etag = handler.get_etag(r.text)
    if not etag:
        handler.send_error(304)
        return
    handler.send_json(r.text, etag)