Exemple #1
0
def view_user(request):

    user = get_user(request)
    page_title = 'User Data'
    subtitle = user['first_last']
    change_pw = False

    if user['auth_mode'] != 'ldap':

        if 'form.submitted' in request.POST:
            user_name = request.POST['user_name']
            first_name = request.POST['first_name']
            last_name = request.POST['last_name']
            email_address = request.POST['email_address']
            password = request.POST['password']

            # FIXME: Need some security checking here
            if user_name != user['login']:
                log.error('Bad person attemting to do bad things to:' %
                          user_name)
            else:

                # Update
                log.info(
                    'UPDATE: user_name=%s,first_name=%s,last_name=%s,email_address=%s,password=%s'
                    % (user_name, first_name, last_name, email_address,
                       '<redacted>'))
                try:
                    user = DBSession.query(User).filter(
                        User.user_name == user_name).one()
                    user.first_name = first_name
                    user.last_name = last_name
                    user.email_address = email_address
                    if password:
                        log.info(
                            'Changing password for: user_name=%s password=<redacted>'
                            % user_name)
                        salt = sha512_crypt.genconfig()[17:33]
                        encrypted_password = sha512_crypt.encrypt(password,
                                                                  salt=salt)
                        user.salt = salt
                        user.password = encrypted_password
                        DBSession.flush()
                        return_url = '/logout?message=Your password has been changed successfully. Please log in again.'
                        return HTTPFound(return_url)

                    DBSession.flush()

                except Exception, e:
                    pass
                    log.error("%s (%s)" % (Exception, e))

        user = get_user(request)
Exemple #2
0
def view_deploys(request):

    page_title = 'Deploys'
    user = get_user(request)

    perpage = 50
    offset = 0
    end = 10
    total = 0
    app = None

    try:
        offset = int(request.GET.getone("start"))
        end = perpage + offset
    except:
        pass

    params = {
        'application_id': None,
        'history': None,
        'deploy_id': None,
        'env': None,
        'to_env': None,
        'to_state': None,
        'commit': None,
        'artifact_id': None,
    }
    for p in params:
        try:
            params[p] = request.params[p]
        except:
            pass

    application_id = params['application_id']
    deploy_id = params['deploy_id']
    env = params['env']
    to_env = params['to_env']
    to_state = params['to_state']
    commit = params['commit']
    artifact_id = params['artifact_id']

    if application_id:
        try:
            q = DBSession.query(Application)
            q = q.filter(Application.application_id == application_id)
            app = q.one()
        except NoResultFound, e:
            error_msg = "No such application id: {0} Exception: {1}".format(
                application_id, e)
            log.error(error_msg)
            raise Exception(
                "No such application id: {0}".format(application_id))
        except Exception, e:
            error_msg = "Error: {0}".format(e)
            log.error(error_msg)
            raise Exception(error_msg)
Exemple #3
0
def view_cp(request):

    page_title = 'Control Panel'
    user = get_user(request)

    return {
        'layout': site_layout(),
        'page_title': page_title,
        'user': user,
    }
Exemple #4
0
def view_test(request):

    page_title = 'Test'
    user = get_user(request)

    return {
        'layout': site_layout(),
        'page_title': page_title,
        'user': user,
    }
Exemple #5
0
def view_help(request):

    page_title = 'Help'
    user = get_user(request)

    return {
        'layout': site_layout(),
        'page_title': page_title,
        'user': user,
        'host_url': request.host_url,
    }
Exemple #6
0
def error(exc, request):

    request.response.status_int = 500
    page_title = 'Internal Server Error'
    user = get_user(request)

    return {
        'layout': site_layout(),
        'page_title': page_title,
        'user': user,
        'error': exc.message
    }
Exemple #7
0
def view_promote(request):

    page_title = 'Promote'
    user = get_user(request)
    office_loc = request.registry.settings['tcw.office_loc']

    error = ''
    message = ''
    promote = ''
    valid_time = None

    params = {
        'deploy_id': None,
        'artifact_id': None,
        'to_env': None,
        'commit': 'false'
    }
    for p in params:
        try:
            params[p] = request.params[p]
        except:
            pass

    deploy_id = params['deploy_id']
    artifact_id = params['artifact_id']
    to_env = params['to_env']
    commit = params['commit']
    referer = request.referer

    if not any((user['promote_prd_auth'],
                user['promote_prd_time_auth'])) and to_env == 'prd':
        to_state = '3'
    else:
        to_state = '2'

    try:
        promote = Artifact.get_promotion(office_loc, to_env, deploy_id,
                                         artifact_id)
    except Exception, e:
        conn_err_msg = e
        return Response(str(conn_err_msg),
                        content_type='text/plain',
                        status_int=500)
