Exemple #1
0
    def create(self):
        """
            Register a user in the database
        """
        pw_hash = auth.hash_password(self.password)

        sql = """
            insert into Users
                (username, password, email, first_name, last_name)
            values
                (%s, %s, %s, %s, %s)
            returning
                user_id
            """

        data = (self.username, pw_hash, self.email, self.fname, self.lname)

        user_id = app.db.exec_query(sql, data, "commit", "returning")
        if user_id:
            self.user_id = user_id
            self.password = pw_hash
            logger.debug("Created new user_id: %s | username: %s" % (user_id, self.username))
        else:
            logger.debug("Failed to create username: %s" % (username))
        return user_id
Exemple #2
0
    def exec_query(self, sql, data, *args, **kwargs):
        """
            Executes a database query and returns the result
            sql = a tuple containing the query as a string
            data = a tuple of data values to insert into the sql
            commit = Does this sql query need an explicit commit? Default false

            args = [
                fetchall - returns the result of a fetchall against the cursor
                fetchone - returns the result of a fetchone against the cursor
                commit - if commit, then the query requires a commit
                returning - returns data from the row inserted
                return_dict - return a list of dictionaries with the column name as the key
                and the value as the dictionary
            ]

        """

        with self.app.app_context():
            db = self.get_db()
            cur = db.cursor()
            result = None

            try:
                cur.execute(sql, data)

                if 'fetchall' in args:
                    result = cur.fetchall()

                if 'fetchone' in args:
                    result = cur.fetchone()

                if 'returning' in args:
                    result = cur.fetchone()[0]

                if 'return_dict' in args:
                    colnames = [desc[0] for desc in cur.description]
                    result_dicts = [ dict(zip(colnames, row)) for row in result ]
                    result = result_dicts

                if 'commit' in args:
                    db.commit()
                    # return True so we know the commit went through
                    if not 'returning' in args:
                        result = True

            except psycopg2.IntegrityError, e:
                logger.warn('db_query failed: %s' % (e[0]))
                logger.debug('db_query == %s data == %s' % (sql, data))
                db.rollback()
                result = None
            except Exception, e:
                logger.warn('db_query failed: %s' % (e[0]))
                logger.debug('db_query == %s data == %s' % (sql, data))
                result = None
Exemple #3
0
    def read(self):
        """
            Read the assignment from the database and set memvars
        """

        sql = ("""
            select
                *
            from
                Assignment
            where
                assignment_id = (%s)
            """
        )

        data = (
            int(self.assignment_id),
        )

        rc = app.db.exec_query(sql, data, 'fetchall', 'return_dict')

        logger.debug("Fetching assignment: %s " % (self.assignment_id))
        if rc:
            logger.debug("Success")
            a = a[0]
            self.title = a['title']
            self.description = a['description']
            self.due_date = a['due_date']
            self.points_possible = a['points_possible']
            self.course_id = a['course_id']
        else:
            logger.debug("Fail")
        return rc
Exemple #4
0
    def delete(self):
        """
            Deletes self from the database
        """

        sql = ("""
            delete from
                Assignment
            where
                assignment_id = (%s)
            """
        )

        data = (
            int(self.assignment_id),
        )

        rc = app.db.exec_query(sql, data, 'commit')

        logger.debug("Deleting assignment: %s for course_id %s"
                    % (self.title, self.course_id))
        if rc:
            logger.debug("Success")
            self.assignment_id = None
        else:
            logger.debug("Failure")
        return rc
Exemple #5
0
    def create(self):
        """
            Writes self to the database
        """

        sql = ("""
            insert into Assignment
                (title, description, due_date, points_possible, course_id)
            values
                (%s, %s, %s, %s, %s)
            returning
                assignment_id
            """
        )

        data = (
            self.title,
            self.description,
            self.due_date,
            self.points_possible,
            int(self.course_id),
        )

        logger.debug("Creating assignment: %s for course_id %s"
                    % (self.title, self.course_id))
        rc = app.db.exec_query(sql, data, 'commit', 'returning')
        if rc:
            logger.debug("Success")
            self.assignment_id = rc
        else:
            logger.debug("Fail")
            self.assignment_id = None

        return rc
