Merge branch 'development' of github.com:Rushilwiz/SkoolOS into development

This commit is contained in:
Nathaniel Kenschaft 2020-06-14 19:00:21 -04:00
commit a0dff03058
34 changed files with 747 additions and 199 deletions

View File

@ -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': []}

View File

@ -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}

View File

@ -14,10 +14,10 @@
</head> </head>
<body> <body>
<div class="d-flex align-items-center justify-content-center" style="height: 100vh"> <div class="d-flex align-items-center justify-content-center" style="height: 100vh">
<a href="https://ion.tjhsst.edu/oauth/authorize/?response_type=code&client_id=QeZPBSKqdvWFfBv1VYTSv9iFGz5T9pVJtNUjbEr6&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2F&scope=read&state=O9QWIinWimSA8Kehr8vxUZHZ0SNPpL" title="Ion" class="border border-dark p-3 btn btn-lg mx-auto" style="box-shadow: 5px 10px;"> <a href="https://ion.tjhsst.edu/oauth/authorize/?response_type=code&client_id=QeZPBSKqdvWFfBv1VYTSv9iFGz5T9pVJtNUjbEr6&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcallback%2F&scope=read&state=yPblNZvC39bYCruLcVibEUzLjXkwaJ" title="Ion" class="border border-dark p-3 btn btn-lg mx-auto" style="box-shadow: 5px 10px;">
<img src="https://ion.tjhsst.edu/static/img/favicon.png"> <img src="https://ion.tjhsst.edu/static/img/favicon.png">
Sign in with Ion Sign in with Ion
</a> </a>
</div> </div>
</body> </body>
</html> </html>

View File

@ -37,7 +37,14 @@ def main():
input("Welcome to SkoolOS. Press any key to create an account") input("Welcome to SkoolOS. Press any key to create an account")
authenticate() authenticate()
else: 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: # while True:
# pass # pass
@ -50,9 +57,14 @@ def authenticate():
#Linux: chromdriver-linux #Linux: chromdriver-linux
#Macos: chromdriver-mac #Macos: chromdriver-mac
#Windows: chromdriver.exe #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') web_dir = os.path.join(os.path.dirname(__file__), 'oauth')
print(web_dir)
os.chdir(web_dir) os.chdir(web_dir)
if os.path.exists("index.html"): if os.path.exists("index.html"):
os.remove("index.html") os.remove("index.html")
@ -86,13 +98,13 @@ def authenticate():
print("states good") print("states good")
browser.quit() browser.quit()
print(code) #print(code)
print(state) print(state)
payload = {'grant_type': 'authorization_code', 'code': code, 'redirect_uri': redirect_uri, 'client_id': client_id, payload = {'grant_type': 'authorization_code', 'code': code, 'redirect_uri': redirect_uri, 'client_id': client_id,
'client_secret': client_secret, 'csrfmiddlewaretoken': state} 'client_secret': client_secret, 'csrfmiddlewaretoken': state}
token = requests.post("https://ion.tjhsst.edu/oauth/token/", data=payload).json() token = requests.post("https://ion.tjhsst.edu/oauth/token/", data=payload).json()
print(token) #print(token)
headers = {'Authorization': f"Bearer {token['access_token']}"} headers = {'Authorization': f"Bearer {token['access_token']}"}
# And finally get the user's profile! # And finally get the user's profile!
@ -105,14 +117,18 @@ def authenticate():
last_name = profile['last_name'] last_name = profile['last_name']
os.chdir(cdir) os.chdir(cdir)
profileFile = open(".profile", "w") # key = Fernet.generate_key()
#profileFile.write(profile.text()) # file = open('key.key', 'wb')
key = Fernet.generate_key() # file.write(key) # The key is type bytes still
file = open('key.key', 'wb') # file.close()
file.write(key) # The key is type bytes still # p = str(profile).encode()
file.close() # f = Fernet(key)
profileFile.write(str(profile)) # encrypted = f.encrypt(p)
profileFile.close()
# profileFile = open(".profile", "wb")
# #profileFile.write(profile.text())
# profileFile.write(encrypted)
# profileFile.close()
sys.exit sys.exit

