def faculty_telegram_GetChatLink(requests): response = {'faculty_telegram_GetChatLink': 'active'} # Redirect user to login page if not authorized and faculty try: processLogin.InstructorVerification(requests) except: logout(requests) return render(requests, 'Module_Account/login.html', response) telegram_chat_name = requests.GET.get('telegram_chat_name') try: telegram_chatObj = Telegram_Chats.objects.get(name=telegram_chat_name) if telegram_chatObj.link == None: response[ 'error_message'] = 'There is no telegram chat link found in the database for this chat at the moment. Please wait a few minutes for the system to update.\n\nIf the problem persist, please check with system administrator.' response['telegram_chat_link'] = telegram_chatObj.link response['telegram_chat_name'] = telegram_chat_name except: traceback.print_exc() return HttpResponse(json.dumps(response), content_type='application/json')
def faculty_HomePage(requests): context = {'faculty_DashboardPage': "active"} # Redirect user to login page if not authorized and faculty try: processLogin.InstructorVerification(requests) except: logout(requests) return render(requests, 'Module_Account/login.html', context) requests.session['userType'] = "Instructor" faculty_username = requests.user.email.split('@')[0] all_SocialAccount = SocialAccount.objects.all() for each_SocialAccount in all_SocialAccount: data = each_SocialAccount.extra_data if data['email'] == requests.user.email: requests.session['user_picture'] = data['picture'] requests.session['user_name'] = data['name'].replace('_', '').strip() try: #Populates the info for the side nav bar for instructor utilities.populateRelevantCourses(requests, instructorEmail=requests.user.email) except Exception as e: traceback.print_exc() context['error_message'] = e.args[0] context['course_section_count'] = len( requests.session['courseList_updated']) context['ITOpsLab_count'] = len(requests.session['courseList_ITOpsLab']) return render(requests, 'Module_TeamManagement/Instructor/instructorDashboard.html', context)
def faculty_Setup_GetAMI(requests): response = {"facutly_Setup_GetAMI": "active"} # Redirect user to login page if not authorized and student try: processLogin.InstructorVerification(requests) except: logout(requests) return render(requests, 'Module_Account/login.html', response) section_number = requests.GET.get('section_number') try: response['images'] = [] response['section_number'] = section_number faculty_email = requests.user.email facultyObj = Faculty.objects.get(email=faculty_email) aws_credentialsObj = facultyObj.awscredential if aws_credentialsObj != None: images_detailObjs = aws_credentialsObj.imageDetails.all() for image in images_detailObjs: response['images'].append({ 'image_name': image.imageName, 'image_id': image.imageId }) except Exception as e: traceback.print_exc() response['error_message'] = 'Error in Get AMI form: ' + e.args[0] return faculty_Setup_Base(requests, response) return HttpResponse(json.dumps(response), content_type='application/json')
def faculty_Event_Base(requests, response=None): response = {"faculty_Event_Base": "active"} # Redirect user to login page if not authorized and student try: processLogin.InstructorVerification(requests) except: logout(requests) return render(requests, 'Module_Account/login.html', response) try: course_title = requests.GET.get('course_title') course_sectionList = requests.session['courseList_ITOpsLab'] response['course_sectionList'] = course_sectionList[course_title] response['course_title'] = course_title # faculty_email = requests.user.email # facultyObj = Faculty.objects.get(email=faculty_email) except Exception as e: traceback.print_exc() response['error_message'] = 'Error during event execution: ' + str( e.args[0]) return render(requests, "Module_TeamManagement/Instructor/ITOpsLabEvent.html", response) return render(requests, "Module_TeamManagement/Instructor/ITOpsLabEvent.html", response)
def faculty_Setup_GetAMIAccounts(requests): response = {"faculty_Setup_GetAMIAccounts": "active"} # Redirect user to login page if not authorized and student try: processLogin.InstructorVerification(requests) except: logout(requests) return render(requests, 'Module_Account/login.html', response) section_numbers = requests.GET.get('section_number') image_id = requests.GET.get('image_id').strip() course_title = requests.GET.get('course_title').strip() if '_' in section_numbers: section_numbers = section_numbers.split('_') else: section_numbers = [section_numbers] # print(section_numbers) # print(image_id) # print(course_title) try: response['shared_accounts_list'] = [] response['nonshared_accounts_list'] = [] imageObj = Image_Details.objects.get(imageId=image_id) shared_accounts = [] if imageObj.sharedAccNum == None else imageObj.sharedAccNum course_sectionList = requests.session['courseList_ITOpsLab'] section_teamList = utilities.getAllTeamDetails(course_sectionList, course_title) for section_number in section_numbers: for details in section_teamList[section_number]: if details["account_number"] in shared_accounts: response['shared_accounts_list'].append({ 'team_name': details["team_name"], 'account_number': details["account_number"] }) else: response['nonshared_accounts_list'].append({ 'team_name': details["team_name"], 'account_number': details["account_number"] }) except Exception as e: traceback.print_exc() response[ 'error_message'] = 'Error in Get AMI-Accounts form: ' + e.args[0] return faculty_Setup_Base(requests, response) return HttpResponse(json.dumps(response), content_type='application/json')
def test_instructor_verification(self): self.instructor = Faculty.objects.create(email="*****@*****.**",username ="******",firstname="ChuanHui",lastname="Lee") request = self.factory.get('/instructor/home/') request.user = self.instructor try: processLogin.InstructorVerification(request) response = True except: response = False self.assertTrue(response) request.user = None try: processLogin.InstructorVerification(request) response = True except: response = False self.assertFalse(response) Faculty.objects.all().delete()
def faculty_telegram_UpdateChatMembers(requests): response = {"faculty_telegram_UpdateChatMembers": "active"} tele_chat_type = { 'Channel': Channel, 'Group': Chat, } # Redirect user to login page if not authorized and faculty try: processLogin.InstructorVerification(requests) except: logout(requests) return render(requests, 'Module_Account/login.html', response) course_section = requests.POST.get('course_section') telegram_chat_name = requests.POST.get('chat_name').replace('_', ' ') print('Telegram Chat Name: ' + telegram_chat_name) print('Course Section: ' + course_section) try: telegram_chat = Telegram_Chats.objects.get(name=telegram_chat_name) client = tele_util.getClient(requests.user.email.split('@')[0]) try: members, count = tele_util.getMembers( client, telegram_chat.name, tele_chat_type[telegram_chat.type]) except OperationalError: raise Exception( 'Please wait a few minutes for the chat to be initialize, before updating chat members. If the problem persist, please check with system administrator.' ) if count > 0: telegram_chat.members = '_'.join(members) telegram_chat.save() else: # telegram_chat.delete() raise Exception( 'Chat does not exists within Telegram client. Please remove chat from the system.' ) tele_util.disconnectClient(client) except Exception as e: # traceback.print_exc() requests.POST = requests.POST.copy() requests.POST['chat_name'] = None response['courses'] = requests.session['courseList_updated'] response['error_message'] = str(e.args[0]) return faculty_telegram_Base(requests, response) requests.POST = requests.POST.copy() requests.POST['chat_name'] = telegram_chat_name response['message'] = 'Members successfully updated' return faculty_telegram_Base(requests, response)
def faculty_telegram_CreateGroup(requests): response = {"faculty_telegram_CreateGroup": "active"} # Redirect user to login page if not authorized and faculty try: processLogin.InstructorVerification(requests) except: logout(requests) return render(requests, 'Module_Account/login.html', response) group_name = requests.POST.get('group_name') additional_username = '******' course_section = requests.POST.get('course_section') print('Group Name: ' + group_name) print('Course Section: ' + course_section) print('Additional Username: '******'Group', ) telegram_chat.save() except: telegram_chat = Telegram_Chats.objects.get(name=group_name) username = requests.user.email.split('@')[0] tasks.createGroup( username=username, group_name=group_name, additional_username=additional_username, schedule=0, ) # Assign to the students of the course_section class_QuerySet = Class.objects.filter(course_section=course_section) for student in class_QuerySet: student.telegram_chats.add(telegram_chat) student.save() except Exception as e: traceback.print_exc() response['courses'] = requests.session['courseList_updated'] response[ 'error_message'] = 'Error during Telegram group creation: ' + str( e.args[0]) return faculty_telegram_Base(requests, response) response['message'] = 'Telegram Group successfully created' return faculty_telegram_Base(requests, response)
def aboutCloudtopus(requests): context={} userEmail = requests.user.email try: processLogin.studentVerification(requests) context['userTypeExtension'] = "Module_TeamManagement/Student/studentBase.html" except: try: processLogin.InstructorVerification(requests) context['userTypeExtension'] = "Module_TeamManagement/Instructor/instructorBase.html" except: logout(requests) return render(requests, 'Module_Account/login.html', response) return render(requests,"Module_TeamManagement/aboutCloudtopus.html",context)
def faculty_Event_GetServers(requests): response = {"faculty_Event_GetServers": "active"} # Redirect user to login page if not authorized and student try: processLogin.InstructorVerification(requests) except: logout(requests) return render(requests, 'Module_Account/login.html', response) section_numbers = requests.GET.get('section_number').split('_') course_title = requests.GET.get('course_title') try: courseList = requests.session['courseList_ITOpsLab'] team_account_numberList = utilities_DM.getAllTeamDetails( courseList, course_title) servers = [] parent = False slave = False for section_number in section_numbers: for team in team_account_numberList[section_number]: try: serverObjs = Server_Details.objects.filter( account_number=team['account_number']) for serverObj in serverObjs: servers.append(serverObj) if serverObj.type == 'Parent': parent = True elif serverObj.type == 'Slave': slave = True except: traceback.print_exc() response['server_count'] = len(servers) response['server_parent_check'] = parent response['server_slave_check'] = slave except: traceback.print_exc() return HttpResponse(json.dumps(response), content_type='application/json')
def faculty_telegram_DeleteChat(requests): response = {'faculty_telegram_DeleteChat': 'active'} # Redirect user to login page if not authorized and faculty try: processLogin.InstructorVerification(requests) except: logout(requests) return render(requests, 'Module_Account/login.html', response) telegram_chat_name = requests.POST.get('chat_name').replace('_', ' ') telegram_chat_type = requests.POST.get('chat_type') print('Telegram Chat Name: ' + str(telegram_chat_name)) print('Telegram Chat Type: ' + str(telegram_chat_type)) try: facultyObj = Faculty.objects.get(email=requests.user.email) tasks.deleteChat( username=requests.user.email.split('@')[0], telegram_username=facultyObj.telegram_username, chat_name=telegram_chat_name, chat_type=telegram_chat_type, schedule=0, ) telegram_chatObj = Telegram_Chats.objects.get(name=telegram_chat_name) telegram_chatObj.delete() requests.POST = requests.POST.copy() requests.POST['chat_name'] = None except Exception as e: traceback.print_exc() response['courses'] = requests.session['courseList_updated'] response[ 'error_message'] = 'Error during deletion of Telegram chat: ' + str( e.args[0]) return faculty_telegram_Base(requests, response) response['message'] = 'Telegram chat successfully deleted' return faculty_telegram_Base(requests, response)
def faculty_Setup_GetAWSKeys(requests): response = {"faculty_Setup_GetAWSKeys": "active"} # Redirect user to login page if not authorized and student try: processLogin.InstructorVerification(requests) except: logout(requests) return render(requests, 'Module_Account/login.html', response) account_number = requests.POST.get('account_number') access_key = requests.POST.get('access_key') secret_access_key = requests.POST.get('secret_access_key') try: if account_number == None or access_key == None or secret_access_key == None: raise Exception( 'Please input an account_number, access_key and secret_access_key' ) faculty_email = requests.user.email facultyObj = Faculty.objects.get(email=faculty_email) # Validate if account_number is a valid account_number valid = aws_util.validateAccountNumber(account_number, access_key, secret_access_key) if not valid: raise Exception( "Invalid parameters. Please specify a valid account number.") # try:UPDATE, except:SAVE Account_Number, Access_Key and Secret_Access_Key to AWS_Credentials try: credentialsObj = facultyObj.awscredential old_account_number = credentialsObj.account_number # Create NEW AWS_Credentials credentialsObj.account_number = account_number credentialsObj.access_key = encode(access_key) credentialsObj.secret_access_key = encode(secret_access_key) credentialsObj.save() facultyObj.awscredential = credentialsObj facultyObj.save() # Delete OLD AWS_Credentials and Images tied to it old_credentialsObj = AWS_Credentials.objects.get( account_number=old_account_number) imageObjs = old_credentialsObj.imageDetails.all() for imageObj in imageObjs: imageObj.delete() old_credentialsObj.delete() except: access_key = encode(access_key) secret_access_key = encode(secret_access_key) credentialsObj = AWS_Credentials.objects.create( account_number=account_number, access_key=access_key, secret_access_key=secret_access_key, ) credentialsObj.save() facultyObj.awscredential = credentialsObj facultyObj.save() response['message'] = 'Successfully updated AWS Credentials' except Exception as e: traceback.print_exc() response['error_message'] = 'Error in AWS Information form: ' + str( e.args[0]) return faculty_Setup_Base(requests, response) return faculty_Setup_Base(requests, response)
def faculty_Setup_Base(requests, response=None): if response == None: response = {"faculty_Setup_Base": "active"} # Redirect user to login page if not authorized and student try: processLogin.InstructorVerification(requests) except: logout(requests) return render(requests, 'Module_Account/login.html', response) faculty_email = requests.user.email facultyObj = Faculty.objects.get(email=faculty_email) if requests.method == 'GET': course_title = requests.GET.get('course_title') else: course_title = requests.POST.get('course_title') response['course_title'] = course_title response['first_section'] = requests.session['courseList_updated'][ course_title][0]['section_number'] try: response['deployment_packages'] = [] response['account_number'] = '' response['access_key'] = '' response['secret_access_key'] = '' response['section_numbers'] = [] # Retrieve Setions that are under Course section registered for ITopslab for faculty course_sectionList = requests.session['courseList_updated'][ course_title] for course_section in course_sectionList: response['section_numbers'].append( course_section['section_number']) # Retrieve GitHub link from Deployment_Package deployment_packageObjs = Deployment_Package.objects.all() if len(deployment_packageObjs) > 0: for deployment_packageObj in deployment_packageObjs: response['deployment_packages'].append({ 'package_name': deployment_packageObj.deployment_name, 'package_link': deployment_packageObj.deployment_link }) response['dps_count'] = len(response['deployment_packages']) # Retrieve Access_Key and Secret_Access_Key from AWS_Credentials aws_credentials = facultyObj.awscredential if aws_credentials != None: response['account_number'] = aws_credentials.account_number response['access_key'] = decode(aws_credentials.access_key) response['secret_access_key'] = decode( aws_credentials.secret_access_key) # Compare AWS data with DB data; IF not in DB, add into DB image_list = aws_util.getAllImages(response['account_number'], response['access_key'], response['secret_access_key']) for image in image_list: if len(aws_credentials.imageDetails.all()) == 0: image_detailsObj = utilities.addImageDetails(image) aws_credentials.imageDetails.add(image_detailsObj) else: querySet = aws_credentials.imageDetails.filter( imageId=image['Image_ID']) if len(querySet) == 0: image_detailsObj = utilities.addImageDetails(image) aws_credentials.imageDetails.add(image_detailsObj) else: imageObj = querySet[0] shared_acct_nums = [] if imageObj.sharedAccNum == None else imageObj.sharedAccNum.split( '_') registered_acct_nums = utilities.getRegisteredUsers( image['Launch_Permissions']) # Add Image to AWS_Credentials for acct in registered_acct_nums: utilities.addImageToUser(imageObj, acct) # Remove Image from AWS_Credentials for acct in shared_acct_nums: if acct not in registered_acct_nums: utilities.removeImageFromAUser(imageObj, acct) shared_acct_nums = '_'.join(registered_acct_nums) imageObj.sharedAccNum = None if len( shared_acct_nums) == 0 else shared_acct_nums imageObj.save() # Compare DB data with AWS data: IF not in AWS, delete from DB images = aws_credentials.imageDetails.all() for image_detailObj in images: db_image_id = image_detailObj.imageId match = False for image in image_list: aws_image_id = image['Image_ID'] if db_image_id == aws_image_id: match = True if not match: image_detailObj.delete() except Exception as e: traceback.print_exc() response[ 'error_message'] = 'Error during retrieval of information (Setup): ' + str( e.args[0]) return render(requests, "Module_TeamManagement/Instructor/ITOpsLabSetup.html", response) return render(requests, "Module_TeamManagement/Instructor/ITOpsLabSetup.html", response)
def faculty_Dashboard(requests): context = {"faculty_Dashboard": "active"} # Redirect user to login page if not authorized and faculty try: processLogin.InstructorVerification(requests) except: logout(requests) return render(requests, 'Module_Account/login.html', context) requests.session['userType'] = "Instructor" faculty_username = requests.user.email.split('@')[0] all_SocialAccount = SocialAccount.objects.all() for each_SocialAccount in all_SocialAccount: data = each_SocialAccount.extra_data if data['email'] == requests.user.email: requests.session['user_picture'] = data['picture'] requests.session['user_name'] = data['name'].replace('_', '').strip() try: courseStudents = [] #Populates the info for the side nav bar for instructor utilities.populateRelevantCourses(requests, instructorEmail=requests.user.email) facultyObj = Faculty.objects.get(email=requests.user.email) registered_course_section = facultyObj.course_section.all() courses = {} students = [] tele_data = {} previouscourse = "a" #filler for course_section in registered_course_section: course_title = course_section.course.course_title if "G0" in (course_section.course_section_id): courses[course_title] = {"count": 0, "sectionCount": 0} else: if course_title not in courses: courses[course_title] = {} if previouscourse != "a": courses[previouscourse]["count"] = len(courseStudents) courses[previouscourse][ "sectionCount"] = sectionCounter courses[previouscourse]["toolImage_list"] = toolsList courseStudents = [] previoussection = "a" previouscourse = course_title sectionCounter = 0 toolsList = [] if previoussection != course_section: sectionCounter += 1 classObj = Class.objects.all().filter( course_section=course_section) for student in classObj: students.append(student) courseStudents.append(student) try: currentCourseTools = course_section.learning_tools.split( "_") for tools in currentCourseTools: if tools not in toolsList: toolsList.append(tools) except: pass previoussection = course_section if previouscourse != "a": courses[previouscourse]["count"] = len(courseStudents) courses[previouscourse]["sectionCount"] = sectionCounter courses[previouscourse]["toolImage_list"] = toolsList context['section_count'] = len(registered_course_section) context['course_count'] = len(courses) context['course_list'] = courses context['student_count'] = len(students) except: traceback.print_exc() context = {'messages': ['Invalid user account']} return render(requests, 'Module_Account/login.html', context) context["courses"] = requests.session['courseList_updated'] # Get number of weeks since school term start and reamining weeks till school term ends past_weeks, remaining_weeks = utilities.getRemainingWeeks() if past_weeks != None and remaining_weeks != None: context['past_weeks'] = past_weeks context['remaining_weeks'] = remaining_weeks context['progress'] = (past_weeks / (past_weeks + remaining_weeks)) * 100 else: context['past_weeks'] = 0 context['remaining_weeks'] = 0 context['progress'] = 0 # Reads web scrapper results trailResults = utilities.populateTrailheadInformation( requests, instructorEmail=requests.user.email) context.update(trailResults) context[ 'message'] = 'Successful retrieval of faculty\'s overview information' #print(context) return render(requests, "Module_TeamManagement/Instructor/instructorHome.html", context)
def faculty_telegram_SendMessage(requests): response = {"faculty_telegram_SendMessage": "active"} tele_chat_type = { 'Channel': Channel, 'Group': Chat, } # Redirect user to login page if not authorized and faculty try: processLogin.InstructorVerification(requests) except: logout(requests) return render(requests, 'Module_Account/login.html', response) message = requests.POST.get('message') telegram_chat_type = requests.POST.get('telegram_chat_type') telegram_chat_name = requests.POST.get('telegram_chat_name').replace( '_', ' ') print('Telegram Chat Type: ' + telegram_chat_type) print('Telegram Chat Name: ' + telegram_chat_name) print('Message: ' + message) requests.POST = requests.POST.copy() requests.POST['chat_name'] = telegram_chat_name try: client = tele_util.getClient(requests.user.email.split('@')[0]) if message == None or message == '': raise Exception('Please specify a message for broadcasting.') try: telegram_chat = Telegram_Chats.objects.get(name=telegram_chat_name) if not tele_util.dialogExists(client, telegram_chat_name, tele_chat_type[telegram_chat_type]): raise Exception( 'Chat does not exists within Telegram client therefore, message cannot be sent. Please remove chat from the system.' ) except OperationalError: raise Exception( 'Please wait a few minutes for the chat to be initialize, before sending a message. If the problem persist, please check with system administrator.' ) except ObjectDoesNotExist: raise Exception('Chat does not exists within database.') if requests.POST.get('datetime') == 'now' or requests.POST.get( 'setDate') == None: scheduled_datetime = datetime.now() else: scheduled_datetime = (datetime.strptime( requests.POST.get('setDate'), '%Y-%m-%dT%H:%M')) period = scheduled_datetime - datetime.now() tasks.sendMessage( username=requests.user.email.split('@')[0], chat_type=telegram_chat_type, chat_name=telegram_chat_name, message=message, schedule=period, ) except Exception as e: # traceback.print_exc() response['courses'] = requests.session['courseList_updated'] response['error_message'] = str(e.args[0]) return faculty_telegram_Base(requests, response) finally: tele_util.disconnectClient(client) response['message'] = 'Message successfully sent' return faculty_telegram_Base(requests, response)
def faculty_Event_Execute(requests): response = {"faculty_Event_Execute": "active"} events = { 'stop': { 'method': tasks.stopServer, 'message': 'Successfully stopped ', 'message_scheduled': 'Successfully scheduled "STOP" event for ', }, 'dos': { 'method': tasks.dosAttack, 'message': 'Successfully triggered DoS attack to', 'message_scheduled': 'Successfully scheduled "DoS" event for ', }, 'stopapp': { 'method': tasks.stopWebApplication, 'message': 'Successfully killed the web application of ', 'message_scheduled': 'Successfully scheduled "STOP WEB APP" event for ', }, } # Redirect user to login page if not authorized and student try: processLogin.InstructorVerification(requests) except: logout(requests) return render(requests, 'Module_Account/login.html', response) faculty_email = requests.user.email facultyObj = Faculty.objects.get(email=faculty_email) course_sectionList = requests.session['courseList_ITOpsLab'] course_title = requests.POST.get('course_title') section_numberList = requests.POST.getlist('section_number') server_type = requests.POST.get('server_type') event_type = requests.POST.get('event_type') if requests.POST.get('datetime') == 'now' or requests.POST.get( 'setDate') == None: scheduled_datetime = datetime.now() else: scheduled_datetime = (datetime.strptime(requests.POST.get('setDate'), '%Y-%m-%dT%H:%M')) print('Course Title: ' + course_title) print('Section Numbers: ' + '_'.join(section_numberList)) print('Server Type: ' + server_type) print('Event Type: ' + event_type) print('Schedule Datatime: ' + str(scheduled_datetime)) try: serverList = [] team_details = utilities_DM.getAllTeamDetails(course_sectionList, course_title) for section_number in section_numberList: for details in team_details[section_number]: querySet_serverList = Server_Details.objects.filter( account_number=details["account_number"]) for server in querySet_serverList: if server.type == server_type and server.state == 'Live': serverList.append({ 'server_ip': server.IP_address, 'server_id': server.instanceid, 'server_account': server.account_number.account_number }) if len(serverList) > 0: period = scheduled_datetime - datetime.now() events[event_type]['method'](server_list=serverList, schedule=period, section_numbers=section_numberList, server_type=server_type) except Exception as e: traceback.print_exc() response['error_message'] = 'Error during event execution: ' + str( e.args[0]) return render(requests, "Module_TeamManagement/Instructor/ITOpsLabEvent.html", response) requests.section_number = course_sectionList[course_title][0][ 'section_number'] if len(serverList) > 0: if requests.POST.get('datetime') == 'now': response['message'] = events[event_type]['message'] + str( len(serverList)) + ' ' + str(server_type) + ' servers.' time.sleep(6) else: response[ 'message'] = events[event_type]['message_scheduled'] + str( len(serverList)) + ' ' + str(server_type) + ' servers.' else: response['error_message'] = 'All ' + str( server_type ) + ' servers are currently down. Unable to send event to ' + str( server_type) + ' servers.' return views_DM.faculty_Monitor_Base(requests, response)
def faculty_Setup_ShareAMI(requests): response = {"faculty_Setup_ShareAMI": "active"} # Redirect user to login page if not authorized and student try: processLogin.InstructorVerification(requests) except: logout(requests) return render(requests, 'Module_Account/login.html', response) choosen_account_list = requests.POST.getlist('account_numbers') image_id = requests.POST.get('image_id') faculty_email = requests.user.email facultyObj = Faculty.objects.get(email=faculty_email) try: # Get the access_key and secret_access_key from DB aws_credentials = facultyObj.awscredential access_key = decode(aws_credentials.access_key) secret_access_key = decode(aws_credentials.secret_access_key) client = aws_util.getClient(access_key, secret_access_key) if choosen_account_list != None: imageObj = Image_Details.objects.get(imageId=image_id) current_account_list = [] if imageObj.sharedAccNum != None and imageObj.sharedAccNum != ' ' and imageObj.sharedAccNum != '': current_account_list = imageObj.sharedAccNum.split('_') # Step 1: ADD the account number to the image permission on AWS add_list = list( set(choosen_account_list) - set(current_account_list)) if len(add_list) > 0: aws_util.addUserToImage(image_id, add_list, client=client) # Step 2: REMOVE the account number from the image permission on AWS # Updated not required #remove_list = list(set(current_account_list)-set(choosen_account_list)) #if len(remove_list) > 0: # aws_util.removeUserFromImage(image_id,remove_list,client=client) new_account_list = set(choosen_account_list).copy() new_account_list.update(set(add_list)) new_account_list = list(new_account_list) # Step 3: UPDATE image_details table with the new set of shared account numbers imageObj.sharedAccNum = choosen_account_list imageObj.save() # Step 4: ADD the image to AWS_Credentials (Student) for account_number in add_list: utilities.addImageToUser(imageObj, account_number) # Step 5 REMOVE the image from AWS_Credentials (Student) for account_number in remove_list: utilities.removeImageFromAUser(imageObj, account_number) response['message'] = 'Successfully shared Deployment Environment' except Exception as e: traceback.print_exc() response['error_message'] = 'Error in Share AMI form: ' + e.args[0] return faculty_Setup_Base(requests, response) return faculty_Setup_Base(requests, response)
def faculty_Overview(requests): context = {} # Redirect user to login page if not authorized and faculty try: processLogin.InstructorVerification(requests) except: logout(requests) return render(requests, 'Module_Account/login.html', context) context = {"faculty_Overview": "active", 'course': {}} faculty_email = requests.user.email if requests.method == "GET": course_section = requests.GET.get('module') course_title = requests.GET.get('course_title') section_number = requests.GET.get('section_number') else: course_section = requests.POST.get('course_section') course_title = course_section[:-2] section_number = course_section[-2:] # Return sections that's related to the course courseList_updated = requests.session['courseList_updated'] context['course_sectionList'] = courseList_updated[course_title] facultyObj = Faculty.objects.get(email=faculty_email) classObj_list = Class.objects.all().filter(course_section=course_section) trailResults = utilities.populateTrailheadInformation( requests, instructorEmail=requests.user.email) context.update(trailResults) if len(classObj_list) > 0: classList = [] # Containing student class objects for enrolled_class in classObj_list: studentInfo = {} studentInfo['team'] = enrolled_class.team_number studentInfo[ 'info'] = enrolled_class.student #Obtains student model from Foreign key studentUserName = enrolled_class.student.email.split("@")[0] try: studentInfo['link'] = Cloud_Learning_Tools.objects.get( id=studentUserName + "_Trailhead").website_link studentPointsPosition = trailResults['CourseTrailResults'][ 'class']['Students_Information']['students'].index( studentUserName) studentInfo['points'] = trailResults['CourseTrailResults'][ 'class']['Students_Information']['points'][ studentPointsPosition] studentInfo['badges'] = trailResults['CourseTrailResults'][ 'class']['Students_Information']['badges'][ studentPointsPosition] except: studentInfo[ 'link'] = "No link" #Exception which is caused by no cle linked studentInfo['points'] = 0 studentInfo['badges'] = 0 classList.append(studentInfo) context['course']['classList'] = classList course_section = Course_Section.objects.get( course_section_id=course_section) if course_section.section_number == 'G0': context['module'] = course_section.course.course_title else: context[ 'module'] = course_section.course.course_title + " " + course_section.section_number context['course_section'] = Course_Section.objects.get( course=course_title, section_number=section_number) context['user'] = facultyObj context['message'] = 'Successful retrieval of faculty\'s profile' return render(requests, "Module_TeamManagement/Instructor/instructorOverview.html", context)
def faculty_Monitor_Base(requests, response=None): if response == None: response = {"faculty_Monitor_Base": "active"} # Redirect user to login page if not authorized and student try: processLogin.InstructorVerification(requests) except: logout(requests) return render(requests, 'Module_Account/login.html', response) if requests.method == "GET": section_num = requests.GET.get('section_number') course_title = requests.GET.get('course_title') else: section_num = requests.POST.get('section_number') course_title = requests.POST.get('course_title') response['server_status'] = [] response['webapp_status'] = [] response['event_log'] = [] requests.session['ESMCourseSection'] = section_num # Retrieve the team_number and account_number for each section course_sectionList = requests.session['courseList_ITOpsLab'] response['first_section'] = course_sectionList[course_title][0][ 'section_number'] response['course_title'] = course_title response['course_sectionList'] = course_sectionList[course_title] try: if section_num == "GAll": # run all servers all_section_details = [] course_details = utilities.getAllTeamDetails( course_sectionList, course_title) for section_number, section_details in course_details.items(): all_section_details += section_details response = utilities.getAllLog(section_num, response) for details in all_section_details: response = utilities.getMonitoringStatus( details["account_number"], details["team_name"], response) else: section_details = utilities.getAllTeamDetails( course_sectionList, course_title)[section_num] response = utilities.getAllLog(section_num, response) for details in section_details: response = utilities.getMonitoringStatus( details["account_number"], details["team_name"], response) # response['event_log'] = utilities.getEventLogs(details["account_number"],details["team_name"]) except Exception as e: traceback.print_exc() response[ 'error_message'] = 'Error during retrieval of information (Monitoring): ' + str( e.args[0]) return render(requests, "Module_TeamManagement/Instructor/ITOpsLabMonitor.html", response) tz = pytz.timezone('Asia/Singapore') response['last_updated'] = str(datetime.datetime.now(tz=tz))[:19] return render(requests, "Module_TeamManagement/Instructor/ITOpsLabMonitor.html", response)
def faculty_telegram_Base(requests, response=None): if response == None: response = {"faculty_telegram_Base": "active"} # Redirect user to login page if not authorized and faculty try: processLogin.InstructorVerification(requests) except: logout(requests) return render(requests, 'Module_Account/login.html', response) if requests.method == "GET": course_section = requests.GET.get('course_section') telegram_chat_name = requests.GET.get('chat_name') else: course_section = requests.POST.get('course_section') telegram_chat_name = requests.POST.get('chat_name') if course_section == None: return render(requests, 'Module_Account/login.html', response) try: # Retrieve Administritive Stuff courseList_updated = requests.session['courseList_updated'] course_section = Course_Section.objects.get( course_section_id=course_section) response['course_sectionList'] = courseList_updated[ course_section.course.course_title] if course_section.section_number == 'G0': to_string = course_section.course.course_title else: to_string = course_section.course.course_title + " " + course_section.section_number response['current_course_section_details'] = { 'id': course_section.course_section_id, 'course_title': course_section.course.course_title, 'section_number': course_section.section_number, 'to_string': course_section.to_string, } # Retrieve Telegram Stuff telegram_chats = Class.objects.filter( course_section=course_section)[0].telegram_chats.all() response['telegram_chats'] = [] for telegram_chat in telegram_chats: response['telegram_chats'].append({'name': telegram_chat.name}) if len(response['telegram_chats']) > 0: if telegram_chat_name == None: first_chat_name = telegram_chats[0].name response[ 'current_telegram_chat'] = utilities.getTelegramChatJSON( chat_name=first_chat_name) else: telegram_chat = Telegram_Chats.objects.get( name=telegram_chat_name) response[ 'current_telegram_chat'] = utilities.getTelegramChatJSON( chat_obj=telegram_chat) except Exception as e: traceback.print_exc() response[ 'error_message'] = 'Error during retrieval of Telegram details: ' + str( e.args[0]) return render( requests, "Module_TeamManagement/Instructor/TelegramManagement.html", response) return render(requests, "Module_TeamManagement/Instructor/TelegramManagement.html", response)