Skip to content

Commit

Permalink
Neil/logging oauth (#305)
Browse files Browse the repository at this point in the history
* Removed manually setting post picture (which was set to facebook's default anyways)

* Removed unused code + added logging for oauth
  • Loading branch information
DumboOctopus authored Nov 27, 2019
1 parent a40a068 commit c358107
Show file tree
Hide file tree
Showing 5 changed files with 104 additions and 74 deletions.
79 changes: 49 additions & 30 deletions meow/meow/backend.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
from social_core.backends.slack import SlackOAuth2
import logging
import traceback
import sys


logger = logging.getLogger('oauth')


class MeowAuth(SlackOAuth2):
Expand All @@ -8,35 +14,48 @@ def get_user_details(self, response):
"""Return user details from Slack account"""
# Build the username with the team $username@$team_url
# Necessary to get unique names for all of slack
user = response['user']
team = response.get('team')
name = user['name']
email = user.get('email')
username = email and email.split('@', 1)[0] or name
fullname = user['real_name']
full_name_list = fullname.split(' ', 1)
first_name = full_name_list[0]
last_name = "" if len(full_name_list) <= 1 else full_name_list[1]

if self.setting('USERNAME_WITH_TEAM', True) and team and \
'name' in team:
username = '{0}@{1}'.format(username, response['team']['name'])

return {
'username': username,
'email': email,
'fullname': fullname,
'first_name': first_name,
'last_name': last_name
}

try:
user = response['user']
team = response.get('team')
name = user['name']
email = user.get('email')
username = email and email.split('@', 1)[0] or name
fullname = user['real_name']
full_name_list = fullname.split(' ', 1)
first_name = full_name_list[0]
last_name = "" if len(full_name_list) <= 1 else full_name_list[1]

if self.setting('USERNAME_WITH_TEAM', True) and team and \
'name' in team:
username = '{0}@{1}'.format(username, response['team']['name'])

return {
'username': username,
'email': email,
'fullname': fullname,
'first_name': first_name,
'last_name': last_name
}
except Exception as e:
logger.error(traceback.format_exc());
raise e # throw it again so the system doesn't do continue



def user_data(self, access_token, *args, **kwargs):
"""Loads user data from service"""
temp_res = kwargs.get("response")
user_id = temp_res['user_id']
response = self.get_json('https://slack.com/api/users.info',
params={'token': access_token, 'user': user_id})
print("LOOK HERE")
if not response.get('id', None):
response['id'] = user_id
return response

try:
"""Loads user data from service"""
temp_res = kwargs.get("response")
user_id = temp_res['user_id']
response = self.get_json('https://slack.com/api/users.info',
params={'token': access_token, 'user': user_id})

if not response.get('id', None):
response['id'] = user_id
return response

except Exception as e:
logger.error(traceback.format_exc());
raise e # throw it again so the system doesn't do continue
70 changes: 43 additions & 27 deletions meow/meow/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,52 +5,68 @@

from scheduler.models import Section, MeowSetting
import requests
import logging
import traceback
import sys

CHANNELS_ENDPOINT = "https://slack.com/api/users.conversations"
PROFILE_ENDPOINT = "https://slack.com/api/users.profile.get"

logger = logging.getLogger('oauth')


def set_roles_and_profile_pic(backend, user, response, details, *args, **kwargs):
if backend.name == 'meow':
access_token = response['access_token']
PARAMS = {'token': access_token,
'types': 'private_channel', 'exclude_archived': 'true'}
slack_res = requests.get(url=CHANNELS_ENDPOINT, params=PARAMS)
slack_res_json = slack_res.json()
channels_list = slack_res_json["channels"]
try:
access_token = response['access_token']
PARAMS = {'token': access_token,
'types': 'private_channel', 'exclude_archived': 'true'}
slack_res = requests.get(url=CHANNELS_ENDPOINT, params=PARAMS)
slack_res_json = slack_res.json()
channels_list = slack_res_json["channels"]

editor_channel = MeowSetting.objects.get(setting_key='editor_channel').setting_value
copy_channel = MeowSetting.objects.get(setting_key='copy_channel').setting_value
online_channel = MeowSetting.objects.get(setting_key='online_channel').setting_value
editor_channel = MeowSetting.objects.get(setting_key='editor_channel').setting_value
copy_channel = MeowSetting.objects.get(setting_key='copy_channel').setting_value
online_channel = MeowSetting.objects.get(setting_key='online_channel').setting_value

editor_group = Group.objects.get(name='Editors')
copy_group = Group.objects.get(name='Copy')
online_group = Group.objects.get(name='Online')
editor_group = Group.objects.get(name='Editors')
copy_group = Group.objects.get(name='Copy')
online_group = Group.objects.get(name='Online')

for channel in channels_list:
if channel["name"] == editor_channel:
user.groups.add(editor_group)
if channel["name"] == copy_channel:
user.groups.add(copy_group)
if channel["name"] == online_channel:
user.groups.add(online_group)
for channel in channels_list:
if channel["name"] == editor_channel:
user.groups.add(editor_group)
if channel["name"] == copy_channel:
user.groups.add(copy_group)
if channel["name"] == online_channel:
user.groups.add(online_group)

set_profile_picture(backend, user, response, details, args, kwargs)
except Exception as e:
logger.error(traceback.format_exc())
raise e # throw it again so the system doesn't do continue

set_profile_picture(backend, user, response, details, args, kwargs)
else:
print('for some reason this is not a slack thing')
return None

def set_profile_picture(backend, user, response, details, *args, **kwargs):

# if backend.name == 'meow':
access_token = response['access_token']
PARAMS = {'token': access_token}
slack_res = requests.get(url=PROFILE_ENDPOINT, params=PARAMS)
slack_res_json = slack_res.json()
print(slack_res.json())
try:
access_token = response.get('access_token', None)
if not access_token:
logger.error("No Access Token provided by response: " + str(response))
PARAMS = {'token': access_token}
slack_res = requests.get(url=PROFILE_ENDPOINT, params=PARAMS)
slack_res_json = slack_res.json()
logger.info("User signed in: " + str(slack_res.json()))


user.profile_img = slack_res_json["profile"]["image_original"]
user.save()
user.profile_img = slack_res_json["profile"].get("image_original", None)
user.save()
except Exception as e:
logger.error(traceback.format_exc())
raise e # throw it again so the system doesn't do continue
# else:
# return None
12 changes: 8 additions & 4 deletions meow/meow/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@
'formatters': {
'simple_server': {
'()': 'django.utils.log.ServerFormatter',
'format': '[%(server_time)s] %(message)s',
'format': '[%(asctime)s|%(levelname)s] %(message)s',
},

},
Expand All @@ -185,8 +185,8 @@
'logfile': {
'level':'DEBUG',
'class':'logging.handlers.RotatingFileHandler',
'filename': os.path.join(BASE_DIR, 'meow2.log'),
'maxBytes': 1024*1024*3, # 15MB
'filename': os.path.join(BASE_DIR, 'meow.log'),
'maxBytes': 1024*1024*3, # 3MB
'backupCount': 3,
'formatter': 'simple_server'
},
Expand Down Expand Up @@ -215,7 +215,11 @@
'scheduler': {
'handlers': ['console', 'console_debug_false', 'logfile'],
'level': 'INFO',
}
},
'oauth': {
'handlers': ['console', 'console_debug_false', 'logfile'],
'level': 'INFO',
},
# this logger logs 4XX and 5XX responses
# 'django.server': {
# 'handlers': ['django.server'],
Expand Down
4 changes: 0 additions & 4 deletions meow/scheduler/management/commands/sendfacebook.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,6 @@ def handle(self, *args, **options):
"path": PAGE_ID + '/feed',
"message": smpost.post_facebook,
}
if photo_url:
data['picture'] = photo_url
else:
data['picture'] = fb_default_photo

if url:
data['link'] = url
Expand Down
13 changes: 4 additions & 9 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit c358107

Please sign in to comment.