Skip to content

Commit

Permalink
Update
Browse files Browse the repository at this point in the history
- login & registration is complete
- now gotta work on confirmation
- then dashboard
- then scrape tool for rpi
- then do more touch up
- then idk, maybe end project there or get more universities onboard or integrate with some YACS project or something 👍
  • Loading branch information
nishi7409 committed Dec 30, 2020
1 parent b193490 commit 1730577
Show file tree
Hide file tree
Showing 20 changed files with 311 additions and 61 deletions.
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
venv/
.env
node_modules
web_app/app/microservices/googleCal/credentials.json
web_app/app/microservices/googleCal/*.json
web_app/app/microservices/googleCal/*.pickle
*.pickle
web_app/mydatabase
3 changes: 3 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,6 @@ google-api-python-client
google-auth-httplib2
google-auth-oauthlib
ics
psycopg2-binary==2.8.3
discord
requests
Binary file modified web_app/app/__pycache__/models.cpython-36.pyc
Binary file not shown.
Binary file modified web_app/app/__pycache__/views.cpython-36.pyc
Binary file not shown.
49 changes: 49 additions & 0 deletions web_app/app/microservices/googleCal/Google.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import pickle
import datetime
import os
from google_auth_oauthlib.flow import Flow, InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from google.auth.transport.requests import Request


def Create_Service(client_secret_file, api_name, api_version, *scopes):
print(client_secret_file, api_name, api_version, scopes, sep='-')
CLIENT_SECRET_FILE = client_secret_file
API_SERVICE_NAME = api_name
API_VERSION = api_version
SCOPES = [scope for scope in scopes[0]]
print(SCOPES)

cred = None

pickle_file = f'token_{API_SERVICE_NAME}_{API_VERSION}.pickle'
# print(pickle_file)

if os.path.exists(pickle_file):
with open(pickle_file, 'rb') as token:
cred = pickle.load(token)

if not cred or not cred.valid:
if cred and cred.expired and cred.refresh_token:
cred.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
CLIENT_SECRET_FILE, SCOPES)
cred = flow.run_local_server()

with open(pickle_file, 'wb') as token:
pickle.dump(cred, token)

try:
service = build(API_SERVICE_NAME, API_VERSION, credentials=cred)
print(API_SERVICE_NAME, 'service created successfully')
return service
except Exception as e:
print(e)
return None


def convert_to_RFC_datetime(year=1900, month=1, day=1, hour=0, minute=0):
dt = datetime.datetime(year, month, day, hour, minute, 0).isoformat() + 'Z'
return dt
Binary file not shown.
Binary file not shown.
40 changes: 32 additions & 8 deletions web_app/app/microservices/googleCal/urlGenerator.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,40 @@
from .Google import Create_Service
import datetime
import os.path
import os
import json

CLIENT_SECRET_FILE = os.path.abspath("app/microservices/googleCal/credentials.json")
# CLIENT_SECRET_FILE = "./microservices/googleCal/credentials.json"
API_NAME = "calendar"
API_VERSION = "v3"
SCOPES = ["https://www.googleapis.com/auth/calendar"]

# generate google calendar link for user
def createURL():
name = "Nishant Srivastava"
school = "rpi.edu"
api.create(name,school)
return(link)
def createURL(name, email):
name = name.strip()
school = email.strip().split("@")[1].split(".")[0]

service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES)

# Nishant Srivastava - rpi
calendarName = name+" - "+school

calendar = {
'summary': calendarName,
'timeZone': 'America/New_York'
}

newCalendar = service.calendars().insert(body=calendar).execute()
return(newCalendar['id'])

# when user deletes account, delete calendar
def deleteURL(link):
api.delete(link)
def deleteURL(id):
service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES)
service.calendars().delete(calendarID=id).execute()
pass

# :~)

if __name__ == "__main__":
# createURL("Nishant Srivastava", "[email protected]")
pass
28 changes: 28 additions & 0 deletions web_app/app/migrations/0003_auto_20201229_1753.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Generated by Django 2.2.13 on 2020-12-29 17:53

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('app', '0002_auto_20201227_1759'),
]

operations = [
migrations.AddField(
model_name='student',
name='status',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='university',
name='registeredStudents',
field=models.IntegerField(default=0),
),
migrations.AlterField(
model_name='student',
name='phone_num',
field=models.CharField(max_length=200),
),
]
29 changes: 29 additions & 0 deletions web_app/app/migrations/0004_auto_20201230_1323.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Generated by Django 2.2.13 on 2020-12-30 13:23

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('app', '0003_auto_20201229_1753'),
]

operations = [
migrations.AddField(
model_name='student',
name='user',
field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='student',
name='calendar_link',
field=models.CharField(max_length=200),
),
migrations.DeleteModel(
name='URLCalendar',
),
]
Binary file not shown.
Binary file not shown.
59 changes: 51 additions & 8 deletions web_app/app/models.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,63 @@
from django.db import models
from django import forms
from django.contrib.auth.models import User
from django.core.validators import MaxValueValidator, MinValueValidator, validate_email
import json

# Create your models here.
class University(models.Model):
name = models.CharField(max_length=200, null=False, blank=False)
domain = models.CharField(max_length=20, null=False, blank=False)
registeredStudents = models.IntegerField(null=False, blank=False)
registeredStudents = models.IntegerField(default=0, null=False, blank=False)

class Student(models.Model):
name = models.CharField(max_length=100, null=False, blank=False)
user = models.OneToOneField(User, null=False, on_delete=models.CASCADE)
email = models.CharField(max_length=100, null=False, blank=False)
name = models.CharField(max_length=100, null=False, blank=False)
phone_num = models.CharField(max_length=200, null=False, blank=False)
status = models.IntegerField(null=False, blank=False)
calendar_link = models.ForeignKey("URLCalendar", on_delete=models.CASCADE)
status = models.IntegerField(default=0, null=False, blank=False)
calendar_link = models.CharField(max_length=600, null=False, blank=False)
# calendar_link = models.ForeignKey("URLCalendar", on_delete=models.CASCADE)

# class URLCalendar(models.Model):
# calendar = models.CharField(max_length=200, null=False, blank=False)

class UserForm(forms.ModelForm):
"""
UserForm is the form for user registration
"""
password1 = forms.CharField(label="Password", widget=forms.PasswordInput())
password2 = forms.CharField(label="Confirm Password", widget=forms.PasswordInput())
class Meta:
model = User
fields = (
'email',
)

def clean_email(self):
email = self.cleaned_data.get('email')
# will raise a ValidationError if email is invalid
validate_email(email)
return email

def clean_password2(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
raise forms.ValidationError("The two passwords do not match", 'password_mismatch')
return password2

def save(self, commit=True):
user = super(UserForm, self).save(commit=False)
user.set_password(self.cleaned_data['password1'])
user.username = user.email
if commit:
user.save()
return user

class URLCalendar(models.Model):
calendar = models.CharField(max_length=200, null=False, blank=False)

def saveUni(self):
pass
# class UserProfile(models.Model):
# # links the UserProfile to a User model
# # User model is Django's authentication model: contains username, password, etc.
# user = models.OneToOneField(User, on_delete=models.CASCADE)
# creation_time = models.DateTimeField()
43 changes: 30 additions & 13 deletions web_app/app/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django import forms
import json
from .microservices.googleCal import urlGenerator
import discord
# from discord import Webhook, RequestsWebhookAdapter
import json
import requests

# home page
def index(request):
Expand All @@ -23,28 +26,42 @@ def index(request):
# sign up page
def signUp(request):
if request.method == "POST":
name = request.post['name']
email = request.post['email']
phoneNum = request.post['phoneNum']

name = request.POST['name']
email = request.POST['email']
phoneNum = request.POST['phoneNumber']
print("HELLO!")
form = UserForm(data = request.POST)

print(form)
if form.is_valid():
user = form.save()
print("gets here")

user.is_active = False
user.save()

uniqueURL = URLCalendar(calendar=urlGenerator.createURL())
newStudent = Student(name=name, email=email, phone_num=phoneNum, status=False, calendar_link=uniqueURL)
# uniqueURL = URLCalendar(calendar=urlGenerator.createURL(name, email))
# uniqueURL.save()
uniqueURL = urlGenerator.createURL(name, email)
# print("Unique URL is " + uniqueURL)
newStudent = Student(name=name, email=email, phone_num=phoneNum, calendar_link=uniqueURL)
newStudent.save()

print("Saved student object")

# https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook
webhookURL = "https://discord.com/api/webhooks/793900861436461077/y4vdzi7E9vitmOjtHAiCIVgTnvP5__rIqI_y3b4a0i-9hd-nLXygKt_gTdaa_yL4QmPJ"
webhook = discord.Webhook.from_url(webhookURL, adapter=discord.RequestsWebhookAdapter())
embed = discord.Embed(title="New User", description="A new user has registered with CourseCal!", colour=0x47ff8e)
embed.add_field(name="Name", value=name)
embed.add_field(name="Email", value=email)
embed.add_field(name="Calendar ID", value=uniqueURL)
webhook.send(embed=embed)

html_msg = f"<p><a href='{request.build_absolute_uri('/register/confirm/')}{user.id}'>Click here to activate your account!</a></p>"
mail.send_mail("Account Confirmation", "Please confirm your account registration.", settings.EMAIL_HOST_USER, [user.email], html_message=html_msg)
return render(request, 'sign-up.html', {"success":"Check your email, I sent you an account confirmation link!"})
else:
pass
else:
form = UserCreationForm()
return render(request, 'sign-up.html', {"error": "Error: There was a form error. Retype the above information and resubmit!"})
return render(request, 'sign-up.html', {})

# sign up page
Expand All @@ -64,11 +81,11 @@ def userLogin(request):
request.session['user_name'] = username
# user_id = User.objects.filter(username = username).values('id').first()
# request.session['user_id'] = user_id['id']
return render(request, 'dashboard.html', {'error': 'Success and account is activated'})
return render(request, 'login.html', {'success': 'Success and account is activated'})

# user is valid, but not active
else:
return render(request, 'login.html', {'error': 'Success, but account is deactivated'})
return render(request, 'login.html', {'success': 'Success, but account is deactivated'})

# user doesn't exist
else:
Expand Down
Binary file modified web_app/mydatabase
Binary file not shown.
21 changes: 21 additions & 0 deletions web_app/static/scripts/sign-up.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
function validate(){
var name = document.forms["signUpForm"]["name"].value;
var email = document.forms["signUpForm"]["email"].value;
var password = document.forms["signUpForm"]["password"].value;
var retypedPassword = document.forms["signUpForm"]["retypePassword"].value;
var phoneNumber = document.forms["signUpForm"]["phoneNumber"].value;

if (name == "" || name == null ||){
alert("Error: Name can not be blank!");
return(false);
}else if (email == "" || email == null || email.includes(".edu")){
alert("Error: Email didn't pass check (was null or was not a .edu email)");
return(false);
}else if (password !== retypedPassword || password == null || password == "" || retypePassword == null || retypePassword == ""){
alert("Error: Passwords do not match!");
return(false);
}else if (phoneNumber == "" || phoneNumber == null || phoneNumber.includes("-")){
alert("Error: Phone number is null, empty, or contains dashes!");
return(false);
}
}
6 changes: 6 additions & 0 deletions web_app/templates/login.html
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@
<strong>{{ error|escape }}</strong>
</div>
{% endif %}
{% if success %}
<br>
<div class="notification is-success" r">
<strong>{{ success|escape }}</strong>
</div>
{% endif %}
<br>
<div class="control">
<button type="submit" id="loginButton" class="button is-success">Login</button>
Expand Down
Loading

0 comments on commit 1730577

Please sign in to comment.