View File

@ -386,10 +386,17 @@ class Student:
command('git checkout master') command('git checkout master')
os.chdir(cdir) os.chdir(cdir)
data = getStudent("2022rkhondak") # data = getStudent("2022rkhondak")
s = Student(data) # s = Student(data)
#s.viewClass("APLit_eharris1") # #s.viewClass("APLit_eharris1")
#s.updateClass("APLit_eharris1") # #s.updateClass("APLit_eharris1")
#s.update() # #s.update()
s.exitCLI() # s.exitCLI()
def main():
print("noooo")
pass
if __name__ == "__main__":
# stuff only to run when not called via 'import' here
main()

View File

@ -659,8 +659,8 @@ t = Teacher(data)
#ar = ['2022rkhondak','2022inafi','2023rumareti'] #ar = ['2022rkhondak','2022inafi','2023rumareti']
#extra = t.reqAddStudentList(ar, "APLit_eharris1") #extra = t.reqAddStudentList(ar, "APLit_eharris1")
#print(extra) #print(extra)
t.getStudents('2022rkhondak') # t.getStudents('2022rkhondak')
t.getChanges('2022rkhondak','APLit_eharris1', 10) # t.getChanges('2022rkhondak','APLit_eharris1', 10)
''' '''
TO-DO TO-DO

View File

