Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Integrate auth0 and test and fix studyportal #55

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docker-compose-dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ services:
CLIENT_SECRET: ${CLIENT_SECRET}
ACCESS_URL: ${ACCESS_URL}
USER_URL: ${USER_URL}
USER_INFO_URL: ${USER_INFO_URL}
ACCOUNTS_URL: ${ACCOUNTS_URL}
REDIRECT_URL: ${REDIRECT_URL}
stdin_open: true
Expand Down
1 change: 1 addition & 0 deletions docker/development/Dockerfile.dev
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,6 @@ RUN chmod +x run.sh
# Install the dependencies system-wide
# TODO: Use build args to avoid installing dev dependencies in production
RUN pip install -r requirements.txt
RUN pip install -U python-dotenv

ENTRYPOINT ["./run.sh"]
1 change: 1 addition & 0 deletions ingest.sh
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ user.save()
"
EOF
# Create database
docker exec $POSTGRES_CONTAINER_NAME /bin/bash -c 'createuser -s --role=studyportal studyportal'
docker exec $POSTGRES_CONTAINER_NAME /bin/bash -c 'PGPASSWORD=studyportal createdb -h localhost -U studyportal studyportal'
# Ingest mock data
docker exec $NEXUS_CONTAINER_NAME /bin/bash -c 'python3 data.py'
Expand Down
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,5 @@ channels_redis==2.4.2
black==20.8b1
Pillow==8.1.2
gunicorn==20.1.0
authlib==1.0
python-dotenv==0.19
9 changes: 9 additions & 0 deletions resources/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,14 +75,17 @@ def add_file(file, course):
def uploadToDrive(service, folder_id, file_details):
try:
file_metadata = {"name": file_details["name"], "parents": [folder_id]}
print("file_metadata", file_metadata)
media = MediaFileUpload(
file_details["location"], mimetype=file_details["mime_type"]
)
print("media", media)
file = (
service.files()
.create(body=file_metadata, media_body=media, fields="id")
.execute()
)
print("file", file)
return file.get("id")
except errors.HttpError as error:
print("An error occurred:", error)
Expand Down Expand Up @@ -161,10 +164,12 @@ def get_file_details_and_upload(
ext = "docx"
rand = str(random.randint(0, 100000))
temp = open("temp" + rand + "." + ext, "wb")
print("yahan?")
if is_file_object:
temp.write(file_data)
else:
temp.write(base64.b64decode(base64String))
print("aabhi")
file_details = {
"name": name,
"mime_type": mime_type,
Expand All @@ -182,12 +187,16 @@ def get_file_details_and_upload(
folder_id = structure["study"][course.department.abbreviation][course.code][
folder_identifier
]
print("aagye?")
driveid = uploadToDrive(driveinit(), folder_id, file_details)
print("yeh hai driveid", driveid)
updatePermissions(driveinit(), driveid)
print("kuch kiya")
os.remove("temp" + rand + "." + ext)
# end of manipulation
return {"size": size, "driveid": driveid, "ext": ext}
except Exception:
print("kuch nhi hua")
os.remove("temp" + rand + "." + ext)
return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)

Expand Down
6 changes: 6 additions & 0 deletions studyportal/drive/drive.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,25 @@ def driveinit():
"openid",
"https://www.googleapis.com/auth/userinfo.email",
]
print("here yet?")
if os.path.exists(PICKLE):
with open(PICKLE, "rb") as token:
creds = pickle.load(token)
print("wbt")
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
print("refreshinmg", creds)
creds.refresh(Request())
print("???")
else:
print("something else")
flow = InstalledAppFlow.from_client_secrets_file(CREDENTIALS, SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open(PICKLE, "wb") as token:
pickle.dump(creds, token)
print("hi")
service = build("drive", "v3", credentials=creds)

user_service = build("oauth2", "v2", credentials=creds)
Expand Down
7 changes: 5 additions & 2 deletions studyportal/falcon/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,13 @@ def get_logged_in_user(config, cookies):
cookie = cookies[COOKIE_NAME]
if cookie == "":
return ""
token = get_token(config)
#token = get_token(config)
#we are passing the token as a cookie
user_data = make_request(
config.URLResourceOwner + "logged_in_user/" + cookie, token
#config.URLResourceOwner + "logged_in_user/" + cookie, token
config.URLResourceOwner, cookie
)
print(user_data)
return user_data


Expand Down
9 changes: 7 additions & 2 deletions studyportal/falcon/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,14 @@
client_secret = os.environ.get("CLIENT_SECRET")
access_url = os.environ.get("ACCESS_URL")
user_url = os.environ.get("USER_URL")
userinfo_url = os.environ.get("USER_INFO_URL")
accounts_url = os.environ.get("ACCOUNTS_URL")
redirect_url = os.environ.get("REDIRECT_URL")

# config = client.FalconClient(
# client_id, client_secret, access_url, user_url, accounts_url, redirect_url
# )

config = client.FalconClient(
client_id, client_secret, access_url, user_url, accounts_url, redirect_url
)
client_id, client_secret, access_url, userinfo_url, accounts_url, redirect_url
)
19 changes: 18 additions & 1 deletion studyportal/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

import os
import yaml
from pathlib import Path

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
CUR_DIR = os.path.dirname(os.path.abspath(__file__))
Expand Down Expand Up @@ -60,28 +61,38 @@
]

MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware",
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"corsheaders.middleware.CorsMiddleware",
]

