Skip to content

Commit

Permalink
Merge pull request #292 from zstenger93/api_new
Browse files Browse the repository at this point in the history
Api new
  • Loading branch information
zstenger93 authored Mar 3, 2024
2 parents c3c17c6 + 2a17301 commit efddefb
Show file tree
Hide file tree
Showing 7 changed files with 227 additions and 177 deletions.
73 changes: 19 additions & 54 deletions backend/user_api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@
from django_otp import match_token
from email.mime.image import MIMEImage

from django.core.files.storage import default_storage
from django.core.files.images import ImageFile

from .authentication import account_activation_token, is_authenticated
from .serializers import UserRegisterSerializer, UserLoginSerializer, UserSerializer
from .validations import user_registration, is_valid_email, is_valid_password
Expand All @@ -40,6 +43,7 @@
import qrcode
import logging
from io import BytesIO
from PIL import Image

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -158,12 +162,15 @@ class updateProfile(APIView):
def post(self, request):
if request.user.is_authenticated:
data = request.data
if data.get('profile_picture'):
request.user.profile_picture = data.get('profile_picture')
if 'profile_picture' in request.FILES:
if default_storage.exists(request.user.profile_picture.path):
default_storage.delete(request.user.profile_picture.path)
image = ImageFile(request.FILES['profile_picture'])
request.user.profile_picture.save(image.name, image, save=True)
if data.get('email'):
request.user.email = data.get('email')
if data.get('username'):
request.user.username = data.get('username')
request.user.vusername = data.get('username')
if data.get('title'):
request.user.title = data.get('title')
if data.get('AboutMe'):
Expand Down Expand Up @@ -228,15 +235,20 @@ def get(self, request):

username = user_response.json()["login"]
email = user_response.json()["email"]

profile_picture_url = user_response.json()["image"]["versions"]["medium"]
response = requests.get(profile_picture_url)
img = Image.open(BytesIO(response.content))
image_name = os.path.basename(profile_picture_url)
directory = 'profile_pictures/'
save_path = os.path.join(directory, image_name)
img.save(save_path)

intra_lvl = user_response.json()["cursus_users"][1]["level"]
school = user_response.json()["campus"][0]["name"]
ft_url = user_response.json()["url"],
ft_user = True

# with open('output.json', 'w') as f:
# json.dump(user_response.json(), f, indent=4)

titles = user_response.json().get("titles", [])
title = ""
if titles:
Expand All @@ -250,7 +262,7 @@ def get(self, request):
'username': username,
'email': email,
'title': title,
'profile_picture': profile_picture_url,
'profile_picture': save_path.replace('/app/backend/media', ''),
'intra_level': intra_lvl,
'school': school,
'ft_url': ft_url,
Expand Down Expand Up @@ -309,53 +321,6 @@ def post(self, request):
return response


class updateProfile(APIView):
permission_classes = (permissions.IsAuthenticated,)
authentication_classes = (BlacklistCheckJWTAuthentication,)
##
def post(self, request):
if request.user.is_authenticated:
data = request.data
if data.get('profile_picture'):
request.user.profile_picture = data.get('profile_picture')
if data.get('email'):
request.user.email = data.get('email')
if data.get('username'):
request.user.username = data.get('username')
if data.get('title'):
request.user.title = data.get('title')
if data.get('AboutMe'):
request.user.AboutMe = data.get('AboutMe')
if data.get('school'):
request.user.school = data.get('school')
if data.get('wins'):
request.user.wins = data.get('wins')
if data.get('losses'):
request.user.losses = data.get('losses')
if data.get('win_rate'):
if request.user.total_matches == 0:
request.user.win_rate = 0
else:
request.user.win_rate = request.user.wins / request.user.total_matches
if data.get('total_matches'):
request.user.total_matches = data.get('total_matches')
if data.get('match_history'):
history = request.user.match_history
if history is None:
history = []
history.append(data.get('match_history'))
request.user.match_history = history
if data.get('TwoFA'):
request.user.TwoFA = data.get('TwoFA')
if data.get('password'):
request.user.set_password(data.get('password'))
request.user.save()

return Response({"detail": "Profile updated"}, status=status.HTTP_200_OK)
else:
return Response({"detail": "No active user session"}, status=status.HTTP_400_BAD_REQUEST)


class activateTwoFa(APIView):
permission_classes = (permissions.IsAuthenticated,)
authentication_classes = (BlacklistCheckJWTAuthentication,)
Expand Down
2 changes: 2 additions & 0 deletions docker/frontend/frontend.Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ RUN npm install -g serve

RUN npm install

RUN npm ci

COPY . .

EXPOSE 3000
Expand Down
4 changes: 4 additions & 0 deletions docker/nginx/config/backend.conf
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ server {
add_header 'Access-Control-Allow-Headers' 'Origin, X-Requested-With, Content-Type, Accept, Authorization' always;
}

