示例#1
0
def validate_time_deploy(app_id):

    valid = None

    q = DBSession.query(Application)
    q = q.filter(Application.application_id == app_id)
    app = q.one()
    w = app.deployment_time_windows[0]

    print "WINDOW day_start: %s day_end: %s start_time: %s:%s end_time: %s:%s " % (w.day_start, w.day_end, w.hour_start, w.minute_start, w.hour_end, w.minute_end)

    d = datetime.now()
    
    # check if weekday is Monday - Thursday
    if d.isoweekday() in range(w.day_start, w.day_end + 1) and d.hour*60+d.minute in range(w.hour_start*60+w.minute_start, w.hour_end*60+w.minute_end):
        print "we are in range"
        valid = True

    return {'day_start': 'Monday',
            'day_end': 'Thursday',
            'hour_start': '8',
            'minute_start': '00',
            'hour_end': '16',
            'minute_end': '00',
            'valid': valid
    }
示例#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)
示例#3
0
def local_authenticate(login, password):
    """ Checks the validity of a username/password against what
        is stored in the database. """

    try: 
        q = DBSession.query(User)
        q = q.filter(User.user_name == login)
        db_user = q.one()
    except Exception, e:
        log.error("%s (%s)" % (Exception, e))
        pass
示例#4
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)
示例#5
0
def local_groupfinder(userid, request):
    """ queries the db for a list of groups the user belongs to.
        Returns either a list of groups (empty if no groups) or None
        if the user doesn't exist. """

    groups = None
    try:
        user = DBSession.query(User).filter(User.user_name==userid).one()
        groups = user.get_all_assignments()
    except Exception, e:
        pass
        log.error("%s (%s)" % (Exception, e))
示例#6
0
def get_jenkins_template_url(job_type):
    log.info(
        "Retrieving jenkins tempalte job from DB for job type: {0}".format(
            job_type))
    try:
        q = DBSession.query(JenkinsTemplate)
        q = q.filter(JenkinsTemplate.job_type == job_type)
        job = q.one()
        log.info("Tempalte job is: {0}".format(job.job_url))
        return job.job_url
    except Exception, e:
        msg = 'Failed to retrieve conf template from db: {0}'.format(e)
        log.error(msg)
        raise Exception(msg)
示例#7
0
def get_all_groups():
    """ Gets all the groups that are configured in
        the db and returns a dict of everything. """

    # Get the groups from the db
    group_perms = []
    r = DBSession.query(Group).all()
    for g in range(len(r)):
        ga = r[g].get_all_assignments()
        if ga:
            ga = tuple(ga)
            group_perms.append([r[g].group_name, ga])

    return(group_perms)
示例#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)
示例#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)
示例#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
示例#11
0
    if request.registry.settings['tcw.auth_mode'] == 'ldap':
        try:
            id = request.authenticated_userid
            if id: 
                (first,last) = format_user(id)
                groups = groupfinder(id, request)
                first_last = "%s %s" % (first, last)
                auth = True
        except Exception, e:
            log.error("%s (%s)" % (Exception, e))
            (first_last, id, login, groups, first, last, auth, prd_auth, admin_auth, cp_auth) = ('', '', '', '', '', '', False, False, False, False)
    else:
        try:
            id = request.authenticated_userid
            user = DBSession.query(User).filter(User.user_name==id).one()
            first = user.first_name
            last = user.last_name
            email_address = user.email_address
            groups = local_groupfinder(id, request)
            first_last = "%s %s" % (first, last)
            auth = True
            auth_mode = 'local'
        except Exception, e:
            log.error("%s (%s)" % (Exception, e))
            (first_last, id, login, groups, first, last, auth, prd_auth, admin_auth, cp_auth) = ('', '', '', '', '', '', False, False, False, False)

    try:
        login = validate_username_cookie(request.cookies['un'], request.registry.settings['tcw.cookie_token'])
        login = str(login)
    except: