Merge branch 'develop' into frontend/robin

This commit is contained in:
rchrist 2019-05-14 12:18:41 +02:00
commit 93174fa788
21 changed files with 1175 additions and 651 deletions

View File

@ -62,6 +62,15 @@ dependencies {
// https://mvnrepository.com/artifact/com.mashape.unirest/unirest-java
compile group: 'com.mashape.unirest', name: 'unirest-java', version: '1.3.1'
compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
compile group: 'org.slf4j', name:'slf4j-api', version: '1.7.2'
compile group: 'ch.qos.logback', name:'logback-classic', version: '1.0.9'
compile group: 'ch.qos.logback', name:'logback-core', version: '1.0.9'
testCompile group: 'junit', name: 'junit', version: '4.+'
}
node {

File diff suppressed because it is too large Load Diff

View File

@ -13,14 +13,14 @@
"build": "quasar build"
},
"dependencies": {
"@quasar/extras": "^1.1.1",
"@quasar/extras": "^1.1.2",
"ajv": "6.8.1",
"axios": "^0.18.0",
"quasar": "^1.0.0-beta.17",
"quasar": "^1.0.0-beta.23",
"vue-qrcode-reader": "^1.4.2"
},
"devDependencies": {
"@quasar/app": "^1.0.0-beta.17",
"@quasar/app": "^1.0.0-beta.25",
"@vue/eslint-config-prettier": "^4.0.0",
"babel-eslint": "^10.0.1",
"eslint": "^5.10.0",

View File

@ -72,7 +72,8 @@ module.exports = function (ctx) {
'QPopupEdit',
'QSlideTransition',
'QToggle',
'QLinearProgress'
'QLinearProgress',
'QBtnGroup'
],
directives: [

View File

@ -235,7 +235,7 @@
}
},
created() {
this.evalAuthentication();
//this.evalAuthentication();
},
methods: {
//openURL

View File

@ -1,7 +1,5 @@
<template>
<div>
<!-- <div :is="stationComponent" @q-tb="scrollToBottomState" :stationObject="tempStation">STATION</div>-->
<!-- <div v-show="!stationComponent">-->
<form>
<div class="q-pa-md q-gutter-y-md">
<p class="text-h5">{{ isNewCache ? "Neuen Cache erstellen" : "Cache bearbeiten"}}</p>
@ -94,40 +92,56 @@
</q-item>
</q-card>
<div class="row q-mt-xl">
<q-btn @click="saveCache" class="full-width" color="primary" unelevated stack label="Cache speichern"
<q-btn @click="saveCache" class="full-width q-mb-md" color="primary" unelevated stack label="Cache speichern"
icon="save_alt"/>
<q-btn to="/overview" class="full-width" color="negative" unelevated stack label="Abbrechen" />
</div>
</div>
</form>
<!-- </div>-->
</div>
</template>
<script>
// import station from './StationEdit'
import {mapGetters} from 'vuex';
export default {
name: "Cache",
data() {
return {
// stations: [],
// endStation: {},
//endStation: {},
scrolldown: false,
isNewCache: this.$route.params.id === undefined,
tempCache: {},
//tempCache: {},
}
},
// components: {
// station
// },
beforeRouteUpdate(to, from, next) {
console.log("beforeRouteUpdate: reset data and fetch");
this.$store.commit('cacheCollector/RESET_NEW_CACHE');
next()
},
beforeCreate: function () {
},
created: function () {
console.log("isNewCache: " + this.isNewCache);
console.log("fetch Caches from Store");
//this.tempCache = JSON.parse(JSON.stringify(this.cache));
console.log("Route Params: " + this.$route.params.id);
if (!this.isNewCache) {
this.$axios.get('/api/allCaches')
.then((response) => {
console.log("/api/allCaches");
//console.log(JSON.stringify(response.data));
console.log(response.data);
let cache = response.data.find(cache => Number(cache.id) === Number(this.$route.params.id));
console.log(cache);
let stations = cache.stationen.filter(station => station.description !== "Endstation");
let endstation = cache.stationen.find(station => station.description === "Endstation");
console.log(stations);
console.log(endstation);
this.$store.commit('cacheCollector/SET_CACHE', cache);
this.$store.commit('cacheCollector/SET_STATIONS', stations);
this.$store.commit('cacheCollector/SET_ENDSTATION', endstation);
})
}
},
beforeMount: function () {
},
@ -146,37 +160,12 @@
methods: {
editEndStation() {
console.log("editEndStation()");
const station = this.endStation;
const station = this.$store.getters['cacheCollector/GET_ENDSTATION'];
console.log(station);
if (station.hasOwnProperty('id')) {
//this.$router.push({ path: '/station/'+station.id});
} else {
// TODO Stationen bearbeitbar machen bevor sie abgeschickt werden. Am besten Station Objekt als Übergabe Parameter bei Router
this.$store.commit('cacheCollector/SET_TEMPSTATION', station);
//this.$router.push({path: `/tempendstation/${index}`}); // add parameter
this.$router.push({path: `/tempendstation/`}); // add parameter
}
this.$store.commit('cacheCollector/SET_TEMPSTATION', station);
this.$router.push({path: `/tempendstation/`}); // add parameter
},
// getStations() {
// console.log("get Stations");
// let stations = this.computedStations.get();
// this.stations = stations.filter(station => station.description !== "Endstation");
// console.log(this.stations);
// this.endStation = stations.filter(station => station.description === "Endstation");
// console.log(this.endStation);
// },
// setStations() {
// let stations = this.stations;
// stations.push(this.endStation);
// this.computedStations.set(stations);
// },
// cacheToStore() {
// // push tempCache to Store
// console.log("set Cache");
// this.$store.commit('cacheCollector/SET_CACHE', JSON.parse(JSON.stringify(this.tempCache)));
// // this.SET_CACHE(JSON.parse(JSON.stringify(this.tempCache)));
// },
addStation() {
this.$router.push({path: '/station'});
},
@ -199,10 +188,10 @@
},
saveCache() {
// commit to store, send to api, if success -> reset store
let cache = JSON.parse(JSON.stringify(this.computedCache));
console.log(cache);
cache.stationen.push(this.computedEndstation);
if (this.isNewCache) {
let cache = JSON.parse(JSON.stringify(this.computedCache));
console.log(cache);
cache.stationen.push(this.computedEndstation);
this.$axios.post('/api/createCache', cache)
.then((response) => {
@ -210,21 +199,16 @@
this.$store.commit('cacheCollector/RESET_NEW_CACHE');
this.$router.push({path: '/overview'});
}).catch((error) => {
//TODO: Fehlermeldungen
// Error
let msg;
let title;
if (error.response) {
// The request was made and the server responded with a status code
title = "Problem with response!";
msg = error.response;
title = "Bitte Eingaben überprüfen!";
msg = error.response.data;
} else if (error.request) {
// The request was made but no response was received
title = "Problem with request!";
msg = "Error occured due to wrong server request!"
title = "Verbindungsfehler!";
msg = "Es konnte keine Verbindung zum Server aufgebaut werden. Versuchen Sie es später noch einmal!"
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
title = "Error";
msg = error.message;
console.log('Error', error.message);
@ -233,26 +217,33 @@
this.$store.commit('dialog/NEW_MESSAGE_DIALOG', {message: msg, title: title,});
})
} else {
// TODO update existing Cache
this.$axios.put('/api/editCache', cache)
.then((response) => {
console.log("POST api/editCache: " + response.statusText);
this.$store.commit('cacheCollector/RESET_NEW_CACHE');
this.$router.push({path: '/overview'});
}).catch((error) => {
let msg;
let title;
if (error.response) {
title = "Bitte Eingaben überprüfen!";
msg = error.response.data;
} else if (error.request) {
title = "Verbindungsfehler!";
msg = "Es konnte keine Verbindung zum Server aufgebaut werden. Versuchen Sie es später noch einmal!"
console.log(error.request);
} else {
title = "Error";
msg = error.message;
console.log('Error', error.message);
}
console.log(error.config);
this.$store.commit('dialog/NEW_MESSAGE_DIALOG', {message: msg, title: title,});
})
}
},
},
computed: {
...mapGetters({
//cache: 'cacheCollector/GET_CACHE',
//endStation: 'cacheCollector/GET_ENDSTATION'
}),
// computedStations: {
// set(value) {
// console.log("set stations");
// this.computedCache.set(value);
// },
// get() {
// console.log("get stations");
// let stations = this.computedCache.stationen;
// return stations.filter(station => station.description !== "Endstation");
// }
// },
computedCache: {
set(value) {
console.log("set cache");

View File

@ -109,36 +109,31 @@
localStorage.setItem('userMail', JSON.stringify(data.email));
this.evalAuthentication();
this.$router.push({path: `/overview`})
})
.catch((error) => {
let message;
let header = "Fehler: ";
if (error.response) {
console.log("ERROR RESPONSE");
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
message = error.response.data.error;
header += error.response.status;
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
message = "Anfrage fehlgeschlagen.";
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
message = error.message;
}
console.log(error.config);
this.$store.commit('dialog/NEW_MESSAGE_DIALOG', { message: message, title: header, });
}).finally(() => {
}).catch((error) => {
let msg;
let title;
if (error.response) {
title = "Fehler!";
msg = error.response.data;
} else if (error.request) {
title = "Verbindungsfehler!";
msg = "Es konnte keine Verbindung zum Server aufgebaut werden. Versuchen Sie es später noch einmal!"
console.log(error.request);
} else {
title = "Error";
msg = error.message;
console.log('Error', error.message);
}
console.log(error.config);
this.$store.commit('dialog/NEW_MESSAGE_DIALOG', {message: msg, title: title,});
}).finally(() => {
this.loading = false;
this.evalAuthentication();
})
},
evalAuthentication: function () {
this.$store.commit('auth/SET_AUTHENTICATED');
// this.$store.commit('auth/SET_USER');
this.$store.commit('auth/SET_USER');
},
logout: function () {
console.log("logout()");

View File

@ -11,8 +11,8 @@
indicator-color="cyan-14"
switch-indicator
>
<q-tab name="startedCaches" label="Angefangene Caches" icon="playlist_play"/>
<q-tab name="finishedCaches" label="Beendete Caches" icon="playlist_add_check"/>
<q-tab name="startedCaches" label="Angefangen" icon="playlist_play"/>
<q-tab name="finishedCaches" label="Beendet" icon="playlist_add_check"/>
</q-tabs>
<q-separator color="grey-4"/>
</div>
@ -115,7 +115,7 @@
},
},
created: function () {
this.$store.commit('auth/SET_AUTHENTICATED');
// this.$store.commit('auth/SET_AUTHENTICATED');
this.fetchUserCaches();
},
methods: {

View File

@ -60,7 +60,7 @@
label="Belohnung" size="xs"/>
<q-btn v-if="hasAdminState" @click="confirmDelete(cache.id)" unelevated color="negative" stack
icon="delete" size="xs"/>
<q-btn disable v-if="hasAdminState" @click="editCache(cache.id)" unelevated color="primary" stack
<q-btn v-if="hasAdminState" @click="editCache(cache.id)" unelevated color="primary" stack
icon="edit" size="xs"/>
<q-btn v-if="hasAdminState" @click="generateQrCodes(cache.id)" unelevated color="primary" stack
icon="image" label="QRCodes" size="xs"/>
@ -118,17 +118,16 @@
return this.$store.getters['auth/GET_ADMINSTATE'];
}
},
beforeMount() {
},
async created() {
console.log("created(): " + this.caches);
// this.$store.commit('auth/SET_AUTHENTICATED');
// this.$store.commit('auth/SET_USER');
await this.fetchAllCaches();
this.render = await this.fetchMyCaches();
this.loadData();
},
methods: {
async loadData() {
this.render = false;
await this.fetchAllCaches();
this.render = await this.fetchMyCaches();
},
getColorClass(cache) {
switch (this.getCacheAccesDefinition(cache)) {
case -1:
@ -166,26 +165,22 @@
this.initMap();
resolve(true);
}).catch((error) => {
let message;
let header = "Fehler: ";
let msg;
let title;
if (error.response) {
console.log("ERROR RESPONSE");
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
message = error.response.data.error;
header += error.response.status;
title = "Bitte Eingaben überprüfen!";
msg = error.response.data;
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
message = "Anfrage fehlgeschlagen.";
title = "Verbindungsfehler!";
msg = "Es konnte keine Verbindung zum Server aufgebaut werden. Versuchen Sie es später noch einmal!"
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
title = "Error";
msg = error.message;
console.log('Error', error.message);
message = error.message;
}
console.log(error.config);
this.$store.commit('dialog/NEW_MESSAGE_DIALOG', {message: message, title: header,});
this.$store.commit('dialog/NEW_MESSAGE_DIALOG', {message: msg, title: title,});
resolve(true);
})
})
@ -236,7 +231,8 @@
addCache() {
this.$router.push({path: `/cache`})
},
editCache() {
editCache(cacheID) {
this.$router.push({path: `/cache/${cacheID}`})
},
initMap() {
console.log("Signalwort: " + this.pois);
@ -254,30 +250,26 @@
},
deleteCache(id) {
console.log('delete cache: ' + id);
axios.get('/api/deleteCache', {params: {cacheID: id}})
this.$axios.delete('/api/deleteCache', {params: {cacheID: id}})
.then((response) => {
this.fetchAllCaches()
this.loadData();
}).catch((error) => {
let message;
let header = "Fehler: ";
let msg;
let title;
if (error.response) {
console.log("ERROR RESPONSE");
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
message = error.response.data.error;
header += error.response.status;
title = "Fehler!";
msg = error.response.data;
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
message = "Anfrage fehlgeschlagen.";
title = "Verbindungsfehler!";
msg = "Es konnte keine Verbindung zum Server aufgebaut werden. Versuchen Sie es später noch einmal!"
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
title = "Error";
msg = error.message;
console.log('Error', error.message);
message = error.message;
}
console.log(error.config);
this.$store.commit('dialog/NEW_MESSAGE_DIALOG', {message: message, title: header,});
this.$store.commit('dialog/NEW_MESSAGE_DIALOG', {message: msg, title: title,});
})
},
startCache(cacheID) {
@ -299,9 +291,24 @@
console.log(response.data);
currentStationID = response.data.aktuelleStation.id;
this.$router.push({path: `/station/${cacheID}/${currentStationID}`});
})
.catch((error) => {
});
}).catch((error) => {
let msg;
let title;
if (error.response) {
title = "Fehler!";
msg = error.response.data;
} else if (error.request) {
title = "Verbindungsfehler!";
msg = "Es konnte keine Verbindung zum Server aufgebaut werden. Versuchen Sie es später noch einmal!"
console.log(error.request);
} else {
title = "Error";
msg = error.message;
console.log('Error', error.message);
}
console.log(error.config);
this.$store.commit('dialog/NEW_MESSAGE_DIALOG', {message: msg, title: title,});
})
}
},
goToReward(cacheID) {
@ -316,9 +323,24 @@
console.log(response.data);
currentStationID = response.data.aktuelleStation.id;
this.$router.push({path: `/CacheEnd/${params.cacheID}`});
})
.catch((error) => {
});
}).catch((error) => {
let msg;
let title;
if (error.response) {
title = "Fehler!";
msg = error.response.data;
} else if (error.request) {
title = "Verbindungsfehler!";
msg = "Es konnte keine Verbindung zum Server aufgebaut werden. Versuchen Sie es später noch einmal!"
console.log(error.request);
} else {
title = "Error";
msg = error.message;
console.log('Error', error.message);
}
console.log(error.config);
this.$store.commit('dialog/NEW_MESSAGE_DIALOG', {message: msg, title: title,});
})
}
},