location /media/ {
alias /app/backend/media/;
}

location ~ ^/static/js/main\.[a-f0-9]+\.js$ {
autoindex on;
alias /app/frontend/build/static/js/;
Expand Down
194 changes: 146 additions & 48 deletions frontend/src/components/API.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,49 +2,83 @@ import axios from "axios";
import Cookies from "js-cookie";

export const fetchUserDetails = async (
setUserDetails,
setUsername,
setImageUrl,
redirectUri
) => {
const response = await getUserDetails({ redirectUri });
setUserDetails(response.data.user);
setUserDetails,
setUsername,
setImageUrl,
redirectUri
) => {
const response = await getUserDetails({ redirectUri });
setUserDetails(response.data.user);
setUsername(response.data.user.username);
if (response.data.user.profile_picture) {
let url = response.data.user.profile_picture;
setImageUrl(url);
}
};

console.log(response.data.user);
export const getUserDetails = async ({ redirectUri }) => {
let response = {};
try {
const token = Cookies.get("access");
response = await axios.get(`${redirectUri}/api/profile`, {
headers: {
Authorization: `Bearer ${token}`,
},
withCredentials: true,
});
} catch (error) {
console.log(error);
}
return response;
};

setUsername(response.data.user.username);
export const changeUsername = async ({ redirectUri, username }) => {
let response = {};
try {
const token = Cookies.get("access");
response = await axios.post(
`${redirectUri}/api/updateProfile`,
{ username: username },
{
headers: {
Authorization: `Bearer ${token}`,
},
withCredentials: true,
}
);
} catch (error) {
console.log(error);
}
return response;
};

if (response.data.user.profile_picture) {
let url = decodeURIComponent(
response.data.user.profile_picture.replace("/media/", "")
).replace(":", ":/");
setImageUrl(url);
}
};

export const getUserDetails = async ({ redirectUri }) => {
let response = {};
try {
const token = Cookies.get('access');
response = await axios.get(`${redirectUri}/api/profile`, {
headers: {
Authorization: `Bearer ${token}`,
},
withCredentials: true,
});
} catch (error) {
console.log(error);
}
return response;
};
export const changeAbout = async ({ redirectUri, about }) => {
let response = {};
try {
const token = Cookies.get("access");
response = await axios.post(
`${redirectUri}/api/updateProfile`,
{ AboutMe: about },
{
headers: {
Authorization: `Bearer ${token}`,
},
withCredentials: true,
}
);
} catch (error) {
console.log(error);
}
return response;
};

export const changeUsername = async ({ redirectUri, username }) => {
export const changePassword = async ({ redirectUri, password }) => {
let response = {};
try {
const token = Cookies.get('access');
response = await axios.post(
`${redirectUri}/api/updateProfile`,
{ username: username },
{ password: password },
{
headers: {
Authorization: `Bearer ${token}`,
Expand All @@ -58,22 +92,86 @@ export const fetchUserDetails = async (
return response;
};

export const changeAbout = async ({ redirectUri, about }) => {
export const changeAvatar = async ({ redirectUri, file }) => {
let response = {};
try {
const token = Cookies.get('access');
response = await axios.post(
`${redirectUri}/api/updateProfile`,
{ AboutMe: about },
{
headers: {
Authorization: `Bearer ${token}`,
},
withCredentials: true,
}
);
const token = Cookies.get('access');
const formData = new FormData();
formData.append('profile_picture', file);

response = await axios.post(
`${redirectUri}/api/updateProfile`,
formData,
{
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'multipart/form-data',
},
withCredentials: true,
}
);
} catch (error) {
console.log(error);
console.log(error);
}
return response;
};
};

export const activate2FA = async ({ redirectUri }) => {
let response = {};
try {
const token = Cookies.get("access");
response = await axios.post(
`${redirectUri}/api/activateTwoFa`,
{},
{
headers: {
Authorization: `Bearer ${token}`,
},
withCredentials: true,
}
);
} catch (error) {
console.log(error);
}
return response;
};

export const deactivate2FA = async ({ redirectUri }) => {
let response = {};
try {
const token = Cookies.get("access");
response = await axios.post(
`${redirectUri}/api/deactivateTwoFa`,
{},
{
headers: {
Authorization: `Bearer ${token}`,
},
withCredentials: true,
}
);
} catch (error) {
console.log(error);
}
return response;
};

export const deleteAccount = async ({ redirectUri }) => {
let response = {};
try {
const token = Cookies.get("access");
response = await axios.post(
`${redirectUri}/api/accountDeletion`,
{},
{
headers: {
Authorization: `Bearer ${token}`,
},
withCredentials: true,
}
);
} catch (error) {
console.log(error);
}
return response;
};
Loading

0 comments on commit efddefb

Please sign in to comment.