def setup_usersearch(): """ Show a page allowing the admin search for users, or create new ones""" user_id = session['user_id'] if not check_perm(user_id, -1, "useradmin"): flash("You do not have User Administration access.") return redirect(url_for('setup_top')) users = [] nonefound = False if request.method == "POST": if 'usersearch_name' in request.form: needle = request.form['usersearch_name'] if len(needle) < 2: flash("Search term too short, please try something longer") else: uids = Users2.find(needle) users = [Users2.get_user(uid) for uid in uids] if len(users) == 0: nonefound = True else: users.sort(key=lambda x: x['uname']) return render_template( 'setup_usersearch.html', users=users, nonefound=nonefound )
def setup_usersummary(view_id): """ Show an account summary for the given user account. """ user_id = session['user_id'] if not check_perm(user_id, -1, "useradmin"): flash("You do not have User Administration access.") return redirect(url_for('setup_top')) is_sysadmin = check_perm(user_id, -1, 'sysadmin') user = Users2.get_user(view_id) examids = Exams.get_exams_done(view_id) exams = [] for examid in examids: exam = Exams.get_exam_struct(examid) started = General.human_date(exam['start']) exam['started'] = started exam['viewable'] = satisfy_perms(user_id, exam['cid'], ("viewmarks", )) exams.append(exam) exams.sort(key=lambda x: x['start_epoch'], reverse=True) course_ids = Users2.get_courses(view_id) courses = [] for course_id in course_ids: courses.append(Courses2.get_course(course_id)) user_is_admin = check_perm(view_id, 0, 'sysadmin') return render_template('setup_usersummary.html', user=user, exams=exams, courses=courses, is_sysadmin=is_sysadmin, user_is_admin=user_is_admin)
def setup_change_pass_submit(): """ Set a new password """ user_id = session['user_id'] user = Users2.get_user(user_id) if "newpass" not in request.form or "confirm" not in request.form: flash("Please provide your new password") return redirect(url_for("setup_change_pass")) newpass = request.form['newpass'] confirm = request.form['confirm'] if len(newpass) < 7: flash("Password is too short, please try something longer.") return redirect(url_for("setup_change_pass")) if not newpass == confirm: flash("Passwords do not match") return redirect(url_for("setup_change_pass")) Users2.set_password(user_id=user_id, clearpass=newpass) audit(1, user_id, user_id, "Setup", "%s reset password for %s." % (user['uname'], user['uname'])) flash("Password changed") return redirect(url_for("setup_myprofile"))
def setup_usersearch(): """ Show a page allowing the admin search for users, or create new ones""" user_id = session['user_id'] if not check_perm(user_id, -1, "useradmin"): flash("You do not have User Administration access.") return redirect(url_for('setup_top')) users = [] nonefound = False if request.method == "POST": if 'usersearch_name' in request.form: needle = request.form['usersearch_name'] if len(needle) < 2: flash("Search term too short, please try something longer") else: uids = Users2.find(needle) users = [Users2.get_user(uid) for uid in uids] if len(users) == 0: nonefound = True else: users.sort(key=lambda x: x['uname']) return render_template('setup_usersearch.html', users=users, nonefound=nonefound)
def setup_myprofile(): """ Show an account summary for the current user account. """ user_id = session['user_id'] user = Users2.get_user(user_id) course_ids = Users2.get_courses(user_id) courses = [] for course_id in course_ids: courses.append(Courses2.get_course(course_id)) return render_template('setup_myprofile.html', user=user, courses=courses)
def users_update_from_feed(upids): """ Given a list of upids, go through and try to fetch details from feed, updating/creating the accounts if needed. """ for upid in upids: user_id = Users2.uid_by_uname(upid) if not user_id: # we don't know who they are, so create them. for feed in UFeeds.all_list(): try: out = feeds_run_user_script(feed.script, args=[upid, ]) except BaseException as err: L.error("Exception in user feed '%s': %s" % (feed.script, err)) continue res = out.splitlines() if res[0].startswith("ERROR"): L.error("Error running user feed '%s': %s" % (feed.script, res)) continue line = res[1] studentid = "" try: (upid, name, email, studentid) = line.split(',') except ValueError: try: (upid, name, email) = line.split(',') except ValueError: continue given = name.split(" ")[0] try: family = " ".join(name.split(" ")[1:]) except ValueError: family = "" Users2.create(upid, '', given, family, 2, studentid, email, None, 'feed', '', True) break else: L.error("Error running user feed for existing account %s" % user_id) return
def login_forgot_pass_submit(): """ Forgot their password. Grab their username and send them a reset email. """ if "cancel" in request.form: flash("Password reset cancelled.") return redirect(url_for("login_local")) username = sanitize_username(request.form.get('username', None)) if username == "admin": flash("""The admin account cannot do an email password reset, please see the Installation instructions.""") return redirect(url_for("login_forgot_pass")) if username: user_id = Users2.uid_by_uname(username) else: user_id = None if not user_id: flash("Unknown username ") return redirect(url_for("login_forgot_pass")) user = Users2.get_user(user_id) if not user['source'] == "local": flash("Your password is not managed by OASIS, " "please contact IT Support.") return redirect(url_for("login_forgot_pass")) code = Users.gen_confirm_code() Users.set_confirm_code(user_id, code) email = user['email'] if not email: flash("We do not appear to have an email address on file for " "that account.") return redirect(url_for("login_forgot_pass")) text_body = render_template(os.path.join("email", "forgot_pass.txt"), code=code) html_body = render_template(os.path.join("email", "forgot_pass.html"), code=code) send_email(user['email'], from_addr=None, subject="OASIS Password Reset", text_body=text_body, html_body=html_body) return render_template("login_forgot_pass_submit.html")
def setup_myprofile(): """ Show an account summary for the current user account. """ user_id = session['user_id'] user = Users2.get_user(user_id) course_ids = Users2.get_courses(user_id) courses = [] for course_id in course_ids: courses.append(Courses.get_course(course_id)) return render_template( 'setup_myprofile.html', user=user, courses=courses )
def login_email_passreset(code): """ They've clicked on a password reset link. Log them in (might as well) and send them to the password reset page.""" # This will also confirm their email if they haven't. # Doesn't seem to be any harm in doing that if len(code) > 20: abort(404) uid = Users.verify_confirm_code(code) if not uid: abort(404) Users.set_confirm(uid) Users.set_confirm_code(uid, "") user = Users2.get_user(uid) session['username'] = user['uname'] session['user_id'] = uid session['user_givenname'] = user['givenname'] session['user_familyname'] = user['familyname'] session['user_fullname'] = user['fullname'] session['user_authtype'] = "local" audit(1, uid, uid, "UserAuth", "%s logged in using password reset email" % (session['username'],)) flash("Please change your password") return redirect(url_for("setup_change_pass"))
def cadmin_assign_coord(course_id): """ Set someone as course coordinator """ course = Courses2.get_course(course_id) if not course: abort(404) if not "coord" in request.form: abort(400) new_uname = request.form["coord"] # TODO: Sanitize username try: new_uid = Users2.uid_by_uname(new_uname) except KeyError: flash("User '%s' Not Found" % new_uname) else: if not new_uid: flash("User '%s' Not Found" % new_uname) else: Permissions.add_perm(new_uid, course_id, 3) # courseadmin Permissions.add_perm(new_uid, course_id, 4) # coursecoord flash("%s can now control the course." % (new_uname,)) return redirect(url_for("cadmin_config", course_id=course_id))
def cadmin_editgroup_member(course_id, group_id): """ Perform operation on group member. Remove/Edit/Etc """ cur_user = session['user_id'] group = None try: group = Groups.Group(g_id=group_id) except KeyError: abort(404) if not group: abort(404) done = False cmds = request.form.keys() # "remove_UID", only know how to remove for now. for cmd in cmds: if '_' in cmd: op, uid = cmd.split("_", 1) if op == "remove": uid = int(uid) user = Users2.get_user(uid) L.info("courseadmin: user %s removed from group %s by %s" % (uid, group_id, cur_user)) group.remove_member(uid) flash("%s removed from group" % user['uname']) done = True if not done: flash("No actions?") return redirect(url_for('cadmin_editgroup', course_id=course_id, group_id=group_id))
def cadmin_editgroup_addperson(course_id, group_id): """ Add a person to the group. """ group = None try: group = Groups.Group(g_id=group_id) except KeyError: abort(404) if not group: abort(404) if "uname" not in request.form: abort(400) new_uname = sanitize_username(request.form['uname']) try: new_uid = Users2.uid_by_uname(new_uname) except KeyError: flash("User '%s' Not Found" % new_uname) else: if not new_uid: flash("User '%s' Not Found" % new_uname) elif new_uid in group.members(): flash("%s is already in the group." % new_uname) else: group.add_member(new_uid) flash("Added %s to group." % (new_uname, )) return redirect( url_for('cadmin_editgroup', course_id=course_id, group_id=group_id))
def cadmin_assign_coord(course_id): """ Set someone as course coordinator """ cur_user = session['user_id'] course = Courses2.get_course(course_id) if not course: abort(404) if "coord" not in request.form: abort(400) new_uname = sanitize_username(request.form['coord']) try: new_uid = Users2.uid_by_uname(new_uname) except KeyError: flash("User '%s' Not Found" % new_uname) else: if not new_uid: flash("User '%s' Not Found" % new_uname) else: L.info("courseadmin: user %s assigned as coordinator to course %s by %s" % (new_uid, course_id, cur_user)) Permissions.add_perm(new_uid, course_id, 3) # courseadmin Permissions.add_perm(new_uid, course_id, 4) # coursecoord flash("%s can now control the course." % (new_uname,)) return redirect(url_for('cadmin_config', course_id=course_id))
def cadmin_editgroup_member(course_id, group_id): """ Perform operation on group member. Remove/Edit/Etc """ group = None try: group = Groups.Group(g_id=group_id) except KeyError: abort(404) if not group: abort(404) done = False cmds = request.form.keys() # expecting "remove_UID" for cmd in cmds: if '_' in cmd: op, uid = cmd.split("_", 1) if op == "remove": uid = int(uid) user = Users2.get_user(uid) group.remove_member(uid) flash("%s removed from group" % user['uname']) done = True if not done: flash("No actions?") return redirect(url_for('cadmin_editgroup', course_id=course_id, group_id=group_id))
def cadmin_editgroup_addperson(course_id, group_id): """ Add a person to the group. """ group = None try: group = Groups.Group(g_id=group_id) except KeyError: abort(404) if not group: abort(404) if "uname" not in request.form: abort(400) new_uname = sanitize_username(request.form['uname']) try: new_uid = Users2.uid_by_uname(new_uname) except KeyError: flash("User '%s' Not Found" % new_uname) else: if not new_uid: flash("User '%s' Not Found" % new_uname) elif new_uid in group.members(): flash("%s is already in the group." % new_uname) else: group.add_member(new_uid) flash("Added %s to group." % (new_uname,)) return redirect(url_for('cadmin_editgroup', course_id=course_id, group_id=group_id))
def cadmin_editgroup_member(course_id, group_id): """ Perform operation on group member. Remove/Edit/Etc """ cur_user = session['user_id'] group = None try: group = Groups.Group(g_id=group_id) except KeyError: abort(404) if not group: abort(404) done = False cmds = request.form.keys() # "remove_UID", only know how to remove for now. for cmd in cmds: if '_' in cmd: op, uid = cmd.split("_", 1) if op == "remove": uid = int(uid) user = Users2.get_user(uid) L.info("courseadmin: user %s removed from group %s by %s" % (uid, group_id, cur_user)) group.remove_member(uid) flash("%s removed from group" % user['uname']) done = True if not done: flash("No actions?") return redirect( url_for('cadmin_editgroup', course_id=course_id, group_id=group_id))
def cadmin_assign_coord(course_id): """ Set someone as course coordinator """ cur_user = session['user_id'] course = Courses2.get_course(course_id) if not course: abort(404) if "coord" not in request.form: abort(400) new_uname = sanitize_username(request.form['coord']) try: new_uid = Users2.uid_by_uname(new_uname) except KeyError: flash("User '%s' Not Found" % new_uname) else: if not new_uid: flash("User '%s' Not Found" % new_uname) else: L.info( "courseadmin: user %s assigned as coordinator to course %s by %s" % (new_uid, course_id, cur_user)) Permissions.add_perm(new_uid, course_id, 3) # courseadmin Permissions.add_perm(new_uid, course_id, 4) # coursecoord flash("%s can now control the course." % (new_uname, )) return redirect(url_for('cadmin_config', course_id=course_id))
def login_email_passreset(code): """ They've clicked on a password reset link. Log them in (might as well) and send them to the password reset page.""" # This will also confirm their email if they haven't. # Doesn't seem to be any harm in doing that if len(code) > 20: abort(404) uid = Users.verify_confirm_code(code) if not uid: abort(404) Users.set_confirm(uid) Users.set_confirm_code(uid, "") user = Users2.get_user(uid) session['username'] = user['uname'] session['user_id'] = uid session['user_givenname'] = user['givenname'] session['user_familyname'] = user['familyname'] session['user_fullname'] = user['fullname'] session['user_authtype'] = "local" audit(1, uid, uid, "UserAuth", "%s logged in using password reset email" % (session['username'], )) flash("Please change your password") return redirect(url_for("setup_change_pass"))
def setup_change_pass(): """ Ask for a new password """ user_id = session['user_id'] user = Users2.get_user(user_id) return render_template( 'setup_changepassword.html', user=user, )
def group_update_from_feed(group_id, refresh_users=False): """ Update group membership from it's feed Returns (added, removed, unknown) with usernames of users """ group = Groups.Group(g_id=group_id) if not group.source == 'feed': return feed = Feeds.Feed(f_id=group.feed) scriptrun = ' '.join([feed.script, group.feedargs]) try: output = feeds_run_group_script(feed.script, args=[group.feedargs, ]) except BaseException as err: L.error("Exception in group feed '%s': %s" % (scriptrun, err)) raise removed = [] added = [] unknown = [] old_members = group.member_unames() new_members = output.split()[1:] for uname in new_members: uid = Users2.uid_by_uname(uname) if not uid: users_update_from_feed([uname, ]) L.info("Group feed contained unknown user account %s" % uname) unknown.append(uname) continue if uname not in old_members: group.add_member(uid) added.append(uname) for uname in old_members: if uname not in new_members: uid = Users2.uid_by_uname(uname) group.remove_member(uid) removed.append(uname) if refresh_users: for uname in group.member_unames(): uid = Users2.uid_by_uname(uname) user_update_details_from_feed(uid, uname) return added, removed, unknown
def login_local_submit(): """ They've entered some credentials on the local login screen. Check them, then set up the session or redirect back with an error. """ if 'username' not in request.form or 'password' not in request.form: L.info("Failed Login") flash("Incorrect name or password.") return redirect(url_for("login_local")) username = sanitize_username(request.form['username']) password = request.form['password'] user_id = Users2.verify_pass(username, password) if not user_id: L.info("Failed Login for %s" % username) flash("Incorrect name or password.") return redirect(url_for("login_local")) user = Users2.get_user(user_id) if not user['confirmed']: flash("""Your account is not yet confirmed. You should have received an email with instructions in it to do so.""") return redirect(url_for("login_local")) session['username'] = username session['user_id'] = user_id session['user_givenname'] = user['givenname'] session['user_familyname'] = user['familyname'] session['user_fullname'] = user['fullname'] session['user_authtype'] = "local" audit(1, user_id, user_id, "UserAuth", "%s successfully logged in locally" % (session['username'],)) if 'redirect' in session: L.info("Following redirect for %s" % username) target = OaConfig.parentURL + session['redirect'] del session['redirect'] return redirect(target) L.info("Successful Login for %s" % username) return redirect(url_for("main_top" ""))
def cadmin_exam_viewmarked(course_id, exam_id, student_uid): """ Show a student's marked assessment results """ course = Courses2.get_course(course_id) try: exam = Exams.get_exam_struct(exam_id, course_id) except KeyError: exam = {} abort(404) results, examtotal = Assess.render_own_marked_exam(student_uid, exam_id) if examtotal is False: status = 0 else: status = 1 marktime = Exams.get_mark_time(exam_id, student_uid) firstview = Exams.get_student_start_time(exam_id, student_uid) submittime = Exams.get_submit_time(exam_id, student_uid) try: datemarked = General.human_date(marktime) except AttributeError: datemarked = None try: datefirstview = General.human_date(firstview) except AttributeError: datefirstview = None try: datesubmit = General.human_date(submittime) except AttributeError: datesubmit = None user = Users2.get_user(student_uid) if submittime and firstview: taken = submittime-firstview takenmins = (taken.seconds/60) else: takenmins = None return render_template( "cadmin_markedresult.html", course=course, exam=exam, results=results, examtotal=examtotal, datesubmit=datesubmit, datemarked=datemarked, datefirstview=datefirstview, taken=takenmins, user=user, status=status )
def login_webauth_submit(): """ The web server should have verified their credentials and provide it in env['REMOTE_USER'] Check them, then set up the session or redirect back with an error. If we haven't seen them before, check with our user account feed(s) to see if we can find them. """ if 'REMOTE_USER' not in request.environ: L.error( "REMOTE_USER not provided by web server and 'webauth' is being attempted." ) return redirect(url_for("login_webauth_error")) username = request.environ['REMOTE_USER'] if '@' in username and OaConfig.webauth_ignore_domain: username = username.split('@')[0] user_id = Users2.uid_by_uname(username) if not user_id: Users2.create(username, '', '', '', 1, '', '', None, 'unknown', '', True) user_id = Users2.uid_by_uname(username) user = Users2.get_user(user_id) session['username'] = username session['user_id'] = user_id session['user_givenname'] = user['givenname'] session['user_familyname'] = user['familyname'] session['user_fullname'] = user['fullname'] session['user_authtype'] = "httpauth" audit(1, user_id, user_id, "UserAuth", "%s successfully logged in via webauth" % session['username']) if 'redirect' in session: target = OaConfig.parentURL + session['redirect'] del session['redirect'] return redirect(target) return redirect(url_for("main_top"))
def login_local_submit(): """ They've entered some credentials on the local login screen. Check them, then set up the session or redirect back with an error. """ if 'username' not in request.form or 'password' not in request.form: L.info("Failed Login") flash("Incorrect name or password.") return redirect(url_for("login_local")) username = sanitize_username(request.form['username']) password = request.form['password'] user_id = Users2.verify_pass(username, password) if not user_id: L.info("Failed Login for %s" % username) flash("Incorrect name or password.") return redirect(url_for("login_local")) user = Users2.get_user(user_id) if not user['confirmed']: flash("""Your account is not yet confirmed. You should have received an email with instructions in it to do so.""") return redirect(url_for("login_local")) session['username'] = username session['user_id'] = user_id session['user_givenname'] = user['givenname'] session['user_familyname'] = user['familyname'] session['user_fullname'] = user['fullname'] session['user_authtype'] = "local" audit(1, user_id, user_id, "UserAuth", "%s successfully logged in locally" % (session['username'], )) if 'redirect' in session: L.info("Following redirect for %s" % username) target = OaConfig.parentURL + session['redirect'] del session['redirect'] return redirect(target) L.info("Successful Login for %s" % username) return redirect(url_for("main_top" ""))
def setup_useraudit(audit_id): """ Show all the audit entries for the given user account. """ user_id = session['user_id'] if not check_perm(user_id, -1, "useradmin"): flash("You do not have User Administration access.") return redirect(url_for('setup_top')) user = Users2.get_user(audit_id) audits = get_records_by_user(audit_id) for aud in audits: aud['humantime'] = General.human_date(aud['time']) return render_template('setup_useraudit.html', user=user, audits=audits)
def cadmin_exam_results(course_id, exam_id): """ View the results of an assessment """ course = Courses2.get_course(course_id) if not course: abort(404) exam = Exams.get_exam_struct(exam_id, course_id) if not exam: abort(404) if not int(exam['cid']) == int(course_id): flash("Assessment %s does not belong to this course." % int(exam_id)) return redirect(url_for('cadmin_top', course_id=course_id)) exam['start_date'] = int(date_from_py2js(exam['start'])) exam['end_date'] = int(date_from_py2js(exam['end'])) exam['start_hour'] = int(exam['start'].hour) exam['end_hour'] = int(exam['end'].hour) exam['start_minute'] = int(exam['start'].minute) exam['end_minute'] = int(exam['end'].minute) groups = [Groups.Group(g_id=g_id) for g_id in Groups.active_by_course(course_id)] results = {} uids = set([]) totals = {} for group in groups: results[group.id] = Exams.get_marks(group, exam_id) for user_id in results[group.id]: uids.add(user_id) if user_id not in totals: totals[user_id] = 0.0 for qt, val in results[group.id][user_id].iteritems(): totals[user_id] += val['score'] questions = Exams.get_qts_list(exam_id) users = {} for uid in uids: users[uid] = Users2.get_user(uid) return render_template( "cadmin_examresults.html", course=course, exam=exam, results=results, groups=groups, users=users, questions=questions, when=datetime.now().strftime("%H:%m, %a %d %b %Y"), totals=totals )
def cadmin_exam_viewmarked(course_id, exam_id, student_uid): """ Show a student's marked assessment results """ course = Courses2.get_course(course_id) try: exam = Exams.get_exam_struct(exam_id, course_id) except KeyError: exam = {} abort(404) results, examtotal = Assess.render_own_marked_exam(student_uid, exam_id) if examtotal is False: status = 0 else: status = 1 marktime = Exams.get_mark_time(exam_id, student_uid) firstview = Exams.get_student_start_time(exam_id, student_uid) submittime = Exams.get_submit_time(exam_id, student_uid) try: datemarked = General.human_date(marktime) except AttributeError: datemarked = None try: datefirstview = General.human_date(firstview) except AttributeError: datefirstview = None try: datesubmit = General.human_date(submittime) except AttributeError: datesubmit = None user = Users2.get_user(student_uid) if submittime and firstview: taken = submittime - firstview takenmins = (taken.seconds / 60) else: takenmins = None return render_template("cadmin_markedresult.html", course=course, exam=exam, results=results, examtotal=examtotal, datesubmit=datesubmit, datemarked=datemarked, datefirstview=datefirstview, taken=takenmins, user=user, status=status)
def cadmin_exam_unsubmit(course_id, exam_id, student_uid): """ "unsubmit" the student's assessment and reset their timer so they can log back on and have another attempt. """ course = Courses2.get_course(course_id) try: exam = Exams.get_exam_struct(exam_id, course.id) except KeyError: exam = {} abort(404) Exams.unsubmit(exam_id, student_uid) user = Users2.get_user(student_uid) flash("""Assessment for %s unsubmitted and timer reset.""" % user["uname"]) return redirect(url_for("cadmin_exam_viewmarked", course_id=course.id, exam_id=exam["id"], student_uid=student_uid))
def login_webauth_submit(): """ The web server should have verified their credentials and provide it in env['REMOTE_USER'] Check them, then set up the session or redirect back with an error. If we haven't seen them before, check with our user account feed(s) to see if we can find them. """ if 'REMOTE_USER' not in request.environ: L.error("REMOTE_USER not provided by web server and 'webauth' is being attempted.") return redirect(url_for("login_webauth_error")) username = request.environ['REMOTE_USER'] if '@' in username and OaConfig.webauth_ignore_domain: username = username.split('@')[0] user_id = Users2.uid_by_uname(username) if not user_id: Users2.create(username, '', '', '', 1, '', '', None, 'unknown', '', True) user_id = Users2.uid_by_uname(username) user = Users2.get_user(user_id) session['username'] = username session['user_id'] = user_id session['user_givenname'] = user['givenname'] session['user_familyname'] = user['familyname'] session['user_fullname'] = user['fullname'] session['user_authtype'] = "httpauth" audit(1, user_id, user_id, "UserAuth", "%s successfully logged in via webauth" % session['username']) if 'redirect' in session: target = OaConfig.parentURL + session['redirect'] del session['redirect'] return redirect(target) return redirect(url_for("main_top"))
def setup_usersummary(view_id): """ Show an account summary for the given user account. """ user_id = session['user_id'] if not check_perm(user_id, -1, "useradmin"): flash("You do not have User Administration access.") return redirect(url_for('setup_top')) is_sysadmin = check_perm(user_id, -1, 'sysadmin') user = Users2.get_user(view_id) examids = Exams.get_exams_done(view_id) exams = [] for examid in examids: exam = Exams.get_exam_struct(examid) started = General.human_date(exam['start']) exam['started'] = started exam['viewable'] = satisfy_perms(user_id, exam['cid'], ("viewmarks", )) exams.append(exam) exams.sort(key=lambda x: x['start_epoch'], reverse=True) course_ids = Users2.get_courses(view_id) courses = [] for course_id in course_ids: courses.append(Courses.get_course(course_id)) user_is_admin = check_perm(view_id, 0, 'sysadmin') return render_template( 'setup_usersummary.html', user=user, exams=exams, courses=courses, is_sysadmin=is_sysadmin, user_is_admin=user_is_admin )
def cadmin_exam_results(course_id, exam_id): """ View the results of an assessment """ course = Courses2.get_course(course_id) if not course: abort(404) exam = Exams.get_exam_struct(exam_id, course_id) if not exam: abort(404) if not int(exam['cid']) == int(course_id): flash("Assessment %s does not belong to this course." % int(exam_id)) return redirect(url_for('cadmin_top', course_id=course_id)) exam['start_date'] = int(date_from_py2js(exam['start'])) exam['end_date'] = int(date_from_py2js(exam['end'])) exam['start_hour'] = int(exam['start'].hour) exam['end_hour'] = int(exam['end'].hour) exam['start_minute'] = int(exam['start'].minute) exam['end_minute'] = int(exam['end'].minute) groups = [ Groups.Group(g_id=g_id) for g_id in Groups.active_by_course(course_id) ] results = {} uids = set([]) totals = {} for group in groups: results[group.id] = Exams.get_marks(group, exam_id) for user_id in results[group.id]: uids.add(user_id) if user_id not in totals: totals[user_id] = 0.0 for qt, val in results[group.id][user_id].iteritems(): totals[user_id] += val['score'] questions = Exams.get_qts_list(exam_id) users = {} for uid in uids: users[uid] = Users2.get_user(uid) return render_template("cadmin_examresults.html", course=course, exam=exam, results=results, groups=groups, users=users, questions=questions, when=datetime.now().strftime("%H:%m, %a %d %b %Y"), totals=totals)
def setup_user_remove_sysadmin(): """ Remove sysadmin""" user_id = session['user_id'] if not check_perm(user_id, 0, 1): flash("You do not have User Administration access.") return redirect(url_for('setup_top')) new_user = request.form.get('userid', None) if not new_user: abort(400) user = Users2.get_user(new_user) delete_perm(new_user, 0, 1) flash("%s is no longer a system admin on OASIS" % user['uname']) return redirect(url_for("setup_usersearch"))
def cadmin_permissions(course_id): """ Present a page for them to assign permissions to the course""" course = Courses2.get_course(course_id) permlist = Permissions.get_course_perms(course_id) perms = {} for uid, pid in permlist: # (uid, permission) if not uid in perms: user = Users2.get_user(uid) perms[uid] = {"uname": user["uname"], "fullname": user["fullname"], "pids": []} perms[uid]["pids"].append(pid) return render_template( "courseadmin_permissions.html", perms=perms, course=course, pids=[5, 10, 14, 11, 8, 9, 15, 2] )
def setup_useraudit(audit_id): """ Show all the audit entries for the given user account. """ user_id = session['user_id'] if not check_perm(user_id, -1, "useradmin"): flash("You do not have User Administration access.") return redirect(url_for('setup_top')) user = Users2.get_user(audit_id) audits = get_records_by_user(audit_id) for aud in audits: aud['humantime'] = General.human_date(aud['time']) return render_template( 'setup_useraudit.html', user=user, audits=audits )
def cadmin_exam_unsubmit(course_id, exam_id, student_uid): """ "unsubmit" the student's assessment and reset their timer so they can log back on and have another attempt. """ try: exam = Exams.get_exam_struct(exam_id, course_id) except KeyError: exam = {} abort(404) Exams.unsubmit(exam_id, student_uid) user = Users2.get_user(student_uid) flash("""Assessment for %s unsubmitted and timer reset.""" % user['uname']) return redirect( url_for("cadmin_exam_viewmarked", course_id=course_id, exam_id=exam['id'], student_uid=student_uid))
def cadmin_editgroup(course_id, group_id): """ Present a page for editing a group, membership, etc. """ group = None try: group = Groups.Group(group_id) except KeyError: abort(404) if not group: abort(404) course = Courses2.get_course(course_id) if not course: abort(404) ulist = group.members() members = [Users2.get_user(uid) for uid in ulist] return render_template("courseadmin_editgroup.html", course=course, group=group, members=members)
def cadmin_remove_coord(course_id, coordname): """ Remove someone as course coordinator """ course = Courses2.get_course(course_id) if not course: abort(404) try: new_uid = Users2.uid_by_uname(coordname) except KeyError: flash("User '%s' Not Found" % coordname) else: if not new_uid: flash("User '%s' Not Found" % coordname) else: Permissions.delete_perm(new_uid, course_id, 3) # courseadmin Permissions.delete_perm(new_uid, course_id, 4) # coursecoord flash("%s can no longer control the course." % (coordname,)) return redirect(url_for('cadmin_config', course_id=course_id))
def cadmin_remove_coord(course_id, coordname): """ Remove someone as course coordinator """ course = Courses2.get_course(course_id) if not course: abort(404) try: new_uid = Users2.uid_by_uname(coordname) except KeyError: flash("User '%s' Not Found" % coordname) else: if not new_uid: flash("User '%s' Not Found" % coordname) else: Permissions.delete_perm(new_uid, course_id, 3) # courseadmin Permissions.delete_perm(new_uid, course_id, 4) # coursecoord flash("%s can no longer control the course." % (coordname, )) return redirect(url_for('cadmin_config', course_id=course_id))
def cadmin_permissions(course_id): """ Present a page for them to assign permissions to the course""" course = Courses2.get_course(course_id) permlist = Permissions.get_course_perms(course_id) perms = {} for uid, pid in permlist: # (uid, permission) if uid not in perms: user = Users2.get_user(uid) perms[uid] = { 'uname': user['uname'], 'fullname': user['fullname'], 'pids': [] } perms[uid]['pids'].append(pid) return render_template("courseadmin_permissions.html", perms=perms, course=course, pids=[5, 10, 14, 11, 8, 9, 15, 2])
def cadmin_config(course_id): """ Allow some course configuration """ course = Courses2.get_course(course_id) if not course: abort(404) user_id = session["user_id"] is_sysadmin = check_perm(user_id, -1, "sysadmin") coords = [ Users2.get_user(perm[0]) for perm in Permissions.get_course_perms(course_id) if perm[1] == 3 ] # course_coord groups = Courses.get_groups(course_id) choosegroups = [group for group in Groups.all_groups() if not group.id in groups] return render_template( "courseadmin_config.html", course=course, coords=coords, choosegroups=choosegroups, groups=groups, is_sysadmin=is_sysadmin, )
def cadmin_config(course_id): """ Allow some course configuration """ course = Courses2.get_course(course_id) if not course: abort(404) user_id = session['user_id'] is_sysadmin = check_perm(user_id, -1, 'sysadmin') coords = [ Users2.get_user(perm[0]) for perm in Permissions.get_course_perms(course_id) if perm[1] == 3 ] # course_coord groups = Courses.get_groups(course_id) choosegroups = [ group for group in Groups.all_groups() if group.id not in groups ] return render_template("courseadmin_config.html", course=course, coords=coords, choosegroups=choosegroups, groups=groups, is_sysadmin=is_sysadmin)
def save_perms(request, cid, user_id): """ Save permission changes """ permlist = get_course_perms(cid) perms = {} users = {} for perm in permlist: u = Users2.get_user(perm[0]) uname = u['uname'] if uname not in users: users[uname] = {} users[uname]['fullname'] = u['fullname'] if uname not in perms: perms[uname] = [] perms[uname].append(int(perm[1])) form = request.form if form: # we received a form submission, work out changes and save them fields = [field for field in form.keys() if field[:5] == "perm_"] newperms = {} for field in fields: uname = field.split('_')[1] perm = int(field.split('_')[2]) if uname not in newperms: newperms[uname] = [] newperms[uname].append(perm) for uname in users: uid = Users2.uid_by_uname(uname) for perm in [2, 5, 10, 14, 11, 8, 9, 15]: if uname in newperms and perm in newperms[uname]: if perm not in perms[uname]: add_perm(uid, cid, perm) audit( 1, user_id, uid, "CourseAdmin", "%s given %s permission by %s" % ( uname, get_perm_short(perm), user_id, )) else: if uname in perms and perm in perms[uname]: delete_perm(uid, cid, perm) audit( 1, user_id, uid, "CourseAdmin", "%s had %s permission revoked by %s" % ( uname, get_perm_short(perm), user_id, )) for uname in newperms: uid = Users2.uid_by_uname(uname) if uname not in perms: # We've added a user for perm in [2, 5, 10, 14, 11, 8, 9, 15]: if perm in newperms[uname]: add_perm(uid, cid, perm) audit( 1, user_id, uid, "CourseAdmin", "%s given %s permission by %s" % ( uname, get_perm_short(perm), user_id, )) if "adduser" in form: newuname = form['adduser'] newuid = Users2.uid_by_uname(newuname) if newuid: add_perm(newuid, cid, 10) audit( 1, user_id, newuid, "CourseAdmin", "%s given '%s' permission by %s" % ( newuname, get_perm_short(10), user_id, )) return
def login_signup_submit(): """ They've entered some information and want an account. Do some checks and send them a confirmation email if all looks good. """ # TODO: How do we stop someone using this to spam someone? if not OaConfig.open_registration: abort(404) form = request.form if not ('username' in form and 'password' in form and 'confirm' in form and 'email' in form): flash("Please fill in all fields") return redirect(url_for("login_signup")) username = sanitize_username(form['username']) password = form['password'] confirm = form['confirm'] email = form['email'] if username == "" or password == "" or confirm == "" or email == "": flash("Please fill in all fields") return redirect(url_for("login_signup")) if not confirm == password: flash("Passwords don't match") return redirect(url_for("login_signup")) # basic checks in case they entered their street address or something # a fuller check is too hard or prone to failure if "@" not in email or "." not in email: flash("Email address doesn't appear to be valid") return redirect(url_for("login_signup")) existing = Users2.uid_by_uname(username) if existing: flash("An account with that name already exists, " "please try another username.") return redirect(url_for("login_signup")) code = Users.gen_confirm_code() newuid = Users.create(uname=username, passwd="NOLOGIN", email=email, givenname=username, familyname="", acctstatus=1, studentid="", source="local", confirm_code=code, confirm=False) Users2.set_password(newuid, password) text_body = render_template(os.path.join("email", "confirmation.txt"), code=code) html_body = render_template(os.path.join("email", "confirmation.html"), code=code) send_email(email, from_addr=None, subject="OASIS Signup Confirmation", text_body=text_body, html_body=html_body) return render_template("login_signup_submit.html", email=email)
def exam_results_as_spreadsheet(course_id, group, exam_id): """ Export the assessment results as a XLSX spreadsheet """ course = Courses2.get_course(course_id) exam = Exams.get_exam_struct(exam_id, course_id) uids = set([]) totals = {} results = Exams.get_marks(group, exam_id) for user_id in results: uids.add(user_id) if user_id not in totals: totals[user_id] = 0.0 for qt, val in results[user_id].iteritems(): totals[user_id] += val['score'] questions = Exams.get_qts_list(exam_id) users = {} for uid in uids: users[uid] = Users2.get_user(uid) wb = Workbook() ws = wb.get_active_sheet() ws.title = "Results" ws.cell(row=1, column=0).value = course['name'] ws.cell(row=1, column=1).value = course['title'] ws.cell(row=2, column=0).value = "Assessment:" ws.cell(row=2, column=1).value = exam['title'] ws.cell(row=3, column=0).value = "Group:" ws.cell(row=3, column=1).value = group.name col = 5 qcount = 1 for _ in questions: ws.cell(row=4, column=col).value = "Q%s" % qcount qcount += 1 col += 1 ws.cell(row=4, column=col).value = "Total" row = 5 sortusers = users.keys() sortusers.sort(key=lambda us: users[us]['familyname']) for user_id in sortusers: result = results[user_id] ws.cell(row=row, column=0).value = users[user_id]['uname'] ws.cell(row=row, column=1).value = users[user_id]['student_id'] ws.cell(row=row, column=2).value = users[user_id]['familyname'] ws.cell(row=row, column=3).value = users[user_id]['givenname'] ws.cell(row=row, column=4).value = users[user_id]['email'] col = 5 for pos in questions: for qt in pos: if qt['id'] in result: ws.cell(row=row, column=col).value = result[qt['id']]['score'] col += 1 ws.cell(row=row, column=col).value = totals[user_id] row += 1 return save_virtual_workbook(wb)
def save_perms(request, cid, user_id): """ Save permission changes """ permlist = get_course_perms(cid) perms = {} users = {} for perm in permlist: u = Users2.get_user(perm[0]) uname = u['uname'] if not uname in users: users[uname] = {} users[uname]['fullname'] = u['fullname'] if not uname in perms: perms[uname] = [] perms[uname].append(int(perm[1])) form = request.form if form: # we received a form submission, work out changes and save them fields = [field for field in form.keys() if field[:5] == "perm_"] newperms = {} for field in fields: uname = field.split('_')[1] perm = int(field.split('_')[2]) if not uname in newperms: newperms[uname] = [] newperms[uname].append(perm) for uname in users: uid = Users2.uid_by_uname(uname) for perm in [2, 5, 10, 14, 11, 8, 9, 15]: if uname in newperms and perm in newperms[uname]: if not perm in perms[uname]: add_perm(uid, cid, perm) audit( 1, user_id, uid, "CourseAdmin", "%s given %s permission by %s" % (uname, get_perm_short(perm), user_id,) ) else: if uname in perms and perm in perms[uname]: delete_perm(uid, cid, perm) audit( 1, user_id, uid, "CourseAdmin", "%s had %s permission revoked by %s" % (uname, get_perm_short(perm), user_id,) ) for uname in newperms: uid = Users2.uid_by_uname(uname) if not uname in perms: # We've added a user for perm in [2, 5, 10, 14, 11, 8, 9, 15]: if perm in newperms[uname]: add_perm(uid, cid, perm) audit( 1, user_id, uid, "CourseAdmin", "%s given %s permission by %s" % (uname, get_perm_short(perm), user_id,) ) if "adduser" in form: newuname = form['adduser'] newuid = Users2.uid_by_uname(newuname) if newuid: add_perm(newuid, cid, 10) audit( 1, user_id, newuid, "CourseAdmin", "%s given '%s' permission by %s" % (newuname, get_perm_short(10), user_id,) ) return
def setup_usercreate(): """ Show a page allowing the admin to enter user details to create an account. """ user_id = session['user_id'] if not check_perm(user_id, -1, "useradmin"): flash("You do not have User Administration access.") return redirect(url_for('setup_top')) new_uname = "" new_fname = "" new_sname = "" new_email = "" new_pass = "" new_confirm = "" error = None if request.method == "POST": form = request.form if "usercreate_cancel" in form: flash("User Account Creation Cancelled") return redirect(url_for('setup_usersearch')) if "usercreate_save" in form: new_uname = form.get('new_uname', "") new_fname = form.get('new_fname', "") new_sname = form.get('new_sname', "") new_email = form.get('new_email', "") new_pass = form.get('new_pass', "") new_confirm = form.get('new_confirm', "") if not all((new_uname, new_email, new_pass, new_confirm)): error = "Please fill in all fields." elif Users2.uid_by_uname(new_uname): error = "ERROR: An account already exists with that name" elif new_confirm == "" or not new_confirm == new_pass: error = "Passwords don't match (or are empty)" else: # yaay, it's ok # uname, passwd, givenname, familyname, acctstatus, # studentid, email=None, expiry=None, source="local" Users2.create(new_uname, "nologin-creation", new_fname, new_sname, 2, '', new_email) Users2.set_password(Users2.uid_by_uname(new_uname), new_pass) flash("New User Account Created for %s" % new_uname) new_uname = "" new_fname = "" new_sname = "" new_email = "" new_pass = "" new_confirm = "" if error: flash(error) return render_template( 'setup_usercreate.html', new_uname=new_uname, new_fname=new_fname, new_sname=new_sname, new_email=new_email, new_pass=new_pass, new_confirm=new_confirm )
def setup_usercreate(): """ Show a page allowing the admin to enter user details to create an account. """ user_id = session['user_id'] if not check_perm(user_id, -1, "useradmin"): flash("You do not have User Administration access.") return redirect(url_for('setup_top')) new_uname = "" new_fname = "" new_sname = "" new_email = "" new_pass = "" new_confirm = "" error = None if request.method == "POST": form = request.form if "usercreate_cancel" in form: flash("User Account Creation Cancelled") return redirect(url_for('setup_usersearch')) if "usercreate_save" in form: new_uname = form.get('new_uname', "") new_fname = form.get('new_fname', "") new_sname = form.get('new_sname', "") new_email = form.get('new_email', "") new_pass = form.get('new_pass', "") new_confirm = form.get('new_confirm', "") if not all((new_uname, new_email, new_pass, new_confirm)): error = "Please fill in all fields." elif Users2.uid_by_uname(new_uname): error = "ERROR: An account already exists with that name" elif new_confirm == "" or not new_confirm == new_pass: error = "Passwords don't match (or are empty)" else: # yaay, it's ok # uname, passwd, givenname, familyname, acctstatus, # studentid, email=None, expiry=None, source="local" Users2.create(new_uname, "nologin-creation", new_fname, new_sname, 2, '', new_email) Users2.set_password(Users2.uid_by_uname(new_uname), new_pass) flash("New User Account Created for %s" % new_uname) new_uname = "" new_fname = "" new_sname = "" new_email = "" new_pass = "" new_confirm = "" if error: flash(error) return render_template('setup_usercreate.html', new_uname=new_uname, new_fname=new_fname, new_sname=new_sname, new_email=new_email, new_pass=new_pass, new_confirm=new_confirm)