@ -1,128 +1,128 @@
from datetime import datetime # from datetime import datetime
#
f1 = DefFiles( # f1 = DefFiles(
name="instructions.txt" # name="instructions.txt"
) # )
f1.save() # f1.save()
f2 = DefFiles( # f2 = DefFiles(
name="instructions.txt" # name="instructions.txt"
) # )
f2.save() # f2.save()
f3 = DefFiles( # f3 = DefFiles(
name="sample.txt" # name="sample.txt"
) # )
f3.save() # f3.save()
f4 = DefFiles( # f4 = DefFiles(
name="rubric.txt" # name="rubric.txt"
) # )
f4.save() # f4.save()
#
a1 = Assignment.objects.get(pk=1) # a1 = Assignment.objects.get(pk=1)
a1.files.add(f1) # a1.files.add(f1)
a1.save() # a1.save()
a2 = Assignment.objects.get(pk=2) # a2 = Assignment.objects.get(pk=2)
a2.files.add(f2) # a2.files.add(f2)
a2.save() # a2.save()
a3 = Assignment.objects.get(pk=3) # a3 = Assignment.objects.get(pk=3)
a3.files.add(f3) # a3.files.add(f3)
a3.files.add(f4) # a3.files.add(f4)
a3.save() # a3.save()
#
#################################### # ####################################
#
from api.models import Assignment, Student, Classes, Teacher, DefFiles # from api.models import Assignment, Student, Classes, Teacher, DefFiles
from datetime import datetime # from datetime import datetime
#
f1 = DefFiles( # f1 = DefFiles(
name="instructions.txt" # name="instructions.txt"
) # )
f1.save() # f1.save()
f2 = DefFiles( # f2 = DefFiles(
name="instructions.txt" # name="instructions.txt"
) # )
f2.save() # f2.save()
f3 = DefFiles( # f3 = DefFiles(
name="sample.txt" # name="sample.txt"
) # )
f3.save() # f3.save()
f4 = DefFiles( # f4 = DefFiles(
name="rubric.txt" # name="rubric.txt"
) # )
f4.save() # f4.save()
#
A1 = Assignment( # A1 = Assignment(
name='Week1_HW', # name='Week1_HW',
due_date=datetime.now(), # due_date=datetime.now(),
) # )
A1.save() # A1.save()
A1.files.add(f1) # A1.files.add(f1)
A1.save() # A1.save()
#
A2 = Assignment( # A2 = Assignment(
name='Week2_HW', # name='Week2_HW',
due_date=datetime.now(), # due_date=datetime.now(),
#
) # )
A2.save() # A2.save()
A2.files.add(f2) # A2.files.add(f2)
A2.save() # A2.save()
#
A3 = Assignment( # A3 = Assignment(
name='Journal1', # name='Journal1',
due_date=datetime.now(), # due_date=datetime.now(),
) # )
A3.save() # A3.save()
A3.files.add(f3) # A3.files.add(f3)
A3.files.add(f4) # A3.files.add(f4)
A3.save() # A3.save()
#
#classes # #classes
math = Classes( # math = Classes(
name='Math5', # name='Math5',
#
) # )
math.save() # math.save()
math.assignments.add(A1) # math.assignments.add(A1)
math.assignments.add(A2) # math.assignments.add(A2)
math.save() # math.save()
#
english = Classes( # english = Classes(
name='English', # name='English',
) # )
english.save() # english.save()
english.assignments.add(A3) # english.assignments.add(A3)
english.save() # english.save()
#
#students # #students
raffu = Student( # raffu = Student(
first_name = "Raffu", # first_name = "Raffu",
last_name = "Khondaker", # last_name = "Khondaker",
student_id = 1579460, # student_id = 1579460,
ion_user="2022rkhondak", # ion_user="2022rkhondak",
webmail = "2022rkhondak@tjhsst.edu", # webmail = "2022rkhondak@tjhsst.edu",
grade = 10, # grade = 10,
repo="https://github.com/therealraffi/2022rkhondak.git", # repo="https://github.com/therealraffi/2022rkhondak.git",
) # )
raffu.save() # raffu.save()
raffu.classes.add(math) # raffu.classes.add(math)
raffu.classes.add(english) # raffu.classes.add(english)
raffu.save() # raffu.save()
#
#teachers # #teachers
ng = Teacher( # ng = Teacher(
first_name = "Errin", # first_name = "Errin",
last_name = "Harris", # last_name = "Harris",
ion_user="eharris1" # ion_user="eharris1"
) # )
ng.save() # ng.save()
ng.classes.add(math) # ng.classes.add(math)
ng.save() # ng.save()
#
chao = Teacher( # chao = Teacher(
first_name = "Abagail", # first_name = "Abagail",
last_name = "Bailey", # last_name = "Bailey",
ion_user="AKBailey" # ion_user="AKBailey"
) # )
chao.save() # chao.save()
chao.classes.add(english) # chao.classes.add(english)
chao.save() # chao.save()

View File

