Merge branch 'develop' into frontend/timo

This commit is contained in:
Timo Volkmann 2019-05-15 11:11:22 +02:00
commit c00cdfcec1
6 changed files with 417 additions and 319 deletions

View File

@ -12,7 +12,7 @@
switch-indicator
>
<q-tab name="profile" label="Profil" icon="perm_identity"/>
<q-tab name="teams" label="Team" icon="group"/>
<q-tab v-if="boolAlreadyInTeam" name="teams" label="Team" icon="group"/>
</q-tabs>
<q-separator color="grey-4"/>
</div>
@ -20,100 +20,31 @@
<div class="col flex column">
<q-tab-panels v-model="tab" animated swipeable class="col">
<q-tab-panel name="profile" class=" fit">
<p class="text-h5"> Persönliche Daten </p>
<q-table
:data="data"
:columns="columns"
row-key="name"
hide-header
hide-bottom
table-class="my-custom"
/>
</q-tab-panel>
<q-tab-panel name="teams">
<div class="q-pa-md" align="center">
<q-btn-dropdown color="primary" :label="dropDownSelectedItem" size="20px">
<q-list>
<q-item :clickable="boolAlreadyInTeam" v-close-popup @click="dropDownSelectItem('team')"
:disabled="!boolAlreadyInTeam">
<q-item-section>
<q-item-label v-html="teamName"></q-item-label>
</q-item-section>
</q-item>
<q-item clickable v-close-popup @click="dropDownSelectItem('Offene Teameinladungen')">
<q-item-section avatar>
<q-avatar icon="group_add" color="primary" text-color="white"/>
</q-item-section>
<q-item-section>
<q-item-label>Offene Teameinladungen</q-item-label>
</q-item-section>
</q-item>
<q-item :clickable="!boolAlreadyInTeam" v-close-popup :disabled="boolAlreadyInTeam"
@click="dropDownSelectItem('Neues Team erstellen')">
<q-item-section avatar>
<q-avatar icon="add" color="primary" text-color="white"/>
</q-item-section>
<q-item-section>
<q-item-label v-show="!boolAlreadyInTeam">Neues Team erstellen</q-item-label>
<q-item-label v-show="boolAlreadyInTeam">Neues Team erstellen<br/>(Team verlassen um Option zu
nutzen)
</q-item-label>
</q-item-section>
</q-item>
</q-list>
</q-btn-dropdown>
<q-tab-panel name="profile" class="fit q-pa-none">
<div class="bg-primary q-pa-md">
<p class="text-h3 text-white"> {{userName}} </p>
<p class="text-white"> Meine Email: {{email}} </p>
<p class="text-white"> Mein Rang: {{userRanking}} </p>
<p class="text-white"> Mein Team: {{teamName}} </p>
</div>
<div v-show="boolMyTeam">
<p class="text-h5"> Teammitglieder </p>
<q-table
:data="teamData"
:columns="teamColumns"
row-key="name"
table-class="my-custom"
hide-bottom
:pagination.sync="pagination"
/>
<br/>
<p class="text-h5"> Einladungen </p>
<q-input lazy-rules outlined filled stack-label v-model="inviteMail"
type="text" label="Email des Nutzers"
:rules="[val=>validateEmail(val)||'Bitte Email verwenden']"/>
<div align="center">
<q-btn label="Einladung versenden"
@click="sendTeamInvite()"
:disabled="!teamInviteChecked"
<div class="q-pa-md">
<div>
<q-input v-show="!boolAlreadyInTeam" lazy-rules outlined filled stack-label v-model="newTeamName"
type="text"
label="Teamname eingeben"
:rules="[val=>val.length>=2||'Name muss mindestens 5 Zeichen lang sein!']"/>
<q-btn
v-show="!boolAlreadyInTeam"
:disabled="!newTeamNameValidationSuccesful"
label="Team anlegen"
color="primary"
type="submit"/>
class="full-width"
@click="createTeam()"
unelevated
/>
</div>
<br/>
<p class="text-h5"> Teamstatus </p>
<p>{{currentTeamStatus}}</p>
<q-input lazy-rules outlined filled stack-label v-model="teamStatus"
type="text" label="Neuer Teamstatus"
:rules="[val=>val.length<=160||'Status zu lang!']"/>
<div align="center">
<q-btn label="Teamstatus aktualisieren"
:disabled="!teamStatusChecked"
@click="setTeamStatus()"
color="primary"
type="submit"/>
</div>
<br/>
<q-input lazy-rules outlined filled stack-label v-model="leaveTeamCheck"
type="text" label="BESTÄTIGEN eingeben um das Team zu verlassen"
:rules="[val=>val==='BESTÄTIGEN'||'Schreibweise beachten']"/>
<div align="center">
<q-btn label="Team verlassen"
:disabled="!leaveConfirmed"
@click="leaveTeam()"
color="negative"
type="submit"/>
</div>
</div>
<div v-show="boolInvites">
<p class="text-h5" v-show="!boolAlreadyInTeam"> Teameinladungen </p>
<q-list>
<q-card class="q-mb-md" v-for="teamInvite in teamInvites" :key="teamInvite.id">
<q-expansion-item
@ -125,27 +56,91 @@
:caption="teamInvite.team.teamStatus"
>
<q-item class="q-pr-sm reverse q-gutter-x-sm">
<q-btn @click="joinTeam(teamInvite)" unelevated color="positive" stack icon="arrow_forward"
label="Anfrage annehmen" size="sm"/>
<q-btn :disabled="boolAlreadyInTeam" @click="joinTeam(teamInvite)" unelevated color="positive" stack
icon="arrow_forward"
label="Annehmen" size="sm"/>
<q-btn @click="deleteTeamInvite(teamInvite)" unelevated color="negative" stack icon="delete"
label="Anfrage ablehnen" size="sm"/>
label="Ablehnen" size="sm"/>
</q-item>
</q-expansion-item>
</q-card>
</q-list>
<div align="center">
<q-btn v-show="boolAlreadyInTeam"
label="Team verlassen"
@click="confirmLeave()"
color="negative"
type="submit"/>
</div>
<div v-show="boolCreateTeam">
<q-input lazy-rules outlined filled stack-label v-model="newTeamName" type="text"
label="Teamname eingeben"
:rules="[val=>val.length>=2||'Name muss mindestens 5 Zeichen lang sein!']"/>
<q-btn
:disabled="!newTeamNameValidationSuccesful"
label="Team anlegen"
color="primary"
class="full-width"
@click="createTeam()"
unelevated
</div>
</q-tab-panel>
<q-tab-panel v-if="boolAlreadyInTeam" name="teams" class="q-pa-none">
<div class="bg-primary q-pa-md" v-show="boolAlreadyInTeam">
<p class="text-h3 text-white"> {{teamName}} </p>
<p class="text-white"> Unser Rang: {{teamRanking}} </p>
<p v-show="!boolStatus" class="text-white">
Unser Status: {{currentTeamStatus}}
<q-btn icon="create"
class="on-right"
@click="updateStatus()"
color="amber"/>
</p>
<q-input v-show="boolStatus" lazy-rules outlined filled stack-label v-model="teamStatus"
type="text" label="Neuer Teamstatus" bg-color="white"
:rules="[val=>val.length<=160||'Status zu lang!']"/>
<div v-show="boolStatus" align="center">
<q-btn icon="done"
class="on-left"
:disabled="!teamStatusChecked"
@click="setTeamStatus()"
color="positive"
type="submit"/>
<q-btn icon="clear"
class="on-right"
@click="updateStatus()"
color="negative"
type="submit"/>
</div>
</div>
<div class="bg-white q-pa-md" v-show="boolAlreadyInTeam">
<p class="text-h5"> Teammitglieder </p>
<q-table
v-if="boolTable"
name="teamDataTable"
:data="teamData"
:columns="teamColumns"
row-key="name"
table-class="my-custom"
hide-bottom
:pagination.sync="pagination"
/>
<br/>
<div align="center">
<q-btn label="Nutzer einladen"
@click="activateInvite()"
color="primary"
type="submit"/>
</div>
<br/>
<div align="center">
<q-input v-show="inviteActivated" lazy-rules outlined filled stack-label v-model="inviteMail"
type="text" label="Email des Nutzers"
:rules="[val=>validateEmail(val)||'Bitte Email verwenden']"/>
<q-btn v-show="inviteActivated"
icon="arrow_right_alt"
@click="sendTeamInvite()"
:disabled="!teamInviteChecked"
color="positive"
type="submit"/>
</div>
<br/>
<div align="center">
<q-btn label="Team verlassen"
@click="confirmLeave()"
color="negative"
type="submit"/>
</div>
<br/>
</div>
</q-tab-panel>
@ -184,70 +179,26 @@
teamName: null,
boolAlreadyInTeam: false,
teamRanking: null,
dropDownSelectedItem: null,
boolMyTeam: true,
boolInvites: false,
boolCreateTeam: false,
newTeamName: "",
leaveTeamCheck: "",
teamMembers: [],
teamInvites: [],
columns: [
{
name: 'desc',
required: true,
align: 'left',
field: row => row.name,
format: val => `${val}`,
},
{
name: 'userData',
required: true,
align: 'left',
field: 'userData',
}
],
data: [
{
name: 'Benutzername',
userData: this.userName,
},
{
name: 'E-Mail',
userData: this.email,
},
{
name: 'Rang',
userData: this.userRanking,
},
{
name: 'Team',
userData: this.teamName,
},
{
name: 'Team-Rang',
userData: this.teamRanking,
},
],
inviteActivated: false,
boolStatus: false,
boolTable: true,
boolMemberTableUpdating: false,
teamColumns: [
{
name: 'desc',
label: 'Benutzername',
label: 'Name',
required: true,
align: 'left',
field: row => row.name,
format: val => `${val}`,
},
{
name: 'email',
label: 'Email',
required: true,
align: 'left',
field: 'email',
},
{
name: 'ranking',
label: 'Rangliste (Solo)',
label: 'Rang',
required: true,
align: 'left',
field: 'ranking',
@ -260,7 +211,6 @@
descending: false,
page: 1,
rowsPerPage: 10
// rowsNumber: xx if getting data from a server
},
}
},
@ -289,7 +239,7 @@
return false;
},
leaveConfirmed() {
if (this.leaveTeamCheck === 'BESTÄTIGEN'){
if (this.leaveTeamCheck === 'BESTÄTIGEN') {
return true;
}
return false;
@ -299,14 +249,46 @@
// this.$store.commit('auth/SET_AUTHENTICATED');
// this.$store.commit('auth/SET_USER');
this.userName = JSON.parse(localStorage.getItem('userToken')).name;
this.data[0].userData = this.userName;
this.email = JSON.parse(localStorage.getItem('userMail'));
this.data[1].userData = this.email;
this.getPersonalRanking();
this.getTeamData();
this.fetchTeamInvites();
this.updateTeamData();
},
methods: {
confirmLeave() {
this.$q.dialog({
title: 'Verlassen...',
message: 'Willst du dein aktuelles Team wirklich verlassen?',
persistent: true,
cancel: true,
}).onOk(() => {
console.log('>>>> OK');
this.leaveTeam();
}).onCancel(() => {
console.log('>>>> Cancel')
}).onDismiss(() => {
})
},
activateInvite() {
if (this.inviteActivated) {
this.inviteActivated = false;
} else {
this.inviteActivated = true;
}
},
updateStatus() {
if (this.boolStatus) {
this.boolStatus = false;
} else {
this.boolStatus = true;
}
},
updateTable() {
if (this.boolTable) {
this.boolTable = false;
} else {
this.boolTable = true;
}
},
validateEmail(email) {
let re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
@ -316,12 +298,18 @@
this.$axios.get('/api/getRankingPlace', {params: {email}})
.then((response) => {
this.userRanking = response.data;
this.data[2].userData = this.userRanking;
}).catch((error) => {
this.handleError(error);
})
},
async updateTeamData() {
await this.getTeamData();
this.boolTable = false;
this.boolTable = await this.fetchTeamMembers();
await this.fetchTeamInvites();
},
getTeamData() {
return new Promise(resolve => {
let token;
if (localStorage.getItem('userToken')) {
token = JSON.parse(localStorage.getItem('userToken')).token;
@ -335,41 +323,18 @@
this.teamName = "Aktuell in keinem Team";
this.currentTeamStatus = "";
this.teamRanking = "-";
this.dropDownSelectItem('Offene Teameinladungen');
} else {
this.boolAlreadyInTeam = true;
this.teamName = response.data.name;
this.currentTeamStatus = response.data.teamStatus;
//this.teamRanking = response.data.teamRanking;
this.fetchTeamMembers();
this.teamRanking = "-";
}
this.data[3].userData = this.teamName;
this.dropDownSelectedItem = this.teamName;
this.data[4].userData = this.teamRanking;
console.log("getTeam: " + response);
}).catch((error) => {
this.handleError(error);
}).finally(() => resolve(true));
})
},
dropDownSelectItem(item) {
if (item === 'team') {
this.dropDownSelectedItem = this.teamName;
this.boolMyTeam = true;
this.boolInvites = false;
this.boolCreateTeam = false;
} else if (item === 'Offene Teameinladungen') {
this.dropDownSelectedItem = item;
this.boolMyTeam = false;
this.boolInvites = true;
this.boolCreateTeam = false;
} else {
this.dropDownSelectedItem = item;
this.boolMyTeam = false;
this.boolInvites = false;
this.boolCreateTeam = true;
}
},
createTeam() {
let params = {};
if (localStorage.getItem('userToken')) {
@ -386,6 +351,7 @@
title: "Teamerstellung",
color: "blue"
});
this.updateTeamData();
}).catch((error) => {
this.handleError(error);
})
@ -401,33 +367,38 @@
.then((response) => {
console.log("createTeam: " + response);
this.$store.commit('dialog/NEW_MESSAGE_DIALOG', {
message: "Dus hast das Team " + this.teamName + " verlassen!",
message: "Du hast das Team " + this.teamName + " verlassen!",
title: "Team verlassen",
color: "blue"
});
this.getTeamData();
this.updateTeamData();
}).catch((error) => {
this.handleError(error);
})
},
fetchTeamMembers() {
return new Promise(resolve => {
this.teamData = [];
let name = this.teamName;
this.$axios.get('/api/getTeamMembers', {params: {name}})
.then((response) => {
.then(async (response) => {
console.log(response.data);
this.teamMembers = response.data;
for (var i = 0; i < this.teamMembers.length; i++) {
let member = {};
member.name = this.teamMembers[i].username;
member.email = this.teamMembers[i].email;
this.getMemberRanking(member, member.email);
await this.getMemberRanking(member, member.email);
this.teamData.push(member);
}
}).catch((error) => {
this.handleError(error);
}).finally(() => resolve(true))
})
},
getMemberRanking(member, email) {
return new Promise(resolve => {
this.updateTable();
let ranking;
this.$axios.get('/api/getRankingPlace', {params: {email}})
.then((response) => {
@ -435,9 +406,11 @@
member.ranking = ranking;
}).catch((error) => {
this.handleError(error);
});
}).finally(() => resolve(true))
})
},
fetchTeamInvites() {
return new Promise(resolve => {
let token;
if (localStorage.getItem('userToken')) {
token = JSON.parse(localStorage.getItem('userToken')).token;
@ -450,6 +423,7 @@
console.log(this.teamInvites);
}).catch((error) => {
this.handleError(error);
}).finally(() => resolve(true))
})
},
joinTeam(teamInvite) {
@ -468,7 +442,7 @@
title: "Teambeitrittsanfrage",
color: "blue"
});
this.getTeamData();
this.updateTeamData();
}).catch((error) => {
this.handleError(error);
})
@ -488,7 +462,7 @@
title: "Teambeitrittsanfrage",
color: "blue"
});
this.getTeamData();
this.updateTeamData();
}).catch((error) => {
this.handleError(error);
})
@ -522,10 +496,11 @@
params.teamStatus = this.teamStatus;
this.$axios.put('/api/setTeamStatus', null, {params})
.then((response) => {
this.getTeamData();
this.updateTeamData();
}).catch((error) => {
this.handleError(error);
})
this.updateStatus();
},
handleError(error) {
// Error

View File

@ -6,7 +6,7 @@
<div class="col">
<div class="">
<div class="" style="max-width: 440px">
<q-input lazy-rules outlined filled stack-label v-model="user.name" type="text" label="Benutzername"
<q-input lazy-rules outlined filled stack-label v-model="user.name" type="text" label="Name"
:rules="[val=>val.length>=2||'Name muss mindestens 2 Zeichen lang sein!']"/>
</div>
</div>

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
@ -68,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()));
}
@ -232,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");
}
//----------------------
@ -277,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)) {
@ -310,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");
}
}
@ -337,26 +341,7 @@ 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);
}
@ApiOperation(value = "Checks if the given User has an admin role")
@ -405,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()));
}
@ -416,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);
}
@ -430,6 +417,7 @@ public class Controller {
@ResponseBody
public ResponseEntity getMyCaches(@RequestParam String token) {
logger.warn("API CALL: /api/getMyCaches");
ResponseEntity verifyToken = VerificationUtil.verifyToken(token);
@ -439,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) {
@ -447,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!");
}
}
@ -470,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));
}
@ -530,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");
}
}
@ -567,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");
}
}
@ -622,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
@ -647,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
@ -693,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
@ -761,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.");
}
//----------------------
@ -770,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
@ -783,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();
@ -906,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

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);
@ -81,16 +83,16 @@ 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");
if (station.getDescription().length() == 0 /*|| station.getSolution().length() == 0*/) {
return ResponseEntity.status(400).body("Alle Felder müssen ausgefüllt werden!");
}
if (station.getLattitude() < 9 || station.getLattitude() > 10) {
return ResponseEntity.status(400).body("Lattitude has to be between 9 and 10 degrees");
if (station.getLattitude() < 49 || station.getLattitude() > 50) {
return ResponseEntity.status(400).body("Der Breitengrad einer Station ist außerhalb der Bundesgartenschau");
}
if (station.getLongitude() < 49 || station.getLongitude() > 50) {
return ResponseEntity.status(400).body("Longitude has to be in the range of 49 to 50 degrees");
if (station.getLongitude() < 9 || station.getLongitude() > 10) {
return ResponseEntity.status(400).body("Der Längengrad einer Station 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.");
}
}
}