View File

@ -237,8 +237,8 @@
}
},
created: function () {
this.$store.commit('auth/SET_AUTHENTICATED');
this.$store.commit('auth/SET_USER');
// this.$store.commit('auth/SET_AUTHENTICATED');
// this.$store.commit('auth/SET_USER');
this.userName = JSON.parse(localStorage.getItem('userToken')).name;
this.email = JSON.parse(localStorage.getItem('userMail'));
this.getPersonalRanking();

View File

@ -185,8 +185,8 @@
.then((response) => {
localStorage.setItem('userToken', JSON.stringify(response.data));
localStorage.setItem('userMail', JSON.stringify(data.email));
this.$store.commit('auth/SET_AUTHENTICATED');
this.$store.commit('auth/SET_USER');
// this.$store.commit('auth/SET_AUTHENTICATED');
// this.$store.commit('auth/SET_USER');
this.$router.push({path: `/overview`});
})
.catch((error) => {

View File

@ -3,18 +3,17 @@ import VueRouter from "vue-router";
import routes from "./routes";
import {axiosInstance} from "../boot/axios";
Vue.use(VueRouter);
import store from "../store/index";
Vue.use(VueRouter);
/*
* If not building with SSR mode, you can
* directly export the Router instantiation
*/
export default function({ store }/* { store, ssrContext } */) {
export default function ({store}/* { store, ssrContext } */) {
const Router = new VueRouter({
scrollBehavior: () => ({ x: 0, y: 0 }),
scrollBehavior: () => ({x: 0, y: 0}),
routes,
store,
// Leave these as is and change from quasar.conf.js instead!
@ -36,20 +35,23 @@ export default function({ store }/* { store, ssrContext } */) {
console.log(loggedIn);
const isAdmin = loggedIn ? loggedIn.roles.find(x => x.role === "ADMIN" && x.domain === "geocaching.de") : false;
//const isAdmin = true;
if (!isPublic && !loggedIn) {
return next({
path:'/login',
path: '/login',
query: {redirect: to.fullPath} // Store the full path to redirect the user to after login
});
}
console.log("!isPublic && !loggedIn")
if ((loggedIn && onlyWhenLoggedOut) || (loggedIn && onlyAdmin && !isAdmin)) {
return next('/')
}
if (isPublic) {
console.log("(loggedIn && onlyWhenLoggedOut) || (loggedIn && onlyAdmin && !isAdmin)")
if (isPublic && !loggedIn) {
return next()
}
if (!isPublic && loggedIn) {
console.log("isPublic")
if (!onlyWhenLoggedOut && loggedIn) {
console.log("fetch data...")
axiosInstance.get('/api/getUser', {
params: {
token: loggedIn.token
@ -57,7 +59,6 @@ export default function({ store }/* { store, ssrContext } */) {
})
.then((response) => {
console.log("Token valid!");
store.commit('auth/SET_AUTHENTICATED');
return next();
})
.catch((error) => {
@ -69,18 +70,21 @@ export default function({ store }/* { store, ssrContext } */) {
console.log(error.response.headers);
//store.commit('auth/SET_LOGOUT');
store.commit('dialog/NEW_MESSAGE_DIALOG', {
message: "Ihr Token ist nicht mehr gültig. Bitte loggen Sie sich erneut ein.",
message: "Ihre Session ist abgelaufen. Bitte loggen Sie sich erneut ein.",
title: "Bitte erneut anmelden.",
color: "blue", });
color: "blue",
});
localStorage.removeItem('userToken');
store.commit('auth/SET_AUTHENTICATED');
return next('/Login');
} else {
console.log("unexpected behaviour");
console.log(error);
return next();
}
});
}).finally(() => {
store.commit('auth/SET_AUTHENTICATED');
store.commit('auth/SET_USER');
});
}
console.log(`isPublic: ${isPublic} \nonlyWhenLoggedOut: ${onlyWhenLoggedOut} \nonlyAdmin: ${onlyAdmin}`);
//return next();

View File

@ -14,7 +14,6 @@ export const SET_LOGOUT = (state) => {
localStorage.removeItem('userToken');
state.userAuthenticated = null;
state.isAuthenticated = false;
console.log(localStorage.getItem('userToken'));
};
export const SET_USER = (state) => {
console.log("SET_USER()");
@ -26,16 +25,13 @@ export const SET_USER = (state) => {
}
})
.then((response) => {
console.log("GET/POST /api/getUser - response: ");
console.log(response.data);
console.log("GET /api/getUser");
state.userAuthenticated = response.data;
state.isAuthenticated = true;
if (state.userAuthenticated.hasOwnProperty('password')) delete state.userAuthenticated.password;
console.log(state.userAuthenticated);
})
.catch((error) => {
console.log("Catch Block: ")
console.log(error)
console.log("error")
});
} else {
state.isAuthenticated = false;

View File

@ -42,8 +42,8 @@ export const RESET_NEW_CACHE = (state) => {
};
state.endStation = {
description: "Endstation",
longitude: 9.206628,
lattitude: 49.147734,
longitude: 0.000,
lattitude: 0.000,
solution: "",
};

View File

@ -11,8 +11,8 @@ export default {
tempStation: {},
endStation: {
description: "Endstation",
longitude: 9.206628,
lattitude: 49.147734,
longitude: 0.000,
lattitude: 0.000,
solution: "",
},
}

View File

@ -1,11 +1,13 @@
package hhn.labsw.bugageocaching.controller;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import hhn.labsw.bugageocaching.entities.*;
import hhn.labsw.bugageocaching.helper.POI;
import hhn.labsw.bugageocaching.helper.RankingListHelper;
import hhn.labsw.bugageocaching.helper.TeamRankingListHelper;
import hhn.labsw.bugageocaching.repositories.*;
import hhn.labsw.bugageocaching.util.CacheConstructionUtil;
import hhn.labsw.bugageocaching.util.FinderUtil;
import hhn.labsw.bugageocaching.util.VerificationUtil;
import io.jsonwebtoken.Claims;
@ -24,6 +26,7 @@ import java.util.List;
import static hhn.labsw.bugageocaching.util.CacheConstructionUtil.createCacheUtil;
import static hhn.labsw.bugageocaching.util.CacheConstructionUtil.deleteCacheUtil;
import static hhn.labsw.bugageocaching.util.CacheConstructionUtil.editCacheUtil;
import static hhn.labsw.bugageocaching.util.VerificationUtil.fetchPublicKey;
@RestController
@ -56,8 +59,10 @@ public class Controller {
@Autowired
TeamInviteRepository teamInviteRepository;
private org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(Controller.class);
@PostConstruct
public void init(){
public void init() {
fetchPublicKey();
}
@ -66,6 +71,7 @@ public class Controller {
@RequestMapping(value = "/api/allCaches", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public ResponseEntity getAllCaches() {
logger.warn("API CALL: /api/allCaches");
return ResponseEntity.status(200).body(new Gson().toJson(cacheRepository.findAll()));
}
@ -230,11 +236,11 @@ public class Controller {
System.out.println(durchgefuehrterCache.getName());
if (!cacheID.equals(durchgefuehrterCacheID)) {
return ResponseEntity.status(400).body("The scanned station isn´t the correct following station (Name)");
return ResponseEntity.status(400).body("Die gescannte Station ist nicht die korrekte nachfolge Station");
}
if (!cache.getStationen().contains(station)) {
return ResponseEntity.status(400).body("The scanned station isnt a part of the cache");
return ResponseEntity.status(400).body("Die gescannte Station gehört nicht zu dem gerade bearbeiteten Cache");
}
//----------------------
@ -275,13 +281,13 @@ public class Controller {
Station aktuelleStation = bearbeitet.getAktuelleStation();
if (aktuelleStation == null) {
return ResponseEntity.status(400).body("Database Error");
return ResponseEntity.status(400).body("Es gab einen Fehler. Bitte versuche es erneut oder kontaktiere einen Admin");
}
int i = cache.getStationen().indexOf(station);
if (i == 0) {
return ResponseEntity.status(400).body("The scanned station isn´t the correct following station (i==0)");
return ResponseEntity.status(400).body("Die gescannte Station ist nicht die korrekte nachfolge Station");
}
if (cache.getStationen().get(i - 1).equals(aktuelleStation)) {
@ -308,7 +314,7 @@ public class Controller {
bearbeitetRepository.save(bearbeitet);
return ResponseEntity.status(200).body(new Gson().toJson(bearbeitet));
} else {
return ResponseEntity.status(400).body("The scanned station isn´t the correct following station(nicht letzte)");
return ResponseEntity.status(400).body("Die gescannte Station ist nicht die korrekte nachfolge Station");
}
}
@ -333,28 +339,9 @@ public class Controller {
@CrossOrigin(origins = "*", allowedHeaders = "*") // only for dev purpose
@RequestMapping(value = "/api/editCache", method = RequestMethod.PUT, produces = "application/json")
@ResponseBody
public ResponseEntity editCache(@RequestBody Cache newCache){
public ResponseEntity editCache(@RequestBody Cache newCache) {
//----------------------
//Get Cache
ResponseEntity getCache = FinderUtil.findCacheById(newCache.getId() + "");
if (getCache.getStatusCodeValue() != 200) {
return getCache;
}
Cache oldCache = (Cache) getCache.getBody();
//----------------------
oldCache.setDescription(newCache.getDescription());
oldCache.setName(newCache.getName());
oldCache.setRankingPoints(newCache.getRankingPoints());
oldCache.setReward(newCache.getReward());
oldCache.setStationen(newCache.getStationen());
cacheRepository.save(oldCache);
return ResponseEntity.status(200).body("Cache edited");
return editCacheUtil(newCache);
}
@ApiOperation(value = "Checks if the given User has an admin role")
@ -403,6 +390,7 @@ public class Controller {
@RequestMapping(value = "/api/getAllStations", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public ResponseEntity getAllStations() {
logger.warn("API CALL: /api/getAllStations");
return ResponseEntity.status(200).body(new Gson().toJson(stationRepository.findAll()));
}
@ -414,6 +402,7 @@ public class Controller {
@RequestMapping(value = "/api/deleteCache", method = {RequestMethod.DELETE, RequestMethod.GET}, produces = "application/json")
@ResponseBody
public ResponseEntity deleteCache(@RequestParam String cacheID) {
logger.warn("API CALL: /api/deleteCache");
return deleteCacheUtil(cacheID);
}
@ -428,6 +417,7 @@ public class Controller {
@ResponseBody
public ResponseEntity getMyCaches(@RequestParam String token) {
logger.warn("API CALL: /api/getMyCaches");
ResponseEntity verifyToken = VerificationUtil.verifyToken(token);
@ -437,6 +427,8 @@ public class Controller {
Claims claims = (Claims) verifyToken.getBody();
logger.debug("/api/getMyCaches Token verified");
ResponseEntity getUser = FinderUtil.findUserFromClaim(claims);
if (getUser.getStatusCodeValue() != 200) {
@ -445,17 +437,21 @@ public class Controller {
User user = (User) getUser.getBody();
if (user != null) {
ArrayList<Bearbeitet> bearbeitetList = new ArrayList<>();
logger.debug("/api/getMyCaches Got User: " + user.getEmail());
for (Bearbeitet bearbeitet : bearbeitetRepository.findAll()) {
if (user != null) {
//ArrayList<Bearbeitet> bearbeitetList = new ArrayList<>();
/*for (Bearbeitet bearbeitet : bearbeitetRepository.findAll()) {
if (bearbeitet.getUser().getId() == user.getId()) {
bearbeitetList.add(bearbeitet);
}
}
}*/
List<Bearbeitet> bearbeitetList = bearbeitetRepository.findByUser(user);
logger.debug("/api/getMyCaches Got all bearbeitet entreis of user: " +user.getEmail());
return ResponseEntity.status(200).body(new Gson().toJson(bearbeitetList));
} else {
return ResponseEntity.status(404).body("User was not found in the database");
return ResponseEntity.status(404).body("Es gab einen Fehler. Bitte versuche es erneut oder kontaktiere einen Admin!");
}
}
@ -468,13 +464,19 @@ public class Controller {
@ResponseBody
public ResponseEntity getRankingList() {
logger.warn("API CALL: /api/getRankingList");
List<RankingListHelper> sendBackUsers = new LinkedList<>();
logger.debug("/api/getRankingList create sendBackUsers");
List<Object[]> rankingUsers = userRepository.getRankingList();
logger.debug("/api/getRankingList got Object[] from DB");
for (Object[] obj : rankingUsers) {
RankingListHelper tmp = new RankingListHelper((String) obj[1], (Integer) obj[2]);
System.out.println(tmp);
sendBackUsers.add(tmp);
}
logger.debug("/api/getRankingList Converted Objects to RankingListHelper");
logger.debug("/api/getRankingList RankingList: " + new GsonBuilder().setPrettyPrinting().create().toJson(sendBackUsers));
return ResponseEntity.status(200).body(new Gson().toJson(sendBackUsers));
}
@ -528,7 +530,7 @@ public class Controller {
if (user != null) {
return ResponseEntity.status(200).body(new Gson().toJson(user));
} else {
return ResponseEntity.status(404).body("User was not found in the database");
return ResponseEntity.status(404).body("Es gab einen Fehler. Bitte versuche es erneut oder kontaktiere einen Admin!e");
}
}
@ -565,13 +567,13 @@ public class Controller {
User_Info user_info = user_infoRepository.findUser_InfoByUser(user);
//----------------------
if (user_info.getTeam() != null) {
return ResponseEntity.status(400).body("You already have a team");
return ResponseEntity.status(400).body("Du bist bereits in einem Team. Bitte verlasse dieses Team um ein neues Team zu erstellen!");
}
// checkt, ob der name bereits vorhanden ist
for (Team team : teamRepository.findAll()) {
if (team.getName().equals(name)) {
return ResponseEntity.status(400).body("The teamname is already taken");
return ResponseEntity.status(400).body("Der Teamname ist bereits vergeben. Bitte wähle einen anderen name");
}
}
@ -620,7 +622,7 @@ public class Controller {
User_Info user_info = user_infoRepository.findUser_InfoByUser(user);
//----------------------
if (user_info.getTeam() != null) {
return ResponseEntity.status(400).body("You already have a team");
return ResponseEntity.status(400).body("Du bist bereits in einem Team. Bitte verlasse dieses Team um einem neuen Team beizutreten");
}
//Get team
@ -645,7 +647,7 @@ public class Controller {
// wenn maximalanzahl der teammitglieder erreicht...
if (user_infos.size() >= 10) {
return ResponseEntity.status(400).body("The team already has 10 members");
return ResponseEntity.status(400).body("Das Team hat die Mitgliederanzahlgrenze von 10 Mitgliedern erreicht. Du kannst zurzeit nicht beitreten!");
}
// tritt dem team bei
@ -665,7 +667,7 @@ public class Controller {
@ApiResponse(code = 400, message = "Something went wrong at verification")
})
@CrossOrigin(origins = "*", allowedHeaders = "*") // only for dev purpose
@RequestMapping(value = "/api/leaveTeam", method = RequestMethod.PUT, produces = "application/json")
@RequestMapping(value = "/api/leaveTeam", method = {RequestMethod.PUT, RequestMethod.GET}, produces = "application/json")
@ResponseBody
public ResponseEntity leaveTeam(@RequestParam String token) {
@ -691,7 +693,7 @@ public class Controller {
User_Info user_info = user_infoRepository.findUser_InfoByUser(user);
//----------------------
if (user_info.getTeam() == null) {
return ResponseEntity.status(400).body("You aren´t in any team");
return ResponseEntity.status(400).body("Du bist bereits in keinem Team, welches du verlassen könntest.");
}
//Get team
@ -759,7 +761,7 @@ public class Controller {
User invitedUser = userRepository.findByEmail(invitedUserEmail);
if (invitedUser == null) {
return ResponseEntity.status(404).body("There isnt any user with that email");
return ResponseEntity.status(404).body("Es gibt keinen Benutzer mit dieser email.");
}
//----------------------
@ -768,7 +770,7 @@ public class Controller {
User_Info user_info = user_infoRepository.findUser_InfoByUser(user);
//----------------------
if (user_info.getTeam() == null) {
return ResponseEntity.status(400).body("You aren´t in any team");
return ResponseEntity.status(400).body("Du bist derzeit in keinem Team und kannst deshalb keine Teameinladungen versenden.");
}
//Get team
@ -781,7 +783,7 @@ public class Controller {
Team team = (Team) getTeam.getBody();
if (teamInviteRepository.findByUserAndTeam(invitedUser, team) != null) {
return ResponseEntity.status(400).body("The user is already invited to this team");
return ResponseEntity.status(400).body("Der Benutzer ist bereits in das Team eingeladen.");
}
TeamInvite teamInvite = new TeamInvite();
@ -823,7 +825,7 @@ public class Controller {
List<TeamInvite> teamInvitesList = teamInviteRepository.findByUser(user);
for (TeamInvite tmp : teamInvitesList){
for (TeamInvite tmp : teamInvitesList) {
tmp.setUser(null);
}
@ -904,7 +906,7 @@ public class Controller {
User_Info user_info = user_infoRepository.findUser_InfoByUser(user);
//----------------------
if (user_info.getTeam() == null) {
return ResponseEntity.status(400).body("You aren´t in any team");
return ResponseEntity.status(400).body("Du kannst einen Teamstatus nur setzen, wenn du in einem Team bist.");
}
//Get team
@ -985,7 +987,7 @@ public class Controller {
Cache cache = (Cache) getCache.getBody();
//----------------------
return ResponseEntity.status(200).body(bearbeitetRepository.findByUserAndCache(user, cache));
return ResponseEntity.status(200).body(new Gson().toJson(bearbeitetRepository.findByUserAndCache(user, cache)));
}
@ApiOperation(value = "Returns the ranking place on the leaderboard for a specific user")
@ -1006,7 +1008,7 @@ public class Controller {
@ApiResponse(code = 401, message = "JWT Token expired"),
@ApiResponse(code = 400, message = "Something went wrong at verification")
})
@CrossOrigin(origins = "http://localhost:8081") // only for dev purpose
@CrossOrigin(origins = "*", allowedHeaders = "*") // only for dev purpose
@RequestMapping(value = "/api/getMyStationPOIS", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity getMyStationPOIS(@RequestParam String token) {
// verify user
@ -1072,7 +1074,7 @@ public class Controller {
@ApiResponse(code = 401, message = "JWT Token expired"),
@ApiResponse(code = 400, message = "Something went wrong at verification")
})
@CrossOrigin(origins = "http://localhost:8081") // only for dev purpose
@CrossOrigin(origins = "*", allowedHeaders = "*") // only for dev purpose
@RequestMapping(value = "/api/getTeamOfUser", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity getTeamOfUser(@RequestParam String token) {
@ -1099,6 +1101,75 @@ public class Controller {
return ResponseEntity.status(200).body(user_info.getTeam());
}
@ApiOperation(value = "Returns the Team of a user")
@ApiResponses(value = {
@ApiResponse(code = 404, message = "Database error"),
@ApiResponse(code = 401, message = "JWT Token expired"),
@ApiResponse(code = 400, message = "Something went wrong at verification")
})
@CrossOrigin(origins = "*", allowedHeaders = "*") // only for dev purpose
@RequestMapping(value = "/api/getCurrentStationMap", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity getCurrentStationMap(@RequestParam String token, @RequestParam String cacheID) {
logger.warn("API CALL: /api/getCurrentStationMap");
// verify user
ResponseEntity verifyToken = VerificationUtil.verifyToken(token);
if (verifyToken.getStatusCodeValue() != 200) {
return verifyToken;
}
//get User
Claims claims = (Claims) verifyToken.getBody();
ResponseEntity getUser = FinderUtil.findUserFromClaim(claims);
if (getUser.getStatusCodeValue() != 200) {
return getUser;
}
User user = (User) getUser.getBody();
logger.debug("/api/getCurrentStationMap " + "User verificated: " + user.getEmail());
//----------------------
//Get Cache
ResponseEntity getCache = FinderUtil.findCacheById(cacheID);
if (getCache.getStatusCodeValue() != 200) {
return getCache;
}
Cache cache = (Cache) getCache.getBody();
logger.debug("/api/getCurrentStationMap " + "Cache: " + cache.getName());
//----------------------
ResponseEntity responseBearbeitet = FinderUtil.findBearbeitetByUserAndCache(user, cache);
if (responseBearbeitet.getStatusCodeValue() != 200) {
return responseBearbeitet;
}
Bearbeitet bearbeitet = (Bearbeitet) responseBearbeitet.getBody();
logger.debug("/api/getCurrentStationMap " + "Got Bearbeitet: User: " + bearbeitet.getUser().getEmail() + " Cache: " + bearbeitet.getCache().getName());
Station nextStation = bearbeitet.getAktuelleStation();
logger.debug("/api/getCurrentStationMap " + "Got Station from bearbeitet: " + nextStation.getDescription());
int index = cache.getStationen().indexOf(nextStation);
logger.debug("/api/getCurrentStationMap " + "Index of Station " + nextStation.getDescription() + " in Cache " + cache.getName() + " : " + index);
Station lastStation = cache.getStationen().get(index - 1);
logger.debug("/api/getCurrentStationMap " + "Station before: " + lastStation.getDescription());
POI poi = new POI(cache.getName() + "_Station" + (index - 1.0), (float) lastStation.getLattitude(), (float) lastStation.getLongitude(), 201);
logger.debug("/api/getCurrentStationMap " + "Created POI: " + poi.toString());
return ResponseEntity.status(200).body(new Gson().toJson(poi));
}
@ApiOperation(value = "Test method (Changes its purpose often)")
@ApiResponses(value = {
@ApiResponse(code = 404, message = "Database error"),

View File

@ -45,4 +45,9 @@ public class POI {
public void setCategoryID(int categoryID) {
CategoryID = categoryID;
}
@Override
public String toString() {
return "Name: " + getName() + "; Latitude " + getLatitude() + "; Longitude " + getLongitude() + "; categoryID " + getLongitude();
}
}

View File

@ -8,11 +8,13 @@ import hhn.labsw.bugageocaching.repositories.BearbeitetRepository;
import hhn.labsw.bugageocaching.repositories.CacheRepository;
import hhn.labsw.bugageocaching.repositories.StationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import javax.persistence.RollbackException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Random;
@ -54,24 +56,24 @@ public class CacheConstructionUtil {
// Caches werden in die Datenbank eingetragen
if (cache.getDescription().length() == 0 || cache.getName().length() == 0 || cache.getRankingPoints() == 0.0) {
deleteStationenUtil(cache);
return ResponseEntity.status(400).body("cache fields can´t be empty");
return ResponseEntity.status(400).body("Alle Felder müssen ausgefüllt werden!");
}
if (cache.getStationen().size() < 2) {
deleteStationenUtil(cache);
return ResponseEntity.status(400).body("a cache needs atleast 2 stations");
return ResponseEntity.status(400).body("Ein Cache muss mindestens zwei Stationen besitzen.\nBitte füge noch eine Station hinzu!");
}
for (Cache cache1 : cacheRepository.findAll()) {
if (cache1.getName().equals(cache.getName())) {
deleteStationenUtil(cache);
return ResponseEntity.status(400).body("name is already taken");
return ResponseEntity.status(400).body("Der Cachename ist bereits vergeben. Bitte wähle einen anderen Name!");
}
}
if (cache.getRankingPoints() < 0) {
deleteStationenUtil(cache);
return ResponseEntity.status(400).body("Ranking points has to be a positive number");
return ResponseEntity.status(400).body("Die Punkte für den Cache dürfen nicht negativ sein!");
}
cacheRepository.save(cache);
@ -82,15 +84,15 @@ public class CacheConstructionUtil {
public static ResponseEntity createStationUtil(Station station) {
if (station.getDescription().length() == 0 || station.getLattitude() == 0.0 || station.getLongitude() == 0.0 /*|| station.getSolution().length() == 0*/) {
return ResponseEntity.status(400).body("station fields can´t be empty");
return ResponseEntity.status(400).body("Alle Felder müssen ausgefüllt werden!");
}
if (station.getLattitude() < -90 || station.getLattitude() > 90) {
return ResponseEntity.status(400).body("Lattitude has to be between -90 and 90 Degree");
if (station.getLattitude() < 9 || station.getLattitude() > 10) {
return ResponseEntity.status(400).body("Die Lattitude ist außerhalb der Bundesgartenschau");
}
if (station.getLongitude() < -180 || station.getLongitude() > 180) {
return ResponseEntity.status(400).body("Longitude has to be in the range of -180 to 180 degrees");
if (station.getLongitude() < 49 || station.getLongitude() > 50) {
return ResponseEntity.status(400).body("Die Longitude ist außerhalb der Bundesgartenschau");
}
Random r = new Random();
@ -112,7 +114,7 @@ public class CacheConstructionUtil {
try {
station.setCode(code);
} catch (RollbackException e) {
return ResponseEntity.status(400).body("There was an error generating the unique code");
return ResponseEntity.status(400).body("Es gab einen Fehler beim Konsturieren der QR Codes");
}
stationRepository.save(station);
@ -120,6 +122,103 @@ public class CacheConstructionUtil {
return ResponseEntity.status(200).body(new Gson().toJson(station));
}
public static ResponseEntity editCacheUtil(Cache cache) {
Optional<Cache> oldCacheOptional = cacheRepository.findById(cache.getId());
Cache oldCache;
// List<Station> oldStationen;
if (oldCacheOptional.isPresent()) {
oldCache = oldCacheOptional.get();
// oldStationen = new ArrayList<>(oldCache.getStationen());
} else {
return ResponseEntity.status(404).body("Es gab einen Fehler. Bitte versuchen Sie es erneut oder kontaktieren Sie einen Admin.");
}
ResponseEntity response = new ResponseEntity(HttpStatus.ACCEPTED);
List<Station> newCreatedStationList = new ArrayList<Station>();
for (Station station : cache.getStationen()) {
boolean stationIsNew = true;
for (Station oldStation : oldCache.getStationen()) {
// wenn Station schon vorher vorhanden war, wird diese mit den neuen Daten geupdatet
if (oldStation.getId() == station.getId()) {
response = createStationUtil(station);
stationIsNew = false;
break;
}
}
// wenn Station neu hinzugefügt wurde, wird die Station zusätzlich in die Datenbank gespeichert
if (stationIsNew) {
response = createStationUtil(station);
if (response.getStatusCodeValue() == 200) {
newCreatedStationList.add(station);
}
}
if (response.getStatusCodeValue() == 400) {
// neu erzeugte Stationen werden gelöscht, falls es einen Fehler gibt
// alle veränderten Stationen werden resettet
// for (Station oldStation : oldStationen) {
// stationRepository.save(oldStation);
// }
deleteNewCreatedStationsUtil(newCreatedStationList);
return response;
}
}
// überprüft den Cache nach validen Daten
if (cache.getDescription().length() == 0 || cache.getName().length() == 0 || cache.getRankingPoints() == 0.0) {
deleteNewCreatedStationsUtil(newCreatedStationList);
return ResponseEntity.status(400).body("Alle Felder müssen ausgefüllt sein!");
}
if (cache.getStationen().size() < 2) {
deleteNewCreatedStationsUtil(newCreatedStationList);
return ResponseEntity.status(400).body("Ein Cache muss mindestens zwei Stationen haben. Bitte füge eine weiter Station hinzu!");
}
for (Cache cache1 : cacheRepository.findAll()) {
if (cache1.getName().equals(cache.getName())) {
if (cache1.getId() != oldCache.getId()) {
deleteNewCreatedStationsUtil(newCreatedStationList);
return ResponseEntity.status(400).body("Der Cachename ist bereits vergeben. Bitte wähle einen anderen!");
}
}
}
if (cache.getRankingPoints() < 0) {
deleteNewCreatedStationsUtil(newCreatedStationList);
return ResponseEntity.status(400).body("Die Punkte für den Cache dürfen nicht negativ sein!");
}
cacheRepository.save(cache);
// nicht gebrauchte Stationen müssen noch aus der DB gelöscht werden
// for (Station oldStation : oldCache.getStationen()) {
// // wenn Station entfernt wurde, wird diese auch aus der Datenbank gelöscht
// if (!cache.getStationen().contains(station)) {
// stationRepository.delete(station);
// }
// }
return ResponseEntity.status(200).body(new Gson().toJson(cache));
}
// public static ResponseEntity checkStationUtil(Station station) {
// if (station.getDescription().length() == 0 || station.getLattitude() == 0.0 || station.getLongitude() == 0.0 /*|| station.getSolution().length() == 0*/) {
// return ResponseEntity.status(400).body("station fields can´t be empty");
// }
//
// if (station.getLattitude() < 9 || station.getLattitude() > 10) {
// return ResponseEntity.status(400).body("Lattitude has to be between 9 and 10 degrees");
// }
//
// if (station.getLongitude() < 49 || station.getLongitude() > 50) {
// return ResponseEntity.status(400).body("Longitude has to be in the range of 49 to 50 degrees");
// }
//
// return ResponseEntity.status(200).body(new Gson().toJson(station));
// }
public static void deleteStationenUtil(Cache cache) {
for (Station station : cache.getStationen()) {
try {
@ -130,10 +229,20 @@ public class CacheConstructionUtil {
}
}
public static void deleteNewCreatedStationsUtil(List<Station> newCreatedStationList) {
for (Station station : newCreatedStationList) {
try {
stationRepository.delete(station);
} catch (IllegalArgumentException e) { // station is null
// do nothing
}
}
}
public static ResponseEntity deleteCacheUtil(String cacheID) {
Optional<Cache> optionalCache = cacheRepository.findById(Integer.valueOf(cacheID));
if (!optionalCache.isPresent()) {
return ResponseEntity.status(404).body(new Gson().toJson("There is no cache with the ID " + cacheID));
return ResponseEntity.status(404).body(new Gson().toJson("Es gab einen Fehler beim Löschen des Caches"));
}
Cache cache = optionalCache.get();

View File

@ -89,7 +89,7 @@ public class FinderUtil {
if (cacheOptional.isPresent()) {
return ResponseEntity.status(200).body(cacheOptional.get());
} else {
return ResponseEntity.status(404).body("Couldnt find Cache " + cacheID);
return ResponseEntity.status(404).body("Ein Fehler ist aufgetreten. Bitte versuchen sie es erneut.");
}
}
@ -99,7 +99,7 @@ public class FinderUtil {
if (stationOptional.isPresent()) {
return ResponseEntity.status(200).body(stationOptional.get());
} else {
return ResponseEntity.status(404).body("Couldnt find Station " + stationID);
return ResponseEntity.status(404).body("Ein Fehler ist aufgetreten. Bitte versuchen sie es erneut.");
}
}
@ -111,7 +111,7 @@ public class FinderUtil {
return ResponseEntity.status(200).body(bearbeitet);
}
return ResponseEntity.status(404).body("The user has not started this cache yet");
return ResponseEntity.status(404).body("Ein Fehler ist aufgetreten. Bitte versuchen sie es erneut.");
}
public static ResponseEntity findCacheAccesDefinitionById(String cacheAccesDefinitionID) {
@ -119,7 +119,7 @@ public class FinderUtil {
if (cacheAccesDefinitionOptional.isPresent()) {
return ResponseEntity.status(200).body(cacheAccesDefinitionOptional.get());
} else {
return ResponseEntity.status(404).body("Couldnt find CacheAccesDefinition " + cacheAccesDefinitionID);
return ResponseEntity.status(404).body("Ein Fehler ist aufgetreten. Bitte versuchen sie es erneut.");
}
}
@ -135,11 +135,11 @@ public class FinderUtil {
User user = userOptional.get();
return ResponseEntity.status(200).body(user);
} else {
return ResponseEntity.status(404).body("Couldnt find User " + userID);
return ResponseEntity.status(404).body("Ein Fehler ist aufgetreten. Bitte versuchen sie es erneut.");
}
} catch (ParseException e) {
e.printStackTrace();
return ResponseEntity.status(404).body("String format was corrupt");
return ResponseEntity.status(404).body("Ein Fehler ist aufgetreten. Bitte versuchen sie es erneut.");
}
}
@ -148,7 +148,7 @@ public class FinderUtil {
if (teamOptional.isPresent()) {
return ResponseEntity.status(200).body(teamOptional.get());
} else {
return ResponseEntity.status(404).body("Couldnt find User_Info " + teamID);
return ResponseEntity.status(404).body("Ein Fehler ist aufgetreten. Bitte versuchen sie es erneut.");
}
}
@ -157,7 +157,7 @@ public class FinderUtil {
if (teamInviteOptional.isPresent()) {
return ResponseEntity.status(200).body(teamInviteOptional.get());
} else {
return ResponseEntity.status(404).body("Couldnt find User_Info " + teamInviteID);
return ResponseEntity.status(404).body("Ein Fehler ist aufgetreten. Bitte versuchen sie es erneut.");
}
}
@ -167,7 +167,7 @@ public class FinderUtil {
if (team != null) {
return ResponseEntity.status(200).body(team);
} else {
return ResponseEntity.status(404).body("Couldnt find Team with name " + name);
return ResponseEntity.status(404).body("Ein Fehler ist aufgetreten. Bitte versuchen sie es erneut.");
}
}
@ -189,7 +189,7 @@ public class FinderUtil {
return ResponseEntity.status(200).body(new Gson().toJson(sendBack));
} else {
return ResponseEntity.status(404).body("Couldnt find Team member of Team " + name);
return ResponseEntity.status(404).body("Ein Fehler ist aufgetreten. Bitte versuchen sie es erneut.");
}
}
}

View File

@ -1,5 +1,6 @@
package hhn.labsw.bugageocaching.util;
import hhn.labsw.bugageocaching.controller.Controller;
import hhn.labsw.bugageocaching.fetchObjects.PublicKey;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
@ -16,16 +17,23 @@ public class VerificationUtil {
public static Key publicKey;
public static void fetchPublicKey(){
private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(VerificationUtil.class);
public static void fetchPublicKey() {
RestTemplate restTemplate = new RestTemplate();
try {
logger.warn("POST CONSCTRUCT: FETCH PUBLIC KEY");
PublicKey response = restTemplate.getForObject("http://seserver.se.hs-heilbronn.de:9080/buga19usermanagement/token/publickey", PublicKey.class);
logger.debug("FETCH PUBLIC KEY: Got response from http://seserver.se.hs-heilbronn.de:9080/buga19usermanagement/token/publickey");
byte[] decodedKey = Base64.getDecoder().decode(response.getMessage());
KeyFactory factory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(decodedKey);
Key key = factory.generatePublic(publicKeySpec);
publicKey = key;
logger.debug("FETCH PUBLIC KEY: Decoded Key: " + publicKey.toString());
} catch (Exception e) {
e.printStackTrace();
}
@ -33,18 +41,24 @@ public class VerificationUtil {
//Fehler muss zurückgegeben werden
}
public static ResponseEntity verifyToken(String token){
public static ResponseEntity verifyToken(String token) {
try{
try {
logger.warn("VERIFY TOKEN: token: " + token);
Claims claims = Jwts.parser() //Parse JWT
.setSigningKey(VerificationUtil.publicKey)
.parseClaimsJws(token).getBody();
logger.debug("VERIFY TOKEN: Got Claims: " + claims);
return ResponseEntity.status(200).body(claims);
} catch (ExpiredJwtException e){
return ResponseEntity.status(401).body("JWT Token expired");
} catch (Exception e){
return ResponseEntity.status(400).body("Something went wrong");
} catch (ExpiredJwtException e) {
logger.debug("VERIFY TOKEN: JWT Token expired");
return ResponseEntity.status(401).body("Bitte loggen sie sich erneut ein.");
} catch (Exception e) {
logger.debug("VERIFY TOKEN: Something went wrong verificating");
return ResponseEntity.status(401).body("Bitte loggen sie sich erneut ein.");
}
}
}

View File

@ -5,5 +5,11 @@ spring.jmx.default-domain=buga19geocaching
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.jooq.sql-dialect=org.hibernate.dialect.MariaDBDialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
debug=true
# spring.jpa.show-sql=true
debug=true
# logging level
logging.level.hhn.labsw.bugageocaching=DEBUG
logging.level.root=WARN