@ -1,4 +1,4 @@
# Generated by Django 3.0.7 on 2020-06-13 18:15 # Generated by Django 3.0.7 on 2020-06-14 19:14
from django.conf import settings from django.conf import settings
from django.db import migrations, models from django.db import migrations, models
@ -35,25 +35,15 @@ class Migration(migrations.Migration):
('ion_user', models.CharField(max_length=100, primary_key=True, serialize=False)), ('ion_user', models.CharField(max_length=100, primary_key=True, serialize=False)),
('git', models.CharField(max_length=100)), ('git', models.CharField(max_length=100)),
('email', models.CharField(blank=True, default='', max_length=100)), ('email', models.CharField(blank=True, default='', max_length=100)),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='teachers', to=settings.AUTH_USER_MODEL)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
], ],
), ),
migrations.CreateModel( migrations.CreateModel(
name='Student', name='Student',
fields=[ fields=[
('created', models.DateTimeField(auto_now_add=True)), ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('first_name', models.CharField(max_length=100)), ('website', models.CharField(blank=True, default='https://google.com', max_length=150)),
('last_name', models.CharField(max_length=100)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
('student_id', models.IntegerField()),
('ion_user', models.CharField(max_length=100, primary_key=True, serialize=False)),
('email', models.CharField(blank=True, default='', max_length=100)),
('grade', models.IntegerField()),
('git', models.CharField(max_length=100)),
('repo', models.URLField(blank=True, default='')),
('classes', models.CharField(blank=True, default='', max_length=100)),
('added_to', models.CharField(blank=True, default='', max_length=100)),
('completed', models.TextField(blank=True, default='')),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='students', to=settings.AUTH_USER_MODEL)),
], ],
), ),
migrations.CreateModel( migrations.CreateModel(
@ -67,7 +57,7 @@ class Migration(migrations.Migration):
('default_file', models.CharField(blank=True, default='', max_length=100)), ('default_file', models.CharField(blank=True, default='', max_length=100)),
('confirmed', models.TextField(blank=True, default='')), ('confirmed', models.TextField(blank=True, default='')),
('unconfirmed', models.TextField(blank=True, default='')), ('unconfirmed', models.TextField(blank=True, default='')),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='classes', to=settings.AUTH_USER_MODEL)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
], ],
), ),
migrations.CreateModel( migrations.CreateModel(

View File

@ -0,0 +1,52 @@
# Generated by Django 3.0.7 on 2020-06-14 20:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='student',
name='website',
),
migrations.AddField(
model_name='student',
name='added_to',
field=models.CharField(blank=True, default='', max_length=100),
),
migrations.AddField(
model_name='student',
name='classes',
field=models.CharField(blank=True, default='', max_length=100),
),
migrations.AddField(
model_name='student',
name='completed',
field=models.TextField(blank=True, default=''),
),
migrations.AddField(
model_name='student',
name='git',
field=models.CharField(blank=True, default='https://github.com/', max_length=100),
),
migrations.AddField(
model_name='student',
name='grade',
field=models.IntegerField(blank=True, default=9),
),
migrations.AddField(
model_name='student',
name='repo',
field=models.URLField(blank=True, default=''),
),
migrations.AddField(
model_name='student',
name='student_id',
field=models.IntegerField(blank=True, default=0),
),
]

View File

@ -0,0 +1,43 @@
# Generated by Django 3.0.7 on 2020-06-14 20:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0002_auto_20200614_2034'),
]
operations = [
migrations.RemoveField(
model_name='student',
name='student_id',
),
migrations.RemoveField(
model_name='teacher',
name='created',
),
migrations.RemoveField(
model_name='teacher',
name='email',
),
migrations.RemoveField(
model_name='teacher',
name='first_name',
),
migrations.RemoveField(
model_name='teacher',
name='last_name',
),
migrations.AlterField(
model_name='student',
name='git',
field=models.CharField(blank=True, default='', max_length=100),
),
migrations.AlterField(
model_name='student',
name='grade',
field=models.IntegerField(blank=True),
),
]

View File

@ -0,0 +1,18 @@
# Generated by Django 3.0.7 on 2020-06-14 21:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0003_auto_20200614_2044'),
]
operations = [
migrations.AlterField(
model_name='student',
name='grade',
field=models.IntegerField(blank=True, default=0),
),
]

View File