Exemple #8
0
def view_applications(request):
    page_title = 'Applications'
    user = get_user(request)

    perpage = 50
    offset = 0

    try:
        offset = int(request.GET.getone("start"))
    except:
        pass

    try:
        q = DBSession.query(Application)
        total = q.count()
        applications = q.limit(perpage).offset(offset)
    except Exception, e:
        conn_err_msg = e
        return Response(str(conn_err_msg),
                        content_type='text/plain',
                        status_int=500)
Exemple #9
0
def view_cp_user(request):

    page_title = 'Control Panel - Users'
    user = get_user(request)
    users = DBSession.query(User).all()
    groups = DBSession.query(Group).all()

    params = {
        'mode': None,
        'commit': None,
        'user_id': None,
    }
    for p in params:
        try:
            params[p] = request.params[p]
        except:
            pass

    mode = params['mode']
    commit = params['commit']
    user_id = params['user_id']
    error_msg = None
    this_user = None
    this_groups = None
    subtitle = 'Users'

    if mode == 'add':

        subtitle = 'Add a new user'

        if commit:

            user_names = request.POST.getall('user_name')
            first_names = request.POST.getall('first_name')
            last_names = request.POST.getall('last_name')
            email_addresses = request.POST.getall('email_address')
            passwords = request.POST.getall('password')

            try:
                utcnow = datetime.utcnow()
                for u in range(len(user_names)):
                    salt = sha512_crypt.genconfig()[17:33]
                    encrypted_password = sha512_crypt.encrypt(passwords[u],
                                                              salt=salt)
                    create = User(user_name=user_names[u],
                                  first_name=first_names[u],
                                  last_name=last_names[u],
                                  email_address=email_addresses[u],
                                  salt=salt,
                                  password=encrypted_password,
                                  updated_by=user['login'],
                                  created=utcnow,
                                  updated=utcnow)
                    DBSession.add(create)
                    DBSession.flush()
                    user_id = create.user_id

                    group_assignments = request.POST.getall(
                        'group_assignments')

                    for a in group_assignments:
                        g = DBSession.query(Group).filter(
                            Group.group_name == a).one()
                        create = UserGroupAssignment(group_id=g.group_id,
                                                     user_id=user_id,
                                                     updated_by=user['login'],
                                                     created=utcnow,
                                                     updated=utcnow)
                        DBSession.add(create)

                        DBSession.flush()

                return_url = '/cp/user'
                return HTTPFound(return_url)

            except Exception as ex:
                if type(ex).__name__ == 'IntegrityError':
                    log.error(
                        'User already exists in the db, please edit instead.')
                    # Rollback
                    DBSession.rollback()
                    # FIXME: Return a nice page
                    return HTTPConflict(
                        'User already exists in the db, please edit instead.')
                else:
                    raise
                    # FIXME not trapping correctly
                    DBSession.rollback()
                    error_msg = ("Failed to create user (%s)" % (ex))
                    log.error(error_msg)

    if mode == 'edit':

        subtitle = 'Edit user'

        if not commit:
            try:
                q = DBSession.query(User)
                q = q.filter(User.user_id == user_id)
                this_user = q.one()

                q = DBSession.query(Group)
                q = q.join(UserGroupAssignment,
                           Group.group_id == UserGroupAssignment.group_id)
                q = q.filter(UserGroupAssignment.user_id == this_user.user_id)
                results = q.all()
                this_groups = []
                for r in results:
                    this_groups.append(r.group_name)
            except Exception, e:
                conn_err_msg = e
                return Response(str(conn_err_msg),
                                content_type='text/plain',
                                status_int=500)

        if commit:

            if 'form.submitted' in request.POST:
                user_id = request.POST.get('user_id')
                user_name = request.POST.get('user_name')
                first_name = request.POST.get('first_name')
                last_name = request.POST.get('last_name')
                email_address = request.POST.get('email_address')
                password = request.POST.get('password')
                group_assignments = request.POST.getall('group_assignments')

                # Update the user
                utcnow = datetime.utcnow()
                this_user = DBSession.query(User).filter(
                    User.user_id == user_id).one()
                this_user.user_name = user_name
                this_user.first_name = first_name
                this_user.last_name = last_name
                this_user.email_address = email_address
                if password:
                    salt = sha512_crypt.genconfig()[17:33]
                    encrypted_password = sha512_crypt.encrypt(password,
                                                              salt=salt)
                    this_user.salt = salt
                    this_user.password = encrypted_password
                this_user.updated_by = user['login']
                DBSession.flush()

                for g in groups:
                    if str(g.group_id) in group_assignments:
                        # assign
                        log.debug("Group: %s is in group assignments" %
                                  g.group_name)
                        q = DBSession.query(UserGroupAssignment).filter(
                            UserGroupAssignment.group_id == g.group_id,
                            UserGroupAssignment.user_id == this_user.user_id)
                        check = DBSession.query(q.exists()).scalar()
                        if not check:
                            log.info("Assigning local user %s to group %s" %
                                     (this_user.user_name, g.group_name))
                            update = UserGroupAssignment(
                                group_id=g.group_id,
                                user_id=user_id,
                                updated_by=user['login'],
                                created=utcnow,
                                updated=utcnow)
                            DBSession.add(update)
                            DBSession.flush()
                    else:
                        # delete
                        log.debug(
                            "Checking to see if we need to remove assignment for user: %s in group %s"
                            % (this_user.user_name, g.group_name))
                        q = DBSession.query(UserGroupAssignment).filter(
                            UserGroupAssignment.group_id == g.group_id,
                            UserGroupAssignment.user_id == this_user.user_id)
                        check = DBSession.query(q.exists()).scalar()
                        if check:
                            log.info("Removing local user %s from group %s" %
                                     (this_user.user_name, g.group_name))
                            assignment = DBSession.query(
                                UserGroupAssignment).filter(
                                    UserGroupAssignment.group_id == g.group_id,
                                    UserGroupAssignment.user_id ==
                                    this_user.user_id).one()
                            DBSession.delete(assignment)
                            DBSession.flush()

                return_url = '/cp/user'
                return HTTPFound(return_url)
