Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

student backups with export token authentication #1414

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 69 additions & 1 deletion server/controllers/api.py
Original file line number Diff line number Diff line change
@@ -377,6 +377,55 @@ class GroupSchema(APISchema):
'members': fields.List(fields.Nested(member_fields)),
}

class BackupStaffSchema(APISchema):
post_fields = {
'email': fields.String,
'key': fields.String,
'course': fields.Nested(CourseSchema.get_fields),
'assignment': fields.String,
}

def __init__(self):
APISchema.__init__(self)
self.parser.add_argument('assignment', type=str, required=True,
help='Name of Assignment')
self.parser.add_argument('messages', type=dict, required=True,
help='Backup Contents as JSON')
self.parser.add_argument('email', type=str, required=True,
help='Student Email for Backup')
self.parser.add_argument('submit', type=bool, default=False,
help='Flagged as a submission')

def store_backup(self):
args = self.parse_args()
user = models.User.lookup(args['email'])

assignment = models.Assignment.name_to_assign_info(args['assignment'])
lock_flag = not assignment['active']
eligible_submit = args['submit'] and not lock_flag
if not assignment:
raise ValueError('Assignment does not exist')
lock_flag = not assignment['active']
past_due = dt.utcnow() > assignment['due_date']
backup = make_backup(user, assignment['id'], args['messages'], True)

if past_due:
assign_obj = models.Assignment.by_name(args['assignment'])
extension = models.Extension.get_extension(user, assign_obj, time=backup.created)
# Submissions after the deadline with an extension are allowed
if extension:
backup.submit = True # Need to set if the assignment is inactive
backup.custom_submission_time = extension.custom_submission_time or assign_obj.due_date
eligible_submit = True
elif lock_flag:
raise ValueError('Late Submission of {}'.format(args['assignment']))

models.db.session.commit()

if (eligible_submit and assignment['autograding_key']
and assignment['continuous_autograding']):
submit_continuous(backup)
return backup

class BackupSchema(APISchema):
get_fields = {
@@ -739,6 +788,25 @@ def post(self, user, key=None):
'assignment': assignment.name,
}

class StaffBackup(TokenResource):
""" Backup submission without student authenticated.
Permissions = staff
Used by: Prairie Learn for integration
"""
schema = BackupStaffSchema()
model = models.Backup
@marshal_with(schema.post_fields)
def post(self, offering):
backup = self.schema.store_backup()
backup_url = url_for('student.code', name=backup.assignment.name, submit=backup.submit,
bid=backup.id, _external=True)
return {
'email': backup.submitter.email,
'key': encode_id(backup.id),
'url': backup_url,
'course': backup.assignment.course,
'assignment': backup.assignment.name
}

class ExportBackup(Resource):
""" Export backup retreival resource without submitter information
@@ -1236,7 +1304,6 @@ class ClientRedirectURL(Resource):
"""
schema = ClientRedirectURLSchema()
model = models.Comment

@marshal_with(schema.post_fields)
def post(self, user, client_id):
client = models.Client.query.get(client_id)
@@ -1276,6 +1343,7 @@ def post(self, user, client_id):
api.add_resource(CourseAssignment, COURSE_BASE + '/assignments')
api.add_resource(CourseGrades, COURSE_BASE + '/grades')
api.add_resource(CourseGradesExport, COURSE_BASE + '/export/grades')
api.add_resource(StaffBackup, COURSE_BASE + '/staff/backups/')

# Other
api.add_resource(Enrollment, '/v3/enrollment/<string:email>/')
1 change: 1 addition & 0 deletions server/settings/test.py
Original file line number Diff line number Diff line change
@@ -15,6 +15,7 @@ class Config(DevBaseConfig, BaseConfig):

APPINSIGHTS_INSTRUMENTATIONKEY = ''

PRESERVE_CONTEXT_ON_EXCEPTION = False
@classmethod
def get_default_db_url(cls):
return os.getenv('SQLALCHEMY_URL', 'sqlite:///../oktest.db')
5 changes: 4 additions & 1 deletion tests/__init__.py
Original file line number Diff line number Diff line change
@@ -67,6 +67,7 @@ def setup_course(self):
* 2 staff members (self.staff1, self.staff2) as TAs
* 1 lab assistant (self.lab_assistant1) as lab assistants
* 1 Admin (okadmin@okpy.org)
* 1 export access token named 'test'
"""
self.admin = User(email='okadmin@okpy.org', is_admin=True)
db.session.add(self.admin)
@@ -75,7 +76,9 @@ def setup_course(self):
self.course = Course(
offering='cal/cs61a/sp16',
institution='UC Berkeley',
display_name='CS 61A')
display_name='CS 61A',
export_access_token='test',
export_access_token_active=True)
self.assignment = Assignment(
name='cal/cs61a/sp16/proj1',
creator_id=self.admin.id,
66 changes: 66 additions & 0 deletions tests/test_api.py
Original file line number Diff line number Diff line change
@@ -781,3 +781,69 @@ def test_course_roster(self):
endpoint = '/api/v3/course/cal/cs61a/sp16/roster'
response = self.client.get(endpoint)
self.assert_200(response)

def test_export_token_submit(self, submit=True, delay=10, success=True, export_token='test'):
self.setup_course()

email = self.user1.email
course = self.course
assignment = self.assignment
user = User.lookup(email)
endpoint = f'/api/v3/course/{course.offering}/staff/backups/?export_token={export_token}&email={email}'

# Offset the due date & lock_dates
assignment.due_date = assignment.due_date + dt.timedelta(hours=delay)
assignment.lock_date = assignment.lock_date + dt.timedelta(days=delay)

okversion = Version(name="ok-client", current_version="v1.5.0",
download_link="http://localhost/ok")

db.session.add(okversion)
db.session.commit()

data = {
'assignment': assignment.name,
'messages': {
'file_contents': {
"hog.py": "def add(x, y): pass"
}
},
'submit': True,
}
response = self.client.post(endpoint,
data=json.dumps(data),
headers=[('Content-Type', 'application/json')])

backup = Backup.query.filter(Backup.submitter_id == user.id).first()

assert backup is not None

if success or not submit:
assert response.json['data'] == {
'email': email,
'key': encode_id(backup.id),
'course': {
'id': course.id,
'offering': course.offering,
'display_name': course.display_name,
'active': course.active,
'timezone': 'America/Los_Angeles'
},
'assignment': assignment.name
}
self.assert_200(response)

if not success:
self.assert_403(response)
submit = False
assert response.json['data'] == {
'data': {
'backup': True,
'late': True
}
}

assert backup.assignment == assignment
assert backup.submitter_id == user.id
assert len(backup.messages) == len(data['messages'])
assert backup.submit == submit