@ -39,26 +39,26 @@ class Classes(models.Model):
return super(Classes, self).save(*args, **kwargs) return super(Classes, self).save(*args, **kwargs)
class Teacher(models.Model): class Teacher(models.Model):
owner = models.ForeignKey('auth.User', related_name='teachers', on_delete=models.CASCADE) user = models.OneToOneField(User, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
# classes = models.ManyToManyField(Classes, default="") # classes = models.ManyToManyField(Classes, default="")
classes=models.CharField(max_length=100, default="", blank=True) classes=models.CharField(max_length=100, default="", blank=True)
ion_user=models.CharField(primary_key=True, max_length=100) ion_user=models.CharField(primary_key=True, max_length=100)
git=models.CharField(max_length=100) git=models.CharField(max_length=100)
email=models.CharField(max_length=100, default="", blank=True)
def save(self, *args, **kwargs):
super(Teacher, self).save(*args, **kwargs)
class Student(models.Model): class Student(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE) user = models.OneToOneField(User, on_delete=models.CASCADE)
student_id = models.IntegerField() grade = models.IntegerField(default=0, blank=True)
grade = models.IntegerField() git=models.CharField(default="", max_length=100, blank=True)
git=models.CharField(max_length=100)
repo=models.URLField(default="", blank=True) repo=models.URLField(default="", blank=True)
classes=models.CharField(max_length=100, default="", blank=True) classes=models.CharField(max_length=100, default="", blank=True)
added_to=models.CharField(max_length=100, default="", blank=True) added_to=models.CharField(max_length=100, default="", blank=True)
completed=models.TextField(default="", blank=True) completed=models.TextField(default="", blank=True)
def save(self, *args, **kwargs): def save(self, *args, **kwargs):
return super(Student, self).save(*args, **kwargs) super(Student, self).save(*args, **kwargs)
def __str__(self):
return f"{self.user.username}'s Profile"

View File

@ -10,7 +10,7 @@ class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta: class Meta:
model = User model = User
fields = ['id', 'username', 'students','teachers'] fields = ['id', 'username']
# class DefFilesSerializer(serializers.HyperlinkedModelSerializer): # class DefFilesSerializer(serializers.HyperlinkedModelSerializer):
# class Meta: # class Meta:

View File

@ -2,7 +2,4 @@ from django.contrib.auth.models import User
from django.db.models.signals import post_save from django.db.models.signals import post_save
from django.dispatch import receiver from django.dispatch import receiver
from .models import Student, Teacher from .models import Student, Teacher
)
@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()

View File

