From 7ee41de7a7dd8cd0f5769968fe1805c0123c3b19 Mon Sep 17 00:00:00 2001 From: Pragyansh Chaturvedi Date: Sat, 28 Jan 2023 07:44:27 -0500 Subject: [PATCH] Integrate auth0 and test and fix studyportal --- docker-compose-dev.yml | 1 + docker/development/Dockerfile.dev | 1 + ingest.sh | 1 + requirements.txt | 2 ++ resources/utils.py | 9 ++++++++ studyportal/drive/drive.py | 6 +++++ studyportal/falcon/client.py | 7 ++++-- studyportal/falcon/config.py | 9 ++++++-- studyportal/settings.py | 19 +++++++++++++++- users/auth.py | 8 ++++++- users/migrations/0001_initial.py | 3 ++- users/models.py | 3 ++- users/views.py | 37 ++++++++++++++++++++++++++----- 13 files changed, 92 insertions(+), 14 deletions(-) diff --git a/docker-compose-dev.yml b/docker-compose-dev.yml index 99dbefb..a6cd7d7 100644 --- a/docker-compose-dev.yml +++ b/docker-compose-dev.yml @@ -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 diff --git a/docker/development/Dockerfile.dev b/docker/development/Dockerfile.dev index 4069589..9e62d16 100644 --- a/docker/development/Dockerfile.dev +++ b/docker/development/Dockerfile.dev @@ -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"] diff --git a/ingest.sh b/ingest.sh index 168157b..a5f2c14 100755 --- a/ingest.sh +++ b/ingest.sh @@ -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' diff --git a/requirements.txt b/requirements.txt index 75214c4..d814091 100644 --- a/requirements.txt +++ b/requirements.txt @@ -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 diff --git a/resources/utils.py b/resources/utils.py index d1149c6..a0ff494 100644 --- a/resources/utils.py +++ b/resources/utils.py @@ -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) @@ -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, @@ -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) diff --git a/studyportal/drive/drive.py b/studyportal/drive/drive.py index fe20efa..d3ae188 100644 --- a/studyportal/drive/drive.py +++ b/studyportal/drive/drive.py @@ -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) diff --git a/studyportal/falcon/client.py b/studyportal/falcon/client.py index 457da02..d22459f 100644 --- a/studyportal/falcon/client.py +++ b/studyportal/falcon/client.py @@ -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 diff --git a/studyportal/falcon/config.py b/studyportal/falcon/config.py index 14a147b..175ec50 100644 --- a/studyportal/falcon/config.py +++ b/studyportal/falcon/config.py @@ -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 +) \ No newline at end of file diff --git a/studyportal/settings.py b/studyportal/settings.py index 870f2c2..ad1fd24 100644 --- a/studyportal/settings.py +++ b/studyportal/settings.py @@ -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__)) @@ -60,6 +61,7 @@ ] MIDDLEWARE = [ + "corsheaders.middleware.CorsMiddleware", "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", @@ -67,13 +69,17 @@ "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: @@ -81,7 +87,12 @@ 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 @@ -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") diff --git a/users/auth.py b/users/auth.py index a7192be..f4bd9f4 100644 --- a/users/auth.py +++ b/users/auth.py @@ -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( diff --git a/users/migrations/0001_initial.py b/users/migrations/0001_initial.py index e8b9d35..14cec37 100644 --- a/users/migrations/0001_initial.py +++ b/users/migrations/0001_initial.py @@ -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)), diff --git a/users/models.py b/users/models.py index cd86a03..c174ccf 100644 --- a/users/models.py +++ b/users/models.py @@ -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) diff --git a/users/views.py b/users/views.py index caf1f2c..2249cd5 100644 --- a/users/views.py +++ b/users/views.py @@ -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, @@ -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 = [] @@ -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