示例#1
0
 def testCrowdObjectSSLVerifyFalse(self):
     """Check can create Crowd object with ssl_verify=False"""
     c = crowd.CrowdServer("http://bogus",
                           APP_USER,
                           APP_PASS,
                           ssl_verify=False)
     self.assertIsInstance(c, crowd.CrowdServer)
示例#2
0
 def _client(self):
    return crowd.CrowdServer(
       settings.CROWD_API_URL,
       settings.CROWD_APP_NAME,
       settings.CROWD_APP_PASSWORD,
       ssl_verify=True
    )
示例#3
0
 def _get_client(self):
     crowd_configs = self.config['crowd']
     app_url = crowd_configs['app_url']
     app_user = crowd_configs['app_user']
     app_pass = crowd_configs['app_pass']
     # Create the reusable Crowd object.
     client = crowd.CrowdServer(app_url, app_user, app_pass)
     return client
示例#4
0
    def __init__(self, config):
        super(CrowdAuthenticator, self).__init__(config)

        app_url = config['CROWD_URL']
        app_user = config['CROWD_APP_NAME']
        app_pass = config['CROWD_APP_PASSWORD']

        self._cs = crowd.CrowdServer(app_url, app_user, app_pass)
示例#5
0
 def __init__(self):
     try:
         self._client = crowd.CrowdServer(
             settings.AUTH_CROWD_SERVER_REST_URI,
             settings.AUTH_CROWD_APPLICATION_USER,
             settings.AUTH_CROWD_APPLICATION_PASSWORD)
         self.connect()
     except:
         crowd_logger.exception("Initialize Crowd client failed")
示例#6
0
 def auth(self):
     try:
         crowd_conn = crowd.CrowdServer(self.crowd_url, self.crowd_app,
                                        self.crowd_psw)
         crowd_auth_result = crowd_conn.auth_user(self.username,
                                                  self.password)
     except Exception as e:
         current_app.logger.exception('crowd connection error: '.format(e))
         return None
     else:
         return crowd_auth_result
def check_for_existing_user(cs, username):
    ''' The Crowd API's user_exists function sometimes returns None despite the user existing, so check multiple times to ensure user does/does not exist. '''
    retry_limit = 7
    try_attempts = 0
    user_exists = cs.user_exists(username)
    while (user_exists is
           None) & (try_attempts <
                    retry_limit):  # Returns None if user does not yet exist
        cs = crowd.CrowdServer(app_url, app_user, app_pass)
        user_exists = cs.user_exists(username)
        try_attempts += 1
    return True if user_exists else False
示例#8
0
    def setUpClass(cls):
        cls.base_url = 'http://localhost:%d' % PORT
        cls.crowd = crowd.CrowdServer(cls.base_url, APP_USER, APP_PASS)

        cls.server_thread = threading.Thread(target=crowdserverstub.run_server,
                                             args=(PORT, ))
        cls.server_thread.start()

        crowdserverstub.add_app(APP_USER, APP_PASS)
        crowdserverstub.add_user(USER, PASS)

        # There is a race to start the HTTP server before
        # the unit tests begin hitting it. Sleep briefly
        time.sleep(0.2)
def search_user_email(cs, email):
    ''' Same as the user_exists function, we check for a user's info multiple times to ensure user does/doesn't exist '''
    found_email = 'Not found'
    retry_limit = 5
    try_attempts = 0
    while (found_email == 'Not found') & (try_attempts < retry_limit):
        try:
            cs = crowd.CrowdServer(app_url, app_user, app_pass)
            found_email = cs.search('user', 'email', email)['users'][0]
            try_attempts += 1
        except (IndexError, TypeError):
            try_attempts += 1
            continue
    return found_email
示例#10
0
def auth_crowd(username, pwd):
    print(username, pwd)
    cwd = crowd.CrowdServer(current_app.config['CROWD_URL'],
                            current_app.config['CROWD_APP'],
                            current_app.config['CROWD_APPPWD'])
    try:
        user_dict = cwd.auth_user(username, pwd)
        print(user_dict)
        if user_dict is not None:
            return True
        else:
            return False
    except Exception as e:
        print(str(e), 'ffff')
        return False
示例#11
0
def get_user(username):
    cwd = crowd.CrowdServer(current_app.config['CROWD_URL'],
                            current_app.config['CROWD_APP'],
                            current_app.config['CROWD_APPPWD'])
    try:
        user_dict = cwd.get_user(username)
        if user_dict is not None:
            group = cwd.get_groups(username)
            return {
                'username': user_dict.get('name'),
                'displayname': user_dict.get('display-name'),
                'email': user_dict.get('email'),
                'groups': str(group)
            }

        else:
            return None
    except Exception as e:
        return None
SUCCESS = "--status=success"
FAILED = "--status=fail"

#################################################################

with open(os.path.join(SCRIPTPATH, 'crowd.json')) as data_file:
    data = json.load(data_file)

app_url = data['server_url']
app_user = data['app_user']
app_pass = data['app_pass']
allowed_groups = data["allowed_groups"]
allowed_group_prefix = data["allowed_group_prefix"]