@ -43,8 +43,6 @@ INSTALLED_APPS = [
'api', 'api',
'crispy_forms', 'crispy_forms',
'django_forms_bootstrap', 'django_forms_bootstrap',
] ]
REST_FRAMEWORK = { REST_FRAMEWORK = {

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,100 @@
@font-face {
font-family: Futura;
src: url(futura.ttf);
}
@font-face {
font-family: 'Segoe UI';
src: url('Segoe UI.ttf');
}
body {
background: #fafafa;
color: #333333;
margin-top: 5rem;
font-family: 'Segoe UI';
}
h1, h2, h3, h4, h5, h6 {
color: #444444;
}
ul {
margin: 0;
}
.bg-steel {
background: #3cba54;
}
.site-header .navbar-nav .nav-link {
color: #cbd5db;
}
.site-header .navbar-nav .nav-link:hover {
color: #ffffff;
}
.site-header .navbar-nav .nav-link.active {
font-weight: 500;
}
.content-section {
background: #ffffff;
padding: 10px 20px;
border: 1px solid #dddddd;
border-radius: 3px;
margin-bottom: 20px;
}
.article-title {
color: #444444;
}
a.article-title:hover {
color: #428bca;
text-decoration: none;
}
.article-content {
white-space: pre-line;
}
.article-img {
height: 65px;
width: 65px;
margin-right: 16px;
}
.article-metadata {
padding-bottom: 1px;
margin-bottom: 4px;
border-bottom: 1px solid #e3e3e3
}
.article-metadata a:hover {
color: #333;
text-decoration: none;
}
.article-svg {
width: 25px;
height: 25px;
vertical-align: middle;
}
.account-img {
height: 125px;
width: 125px;
margin-right: 20px;
margin-bottom: 16px;
}
.account-heading {
font-size: 2.5rem;
}
.nounderline {
text-decoration: none !important;
color: black !important;
}

View File

@ -17,6 +17,32 @@
</head> </head>
<body> <body>
<header class="site-header">
<nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top">
<div class="container">
<a class="navbar-brand" href="#">
<img src="/docs/4.3/assets/brand/bootstrap-solid.svg" width="30" height="30" class="d-inline-block align-top" alt="">
Bootstrap
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarToggle">
<div class="navbar-nav mr-auto">
<a class="nav-item nav-link" href="{% url 'home' %}">Home</a>
</div>
<!-- Navbar Right Side -->
<div class="navbar-nav">
{% if user.is_authenticated %}
<a class="nav-item nav-link" href="{% url 'profile' %}">{{ user.username }}</a>
<a class="nav-item nav-link" href="{% url 'logout' %}">Logout</a>
{% endif %}
</div>
</div>
</div>
</nav>
</header>
{% block content %}{% endblock %} {% block content %}{% endblock %}
<!-- Bootstrap JS --> <!-- Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>

View File

@ -1,5 +1,3 @@
{% extends "skoolos/base.html" %} {% extends "skoolos/base.html" %}
{% block content %} {% block content %}
<h1>welcome to skoolos</h1>
<h2>it's the future you've been waiting for</h2>
{% endblock content %} {% endblock content %}

View File

@ -1,6 +1,9 @@
from django.urls import path from django.urls import path
from . import views
# Additionally, we include login URLs for the browsable API.
urlpatterns = [ urlpatterns = [
path('', views.home, name='home'),
path('profile/', views.profile, name='profile')
] ]

View File

@ -6,3 +6,7 @@ from django.contrib.auth.decorators import login_required
@login_required() @login_required()
def home (request): def home (request):
return render(request, "skoolos/home.html") return render(request, "skoolos/home.html")
@login_required()
def profile (request):
pass

View File

@ -14,6 +14,7 @@ class UserCreationForm(forms.ModelForm):
first_name = forms.CharField(disabled=True) first_name = forms.CharField(disabled=True)
last_name = forms.CharField(disabled=True) last_name = forms.CharField(disabled=True)
isStudent = forms.BooleanField(widget = forms.HiddenInput()) isStudent = forms.BooleanField(widget = forms.HiddenInput())
git = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Git Username'}))
password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'})) password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'}))
confirm_password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password'})) confirm_password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password'}))
token = forms.CharField(widget = forms.HiddenInput()) token = forms.CharField(widget = forms.HiddenInput())
@ -23,14 +24,9 @@ class UserCreationForm(forms.ModelForm):
def clean(self): def clean(self):
cleaned_data = super(UserCreationForm, self).clean() cleaned_data = super(UserCreationForm, self).clean()
password = cleaned_data.get("password")
confirm_password = cleaned_data.get("confirm_password")
if password != confirm_password:
raise forms.ValidationError("Passwords do not match!")
return cleaned_data return cleaned_data
class Meta: class Meta:
model = User model = User
fields = ('username', 'email', 'first_name', 'last_name', 'password') fields = ('username', 'email', 'first_name', 'last_name', 'git', 'password', 'confirm_password')

View File

@ -1,4 +1,4 @@
# Generated by Django 3.0.7 on 2020-06-13 08:25 # Generated by Django 3.0.7 on 2020-06-14 19:13
from django.db import migrations, models from django.db import migrations, models

View File

@ -0,0 +1,18 @@
# Generated by Django 3.0.7 on 2020-06-14 20:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='token',
name='isStudent',
field=models.BooleanField(default=True),
),
]

View File

@ -0,0 +1,18 @@
# Generated by Django 3.0.7 on 2020-06-14 21:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0002_auto_20200614_2044'),
]
operations = [
migrations.AddField(
model_name='token',
name='grade',
field=models.IntegerField(default=9),
),
]

View File

@ -9,7 +9,8 @@ class Token(models.Model):
email = models.TextField() email = models.TextField()
first_name = models.TextField() first_name = models.TextField()
last_name = models.TextField() last_name = models.TextField()
isStudent = models.BooleanField() grade = models.IntegerField(default=9)
isStudent = models.BooleanField(default=True)
token = models.CharField(max_length=255) token = models.CharField(max_length=255)
def save(self, *args, **kwargs): def save(self, *args, **kwargs):

6
Website/users/pwd.py Normal file
View File

