Skip to content

Commit

Permalink
Swittch twitter and github plugins to use new get_config method
Browse files Browse the repository at this point in the history
  • Loading branch information
shaunagm committed Dec 17, 2021
1 parent 3d3744a commit d803725
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 22 deletions.
8 changes: 6 additions & 2 deletions metagov/metagov/plugins/github/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def refresh_token(self):
"""Requests a new installation access token from Github using a JWT signed by private key."""
installation_id = self.config["installation_id"]
self.state.set("installation_id", installation_id)
token = get_access_token(installation_id)
token = get_access_token(installation_id, community=self.community)
self.state.set("installation_access_token", token)

def initialize(self):
Expand Down Expand Up @@ -55,7 +55,11 @@ def github_request(self, method, route, data=None, add_headers=None, refresh=Fal
"""Makes request to Github. If status code returned is 401 (bad credentials), refreshes the
access token and tries again. Refresh parameter is used to make sure we only try once."""

authorization = f"Bearer {get_jwt()}" if use_jwt else f"token {self.state.get('installation_access_token')}"
if use_jwt:
authorization = f"Bearer {get_jwt(community=self.community)}"
else:
authorization = f"token {self.state.get('installation_access_token')}"

headers = {
"Authorization": authorization,
"Accept": "application/vnd.github.v3+json"
Expand Down
20 changes: 11 additions & 9 deletions metagov/metagov/plugins/github/utils.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
""" Authentication """

import jwt, datetime, logging, requests
from django.conf import settings

from metagov.core.errors import PluginErrorInternal
from metagov.core.utils import get_configuration

import sys

TEST = 'test' in sys.argv

logger = logging.getLogger(__name__)

github_settings = settings.METAGOV_SETTINGS["GITHUB"]
PRIVATE_KEY_PATH = github_settings["PRIVATE_KEY_PATH"]
APP_ID = github_settings["APP_ID"]


def get_private_key():


def get_private_key(community):
PRIVATE_KEY_PATH = get_configuration("GITHUB_PRIVATE_KEY_PATH", community=community)
with open(PRIVATE_KEY_PATH) as f:
lines = f.readlines()
if len(lines) == 1:
Expand All @@ -24,25 +26,25 @@ def get_private_key():
return "".join(lines)


def get_jwt():
def get_jwt(community):
if TEST: return ""

payload = {
# GitHub App's identifier
"iss": APP_ID,
"iss": get_configuration("GITHUB_PRIVATE_KEY_PATH", community=community),
# issued at time, 60 seconds in the past to allow for clock drift
"iat": int(datetime.datetime.now().timestamp()) - 60,
# JWT expiration time (10 minute maximum)
"exp": int(datetime.datetime.now().timestamp()) + (9 * 60)
}
return jwt.encode(payload, get_private_key(), algorithm="RS256")
return jwt.encode(payload, get_private_key(community), algorithm="RS256")


def get_access_token(installation_id):
def get_access_token(installation_id, community=community):
"""Get installation access token using installation id"""
headers = {
"Accept": "application/vnd.github.v3+json",
"Authorization": f"Bearer {get_jwt()}"
"Authorization": f"Bearer {get_jwt(community)}"
}
url = f"https://api.github.com/app/installations/{installation_id}/access_tokens"
resp = requests.request("POST", url, headers=headers)
Expand Down
22 changes: 11 additions & 11 deletions metagov/metagov/plugins/twitter/models.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,14 @@
import logging

from django.conf import settings
from metagov.core.plugin_manager import AuthorizationType, Registry, Parameters, VotingStandard
import tweepy
from metagov.core.models import AuthType, Plugin
from metagov.core.errors import PluginErrorInternal
from metagov.core.utils import get_configuration

logger = logging.getLogger(__name__)


twitter_settings = settings.METAGOV_SETTINGS["TWITTER"]

class TwitterSecrets:
api_key = twitter_settings["API_KEY"]
api_secret_key = twitter_settings["API_SECRET_KEY"]
access_token = twitter_settings["ACCESS_TOKEN"]
access_token_secret = twitter_settings["ACCESS_TOKEN_SECRET"]


"""
Expand All @@ -41,9 +34,16 @@ class Meta:
def tweepy_api(self):
if getattr(self, "api", None):
return self.api
auth = tweepy.OAuthHandler(TwitterSecrets.api_key, TwitterSecrets.api_secret_key)
auth.set_access_token(TwitterSecrets.access_token, TwitterSecrets.access_token_secret)

api_key = get_configuration("TWITTER_API_KEY", community=self.community)
api_secret_key = get_configuration("TWITTER_API_SECRET_KEY", community=self.community)
access_token = get_configuration("TWITTER_ACCESS_TOKEN", community=self.community)
access_token_secret = get_configuration("TWITTER_ACCESS_TOKEN_SECRET", community=self.community)

auth = tweepy.OAuthHandler(api_key, api_secret_key)
auth.set_access_token(access_token, access_token_secret)
self.api = tweepy.API(auth)

return self.api

def initialize(self):
Expand Down Expand Up @@ -88,7 +88,7 @@ def send_direct_message(self, user_id, text):
slug="get-user-id",
description="Gets user id of a Twitter user",
input_schema={
"type": "object",
"type": "object",
"properties": {"screen_name": {"type": "string"}},
"required": ["screen_name"]
}
Expand Down

0 comments on commit d803725

Please sign in to comment.