Skip to content

Commit

Permalink
fix some view and continue to complete the connection between the fro…
Browse files Browse the repository at this point in the history
…nt and the back
  • Loading branch information
lugopi committed Mar 21, 2024
1 parent 885868e commit 983aff4
Show file tree
Hide file tree
Showing 28 changed files with 519 additions and 270 deletions.
8 changes: 4 additions & 4 deletions backend/kodecupid/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,11 @@
SECRET_KEY = 'django-insecure-1s(9a1$*oan-&wjv01x(^$#*0*2x$%8=!=w^wjt2p4!h=7$fqv'

DEBUG = True if os.environ.get('KODECUPID_DEBUG') == 'true' else False
ALLOWED_HOSTS = ['localhost', '127.0.0.1', '[::1]', os.environ.get('KODECUPID_BACKEND_HOST')]
ALLOWED_HOSTS = ['localhost', '127.0.0.1', '[::1]', '192.168.1.159', os.environ.get('KODECUPID_BACKEND_HOST')]


CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = [
"http://localhost",
"http://127.0.0.1",
Expand Down Expand Up @@ -162,5 +163,4 @@
'propagate': True,
},
},
}

}
3 changes: 2 additions & 1 deletion backend/kodecupid/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"""
from django.contrib import admin
from django.urls import path
from kodecupidapp.views import RegisterView, TagListView
from kodecupidapp.views import RegisterView, TagListView, UserDetailsView
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
Expand All @@ -27,5 +27,6 @@
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path('api/user/register/', RegisterView.as_view(), name='register'),
path('api/user/', UserDetailsView.as_view(), name='user-details'),
path('api/tags/', TagListView.as_view(), name='tag-list'),
]
2 changes: 1 addition & 1 deletion backend/kodecupidapp/serializers/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from .user import UserRegistrationSerializer
from .user import *
from .tag import TagSerializer
from .picture import PictureSerializer
from .like import LikeSerializer
2 changes: 1 addition & 1 deletion backend/kodecupidapp/serializers/tag.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@
class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
fields = ['name']
fields = ['id','name']
12 changes: 12 additions & 0 deletions backend/kodecupidapp/serializers/user.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
from rest_framework import serializers
from django.contrib.auth import get_user_model

from .tag import TagSerializer
from .picture import PictureSerializer

Tag = get_user_model().tags.through

User = get_user_model()


class UserRegistrationSerializer(serializers.ModelSerializer):
class Meta:
model = User
Expand All @@ -16,3 +22,9 @@ def create(self, validated_data):
username=validated_data['username'],
password=validated_data['password']
)

class UserDetailsSerializer(serializers.ModelSerializer):

class Meta:
model = User
fields = ['username', 'bio','tags','pfp','looking_for']
2 changes: 1 addition & 1 deletion backend/kodecupidapp/views/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
from .user import RegisterView
from .user import *
from .tag import TagListView
25 changes: 25 additions & 0 deletions backend/kodecupidapp/views/user.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

from rest_framework.permissions import IsAuthenticated
from rest_framework.permissions import AllowAny
from rest_framework_simplejwt.authentication import JWTAuthentication

from ..serializers import UserRegistrationSerializer
from ..serializers import UserDetailsSerializer

class RegisterView(APIView):
permission_classes = [AllowAny]
Expand All @@ -13,3 +18,23 @@ def post(self, request):
serializer.save()
return Response({"message": "User created successfully."}, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class UserDetailsView(APIView):
authentication_classes = [JWTAuthentication]
permission_classes = [IsAuthenticated]

def get(self, request):
user = request.user

serializer = UserDetailsSerializer(user)
return Response(serializer.data)

def put(self, request):
user = request.user
serializer = UserDetailsSerializer(user, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

2 changes: 1 addition & 1 deletion frontend/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8">
<link rel="icon" href="/favicon.ico">
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@5.x/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@7.x/css/materialdesignicons.min.css" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Kodecupid</title>
</head>
Expand Down
Binary file modified frontend/public/favicon.ico
Binary file not shown.
Binary file added frontend/public/jdg-joueur-du-grenier.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion frontend/src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { RouterView } from 'vue-router';
<v-app>
<v-container>
<v-row justify="center">
<v-col cols="12" sm="9" md="10" lg="7" xl="7">
<v-col cols="12" sm="10" md="9" lg="6" xl="6">
<v-main>
<RouterView />
</v-main>
Expand Down
36 changes: 21 additions & 15 deletions frontend/src/components/Navbar.vue
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
<template>
<v-bottom-navigation v-model="value" :bg-color="color()" mode="shift" grow>
<v-btn :to="{ name: 'home' }">
<v-icon aria-hidden="false">
mdi-home
</v-icon>
<span>Home</span>
</v-btn>

<v-btn :to="{ name: 'search' }">
<v-icon aria-hidden="false">
Expand All @@ -21,29 +15,31 @@
<span>Match</span>
</v-btn>

<v-btn :to="{ name: 'account' }">
<v-btn :to="{ name: 'account-show' }">
<v-icon aria-hidden="false">
mdi-account
</v-icon>
<span>Account</span>
</v-btn>

<v-btn :to="{ name: 'signin' }">
<v-btn @click="logout()" v-if="checkAuth()">
<v-icon aria-hidden="false">
mdi-account
mdi-logout
</v-icon>
<span>Signin</span>
<span>Logout</span>
</v-btn>

<v-btn :to="{ name: 'about' }">
<v-icon aria-hidden="false">mdi-information</v-icon>
<span>About</span>
<v-btn v-else :to="{ name: 'signin' }">
<v-icon aria-hidden="false">
mdi-login
</v-icon>
<span>Signin</span>
</v-btn>
</v-bottom-navigation>

</template>

<script>
import router from '@/router';
export default {
name: 'Navbar',
data() {
Expand All @@ -61,7 +57,17 @@ export default {
case 4: return 'orange'
default: return 'blue-grey'
}
},
logout() {
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
router.push({ name: 'signin', replace: true, force: true });
},
checkAuth() {
const token = localStorage.getItem('accessToken');
return token !== null;
}
}
};
</script>
3 changes: 2 additions & 1 deletion frontend/src/configs/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@ export const API_ROUTES = {
USER_SIGNUP: API_SERVER_URL+'/api/user/register/',
USER_SIGNIN: API_SERVER_URL+'/api/token/',
USER_TOKEN_REFRESH: API_SERVER_URL+'/api/token/refresh/',
USER_DETAIL: API_SERVER_URL+'/api/user/',

ACCOUNT: API_SERVER_URL+'/account',
TAG_LIST: API_SERVER_URL+'/api/tags/',

};

Expand Down
17 changes: 12 additions & 5 deletions frontend/src/plugins/axiosPlugin.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,35 @@
import axios from 'axios';
import { store } from '@/store';
import router from '@/router'; // Assuming you have Vue Router set up

export default {
install: (app) => {
console.log('axios plugin installed');
axios.defaults.headers.common['Content-Type'] = 'application/json';
axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('accessToken')}`;

axios.interceptors.response.use(response => response, error => {
const originalRequest = error.config;
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
const refreshToken = localStorage.getItem('refreshToken');

return axios.post(store.routes['USER_SIGNIN'], {
return axios.post(store.routes['USER_TOKEN_REFRESH'], {
'refresh': refreshToken
}, {
withCredentials: true
}).then((response) => {
if (response.status === 200) {
localStorage.setItem('accessToken', response.data.access);
axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('accessToken')}`;
return axios(originalRequest);
} else {
router.push({ name: 'signin',replace: true, force: true });
}

return axios(originalRequest);
}).catch(() => {
router.push({ name: 'signin',replace: true, force: true });
});
}
return Promise.reject(error);
});
app.config.globalProperties.$axios = axios;
}
};
79 changes: 34 additions & 45 deletions frontend/src/router/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,64 +11,53 @@ const router = createRouter({
{
path: '/search',
name: 'search',
component: () => import('@/views/SearchView.vue')
component: () => import('@/views/cupid/SearchView.vue'),
meta: { requiresAuth: true }
},
{
path: '/match',
name: 'match',
component: () => import('@/views/MatchView.vue')
component: () => import('@/views/cupid/MatchView.vue'),
meta: { requiresAuth: true }
},
{
path: '/signup',
name: 'signup',
component: () => import('@/views/SignupView.vue')
},
{
path: '/signin',
name: 'signin',
component: () => import('@/views/SigninView.vue')
path: '/authentication',
name: 'authentication',
component: () => import('@/views/authentication/AuthenticationView.vue'),
children: [
{ path: '', name: 'signin', component: () => import('@/views/authentication/SigninView.vue') },
{ path: 'signup', name: 'signup', component: () => import('@/views/authentication/SignupView.vue') },
]
},
{
path: '/account',
name: 'account',
component: () => import('@/views/AccountView.vue')
},
{
path: '/about',
name: 'about',
component: () => import('@/views/AboutView.vue')
component: () => import('@/views/account/AccountView.vue'),
meta: { requiresAuth: true },
children: [
{ path: '', name: 'account-show', component: () => import('@/views/account/ShowView.vue') },
{ path: 'edit',name: 'account-edit', component: () => import('@/views/account/EditView.vue') }
]
}
],
})



// router.beforeEach((to, from, next) => {
// if (to.meta.requiresAuth) {

// axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('accessToken')}`;
// axios.interceptors.response.use(
// response => response,
// error => {
// if (error.response.status === 401) {
// localStorage.removeItem('accessToken');
// next({ name: 'signin' });
// }
// return Promise.reject(error);
// }
// )
// if () {
// // User is authenticated, allow access
// next();
// } else {
// // User is not authenticated, redirect to login page
// next({ name: 'signin' });
// }
// } else {
// // Route does not require authentication, allow access
// next();
// }
// });

router.beforeEach((to, from, next) => {
// Check if the route requires authentication
if (to.matched.some(record => record.meta.requiresAuth)) {
// Check if the user is authenticated (e.g., by checking if the JWT token exists)
const jwtToken = localStorage.getItem('accessToken');
if (!jwtToken) {
// If the user is not authenticated, redirect to the login page
next({ name: 'signin', query: { redirect: to.fullPath } });
} else {
// If the user is authenticated, proceed to the route
next();
}
} else {
// If the route doesn't require authentication, proceed to the route
next();
}
});

export default router
1 change: 0 additions & 1 deletion frontend/src/store/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import API_ROUTES from '@/configs/constants.js';

export const store = reactive({
routes:API_ROUTES,
user:ref({}),
});

export default store;
5 changes: 0 additions & 5 deletions frontend/src/views/AboutView.vue

This file was deleted.

Loading

0 comments on commit 983aff4

Please sign in to comment.