adapted axios service to new backend layout

This commit is contained in:
Sascha Kühl 2025-04-06 17:09:20 +02:00
parent 69427f1809
commit a350b02731
13 changed files with 106 additions and 119 deletions

View File

@ -1,6 +1,6 @@
import Pitcher from "@/types/Pitcher"; import User from "@/types/User";
export const pitchers: Map<number, Pitcher> = new Map([ export const pitchers: Map<number, User> = new Map([
[ [
1, 1,
{ {

View File

@ -1,5 +1,5 @@
export default function authHeader(): any { export default function authHeader(): any {
const user = JSON.parse(localStorage.getItem('user') || '""'); const user = JSON.parse(localStorage.getItem('auth') || '""');
if (user && user.accessToken) { if (user && user.accessToken) {
// return { Authorization: 'Bearer ' + user.accessToken }; // for Spring Boot back-end // return { Authorization: 'Bearer ' + user.accessToken }; // for Spring Boot back-end

View File

@ -1,10 +1,10 @@
import BullpenPitch from "@/types/BullpenPitch"; import BullpenPitch from "@/types/BullpenPitch";
import Pitcher from "@/types/Pitcher"; import User from "@/types/User";
import PitchType from "@/types/PitchType"; import PitchType from "@/types/PitchType";
export class BullpenSessionService { export class BullpenSessionService {
private static instance: BullpenSessionService; private static instance: BullpenSessionService;
private static nullPitcher: Pitcher = { private static nullPitcher: User = {
id: 0, id: 0,
firstName: "", firstName: "",
lastName: "", lastName: "",
@ -32,7 +32,7 @@ export class BullpenSessionService {
return BullpenSessionService.instance; return BullpenSessionService.instance;
} }
public startSession(pitcher: Pitcher): void { public startSession(pitcher: User): void {
this.pitcher = pitcher; this.pitcher = pitcher;
this.pitches = []; this.pitches = [];
this.currentPitch = this.createPitch(); this.currentPitch = this.createPitch();
@ -68,7 +68,7 @@ export class BullpenSessionService {
this.currentPitch = this.createPitch(); this.currentPitch = this.createPitch();
} }
public getPitcher(): Pitcher { public getPitcher(): User {
return this.pitcher; return this.pitcher;
} }
@ -87,7 +87,7 @@ export class BullpenSessionService {
} }
} }
private pitches: BullpenPitch[] = []; private pitches: BullpenPitch[] = [];
private pitcher: Pitcher = BullpenSessionService.nullPitcher; private pitcher: User = BullpenSessionService.nullPitcher;
private currentPitch: BullpenPitch; private currentPitch: BullpenPitch;
} }

View File

@ -1,34 +0,0 @@
import Pitcher from "@/types/Pitcher";
import api from './Api';
class PitcherService {
private static instance: PitcherService;
private constructor() {}
// Static method to get the instance of the service
public static getInstance(): PitcherService {
if (!PitcherService.instance) {
PitcherService.instance = new PitcherService();
}
return PitcherService.instance;
}
async getAllPitchers(): Promise<Pitcher[]> {
const users = await api.get('/users');
return users.data;
}
async getPitcher(id: number): Promise<Pitcher> {
const pitcher = await api.get(`/users/${id}`);
return pitcher.data;
// const pitcher = pitchers.get(id);
// if (pitcher !== undefined) {
// return pitcher;
// } else {
// return Promise.reject();
// }
}
}
export const pitcherService = PitcherService.getInstance();

View File

@ -2,32 +2,32 @@ import UserInfo from '@/types/UserInfo';
class TokenService { class TokenService {
getLocalRefreshToken() { getLocalRefreshToken() {
const user = JSON.parse(localStorage.getItem("user") || '""'); const user = JSON.parse(localStorage.getItem("auth") || '""');
return user?.refreshToken; return user?.refreshToken;
} }
getLocalAccessToken() { getLocalAccessToken() {
const user = JSON.parse(localStorage.getItem("user")|| '""'); const user = JSON.parse(localStorage.getItem("auth")|| '""');
return user?.accessToken; return user?.accessToken;
} }
updateLocalAccessToken(token: string) { updateLocalAccessToken(token: string) {
const user: UserInfo = JSON.parse(localStorage.getItem("user")|| '""'); const user: UserInfo = JSON.parse(localStorage.getItem("auth")|| '""');
user.accessToken = token; user.accessToken = token;
localStorage.setItem("user", JSON.stringify(user)); localStorage.setItem("auth", JSON.stringify(user));
} }
getUser() { getUser() {
return JSON.parse(localStorage.getItem("user")|| '""'); return JSON.parse(localStorage.getItem("auth")|| '""');
} }
setUser(user: UserInfo) { setUser(user: UserInfo) {
console.log(JSON.stringify(user)); console.log(JSON.stringify(user));
localStorage.setItem("user", JSON.stringify(user)); localStorage.setItem("auth", JSON.stringify(user));
} }
removeUser() { removeUser() {
localStorage.removeItem("user"); localStorage.removeItem("auth");
} }
} }

View File

@ -0,0 +1,14 @@
import User from "@/types/User";
import api from './Api';
class UserService {
async getAllUsers(): Promise<User[]> {
return (await api.get('/users')).data;
}
async getUser(id: number): Promise<User> {
return (await api.get(`/users/${id}`)).data;
}
}
export default new UserService();

View File

@ -1,16 +1,17 @@
import AuthService from '@/services/AuthService' import AuthService from '@/services/AuthService'
import Pitcher from "@/types/Pitcher"; import User from "@/types/User";
import { Module, ActionContext } from 'vuex'; import { Module, ActionContext } from 'vuex';
import { RootState } from './index'; import { RootState } from './index';
import TokenService from "@/services/TokenService"; import TokenService from "@/services/TokenService";
import UserService from "@/services/UserService";
export interface AuthState { export interface AuthState {
isAuthenticated: boolean; isAuthenticated: boolean;
user: Pitcher | null; user: User | null;
} }
const user = JSON.parse(localStorage.getItem('user') || '""'); const user = JSON.parse(localStorage.getItem('auth') || '""');
const initialState = user const initialState = user
? { isAuthenticated: true, user } ? { isAuthenticated: true, user }
@ -55,7 +56,9 @@ const auth: Module<AuthState, RootState> = {
mutations: { mutations: {
loginSuccess(state, user) { loginSuccess(state, user) {
state.isAuthenticated = true; state.isAuthenticated = true;
state.user = user; UserService.getUser(user.id).then((user: User) => {
state.user = user;
});
}, },
loginFailure(state) { loginFailure(state) {
state.isAuthenticated = false; state.isAuthenticated = false;

View File

@ -1,10 +1,12 @@
export default interface Pitcher { export default interface User {
id: number, id: number,
firstName: string, firstName: string,
lastName: string, lastName: string,
gender: string,
handedness: string,
weight: number,
height: number,
dateOfBirth: Date, dateOfBirth: Date,
email: string,
createdAt: Date, createdAt: Date,
updatedAt: Date, updatedAt: Date,
password: string
} }

View File

@ -1,7 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref } from 'vue'; import {computed, ref} from 'vue';
import { IonPage, IonHeader, IonToolbar, IonTitle, IonContent, IonAvatar, IonButton, IonIcon } from '@ionic/vue'; import { IonPage, IonHeader, IonToolbar, IonTitle, IonContent, IonAvatar, IonButton, IonIcon } from '@ionic/vue';
import {playOutline, statsChartOutline, personOutline, logOutOutline} from 'ionicons/icons'; import { playOutline, statsChartOutline, personOutline, logOutOutline } from 'ionicons/icons';
// import userImage from '../assets/groot.jpg' // import userImage from '../assets/groot.jpg'
import {useStore} from "vuex"; import {useStore} from "vuex";
import {useRouter} from "vue-router"; import {useRouter} from "vue-router";
@ -12,6 +12,13 @@ const store = useStore();
const userImage = ref(null); const userImage = ref(null);
// const userImage = ref('../assets/groot.jpg'); // const userImage = ref('../assets/groot.jpg');
const user = computed(() => store.state.auth.user);
console.log('user', user.value);
if (user.value === undefined || user.value === null || user.value === '') {
router.push({ path: '/login' });
}
const startBullpen = () => { const startBullpen = () => {
console.log('Starting bullpen session'); console.log('Starting bullpen session');
router.push({ path: '/prepare' }); router.push({ path: '/prepare' });
@ -52,7 +59,7 @@ const logout = () => {
<ion-icon :icon="personOutline" class="avatar-placeholder" /> <ion-icon :icon="personOutline" class="avatar-placeholder" />
</template> </template>
</ion-avatar> </ion-avatar>
<div class="user-name">{{ firstName }} {{ lastName }}</div> <div class="user-name">{{ user.firstName }} {{ user.lastName }}</div>
</div> </div>
<div class="button-container"> <div class="button-container">

View File

@ -71,7 +71,7 @@ const onLogin = () => {
console.log('check if pitch types are available.'); console.log('check if pitch types are available.');
store.dispatch('pitchTypes/initialize').then(() => { store.dispatch('pitchTypes/initialize').then(() => {
router.push('/home'); router.push({ path: '/home'});
}, error => { }, error => {
console.log(error); console.log(error);
}); });

View File

@ -2,20 +2,20 @@
import { ref, onMounted } from "vue"; import { ref, onMounted } from "vue";
import { useRouter } from "vue-router"; import { useRouter } from "vue-router";
import { IonContent, IonHeader, IonPage, IonTitle, IonToolbar, IonList, IonItem, IonLabel } from '@ionic/vue'; import { IonContent, IonHeader, IonPage, IonTitle, IonToolbar, IonList, IonItem, IonLabel } from '@ionic/vue';
import { pitcherService } from "@/services/PitcherService"; import UserService from "@/services/UserService";
import Pitcher from "@/types/Pitcher"; import User from "@/types/User";
import {bullpenSessionService} from "@/services/BullpenSessionService"; import {bullpenSessionService} from "@/services/BullpenSessionService";
const pitchers = ref<Pitcher[]>([]); const pitchers = ref<User[]>([]);
const router = useRouter(); const router = useRouter();
bullpenSessionService.clear(); bullpenSessionService.clear();
onMounted(async () => { onMounted(async () => {
pitchers.value = await pitcherService.getAllPitchers(); pitchers.value = await UserService.getAllUsers();
}); });
const goToPreparePitch = (pitcher: Pitcher) => { const goToPreparePitch = (pitcher: User) => {
bullpenSessionService.startSession( pitcher ); bullpenSessionService.startSession( pitcher );
router.push({ name: 'PreparePitch' }); router.push({ name: 'PreparePitch' });
}; };

View File

@ -42,61 +42,56 @@ exports.register = (req, res) => {
}); });
}; };
exports.login = (req, res) => { exports.login = async (req, res) => {
Auth.findOne({ try {
where: { const auth = await Auth.findOne({
email: req.body.email where: {
} email: req.body.email
})
.then(async (auth) => {
if (!auth) {
return res.status(404).send({ message: "User Not found." });
} }
await User.findOne({
where: {
authId: auth.id
}
}).then(async (user) => {
const passwordIsValid = auth.validPassword(req.body.password);
if (!passwordIsValid) {
return res.status(401).send({
accessToken: null,
message: "Invalid Password!"
});
}
const token = jwt.sign({ id: auth.id },
config.secret,
{
algorithm: 'HS256',
allowInsecureKeySizes: true,
expiresIn: config.jwtExpiration
});
let refreshToken = await RefreshToken.createToken(auth);
const authorities = [];
user.getRoles().then(roles => {
for (let i = 0; i < roles.length; i++) {
authorities.push("ROLE_" + roles[i].name.toUpperCase());
}
res.status(200).send({
id: user.id,
email: auth.email,
roles: authorities,
accessToken: token,
refreshToken: refreshToken
});
});
}).catch(err => {
res.status(500).send({ message: err.message });
});
})
.catch(err => {
res.status(500).send({ message: err.message });
}); });
if (!auth) {
return res.status(404).send({message: "User Not found."});
}
const passwordIsValid = auth.validPassword(req.body.password);
if (!passwordIsValid) {
return res.status(401).send({
accessToken: null,
message: "Invalid Password!"
});
}
const refreshToken = await RefreshToken.createToken(auth);
const accessToken = jwt.sign({id: auth.id},
config.secret,
{
algorithm: 'HS256',
allowInsecureKeySizes: true,
expiresIn: config.jwtExpiration
});
const user = await User.findOne({
where: {
authId: auth.id
}
});
const authorities = [];
const roles = await user.getRoles();
for (let i = 0; i < roles.length; i++) {
authorities.push("ROLE_" + roles[i].name.toUpperCase());
}
return res.status(200).send({
id: user.id,
email: auth.email,
roles: authorities,
accessToken: accessToken,
refreshToken: refreshToken
});
} catch (err) {
res.status(500).send({ message: err.message });
}
}; };
// exports.logout = (req, res) => { // exports.logout = (req, res) => {

View File

@ -20,6 +20,6 @@ module.exports = function(app) {
); );
app.post("/api/auth/login", controller.login); app.post("/api/auth/login", controller.login);
app.post("/api/auth/logout", controller.logout); // app.post("/api/auth/logout", controller.logout);
app.post("/api/auth/refreshtoken", controller.refreshToken); app.post("/api/auth/refreshtoken", controller.refreshToken);
}; };