Exemple #10
0
def view_ss(request):

    # Globalizing these. Otherwise will be passing them all over the
    # place for no reason.
    global jenkins_user
    global jenkins_pass
    global gerrit_server
    global verify_ssl
    jenkins_user = request.registry.settings['ss.jenkins_user']
    jenkins_pass = request.registry.settings['ss.jenkins_pass']
    gerrit_server = request.registry.settings['ss.gerrit_server']
    verify_ssl = request.registry.settings['ss.verify_ssl']

    page_title = 'Self Service'
    subtitle = 'Add an application'
    user = get_user(request)
    error_msg = None

    params = {
        'mode': None,
        'confirm': None,
        'processed': None,
    }
    for p in params:
        try:
            params[p] = request.params[p]
        except:
            pass

    mode = params['mode']
    confirm = params['confirm']
    processed = params['processed']
    ui = UserInput()

    # Build some lists of choices
    q = DBSession.query(ArtifactType)
    q = q.filter(ArtifactType.name != 'conf')
    artifact_types = q.all()

    q = DBSession.query(JenkinsInstance)
    jenkins_instances = q.all()

    if 'form.edit' in request.POST:
        log.info("Editing self service")

        ui = format_user_input(request, ui)

    if 'form.preprocess' in request.POST:
        log.info("Pre-processing self service")

        ui = format_user_input(request, ui)

        # Set up the list of jobs to check
        jobs = [ui.job_code_url, ui.job_conf_url]
        # Optional jobs
        for j in [ui.job_rolling_restart_url, ui.job_abs_url]:
            if j:
                jobs.append(j)
        if ui.code_review == 'true' and not ui.autosnap:
            jobs.append(ui.job_review_url)

        try:
            check_all_resources(ui.git_repo_name, jobs)
            confirm = 'true'
        except Exception, e:
            error_msg = e
Exemple #11
0
def login(request):
    page_title = 'Login'

    user = get_user(request)

    if request.referer:
        referer_host = request.referer.split('/')[2]
    else:
        referer_host = None

    if request.referer and referer_host == request.host and request.referer.split(
            '/')[3][:6] != 'logout':
        return_url = request.referer
    elif request.path != '/login':
        return_url = request.url
    else:
        return_url = '/applications'

    login = ''
    password = ''
    error = ''

    if 'form.submitted' in request.POST:
        login = request.POST['login']
        password = request.POST['password']

        # AD/LDAP
        if request.registry.settings['tcw.auth_mode'] == 'ldap':
            connector = get_ldap_connector(request)
            data = connector.authenticate(login, password)
        # LOCAL
        else:
            data = local_authenticate(login, password)

        if data is not None:
            dn = data[0]
            encrypted = signed_serialize(
                login, request.registry.settings['tcw.cookie_token'])
            headers = remember(request, dn)
            headers.append(
                ('Set-Cookie',
                 'un=' + str(encrypted) + '; Max-Age=604800; Path=/'))

            return HTTPFound(request.POST['return_url'], headers=headers)
        else:
            error = 'Invalid credentials'

    if request.authenticated_userid:

        if request.path == '/login':
            error = 'You are already logged in'
            page_title = 'Already Logged In'
        else:
            error = 'You do not have permission to access this page'
            page_title = 'Access Denied'

    return {
        'layout': site_layout(),
        'page_title': page_title,
        'user': user,
        'return_url': return_url,
        'login': login,
        'password': password,
        'error': error,
    }