Exemple #6
0
    def update(self):
        """
            Update the assignment in the database
        """

        sql = ("""
            update Assignment set
                title = (%s),
                description = (%s),
                due_date = (%s),
                points_possible = (%s),
                course_id = (%s)
            where
                assignment_id = (%s)
            """
        )

        data = (
            self.title,
            self.description,
            self.due_date,
            self.points_possible,
            int(self.course_id),
            int(self.assignment_id),
        )

        logger.debug("Deleting assignment: %s for course_id %s"
                    % (self.title, self.course_id))
        rc = app.db.exec_query(sql, data, 'commit')

        if rc:
            logger.debug("Success")
        else:
            logger.debug("Fail")
        return rc
Exemple #7
0
    def update(self):
        """
            Update the user's data in the database from member variables
        """

        sql = """
            update Users set
                password = (%s),
                email = (%s),
                first_name = (%s),
                last_name = (%s)
            where
                user_id = (%s)
            """

        data = (self.password, self.email, self.fname, self.lname, int(self.user_id))
        commit = app.db.exec_query(sql, data, "commit")
        if commit:
            logger.debug("Successfully updated user: %s" % (self.username))
        else:
            logger.debug("Failed to update user: %s" % (self.username))
        return commit
Exemple #8
0
    def get_assignments(username, course_title):
        """
            Fetch a list of Assignment objects for a given course id
            returns an empty list if no assignments or error
        """

        sql = ("""
            select
                a.title, a.description, a.due_date, a.points_possible, c.course_id
            from
                Assignment a, Users u, InstructorTeachesCourse itc, Course c
            where
                c.title = (%s)
            and
                u.username = (%s)
            and
                u.user_id = itc.user_id
            and
                c.course_id = itc.course_id
            and
                a.course_id = itc.course_id
            """
        )

        data = (
            course_title,
            username,
        )

        logger.debug("Fetching assignments for user: %s, course_title: %s"
                    % (username, course_title))
        assignments = app.db.exec_query(sql, data, 'fetchall', 'return_dict')
        logger.debug(assignments)
        result = []
        if assignments:
            logger.debug("Success")
            for a in assignments:
                assignment = Assignment(
                    None, a['title'], a['description'],
                    a['due_date'], a['points_possible'], a['course_id'])

                result.append(assignment)
        else:
            logger.debug("Fail")
        return result
Exemple #9
0
def assignment_grade(username):
    """
        GET - Show form for file grader

        POST - Validate and grade all files in the form
    """
    form = None
    if g.user.username == username and g.user.is_authenticated():
        form = AssignmentUploadForm()
        if form.validate_on_submit():
            subprocess.call('rm -rf /var/codeta/completed/*', shell=True)
            subprocess.call('rm -rf /var/codeta/unit_tests/*', shell=True)
            subprocess.call('rm -rf /var/codeta/uploads/*', shell=True)
            student_files = request.files.getlist('archives')
            unit_tests = request.files.getlist('test')

            try:
                logger.debug('saving archives')
                f = [ archives.save(f) for f in student_files ]
                t = [ tests.save(f) for f in unit_tests ]

                f = [ os.path.join(app.config['UPLOADED_ARCHIVES_DEST'], f)
                    for f in os.listdir(app.config['UPLOADED_ARCHIVES_DEST']) ]
                logger.debug(f)
            except UploadNotAllowed:
                flash("You can only upload archive files")
            else:
                logger.debug("Grading files")
                grader = Grader(
                        app.config['UPLOADED_ARCHIVES_DEST'],
                        app.config['GRADER_DIR'],
                        os.path.join(app.config['GRADER_UNITTEST'], t[0]),
                        request.form['test_name'])
                grader.grade(f)

            return redirect(url_for('assignment_reports', username=username))
        else:
            return render_template('assignment/upload.html',form=form)
    else:
        return redirect(url_for('login'))
Exemple #10
0
    def auth_user(username, password):
        """
            Authenticates a user and returns a User object
            if the correct credentials were provided
            otherwise, return None
        """
        logger.debug("User: %s - Pass: %s - auth attempt. " % (username, password))

        sql = """
            select
                *
            from
                Users
            where
                username = (%s)
            """

        data = (username,)

        user = app.db.exec_query(sql, data, "fetchall", "return_dict")
        if user:
            user = user[0]
            if auth.check_password(password, user["password"]):
                user = User(
                    int(user["user_id"]),
                    user["username"],
                    user["password"],
                    user["email"],
                    user["first_name"],
                    user["last_name"],
                )
                logger.debug("User: %s - auth success." % (username))
            else:
                user = None
                logger.debug("User: %s - auth failure." % (username))
        return user
Exemple #11
0
 def validate_archives(form, field):
     if field.data:
         logger.debug(field.data)