Beispiel #1
0
def get_token(code):
    """Request a token from the Slack API."""
    # Set OAuth access object
    oauth = OAuth()

    try:
        # Attempt to make request
        result = oauth.access(client_id=PROJECT_INFO['client_id'],
                              client_secret=PROJECT_INFO['client_secret'],
                              redirect_uri=PROJECT_INFO['valid_url'],
                              code=code)

    except Error as err:
        report_event('oauth_error', {'code': code, 'error': str(err)})
        abort(400)

    if not result.successful:
        report_event('oauth_unsuccessful', {
            'code': code,
            'result': result.__dict__
        })
        abort(400)

    # Setup return info
    info = {
        'token': result.body['access_token'],
        'team_id': result.body['team_id'],
        'bot_id': result.body['bot']['bot_user_id'],
        'bot_token': result.body['bot']['bot_access_token']
    }

    # Return info
    return info
Beispiel #2
0
def get_token(code, scope='user'):
    """Request a token from the Slack API."""
    # Set OAuth access object
    oauth = OAuth()

    # Setup return URL
    return_url = '{0}_url'.format(scope)

    try:
        # Attempt to make request
        result = oauth.access(client_id=PROJECT_INFO['client_id'],
                              client_secret=PROJECT_INFO['client_secret'],
                              redirect_uri=PROJECT_INFO[return_url],
                              code=code)

    except Error as err:
        report_event('oauth_error', {
            'code': code,
            'return_url': return_url,
            'error': str(err)
        })
        abort(400)

    if not result.successful:
        report_event('oauth_unsuccessful', {
            'code': code,
            'return_url': return_url,
            'result': result.__dict__
        })
        abort(400)

    # Return token
    return result.body['access_token']
Beispiel #3
0
def get_token(code, scope='user'):
    ''' Requests a token from the Slack API
    '''

    # Set OAuth access object
    oauth = OAuth()

    # Setup return URL
    return_url = '{0}_url'.format(scope)

    try:
        # Attempt to make request
        result = oauth.access(
            client_id=PROJECT_INFO['client_id'],
            client_secret=PROJECT_INFO['client_secret'],
            redirect_uri=PROJECT_INFO[return_url],
            code=code
        )

    except Error:
        abort(400)

    if not result.successful:
        abort(400)

    # Return token
    return result.body['access_token']
Beispiel #4
0
def get_token(code, scope="user"):
    """Request a token from the Slack API."""
    # Set OAuth access object
    oauth = OAuth()

    # Setup return URL
    return_url = "{0}_url".format(scope)

    try:
        # Attempt to make request
        result = oauth.access(
            client_id=PROJECT_INFO["client_id"],
            client_secret=PROJECT_INFO["client_secret"],
            redirect_uri=PROJECT_INFO[return_url],
            code=code,
        )

    except Error as err:
        report_event("oauth_error", {"code": code, "return_url": return_url, "error": str(err)})
        abort(400)

    if not result.successful:
        report_event("oauth_unsuccessful", {"code": code, "return_url": return_url, "result": result.__dict__})
        abort(400)

    # Return token
    return result.body["access_token"]
Beispiel #5
0
def get_token(code):
    """Request a token from the Slack API."""
    # Set OAuth access object
    oauth = OAuth()

    try:
        # Attempt to make request
        result = oauth.access(
            client_id=PROJECT_INFO['client_id'],
            client_secret=PROJECT_INFO['client_secret'],
            redirect_uri=PROJECT_INFO['valid_url'],
            code=code
        )

    except Error as err:
        report_event('oauth_error', {
            'code': code,
            'error': str(err)
        })
        abort(400)

    if not result.successful:
        report_event('oauth_unsuccessful', {
            'code': code,
            'result': result.__dict__
        })
        abort(400)

    # Setup return info
    info = {
        'token': result.body['access_token'],
        'team_id': result.body['team_id'],
        'bot_id': result.body['bot']['bot_user_id'],
        'bot_token': result.body['bot']['bot_access_token']
    }

    # Return info
    return info