@ -0,0 +1,6 @@
import os
pwd = "heyyy"
path = os.getcwd()
p = os.path.join(path, '../../', 'pwd.txt')
open(p, 'w')

View File

@ -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 import logout as auth_logout
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import login_required
import os
# Create your views here. # Create your views here.
# Thanks Django, what would I do without this comment # Thanks Django, what would I do without this comment
@ -53,12 +54,13 @@ def callback (request):
first_name = profile['first_name'] first_name = profile['first_name']
last_name = profile['last_name'] last_name = profile['last_name']
isStudent = profile['is_student'] isStudent = profile['is_student']
grade = profile['grade']['number']
if User.objects.filter(username=username).count() != 0: if User.objects.filter(username=username).count() != 0:
messages.success(request, "This user already exists!") messages.success(request, "This user already exists!")
return redirect('/login/') return redirect('/login/')
else: else:
token = Token(username = username, email = email, first_name = first_name, last_name = last_name, isStudent = isStudent) token = Token(username = username, email = email, first_name = first_name, last_name = last_name, isStudent = isStudent, grade=grade)
token.save() token.save()
tokenHash = token.token tokenHash = token.token
print(f'/create_account/?token={tokenHash}') print(f'/create_account/?token={tokenHash}')
@ -83,8 +85,12 @@ def create_account (request):
first_name = token.first_name first_name = token.first_name
last_name = token.last_name last_name = token.last_name
isStudent = token.isStudent isStudent = token.isStudent
grade = token.grade
git = cleaned_data.get('git')
password = cleaned_data.get('password') password = cleaned_data.get('password')
user = User.objects.create_user(username=username, user = User.objects.create_user(username=username,
email=email, email=email,
first_name=first_name, first_name=first_name,
@ -92,6 +98,14 @@ def create_account (request):
password=password) password=password)
user.save() user.save()
token.delete() token.delete()
if isStudent:
profile = Student(user=user, git=git, grade=grade)
else:
profile = Teacher(user=user, git=git)
profile.save()
print (user) print (user)
messages.success(request, "Your SkoolOS account has successfully been created") messages.success(request, "Your SkoolOS account has successfully been created")
return redirect(f'/login/?username={username}') return redirect(f'/login/?username={username}')
@ -109,11 +123,14 @@ def create_account (request):
first_name = token.first_name first_name = token.first_name
last_name = token.last_name last_name = token.last_name
isStudent = token.isStudent isStudent = token.isStudent
grade = token.grade
initial = { initial = {
'username': username, 'username': username,
'email': email, 'email': email,
'first_name': first_name, 'first_name': first_name,
'last_name': last_name, 'last_name': last_name,
'grade': grade,
'isStudent': isStudent, 'isStudent': isStudent,
'token': token.token, 'token': token.token,
} }
@ -128,4 +145,4 @@ def create_account (request):
def logout(request): def logout(request):
auth_logout(request) auth_logout(request)
messages.success(request, "You've been logged out!") messages.success(request, "You've been logged out!")
return redirect(request, "/login/") return redirect(request, "/login")

242
skoolos.py Normal file
View File

@ -0,0 +1,242 @@
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
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, auth=('raffukhondaker','hackgroup1'))
print("End service at http://127.0.0.1:8000/ before continuing.")
sys.exit(0)
except:
pass
input("Welcome to SkoolOS. Press any key to create an account")
authenticate()
else:
try:
URL = "http://127.0.0.1:8000/api/"
r = requests.get(url = URL, auth=('raffukhondaker','hackgroup1'))
except:
print("Start Django server first")
sys.exit(0)
f = open('.profile','r')
data = json.loads(f.read())
f.close()
PWD = data['password']
USER = data['username']
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/")
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/callback/?", ""))
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/callback/?", ""))
code = gets.get("code")
if state == gets.get("state"):
state = gets.get("state")
print("states good")
browser.quit()
#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()