# Create the reusable Crowd object
cs = crowd.CrowdServer(app_url, app_user, app_pass)
if not cs.auth_ping():
    raise Exception("Unable to connect to Crowd, please check the credentials.")


def userLogin(args):
    success = cs.auth_user(args[USERNAME], args['password'])
    if success:
        print(SUCCESS)
    else:
        print(FAILED)


def getUserGroups(username):
    groups = cs.get_nested_groups(username)
    if groups:
示例#13
0
 def testAuthAppInvalid(self):
     """Application may not authenticate with invalid credentials"""
     c = crowd.CrowdServer(self.base_url, 'invalidapp', 'xxxxx')
     result = c.auth_ping()
     self.assertFalse(result)
示例#14
0
"""
Authentication microservice for Atlassian Crowd

@author Jerry Chong
"""

import crowd
import argparse
from flask import Flask, redirect, render_template, request, session, url_for
from werkzeug.exceptions import Unauthorized

CROWD_URL = "your crowd URL"
CROWD_USER = "******"
CROWD_PASS = "******"
CROWD_SERVER = crowd.CrowdServer(CROWD_URL, CROWD_USER, CROWD_PASS)
app = Flask(__name__)
app.config.update(SECRET_KEY="your crowd secret",
                  SESSION_COOKIE_DOMAIN="your root domain")


@app.route("/auth")
def authenticate():
    # verify if crowd token is valid, otherwise redirect
    token = session.get("token")
    user = session.get("crowd_user")
    if token and CROWD_SERVER.validate_session(token):
        if user:
            return ('', {"X-CROWD-USER": user})
        else:
            return ''  # = 200 OK
    else:
示例#15
0
 def _authenticate_splunk_app(self):
     app_url = 'crowd-url-here'
     app_user = '******'
     app_pass = '******'
     self.cs = crowd.CrowdServer(app_url, app_user, app_pass)
def complete_request():
    count = 0
    try:
        # Create the jira object and find issues currently assigned (MODIFY W/ YOUR OWN CREDNTIALS)
        jira = JIRA(basic_auth=('chadlei', 'password1234567'),
                    options={'server': 'https://issues.ngptools.com/jira/'})
        access_requests = find_issues(jira)['Access Request']
        # access_requests = [1]

        for request in access_requests:  # CHANGE: loop thru issue numbers in access_requests
            # Retrieve ticket information from Jira
            # ticket_number = 'COLLAB-' + '20560'
            ticket_number = request
            issue = jira.issue(ticket_number)
            first_name = issue.fields.customfield_13915
            last_name = issue.fields.customfield_13916
            display_name = first_name + ' ' + last_name
            email = str(issue.fields.customfield_13917).split(
                ' '
            )[0]  # We split it here just in case the ticket doesn't include the full email address
            request_type = str(issue.fields.customfield_15611)

            # Ensure ticket has not been completed already
            if str(issue.fields.status) in ('Done', 'Closed'):
                print 'Issue has been resolved already - continuing on ....\n'
                continue

            # User information/attributes to add
            password = '******'
            username = (first_name + last_name).encode('utf-8').replace(
                " ", "")
            lastAuthenticated = int(round(time.time()))

            # Create the Crowd object
            cs = crowd.CrowdServer(app_url, app_user, app_pass)

            # Switch case depending on request_type
            request_types = {
                'New User': activate_user,
                'Deactivate User': deactivate_user,
                'Reactivate User': reactivate_user,
                'Update Existing User': update_user
            }

            # Calls appropriate function based off of request_type
            print 'Current ticket: ' + ticket_number
            print 'Request type: ' + request_type
            success = request_types[request_type](jira, issue, cs, username,
                                                  first_name, last_name,
                                                  display_name, password,
                                                  email, ticket_number,
                                                  lastAuthenticated)

            # The Crowd API's user_exists function sometimes returns None/False despite the user existing, so check multiple times to ensure user does/does not exist.
            # SIDE NOTE: this could be turned into a helper function
            retry_limit = 5
            try_attempts = 0
            while (success == 0) & (try_attempts < retry_limit) & (
                    request_type != 'Update Existing User'
            ):  # Returns None if user does not yet exist
                print "[Reattempt #" + str(try_attempts +
                                           1) + " to [" + request_type + "]]"
                cs = crowd.CrowdServer(app_url, app_user, app_pass)
                success = request_types[request_type](jira, issue, cs,
                                                      username, first_name,
                                                      last_name, display_name,
                                                      password, email,
                                                      ticket_number,
                                                      lastAuthenticated)
                try_attempts += 1
                time.sleep(1)
            if success == 0:
                print "Failed to complete ticket - moving onto the next"
                panic_email(username, ticket_number, request_type)
            else:
                completion_email(username, ticket_number, request_type)

            # Adds to the count of completed tickets
            count += success
            print ''
        return count
    except KeyError as e:  # KeyError would mean that there aren't currently any access request tickets in queue
        print emoji.emojize(
            ":winking_face_with_tongue:"
        ) + ' WOOHOO currently no access request tickets in queue WOOHOO ' + emoji.emojize(
            ":winking_face_with_tongue:") + '\n'
        return count