Merge branch 'develop' into backend/michael

This commit is contained in:
Michael 2019-05-14 11:58:37 +02:00
commit 97f9c27d1d
11 changed files with 187 additions and 103 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 {

View File

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

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,7 +199,7 @@
this.$store.commit('cacheCollector/RESET_NEW_CACHE');
this.$router.push({path: '/overview'});
}).catch((error) => {
//TODO: Fehlermeldungen
//TODO: Fehlermeldungen
// Error
let msg;
let title;
@ -233,26 +222,16 @@
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'});
})
}
},
},
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

@ -120,10 +120,14 @@
},
async created() {
console.log("created(): " + this.caches);
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:
@ -232,6 +236,7 @@
this.$router.push({path: `/cache`})
},
editCache(cacheID) {
this.$router.push({path: `/cache/${cacheID}`})
},
initMap() {
console.log("Signalwort: " + this.pois);
@ -249,9 +254,9 @@
},
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: ";

View File

@ -70,7 +70,7 @@ 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",
});

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

@ -58,6 +58,8 @@ public class Controller {
@Autowired
TeamInviteRepository teamInviteRepository;
private org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(Controller.class);
@PostConstruct
public void init() {
fetchPublicKey();
@ -68,6 +70,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()));
}
@ -337,27 +340,6 @@ public class Controller {
@ResponseBody
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);
}
@ -407,6 +389,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()));
}
@ -418,6 +401,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);
}
@ -432,6 +416,7 @@ public class Controller {
@ResponseBody
public ResponseEntity getMyCaches(@RequestParam String token) {
logger.warn("API CALL: /api/getMyCaches");
ResponseEntity verifyToken = VerificationUtil.verifyToken(token);
@ -441,6 +426,8 @@ public class Controller {
Claims claims = (Claims) verifyToken.getBody();
logger.debug("/api/getMyCaches Token verified");
ResponseEntity getUser = FinderUtil.findUserFromClaim(claims);
if (getUser.getStatusCodeValue() != 200) {
@ -449,14 +436,18 @@ 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");
@ -472,13 +463,18 @@ 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");
return ResponseEntity.status(200).body(new Gson().toJson(sendBackUsers));
}
@ -989,7 +985,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")
@ -1010,7 +1006,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
@ -1076,7 +1072,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) {
@ -1103,6 +1099,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

@ -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;
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();
}
@ -36,14 +44,20 @@ public class VerificationUtil {
public static ResponseEntity verifyToken(String token){
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){
logger.debug("VERIFY TOKEN: JWT Token expired");
return ResponseEntity.status(401).body("JWT Token expired");
} catch (Exception e){
logger.debug("VERIFY TOKEN: Something went wrong verificating");
return ResponseEntity.status(400).body("Something went wrong");
}
}

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