Beispiel #6
0
def get_token(code):
    """Request a token from the Slack API."""
    oauth = OAuth()
    result = None

    try:
        # Attempt to make request
        result = oauth.access(
            client_id=project_info['client_id'],
            client_secret=project_info['client_secret'],
            redirect_uri=project_info['valid_url'],
            code=code
        )

    except Error as err:
        report_event('oauth_error', {
            'code': code,
            'error': str(err)
        })
        abort(400)

    if not result or not result.successful:
        report_event('oauth_unsuccessful', {
            'code': code,
            'result': result.__dict__
        })
        abort(400)

    # Setup return info
    info = {
        'team_id': result.body['team_id'],
        'channel_id': result.body['incoming_webhook']['channel_id'],
        'url': result.body['incoming_webhook']['url']
    }

    # Return info
    return info
Beispiel #7
0
def auth(request):
    logger.info('Authentication')

    code = request.GET.get('code')
    state = request.GET.get('state', None)
    error = request.GET.get('error', None)

    client_id = os.environ.get('SLACK_CLIENT_ID')
    client_secret = os.environ.get('SLACK_CLIENT_SECRET')

    logger.debug(request.GET)
    logger.debug(code)
    logger.debug(state)

    if error:
        # TODO Make a popup that says there was an error signing in
        return redirect('slack-info')

    try:
        data = OAuth().access(client_id, client_secret, code).body
        logger.debug(data)
    except Exception as e:
        logger.exception(e)
        return redirect('slack-info')

    if state == 'appAdded':
        access_token = data['access_token']

        slack = Slacker(access_token)
        logger.info("Slack API interfaced")

        user_id = data['user_id']
        team_id = data['team_id']

        logger.debug("Adding team \"{}\" to the database.".format(team_id))

        ch_list = slack.channels.list().body['channels']
        ch_ids = [c['id'] for c in ch_list]

        for ch in ch_ids:
            general = slack.channels.info(ch).body['channel']
            if general['is_general']:
                break

        logger.info("The general channel for team {} is #{name}({id})".format(
            team_id, **general))

        # Make a new team
        try:
            team, created = Team.objects.update_or_create(
                team_id=team_id,
                defaults={
                    'access_token': access_token,
                    'approval_channel': user_id,
                    'post_channel': general['id'],
                    'last_edit': user_id
                })
            logger.info("Team added to database!")
        except Exception as e:
            logger.exception(e)
            return redirect('slack-info')

        return redirect(signin_link)
    elif state == "resumeSignIn":
        team_data = data['team']

        # Pull this teams data and events out of the DB
        try:
            team = Team.objects.get(team_id=team_data['id'])
            logger.info("Team data loaded for " + team_data['id'])
        except Exception as e:
            logger.exception(e)
            # TODO Make slack-info post a dialog about not being able to login
            return redirect('slack-info')

        try:
            slack = Slacker(team.access_token)
            user_data = slack.users.info(data['user']['id']).body['user']
            is_admin = user_data['is_admin'] or user_data['is_owner']
        except Exception as e:
            logger.exception(e)
            return redirect('slack-info')

        if not is_admin and team.admin_only_edit:
            logger.info("Signin requires an admin and wasn't.")
            # TODO Make slack-info post a dialog about not being an admin
            return redirect('slack-info')

        try:
            form = TeamSettingsForm(instance=team)
            logger.info("Loading settings page")
        except Exception as e:
            logger.exception(e)
            return redirect('slack-info')

        # Go config display it
        return render(
            request, 'config.html', {
                'form': form,
                'user_id': user_data['id'],
                'team_name': team_data['name'],
                'team_id': team_data['id']
            })
    else:
        logger.warning('Unknown auth state passed.')
        return redirect('slack-info')