ROOT_URLCONF = "studyportal.urls"

CORS_ORIGIN_WHITELIST = (
"https://study.sdslabs.co",
"http://10.25.1.18:3005",
"http://localhost:3005",
"https://10.25.1.18:3005",
"https://localhost:3005",
"http://0.0.0.0:3005"
)

if DEBUG:
whitelist = list(CORS_ORIGIN_WHITELIST)
whitelist.append("http://studyportal.sdslabs.local")
whitelist.append("http://localhost:3005")
whitelist.append("http://127.0.0.1:3005")
whitelist.append("https://localhost:3005")
whitelist.append("https://127.0.0.1:3005")
whitelist.append("http://0.0.0.0:3005")
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = tuple(whitelist)
print("bhendalund0")

CORS_ALLOW_CREDENTIALS = True

Expand Down Expand Up @@ -183,3 +194,9 @@

MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = "/media/"


# Load Auth0 application settings into memory
AUTH0_DOMAIN = os.environ.get("AUTH0_DOMAIN")
AUTH0_CLIENT_ID = os.environ.get("AUTH0_CLIENT_ID")
AUTH0_CLIENT_SECRET = os.environ.get("AUTH0_CLIENT_SECRET")
8 changes: 7 additions & 1 deletion users/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,14 @@

def authorize_user(request):
cookies = request.COOKIES
print(cookies)
print("\n\n\n\n\n\n\n\n\n\n\n\n\n")
try:
user = client.get_logged_in_user(config, {"sdslabs": cookies["sdslabs"]})
user = client.get_logged_in_user(config, {"sdslabs": request.headers["Authorization"].split(" ")[1]})
#user = request.headers["Authorization"].split(" ")[1]
print("\n\n\n\n\n\n\n\n")
print(user)
print("\n\n\n\n\n\n\n\n\n")
for key in user:
if key == "error":
return Response(
Expand Down
3 changes: 2 additions & 1 deletion users/migrations/0001_initial.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ class Migration(migrations.Migration):
"id",
models.AutoField(editable=False, primary_key=True, serialize=False),
),
("auth_id", models.IntegerField(default=0)),
#("auth_id", models.IntegerField(default=0)),
("auth_id", models.CharField(default="", max_length=100)),
("username", models.CharField(default="", max_length=100)),
("email", models.CharField(default="", max_length=100)),
("profile_image", models.URLField(max_length=500)),
Expand Down
3 changes: 2 additions & 1 deletion users/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@

class User(models.Model):
id = models.AutoField(primary_key=True, editable=False)
auth_id = models.IntegerField(default=0)
#auth_id = models.IntegerField(default=0)
auth_id = models.CharField(max_length=100, default="")
username = models.CharField(max_length=100, default="")
email = models.CharField(max_length=100, default="")
profile_image = models.URLField(max_length=500)
Expand Down
37 changes: 31 additions & 6 deletions users/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,27 +49,46 @@ def create_user(user_details):

class UserViewSet(APIView):
def get(self, request):
print("\n\n\n\n\n\n\n\n\n\n\n")
print(request.headers["Authorization"])
print("\n\n\n\n\n\n\n\n\n\n\n")
token = request.headers["Authorization"].split(" ")[1]
if token == "None":
tokenType = request.headers["Authorization"].split(" ")[0]
if tokenType == "StudyPortal":
"""
This following section handles the external auth flow
"""
user = authorize_user(request)
if user is not None:
queryset = User.objects.filter(auth_id=user["id"])
#queryset = User.objects.filter(auth_id=user["id"])
print(user["sub"])
print(int(user["sub"].split("|")[1]))
print(type(int(user["sub"].split("|")[1])))
queryset = User.objects.filter(auth_id=int(user["sub"].split("|")[1])%2147483647)
print("queryset hogya", int(user["sub"].split("|")[1])%2147483647)
serializer = UserSerializer(queryset, many=True)
print("serializer", serializer.data)

if serializer.data == []:
data = {
"auth_id": user["id"],
"username": user["username"],
#"auth_id": user["id"],
"auth_id": int(user["sub"].split("|")[1])%2147483647,
#"username": user["username"],
"username": user["name"],
"email": user["email"],
"profile_image": user["image_url"],
#"profile_image": user["image_url"],
"profile_image": user["picture"],
"role": "user",
}
print(data)
create_user(data)
queryset = User.objects.filter(auth_id=user["id"])
#queryset = User.objects.filter(auth_id=user["id"])
queryset = User.objects.filter(auth_id=int(user["sub"].split("|")[1])%2147483647)
print("second queryset")
serializer = UserSerializer(queryset, many=True)
user = serializer.data[0]
print("user after second queryset")
print(user)
encoded_jwt = jwt.encode(
{"username": user["username"], "email": user["email"]},
SECRET_KEY,
Expand All @@ -86,6 +105,10 @@ def get(self, request):
)
else:
user = getUserFromJWT(token)
#user = authorize_user(request)
print("\n\n\n\n\n\n\n\n\n")
print("yeh mera user from line 94")
print(user)
if user is not None:
courselist = user["courses"]
courses = []
Expand Down Expand Up @@ -287,8 +310,10 @@ def get(self, request, user):

@check_user
def post(self, request, user):
print("\n\n\n\n\n")
file = request.data["file"]
name = request.data["name"]
print(name)
course = Course.objects.get(id=request.data["course"])
file_details = get_file_details_and_upload(
file, name, request.data["filetype"], course, True, False
Expand Down