Skip to content

Commit

Permalink
fix authentication issue localhost and refactor vue component and sto…
Browse files Browse the repository at this point in the history
…re usage
  • Loading branch information
stevegerrits committed Mar 26, 2024
1 parent 2049915 commit c7ea852
Show file tree
Hide file tree
Showing 15 changed files with 294 additions and 256 deletions.
52 changes: 26 additions & 26 deletions frontend/src/components/FilterComponent.vue
Original file line number Diff line number Diff line change
Expand Up @@ -21,36 +21,35 @@

<script>
import ApiService from '@/services/apiService';
import { mapActions, mapMutations } from 'vuex';
import { useVespaStore } from '@/stores/vespaStore';
export default {
data: () => ({
selectedMunicipalities: [],
municipalities: [],
selectedYears: [],
jaartallen: [2020, 2021, 2022, 2023],
anbAreasActief: false,
}),
computed: {
formattedMunicipalities() {
const formatted_municipalities = this.municipalities.map(municipality => {
return {
name: municipality.name,
id: municipality.id
};
});
return formatted_municipalities;
},
data() {
return {
selectedMunicipalities: [],
municipalities: [],
selectedYears: [],
jaartallen: [2020, 2021, 2022, 2023],
anbAreasActief: false,
};
},
watch: {
selectedMunicipalities(newVal) {
if (newVal.length === 0) {
this.$emit('updateFilters', { municipalities: [], years: this.selectedYears, anbAreasActief: this.anbAreasActief });
}
selectedMunicipalities: {
handler() {
this.emitFilterUpdate();
},
deep: true,
},
},
computed: {
formattedMunicipalities() {
return this.municipalities.map(municipality => ({
name: municipality.name,
id: municipality.id
}));
},
},
methods: {
...mapActions(['updateSelectedMunicipalities']),
...mapMutations(['setSelectedMunicipalities']),
async fetchMunicipalities() {
try {
const response = await ApiService.get('/municipalities/');
Expand All @@ -64,7 +63,8 @@ export default {
}
},
emitFilterUpdate() {
this.$emit('updateFilters', {
const vespaStore = useVespaStore();
vespaStore.applyFilters({
municipalities: this.selectedMunicipalities,
years: this.selectedYears,
anbAreasActief: this.anbAreasActief
Expand All @@ -75,4 +75,4 @@ export default {
this.fetchMunicipalities();
},
}
</script>
</script>
2 changes: 1 addition & 1 deletion frontend/src/components/LoginPage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export default {
const login = async () => {
try {
await vespaStore.loginAction({ username: username.value, password: password.value });
await vespaStore.login({ username: username.value, password: password.value });
router.push('/map');
} catch (error) {
loginError.value = "Failed to login. Please check your username and password.";
Expand Down
150 changes: 7 additions & 143 deletions frontend/src/components/MapPage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,8 @@

<script>
import { useVespaStore } from '@/stores/vespaStore';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { computed, onMounted, ref, watch } from 'vue';
import { computed, onMounted } from 'vue';
import FilterComponent from './FilterComponent.vue';
import FooterComponent from './FooterComponent.vue';
import NavbarComponent from './NavbarComponent.vue';
Expand All @@ -61,146 +60,14 @@ export default {
},
setup() {
const vespaStore = useVespaStore();
const map = ref(null);
const markers = ref([]);
const selectedObservation = ref(null);
const isEditing = ref(false);
const selectedObservation = computed(() => vespaStore.selectedObservation);
const isEditing = computed(() => vespaStore.isEditing);
const markers = computed(() => vespaStore.markers);
const map = computed(() => vespaStore.map);
const isLoggedIn = computed(() => vespaStore.isLoggedIn);
const parseLocation = (locationStr) => {
// Check if the string includes 'POINT'
if (locationStr.includes('POINT')) {
// Extract the numbers after 'POINT (' and before the closing ')'
const matches = locationStr.match(/POINT\s*\(([^)]+)\)/);
if (matches) {
const points = matches[1].split(' ');
// Assuming the format is 'POINT (lng lat)'
const lat = parseFloat(points[1]);
const lng = parseFloat(points[0]);
return { lat, lng };
}
}
console.error("Unable to parse location:", locationStr);
return null;
};
const observations = computed(() => vespaStore.observations.map(obs => ({
...obs,
location: parseLocation(obs.location)
})));
const filtersConfig = computed(() => ({
minCreationDatetime: { label: 'Min Creation Date', type: 'date', value: '' },
maxCreationDatetime: { label: 'Max Creation Date', type: 'date', value: '' },
// Assuming these options are loaded from the store or another source
municipalities: { label: 'Municipality', type: 'select', options: vespaStore.municipalities, value: [] },
years: { label: 'Year', type: 'select', options: vespaStore.years, value: [] }
}));
const filters = ref({
minCreationDatetime: '',
maxCreationDatetime: '',
municipalities: [],
years: []
});
const updateSelectOptions = computed(() => {
// Example logic to update options
filtersConfig.value.municipalities.options = vespaStore.municipalities; // Assuming your store has this data
filtersConfig.value.years.options = vespaStore.years; // Assuming your store has this data
});
// Function to update filters based on user input
const updateFilters = (updatedFilters) => {
// Loop through the updated filters and apply changes
Object.keys(updatedFilters).forEach(key => {
if (filters.value.hasOwnProperty(key)) {
filters.value[key] = updatedFilters[key];
}
});
// Call a method to apply these filters
applyFilters();
};
// Function to apply filters and fetch data based on the current filter state
const applyFilters = async () => {
// Construct the filter query based on the current state of `filters`
// This query will depend on how your API expects to receive these filters
let filterQuery = '?';
// Append each filter to the query string if it's not empty
Object.keys(filters.value).forEach(key => {
const value = filters.value[key];
if (value && Array.isArray(value) && value.length) {
filterQuery += `${key}=${value.join(',')}&`;
} else if (value) {
filterQuery += `${key}=${value}&`;
}
});
// Remove the last '&' for a clean query string
filterQuery = filterQuery.slice(0, -1);
// Assuming you have a method in your Pinia store to fetch observations with the constructed query
await vespaStore.getObservations(filterQuery);
};
const fetchObservations = async () => {
// Assuming you have a method to construct the filter query based on some criteria
const filterQuery = ''; // Construct your filter query here
await vespaStore.getObservations(filterQuery);
};
const initializeMapAndMarkers = () => {
if (!map.value && document.getElementById('mapid')) { // Ensure the element is there
map.value = L.map('mapid').setView([51.0, 4.5], 9);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'Map data © OpenStreetMap contributors',
maxZoom: 18,
}).addTo(map.value);
// Now that the map is guaranteed to be initialized, call updateMarkers
updateMarkers();
}
};
watch(observations, (newObservations) => {
// Update markers based on new observations
markers.value.forEach(marker => marker.remove());
markers.value = [];
newObservations.forEach(obs => {
if (obs.location) {
const marker = L.marker([obs.location.lat, obs.location.lng])
.addTo(map.value)
.on('click', () => { selectedObservation.value = obs; });
markers.value.push(marker);
}
});
}, { deep: true });
const updateMarkers = () => {
if (map.value && observations.value) {
markers.value.forEach(marker => marker.remove()); // Remove existing markers
markers.value = []; // Reset markers array
observations.value.forEach(observation => {
if (observation.location) {
const customIcon = L.divIcon({
className: 'custom-div-icon',
html: "<i class='fa fa-bug' style='color: black; font-size: 24px;'></i>",
iconSize: [30, 42],
iconAnchor: [15, 42]
});
const marker = L.marker([observation.location.lat, observation.location.lng], { icon: customIcon })
.addTo(map.value)
.on('click', () => {
selectedObservation.value = observation;
// Additional logic for selecting an observation
});
markers.value.push(marker);
}
});
}
};
const startEdit = () => {
isEditing.value = true;
};
Expand All @@ -215,19 +82,16 @@ export default {
};
onMounted(async () => {
await fetchObservations();
initializeMapAndMarkers();
await vespaStore.getObservations();
vespaStore.initializeMapAndMarkers();
});
return {
selectedObservation,
isEditing,
markers,
map,
isLoggedIn,
filtersConfig,
updateFilters,
startEdit,
confirmUpdate,
cancelEdit,
Expand Down
2 changes: 0 additions & 2 deletions frontend/src/services/apiService.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ const instance = axios.create({
function getCookie(name) {
const value = '; ' + document.cookie;
const parts = value.split('; ' + name + '=');
console.log('parts', parts)
if (parts.length === 2) return parts.pop().split(';').shift() || null;
return null;
}
Expand All @@ -20,7 +19,6 @@ const ApiService = {
getAxiosInstance() {
instance.interceptors.request.use((config) => {
const csrfToken = getCookie('csrftoken');
console.log('csrfToken', csrfToken)
if (csrfToken) {
config.headers['X-CSRFToken'] = csrfToken;
}
Expand Down
Loading

0 comments on commit c7ea852

Please sign in to comment.