diff --git a/.profile b/.profile deleted file mode 100644 index df779be..0000000 --- a/.profile +++ /dev/null @@ -1 +0,0 @@ -{'absences': 2, 'address': None, 'counselor': {'first_name': 'Sean', 'full_name': 'Sean Burke', 'id': 37, 'last_name': 'Burke', 'url': 'https://ion.tjhsst.edu/api/profile/37', 'user_type': 'counselor', 'username': 'SPBurke'}, 'display_name': 'Raffu Khondaker', 'emails': [], 'first_name': 'Raffu', 'full_name': 'Raffu Khondaker', 'grade': {'name': 'sophomore', 'number': 10}, 'graduation_year': 2022, 'id': 36508, 'ion_username': '2022rkhondak', 'is_announcements_admin': False, 'is_eighth_admin': False, 'is_student': True, 'is_teacher': False, 'last_name': 'Khondaker', 'middle_name': 'Al', 'nickname': '', 'phones': [], 'picture': 'https://ion.tjhsst.edu/api/profile/36508/picture', 'sex': 'Male', 'short_name': 'Raffu', 'title': None, 'tj_email': '2022rkhondak@tjhsst.edu', 'user_type': 'student', 'websites': []} \ No newline at end of file diff --git a/BackgroundService/bgservice.py b/BackgroundService/bgservice.py index ed26c76..e2c4411 100644 --- a/BackgroundService/bgservice.py +++ b/BackgroundService/bgservice.py @@ -1,58 +1,102 @@ -import os -import sys -import signal import time -import event_processor +import sys +import os +import pyinotify -class SkoolOSDaemon: - """Constructor""" - def __init__(self, work_dir='/tmp'): - self.work_dir = work_dir - self.start_time = None - self.end_time = None - self.log_file = None - def __write_pid_file(self): - try: - dirName = "/tmp/skooloslogs" - # Create log Directory - os.mkdir(dirName) - except FileExistsError: - pass - pid = str(os.getpid()) - file_ = open('/tmp/skoolosdaemonpid', 'w') - file_.write(pid) - file_.close() - def readable_time(self, input_time): - return time.strftime("%A, %B %d, %Y %H:%M:%S", time.localtime(input_time)) - def start(self): - self.__write_pid_file() - self.start_time = time.time() - self.log_file = open('/tmp/skooloslogs/' + str(self.start_time), 'w') - self.log_file.write("Start time: \n" + self.readable_time(self.start_time) + "\n\n") - sys.stdout = self.log_file - event_processor.watch_dir(self.work_dir) - def stop(self): - event_processor.stop_watching() - self.end_time = time.time() - self.log_file.write("Stop time: \n" + self.readable_time(self.end_time)) - self.log_file.write("Total work time: " + - time.strftime("%H:%M:%S", time.gmtime(self.end_time - self.start_time))) +class EventHandler(pyinotify.ProcessEvent): + _methods = [ + "IN_CREATE", + "IN_CLOSE_WRITE", + "IN_DELETE", + "IN_MOVED_TO", + "IN_MOVED_FROM", + "IN_OPEN", + ] + + def process_IN_CREATE(self, event): + description = \ + "Event: Created file\n" \ + "Event Path: {}\n" \ + "Timestamp: {}\n".format( + event.pathname, + time.strftime("%A, %B %d, %Y %H:%M:%S", time.localtime()) + ) + print(description) + + def process_IN_CLOSE_WRITE(self, event): + description = \ + "Event: Wrote to a file\n" \ + "Event Path: {}\n" \ + "Timestamp: {}\n".format( + event.pathname, + time.strftime("%A, %B %d, %Y %H:%M:%S", time.localtime()) + ) + print(description) + + def process_IN_DELETE(self, event): + description = \ + "Event: Deleted file\n" \ + "Event Path: {}\n" \ + "Timestamp: {}\n".format( + event.pathname, + time.strftime("%A, %B %d, %Y %H:%M:%S", time.localtime()) + ) + print(description) + + def process_IN_MOVED_TO(self, event): + description = \ + "Event: Moved a file in\n" \ + "Event Path: {}\n" \ + "Timestamp: {}\n".format( + event.pathname, + time.strftime("%A, %B %d, %Y %H:%M:%S", time.localtime()) + ) + print(description) + + def process_IN_MOVED_FROM(self, event): + description = \ + "Event: Moved a file out\n" \ + "Event Path: {}\n" \ + "Timestamp: {}\n".format( + event.pathname, + time.strftime("%A, %B %d, %Y %H:%M:%S", time.localtime()) + ) + print(description) + + def process_IN_OPEN(self, event): + description = \ + "Event: Opened file\n" \ + "Event Path: {}\n" \ + "Timestamp: {}\n".format( + event.pathname, + time.strftime("%A, %B %d, %Y %H:%M:%S", time.localtime()) + ) + print(description) +NOTIFIER = None -logger = None - -def Main(): - def signal_handler(signum, frame): - logger.stop() - signal.signal(signal.SIGINT, signal_handler) - # signal.signal(signal.SIGTERM, signal_handler) - global logger - logger = SkoolOSDaemon("/tmp") - logger.start() +def watch_dir(watched_dir="/tmp", logdir="/tmp/skooloslogs"): + if not os.path.exists(logdir): + os.makedirs(logdir) + logfile = open( + logdir + "skoolos_" + time.strftime("%m%d%Y-%H%M%S", time.localtime()), + 'w') + sys.stdout = logfile + print("Start time: " + + time.strftime("%A, %B %d, %Y %H:%M:%S", time.localtime()) + "\n\n") + global NOTIFIER + wm = pyinotify.WatchManager() + mask = pyinotify.IN_CREATE | pyinotify.IN_CLOSE_WRITE | pyinotify.IN_DELETE | \ + pyinotify.IN_MOVED_TO | pyinotify.IN_MOVED_FROM | pyinotify.IN_OPEN + NOTIFIER = pyinotify.ThreadedNotifier(wm, EventHandler()) + NOTIFIER.start() + wm.add_watch(watched_dir, mask, rec=True) -if __name__ == "__main__": - Main() +def stop_watching(): + NOTIFIER.stop() + print("End time: " + + time.strftime("%A, %B %d, %Y %H:%M:%S", time.localtime()) + "\n\n") diff --git a/BackgroundService/event_processor.py b/BackgroundService/event_processor.py deleted file mode 100644 index 55c5e15..0000000 --- a/BackgroundService/event_processor.py +++ /dev/null @@ -1,65 +0,0 @@ -import time -import pyinotify - - -def readable_time(input_time): - return time.strftime("%A, %B %d, %Y %H:%M:%S", time.localtime(input_time)) - - -class EventProcessor(pyinotify.ProcessEvent): - _methods = ["IN_OPEN", - "IN_CREATE", - "IN_CLOSE_WRITE", - "IN_DELETE", - "IN_MOVED_TO", - "IN_MOVED_FROM", - ] - - -def __method_format(method): - return { - "IN_OPEN":"Opened a file", - "IN_CREATE":"Created a file", - "IN_CLOSE_WRITE":"Wrote to a file", - "IN_DELETE":"Deleted a file", - "IN_MOVED_TO":"Moved a file or directory in from elsewhere", - "IN_MOVED_FROM":"Moved a file or directory elsewhere", - }.get(method, "Unknown event") - - -def __process_generator(cls, method): - def _method_name(self, event): - description = "Event description: {}\n" \ - "Path name: {}\n" \ - "Event Name: {}\n" \ - "Timestamp: {}\n".format(__method_format(method), - event.pathname, - event.maskname, - readable_time(time.time()) - ) - if "IN_DELETE" in description: - description += "WARNING: Unexpected file deletion\n" - if "IN_MOVED_TO" in description: - description += "WARNING: Unexpected file add to work\n" - if "IN_MOVED_FROM" in description: - description += "WARNING: Unexpected file moved out of directory\n" - print(description) - _method_name.__name__ = "process_{}".format(method) - setattr(cls, _method_name.__name__, _method_name) - - -EVENT_NOTIFIER = None - - -def watch_dir(dir_to_watch): - global EVENT_NOTIFIER - for method in EventProcessor._methods: - __process_generator(EventProcessor, method) - watch_manager = pyinotify.WatchManager() - EVENT_NOTIFIER = pyinotify.ThreadedNotifier(watch_manager, EventProcessor()) - watch_manager.add_watch(dir_to_watch, pyinotify.ALL_EVENTS, rec=True) - EVENT_NOTIFIER.loop() - - -def stop_watching(): - EVENT_NOTIFIER.stop() diff --git a/BackgroundService/test.py b/BackgroundService/test.py deleted file mode 100644 index b797228..0000000 --- a/BackgroundService/test.py +++ /dev/null @@ -1,19 +0,0 @@ -from bgservice import SkoolOSDaemon as sod -import threading - -logger = sod() - - -if __name__ == "__main__": - line=1 - print(line) - line+=1 - logger.start() - print(line) - line+=1 - input("Enter any key when you are done modifyng the /tmp/ directory") - print(line) - line+=1 - logger.stop() - print(line) - line+=1 diff --git a/CLI/.profile b/CLI/.profile deleted file mode 100644 index ca78410..0000000 --- a/CLI/.profile +++ /dev/null @@ -1 +0,0 @@ -{'id': 1000417, 'ion_username': '2023rumareti', 'sex': 'Male', 'title': None, 'display_name': 'Rushil Umaretiya', 'full_name': 'Rushil Umaretiya', 'short_name': 'Rushil', 'first_name': 'Rushil', 'middle_name': 'Haresh', 'last_name': 'Umaretiya', 'nickname': None, 'tj_email': '2023rumareti@tjhsst.edu', 'emails': ['rushilwiz@gmail.com', 'r@crucialnet.org'], 'grade': {'number': 9, 'name': 'freshman'}, 'graduation_year': 2023, 'user_type': 'student', 'phones': ['Mobile Phone: 7034570803'], 'websites': ['http://crucialnet.org'], 'counselor': {'id': 115, 'url': 'https://ion.tjhsst.edu/api/profile/115', 'user_type': 'counselor', 'username': 'kchamblin', 'full_name': 'Kerry Hamblin', 'first_name': 'Kerry', 'last_name': 'Hamblin'}, 'address': None, 'picture': 'https://ion.tjhsst.edu/api/profile/1000417/picture', 'is_eighth_admin': False, 'is_announcements_admin': False, 'is_teacher': False, 'is_student': True, 'absences': 1} diff --git a/CLI/oauth/index.html b/CLI/oauth/index.html deleted file mode 100644 index cdce72e..0000000 --- a/CLI/oauth/index.html +++ /dev/null @@ -1,23 +0,0 @@ - - - Sign into Ion - - - - - - -
- - - Sign in with Ion - -
- - diff --git a/CLI/skoolos.py b/CLI/skoolos.py index 73c7e37..9477806 100644 --- a/CLI/skoolos.py +++ b/CLI/skoolos.py @@ -37,7 +37,14 @@ def main(): input("Welcome to SkoolOS. Press any key to create an account") authenticate() else: - print(open(".profile", "r").read()) + file = open('key.key', 'rb') + key = file.read() # The key will be type bytes + file.close() + f = Fernet(key) + file = open('.profile', 'rb') + p = file.read() # The key will be type bytes + file.close() + # while True: # pass @@ -50,9 +57,14 @@ def authenticate(): #Linux: chromdriver-linux #Macos: chromdriver-mac #Windows: chromdriver.exe + if('CLI' in os.getcwd()): + path = os.path.join(os.getcwd(), '../','chromedriver-mac') + else: + path = os.path.join(os.getcwd(), 'chromedriver-mac') - + browser = webdriver.Chrome(path) web_dir = os.path.join(os.path.dirname(__file__), 'oauth') + print(web_dir) os.chdir(web_dir) if os.path.exists("index.html"): os.remove("index.html") @@ -86,13 +98,13 @@ def authenticate(): print("states good") browser.quit() - print(code) + #print(code) print(state) payload = {'grant_type': 'authorization_code', 'code': code, 'redirect_uri': redirect_uri, 'client_id': client_id, 'client_secret': client_secret, 'csrfmiddlewaretoken': state} token = requests.post("https://ion.tjhsst.edu/oauth/token/", data=payload).json() - print(token) + #print(token) headers = {'Authorization': f"Bearer {token['access_token']}"} # And finally get the user's profile! @@ -105,14 +117,18 @@ def authenticate(): last_name = profile['last_name'] os.chdir(cdir) - profileFile = open(".profile", "w") - #profileFile.write(profile.text()) - key = Fernet.generate_key() - file = open('key.key', 'wb') - file.write(key) # The key is type bytes still - file.close() - profileFile.write(str(profile)) - profileFile.close() + # key = Fernet.generate_key() + # file = open('key.key', 'wb') + # file.write(key) # The key is type bytes still + # file.close() + # p = str(profile).encode() + # f = Fernet(key) + # encrypted = f.encrypt(p) + + # profileFile = open(".profile", "wb") + # #profileFile.write(profile.text()) + # profileFile.write(encrypted) + # profileFile.close() sys.exit diff --git a/CLI/s-git.py b/CLI/student.py similarity index 97% rename from CLI/s-git.py rename to CLI/student.py index 4a007af..711c99e 100644 --- a/CLI/s-git.py +++ b/CLI/student.py @@ -386,10 +386,17 @@ class Student: command('git checkout master') os.chdir(cdir) -data = getStudent("2022rkhondak") -s = Student(data) -#s.viewClass("APLit_eharris1") -#s.updateClass("APLit_eharris1") -#s.update() -s.exitCLI() +# data = getStudent("2022rkhondak") +# s = Student(data) +# #s.viewClass("APLit_eharris1") +# #s.updateClass("APLit_eharris1") +# #s.update() +# s.exitCLI() +def main(): + print("noooo") + pass + +if __name__ == "__main__": + # stuff only to run when not called via 'import' here + main() diff --git a/CLI/t-git.py b/CLI/teacher.py similarity index 99% rename from CLI/t-git.py rename to CLI/teacher.py index 4e81255..d34ae79 100644 --- a/CLI/t-git.py +++ b/CLI/teacher.py @@ -659,8 +659,8 @@ t = Teacher(data) #ar = ['2022rkhondak','2022inafi','2023rumareti'] #extra = t.reqAddStudentList(ar, "APLit_eharris1") #print(extra) -t.getStudents('2022rkhondak') -t.getChanges('2022rkhondak','APLit_eharris1', 10) +# t.getStudents('2022rkhondak') +# t.getChanges('2022rkhondak','APLit_eharris1', 10) ''' TO-DO diff --git a/Website/api/serializers.py b/Website/api/serializers.py index 46571fc..2904a07 100644 --- a/Website/api/serializers.py +++ b/Website/api/serializers.py @@ -1,5 +1,5 @@ from django.contrib.auth.models import User, Group -from .models import Student, Teacher, Class, Assignment, DefFiles +from .models import Student, Teacher, Classes, Assignment, DefFiles from rest_framework import serializers, permissions from django.contrib.auth.models import User from .permissions import IsOwnerOrReadOnly,isTeacher @@ -10,44 +10,46 @@ class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User - fields = ['id', 'username', 'students','teachers'] + fields = ['id', 'username'] # class DefFilesSerializer(serializers.HyperlinkedModelSerializer): # class Meta: # model = DefFiles -# fields = ['name', 'path','assignment','Class', "teacher",'url', 'id'] +# fields = ['name', 'path','assignment','classes', "teacher",'url', 'id'] class AssignmentSerializer(serializers.HyperlinkedModelSerializer): - #permissions_Class = [permissions.IsAuthenticatedOrReadOnly] + #permissions_classes = [permissions.IsAuthenticatedOrReadOnly] # files = DefFilesSerializer(many=True, read_only=True,allow_null=True) owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Assignment - # fields = ['url','name', 'due_date', 'path' , "Class","teacher",'owner'] - fields = ['name', 'due_date', 'path' , "Class","teacher",'owner'] + # fields = ['url','name', 'due_date', 'path' , "classes","teacher",'owner'] + fields = ['name', 'due_date', 'path' , "classes","teacher",'owner'] -class ClassSerializer(serializers.HyperlinkedModelSerializer): +class ClassesSerializer(serializers.HyperlinkedModelSerializer): # assignments = AssignmentSerializer(many=True, read_only=True,allow_null=True) # default_file=DefFilesSerializer(many=True, read_only=True,allow_null=True) owner = serializers.ReadOnlyField(source='owner.username') class Meta: - model = Class + model = Classes # fields = ['url','name', 'repo','path', "teacher",'assignments',"default_file", 'confirmed', 'unconfirmed','owner'] fields = ['name', 'repo','path', "teacher",'assignments',"default_file", 'confirmed', 'unconfirmed','owner'] class StudentSerializer(serializers.HyperlinkedModelSerializer): - # Class = ClassSerializer(many=True, read_only=True,allow_null=True) + # classes = ClassesSerializer(many=True, read_only=True,allow_null=True) owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Student - # fields = ['url','first_name', 'last_name', 'grade','email','student_id', 'git','ion_user','Class','added_to','completed', 'repo','owner'] - fields = ['first_name', 'last_name', 'grade','email','student_id', 'git','ion_user','Class','added_to','completed', 'repo','owner'] + # fields = ['url','first_name', 'last_name', 'grade','email','student_id', 'git','ion_user','classes','added_to','completed', 'repo','owner'] + fields = ['grade','email','student_id', 'git','ion_user','classes','added_to','completed', 'repo','owner'] class TeacherSerializer(serializers.ModelSerializer): - # Class = ClassSerializer(many=True, read_only=True,allow_null=True) + # classes = ClassesSerializer(many=True, read_only=True,allow_null=True) owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Teacher - # fields = ['url','first_name', 'last_name','git','ion_user', 'email','Class','owner'] - fields = ['first_name', 'last_name','git','ion_user', 'email','Class','owner'] + # fields = ['url','first_name', 'last_name','git','ion_user', 'email','classes','owner'] + fields = ['first_name', 'last_name','git','ion_user', 'email','classes','owner'] + + diff --git a/Website/users/pwd.py b/Website/users/pwd.py new file mode 100644 index 0000000..a91574a --- /dev/null +++ b/Website/users/pwd.py @@ -0,0 +1,6 @@ +import os + +pwd = "heyyy" +path = os.getcwd() +p = os.path.join(path, '../../', 'pwd.txt') +open(p, 'w') \ No newline at end of file diff --git a/Website/users/views.py b/Website/users/views.py index b4dbfc6..8047b35 100644 --- a/Website/users/views.py +++ b/Website/users/views.py @@ -16,6 +16,7 @@ from django.contrib.auth import login as auth_login from django.contrib.auth import logout as auth_logout from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required +import os # Create your views here. # Thanks Django, what would I do without this comment diff --git a/requirements.txt b/requirements.txt index 9a6e972..ceb2027 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,27 +1,61 @@ +appdirs==1.4.3 +arandr==0.1.10 asgiref==3.2.7 +astroid==2.4.2 +CacheControl==0.12.6 certifi==2020.4.5.1 chardet==3.0.4 click==7.1.2 +colorama==0.4.3 +contextlib2==0.6.0 +distlib==0.3.0 +distro==1.4.0 Django==3.0.7 django-cors-middleware==1.5.0 django-crispy-forms==1.9.1 django-oauth-toolkit==1.3.2 djangorestframework==3.11.0 +greenlet==0.4.16 +html5lib==1.0.1 idna==2.9 +isort==4.3.21 +lazy-object-proxy==1.4.3 +mccabe==0.6.1 +meson==0.53.2 +msgpack==0.6.2 oauthlib==3.1.0 +ordered-set==3.1.1 +packaging==20.1 +pep517==0.8.1 +Pillow==7.1.2 +progress==1.5 prompt-toolkit==1.0.14 +pulsemixer==1.5.0 +pycairo==1.19.1 pyclipper==1.1.0.post3 Pygments==2.6.1 +PyGObject==3.34.0 pyinotify==0.9.6 PyInquirer==1.0.3 +pylint==2.5.3 +pynvim==0.4.1 +pyparsing==2.4.6 pyperclip==1.8.0 +pytoml==0.1.21 pytz==2020.1 +pywal==3.3.0 regex==2020.5.14 requests==2.23.0 requests-oauthlib==1.3.0 +retrying==1.3.3 selenium==3.141.0 six==1.15.0 sqlparse==0.3.1 +team==1.0 +toml==0.10.0 urllib3==1.25.9 wcwidth==0.2.3 +webencodings==0.5.1 Werkzeug==1.0.1 +wpgtk==6.1.3 +wrapt==1.12.1 diff --git a/skoolos.py b/skoolos.py new file mode 100644 index 0000000..a802814 --- /dev/null +++ b/skoolos.py @@ -0,0 +1,273 @@ +import sys +from urllib.parse import urlparse +import requests +from requests_oauthlib import OAuth2Session +from selenium import webdriver +import os.path +import time +import http.server +import socketserver +from threading import Thread +from werkzeug.urls import url_decode +import pprint +from PyInquirer import prompt, print_json +import json +import os +import argparse +import webbrowser + +client_id = r'QeZPBSKqdvWFfBv1VYTSv9iFGz5T9pVJtNUjbEr6' +client_secret = r'0Wl3hAIGY9SvYOqTOLUiLNYa4OlCgZYdno9ZbcgCT7RGQ8x2f1l2HzZHsQ7ijC74A0mrOhhCVeZugqAmOADHIv5fHxaa7GqFNtQr11HX9ySTw3DscKsphCVi5P71mlGY' +redirect_uri = 'http://localhost:8000/callback/' +token_url = 'https://ion.tjhsst.edu/oauth/token/' +scope = ["read"] +USER = "" +PWD = "" + +def main(): + print("") + print("░██████╗██╗░░██╗░█████╗░░█████╗░██╗░░░░░  ░█████╗░░██████╗") + print("██╔════╝██║░██╔╝██╔══██╗██╔══██╗██║░░░░░  ██╔══██╗██╔════╝") + print("╚█████╗░█████═╝░██║░░██║██║░░██║██║░░░░░  ██║░░██║╚█████╗░") + print("░╚═══██╗██╔═██╗░██║░░██║██║░░██║██║░░░░░  ██║░░██║░╚═══██╗") + print("██████╔╝██║░╚██╗╚█████╔╝╚█████╔╝███████╗  ╚█████╔╝██████╔╝") + print("╚═════╝░╚═╝░░╚═╝░╚════╝░░╚════╝░╚══════╝  ░╚════╝░╚═════╝░") + print("") + + if not os.path.exists(".profile"): + # try: + # URL = "http://127.0.0.1:8000/api/" + # r = requests.get(url = URL) + # print("Stop any processes running on http://127.0.0.1:8000/ before continuing") + # except: + # pass + input("Welcome to SkoolOS. Press any key to create an account") + #webbrowser.open("http://127.0.0.1:8000/login", new=2) + authenticate() + # else: + # try: + # URL = "http://127.0.0.1:8000/api/" + # f = open('.profile','r') + # data = json.loads(f.read()) + # f.close() + # PWD = data['password'] + # USER = data['username'] + # r = requests.get(url = URL, auth=(USER,PWD)) + # except: + # print("Incorrect password.") + # sys.exit(0) + # if(data['is_student']): + # studentCLI() + # else: + # teacherCLI() + + + + # while True: + # pass +def studentCLI(): + from CLI import student + data = getStudent(USER) + print(data) + student = student.Student(data) + print(student) + +def teacherCLI(): + from CLI.teacher import Teacher + print("fail") + +def getStudent(ion_user): + URL = "http://127.0.0.1:8000/api/students/" + ion_user + "/" + r = requests.get(url = URL, auth=('raffukhondaker','hackgroup1')) + if(r.status_code == 200): + data = r.json() + return data + elif(r.status_code == 404): + return None + print("Make new account!") + elif(r.status_code == 403): + return None + print("Invalid username/password") + else: + return None + print(r.status_code) + +def getDB(url): + r = requests.get(url = url, auth=('raffukhondaker','hackgroup1')) + print("GET:" + str(r.status_code)) + return(r.json()) + +def postDB(data, url): + r = requests.post(url = url, data=data, auth=('raffukhondaker','hackgroup1')) + print("POST:" + str(r.status_code)) + return(r.json()) + +def putDB(data, url): + r = requests.put(url = url, data=data, auth=('raffukhondaker','hackgroup1')) + print("PUT:" + str(r.status_code)) + return(r.json()) + +def delDB(url): + r = requests.delete(url = url, auth=('raffukhondaker','hackgroup1')) + print("DELETE:" + str(r.status_code)) + return None + +def makePass(): + questions = [ + { + 'type': 'password', + 'name': 'pwd', + 'message': 'Enter SkoolOS Password (NOT ION PASSWORD): ', + }, + ] + pwd = prompt(questions)['pwd'] + while(len(pwd) < 7): + print("Password too short (Must be over 6 characters)") + pwd = prompt(questions)['pwd'] + conf = [ + { + 'type': 'password', + 'name': 'pwd', + 'message': 'Re-enter password: ', + }, + ] + pwd2 = prompt(conf)['pwd'] + while(not pwd == pwd2): + print("Passwords do not match.") + pwd2 = prompt(conf)['pwd'] + else: + print("PASSWORD SAVED") + return pwd + +def authenticate(): + oauth = OAuth2Session(client_id=client_id, redirect_uri=redirect_uri, scope=scope) + authorization_url, state = oauth.authorization_url("https://ion.tjhsst.edu/oauth/authorize/") + + cdir = os.getcwd() + #Linux: chromdriver-linux + #Macos: chromdriver-mac + #Windows: chromdriver.exe + if('CLI' in os.getcwd()): + path = os.path.join(os.getcwd(), '../','chromedriver-mac') + else: + path = os.path.join(os.getcwd(), 'chromedriver-mac') + + browser = webdriver.Chrome(path) + # web_dir = os.path.join(os.getcwd(), 'CLI', 'oauth') + # print(web_dir) + # os.chdir(web_dir) + # if os.path.exists("index.html"): + # os.remove("index.html") + + # template = open("template.html", "r") + # index = open("index.html", "w") + # for line in template: + # index.write(line.replace('AUTH_URL', authorization_url)) + # template.close() + # index.close() + + # server = Thread(target=create_server) + # server.daemon = True + # server.start() + + browser.get("localhost:8000/login") + + # while "http://localhost:8000/callback/?code" not in browser.current_url: + # time.sleep(0.25) + + url = browser.current_url + gets = url_decode(url.replace("http://localhost:8000/login/?", "")) + while "http://localhost:8000/login/?username=" not in browser.current_url and (not browser.current_url == "http://localhost:8000/"): #http://localhost:8000/ + time.sleep(0.25) + + url = browser.current_url + gets = url_decode(url.replace("http://localhost:8000/login/?username=", "")) + # code = gets.get("code") + # if state == gets.get("state"): + # state = gets.get("state") + # print("states good") + browser.quit() + questions = [ + { + 'type': 'input', + 'name': 'username', + 'message': 'Enter SkoolOS Username (Same as ION Username): ', + }, + { + 'type': 'password', + 'name': 'pwd', + 'message': 'Enter SkoolOS Password (NOT ION PASSWORD): ', + }, + ] + data =prompt(questions) + pwd = data['pwd'] + user = data['username'] + r = requests.get(url = "http://localhost:8000/api/", auth=(user,pwd)) + while(r.status_code != 200): + print("INCORRECT LOGIN CREDENTIALS") + r = requests.get(url = "http://localhost:8000/api/", auth=(user,pwd)) + data =prompt(questions) + pwd = data['pwd'] + user = data['username'] + print(r.status_code) + r = requests.get(url = "http://localhost:8000/students/" + user + "/", auth=(user,pwd)) + is_student = False + if(r.status_code == 200): + is_student = True + print("Welcome, student " + user) + else: + print("Welcome, teacher " + user) + + #print(code) + print(state) + + payload = {'grant_type': 'authorization_code', 'code': code, 'redirect_uri': redirect_uri, 'client_id': client_id, + 'client_secret': client_secret, 'csrfmiddlewaretoken': state} + token = requests.post("https://ion.tjhsst.edu/oauth/token/", data=payload).json() + #print(token) + headers = {'Authorization': f"Bearer {token['access_token']}"} + + # And finally get the user's profile! + profile = requests.get("https://ion.tjhsst.edu/api/profile", headers=headers).json() + + #pprint.pprint(profile) + username = profile['ion_username'] + email = profile['tj_email'] + first_name = profile['first_name'] + last_name = profile['last_name'] + is_student = profile['is_student'] + password = "" + #password creation + + profile = { + 'username':username, + 'email':email, + 'first_name':first_name, + 'last_name':last_name, + 'is_student':is_student, + 'password':password, + } + os.chdir(cdir) + + profileFile = open(".profile", "w") + profileFile.write(json.dumps(profile)) + profileFile.close() + + #try to make password + password = makePass() + profile['password'] = password + profileFile = open(".profile", "w") + profileFile.write(json.dumps(profile)) + profileFile.close() + + sys.exit + +def create_server(): + port = 8000 + handler = http.server.SimpleHTTPRequestHandler + httpd = socketserver.TCPServer(("", port), handler) + print("serving at port:" + str(port)) + httpd.serve_forever() + +if __name__ == "__main__": + main()