def get_slack_users(): """ Helper function to return all slack users. """ slack_token_url = envvars.get('SLACK_TOKEN_URL') response = requests.get(slack_token_url) return response.json()['members']
def notify_on_slack(message, slack_name, join_link): """ Formats and sends a message to a user on slack. Appends the join_link to the message so the recipient can join the message conversation and reply. """ message_text = '{}\n\nReply <{}|here...>'.format( message.content, join_link, ) fallback_text = '{}: {}| Reply here {}'.format( message.conversation.subject, message.content, join_link, ) attachments = [{ 'title': message.conversation.subject, 'title_link': join_link, 'color': '#00B383', 'text': message_text, 'thumb_url': settings.APP_ICON_URL, 'fallback': fallback_text, 'mrkdwn_in': ['text'], }] slack = slackweb.Slack(url=envvars.get('SLACK_API_URL')) response = slack.notify( channel=slack_name, username="******", attachments=attachments, icon_emoji=":ghost:", ) message.success = True if response == 'ok' else False message.save()
def post(self, request, *args, **kwargs): name = request.POST.get('slack_username', '') name = name.decode('base64', 'strict') message = request.POST.get('slack_message', '') user_id = request.user.id user = User.objects.get(id=user_id) reply_hash = Hasher.gen_hash(user) reply_hash_url = request.build_absolute_uri( reverse( 'reply_feedback', kwargs={'reply_hash': reply_hash}, ) ) slack_api_url = envvars.get('SLACK_API_URL') slack = slackweb.Slack(url=slack_api_url) response = slack.notify(text=message + ' reply to ' + reply_hash_url, channel='@' + name, username="******", icon_emoji=":ghost:") if response == 'ok': sent_feedback = SentFeedback( sender=user, receiver=name, message=message, ) sent_feedback.save() return HttpResponse("success", content_type="text/plain")
def post(self, request, *args, **kwargs): name = request.POST.get('slack_username', '') name = name.decode('base64', 'strict') message = request.POST.get('slack_message', '') user_id = request.user.id user = User.objects.get(id=user_id) reply_hash = Hasher.gen_hash(user) reply_hash_url = request.build_absolute_uri( reverse( 'reply_feedback', kwargs={'reply_hash': reply_hash}, )) slack_api_url = envvars.get('SLACK_API_URL') slack = slackweb.Slack(url=slack_api_url) response = slack.notify(text=message + ' reply to ' + reply_hash_url, channel='@' + name, username="******", icon_emoji=":ghost:") if response == 'ok': sent_feedback = SentFeedback( sender=user, receiver=name, message=message, ) sent_feedback.save() return HttpResponse("success", content_type="text/plain")
""" WSGI config for recruitmenttool project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/ """ import os import envvars envvars.load() os.environ.setdefault("DJANGO_SETTINGS_MODULE", envvars.get('DJANGO_SETTINGS_MODULE')) from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
from django.core.exceptions import ImproperlyConfigured BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def get_env_variable(var_name): try: return os.environ[var_name] except KeyError: error_msg = "Set the %s environment variable" % var_name raise ImproperlyConfigured(error_msg) import envvars envvars.load() SECRET_KEY = envvars.get('BARGAIN_SECRET_KEY') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions',
For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os import envvars envvars.load() BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = envvars.get('DJANGO_SECRETKEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = envvars.get('DEBUG') TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions',
https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os import envvars # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! envvars.load() SECRET_KEY = envvars.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = envvars.get('DEBUG') ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',
""" WSGI config for bargain project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os import envvars from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise from dj_static import Cling # os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bargain.settings") os.environ.setdefault("DJANGO_SETTINGS_MODULE", envvars.get("DJANGO_SETTINGS_MODULE")) application = get_wsgi_application() application = Cling(get_wsgi_application()) application = DjangoWhiteNoise(application)
https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os import envvars envvars.load() BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = envvars.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes',
For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) #SECRET_KEY = 'a$5jn-z#(5yh4ib(+5prgujiu9he=v!@#71k-7h5t#!)b#*n9y' # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! import envvars envvars.load() SECRET_KEY = envvars.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions',
def test_get_int(self): """ Test return value is of the correct type <int> """ self.assertIs(type(envvars.get('INT')), int) self.assertEqual(envvars.get('INT'), 12345)
def test_get_default_value(self): """ Test return value of default value """ self.assertEqual( envvars.get('MISSING_KEY', 'default_value'), 'default_value' )
def test_get_boolean(self): """ Test return value is of the correct type <bool> """ self.assertIs(type(envvars.get('BOOLEAN')), bool) self.assertFalse(envvars.get('BOOLEAN'))
def test_get_quoted_string(self): """ Test return value is of the correct type <string> """ self.assertIs(type(envvars.get('QUOTED_STRING')), str) self.assertEqual('True', envvars.get('QUOTED_STRING'))
def test_get_string(self): """ Test return value is of the correct type <string> """ self.assertIs(type(envvars.get('string')), str) self.assertEqual('This is a string', envvars.get('string'))
Settings for dating project. """ import os import sys import envvars as e from django.contrib.messages import constants as messages PROJECT_DIR = os.path.normpath(os.path.join(os.path.dirname(__file__), '..')) MANAGE_DIR = os.path.normpath(os.path.join(PROJECT_DIR, '..')) ROOT_DIR = os.path.normpath(os.path.join(MANAGE_DIR, '..')) e.load(os.path.join(ROOT_DIR, 'conf/env')) SECRET_KEY = e.get('DJANGO_SECRET') INSTALLED_APPS = [ # django apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', # third-party apps 'allauth', 'allauth.account',
# Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os import dj_database_url import envvars envvars.load() BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = envvars.get('SECRET_KEY') # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social.apps.django_app.default', 'tricks' ) # Authentication backends Setting AUTHENTICATION_BACKENDS = (
from .base import * # Parse database configuration from $DATABASE_URL import dj_database_url import envvars envvars.load() # Honor the 'X-Forwarded-Proto' header for request.is_secure() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Allow all host headers ALLOWED_HOSTS = ['*'] DEBUG = envvars.get('DEBUG') TEMPLATE_DEBUG = False # Static asset configuration #STATIC_ROOT = 'staticfiles' import os STATIC_ROOT = os.path.join(BASE_DIR, 'static') DATABASES = { 'default': dj_database_url.config(), } STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os import envvars # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! envvars.load() SECRET_KEY = envvars.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = envvars.get('DEBUG') ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages',
# Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ def get_env_variable(var_name): try: return os.environ[var_name] except KeyError: error_msg = "Set the %s environment variable" % var_name raise ImproperlyConfigured(error_msg) # # SECURITY WARNING: keep the secret key used in production secret! import envvars envvars.load() SECRET_KEY = envvars.get('SECRET_KEY') ALLOWED_HOSTS = ["*"] DEBUG_TOOLBAR_PATCH_SETTINGS = False # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allaccess', 'allauth',
USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_URL = '/static/' # User authentication AUTH_USER_MODEL = 'finconuser.User' AUTHENTICATION_BACKENDS = ['userplus.backends.UserPlusBackend'] # Email settings EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = envvars.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = envvars.get('EMAIL_HOST_PASSWORD') EMAIL_PORT = 465 EMAIL_USE_SSL = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
# This module defines utilities for integrating Phantom Messenger with Slack. import envvars import slackweb import requests import base64 from Crypto.Cipher import AES from django.conf import settings from django.core.urlresolvers import reverse envvars.load() secret_key = envvars.get('SECRET_KEY') def get_slack_users(): """ Helper function to return all slack users. """ slack_token_url = envvars.get('SLACK_TOKEN_URL') response = requests.get(slack_token_url) return response.json()['members'] def get_slack_name(user): """ Helper function to get user's slack name. """ members = get_slack_users() slack_name = None for member in members: if member.get('profile').get('email') == user.email:
#!/usr/bin/env python import os import sys import envvars if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", envvars.get('PUN_SETTINGS_MODULE')) from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
import os import sys import envvars as e from django.contrib.messages import constants as messages PROJECT_DIR = os.path.normpath(os.path.join(os.path.dirname(__file__), '..')) MANAGE_DIR = os.path.normpath(os.path.join(PROJECT_DIR, '..')) ROOT_DIR = os.path.normpath(os.path.join(MANAGE_DIR, '..')) e.load(os.path.join(ROOT_DIR, 'conf/env')) SECRET_KEY = e.get('DJANGO_SECRET') INSTALLED_APPS = [ # django apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', # third-party apps 'allauth', 'allauth.account',
class UserHasher: """ NOTE: This class has the Hashids package as a dependency. Run 'pip install requirements.txt' to install on your environment. Attributes: timehash_min_length: An integer representing the minimum length of the generated time hash. pkhash_min_length: An integer representing the minimum length of the primary key hash. alphabet: A string representing available characters to construct hash from. delim: A string representing the delimiter to be used to concatenate the generated time hash and primary key hash. """ timehash_min_length = 40 pkhash_min_length = 20 alphabet = 'abcdefghijklmnopqrstuvwyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' delim = "x" # from settings.py envvars.load() secret_key = envvars.get('SECRET_KEY') @staticmethod def gen_hash(registered_user): """Generates a time dependent hash. Accepts an instance of user account and returns a reversible 'time-unique' hash for it. Args: registered_user: A user instance. Returns: A hash composed of a time-stamp hash and a pk-hash delimited by x. """ # get a timestamp (to make each generated hash unique): timestamp = int(time() * 1000) # encode the timestamp with secret_key: hashids = Hashids(salt=UserHasher.secret_key, min_length=UserHasher.timehash_min_length, alphabet=UserHasher.alphabet) timestamp_hash = hashids.encode(timestamp) # encode the user's pk with timestamp: hashids = Hashids(salt=str(timestamp), min_length=UserHasher.pkhash_min_length, alphabet=UserHasher.alphabet) pk_hash = hashids.encode(registered_user.pk) # return the combination delimited by UserHasher.delim: return "%s%s%s" % (timestamp_hash, UserHasher.delim, pk_hash) @staticmethod def reverse_hash(hash_str): """Reverses a hash parsed from the request URL. Accepts a unique hash string representing a user account and decodes it to return an actual intance of that account. Args: hash_str: an hash string. Returns: None if decoded user does not exist. user instance if decoded user exists. """ # split the hash_str with the delim: hashs = hash_str.split(UserHasher.delim) # ensure the list has only 2 parts if len(hashs) != 2: return None try: # decode the timestamp_hash (i.e hashs[0] ) # with the app secret key: hashids = Hashids(salt=UserHasher.secret_key, min_length=UserHasher.timehash_min_length, alphabet=UserHasher.alphabet) timestamp = hashids.decode(hashs[0])[0] # decode the pk_hash (i.e hashs[1] ) with the timestamp: hashids = Hashids(salt=str(timestamp), min_length=UserHasher.pkhash_min_length, alphabet=UserHasher.alphabet) account_pk = hashids.decode(hashs[1])[0] # return the account for that pk if it exists: registered_user = User.objects.get(pk=account_pk) return registered_user except: # return None if it doesn't: return None
USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_URL = '/static/' # User authentication AUTH_USER_MODEL = 'finconuser.User' AUTHENTICATION_BACKENDS = ['userplus.backends.UserPlusBackend'] # Email settings EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = envvars.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = envvars.get('EMAIL_HOST_PASSWORD') EMAIL_PORT = 465 EMAIL_USE_SSL = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
PageNotAnInteger, ) from feedback.views import LoginRequiredMixin from forms import StartConversationForm, PostMessageForm from models import Conversation, Message from slack import ( get_slack_name, get_slack_join_link, get_slack_join_conversation, notify_on_slack, ) envvars.load() secret_key = envvars.get('SECRET_KEY') class ConversationListView(View, LoginRequiredMixin): """ Shows a list of conversations in which the user is a member. """ def get(self, request, *args, **kwargs): """ Handles GET requests to 'conversations route. The following optional GET params can be set to customize the returned content: :q: Keyword to filters/search. Returns only conversations where the subject or the content any of it's messages
""" Settings package initialization. """ import envvars envvars.load() # Ensure development settings are not used in testing and production: if not envvars.get('HEROKU'): from development import * if envvars.get('HEROKU') is not None: from production import * if envvars.get('TRAVIS') is not None: from base import *