Spctr
Spctr
Explore posts from servers
NNuxt
Created by Spctr on 10/31/2024 in #❓・help
JWT issue
I've uploaded my project into a Container and now I have the problem that my req.headers looks different then on localhost development.
// prod

{
host: '<url>:4005',
connection: 'keep-alive',
pragma: 'no-cache',
'cache-control': 'no-cache',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',
accept: 'application/json, text/plain, */*',
origin: 'http://<url>:3005',
referer: 'http://<url>:3005/',
'accept-encoding': 'gzip, deflate',
'accept-language': 'de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7'
}



// localhost

{
host: 'localhost:4000',
connection: 'keep-alive',
pragma: 'no-cache',
'cache-control': 'no-cache',
'sec-ch-ua-platform': '"Windows"',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',
accept: 'application/json, text/plain, */*',
'sec-ch-ua': '"Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"',
'sec-ch-ua-mobile': '?0',
origin: 'http://localhost:3005',
'sec-fetch-site': 'same-site',
'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',
referer: 'http://localhost:3005/',
'accept-encoding': 'gzip, deflate, br, zstd',
'accept-language': 'de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7',
cookie: '<token>'
}
// prod

{
host: '<url>:4005',
connection: 'keep-alive',
pragma: 'no-cache',
'cache-control': 'no-cache',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',
accept: 'application/json, text/plain, */*',
origin: 'http://<url>:3005',
referer: 'http://<url>:3005/',
'accept-encoding': 'gzip, deflate',
'accept-language': 'de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7'
}



// localhost

{
host: 'localhost:4000',
connection: 'keep-alive',
pragma: 'no-cache',
'cache-control': 'no-cache',
'sec-ch-ua-platform': '"Windows"',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',
accept: 'application/json, text/plain, */*',
'sec-ch-ua': '"Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"',
'sec-ch-ua-mobile': '?0',
origin: 'http://localhost:3005',
'sec-fetch-site': 'same-site',
'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',
referer: 'http://localhost:3005/',
'accept-encoding': 'gzip, deflate, br, zstd',
'accept-language': 'de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7',
cookie: '<token>'
}
7 replies
NNuxt
Created by Spctr on 10/31/2024 in #❓・help
JWT issue
This are all the steps it takes ... maybe it's a nest issue I made but I don't know login:
// frontend - nuxt3

async login() {
try {
const { $config } = useNuxtApp();
const login = await axios.post(`${$config.public.backendServer}/api/auth/login`, {
username: this.username,
password: this.password,
}, {withCredentials: true});

if (login.status === 200) {
const { access_token } = login.data; // get access token

if (access_token) {
localStorage.setItem('token', access_token); // save token
}
this.$router.push('/dashboard');
}
} catch (error) {
this.errorMessage = translate('error.login');
}
}
// frontend - nuxt3

async login() {
try {
const { $config } = useNuxtApp();
const login = await axios.post(`${$config.public.backendServer}/api/auth/login`, {
username: this.username,
password: this.password,
}, {withCredentials: true});

if (login.status === 200) {
const { access_token } = login.data; // get access token

if (access_token) {
localStorage.setItem('token', access_token); // save token
}
this.$router.push('/dashboard');
}
} catch (error) {
this.errorMessage = translate('error.login');
}
}
// backend nest

@Post('login')
async loginUser(@Body() body: { username: string; password: string }, @Res() res: Response) {
const { username, password } = body;

const account: Account | null = await this.accountsService.findUserByUsername(username);

if (!account) {
return res.status(401).json({ message: 'Invalid credentials' });
}

const passwordMatches: boolean = bcrypt.compareSync(password, account.passwordHash);

if (!passwordMatches) {
return res.status(401).json({ message: 'Invalid credentials' });
}

const jwt: string = this.jwtService.sign({
username: account.username,
role: account.role,
id: account.id
});
res.cookie('dtn_jwt', jwt, {
httpOnly: true,
secure: true,
maxAge: 10 * 60 * 1000
});

return res.status(200).json({ message: 'Login successful', account: account, access_token: jwt }); // ✅ goes here
}
// backend nest

@Post('login')
async loginUser(@Body() body: { username: string; password: string }, @Res() res: Response) {
const { username, password } = body;

const account: Account | null = await this.accountsService.findUserByUsername(username);

if (!account) {
return res.status(401).json({ message: 'Invalid credentials' });
}

const passwordMatches: boolean = bcrypt.compareSync(password, account.passwordHash);

if (!passwordMatches) {
return res.status(401).json({ message: 'Invalid credentials' });
}

const jwt: string = this.jwtService.sign({
username: account.username,
role: account.role,
id: account.id
});
res.cookie('dtn_jwt', jwt, {
httpOnly: true,
secure: true,
maxAge: 10 * 60 * 1000
});

return res.status(200).json({ message: 'Login successful', account: account, access_token: jwt }); // ✅ goes here
}
// frontend - nuxt3 [ /middleware/routeProtection.ts ]

async function isUserAuthenticated(): Promise<any> {
const { user, setUser } = useUserStore();
if (user.value) {
return { user: user.value };
}

try {
const { $config } = useNuxtApp();
// ✅ sends request to the backend [ nest ]
const response = await axios.get(`${$config.public.backendServer}/api/auth/verify`, { withCredentials: true });
user.value = response.data.user;
return { user: response.data.user };
} catch (error) {
return { user: null };
}
}
// frontend - nuxt3 [ /middleware/routeProtection.ts ]

async function isUserAuthenticated(): Promise<any> {
const { user, setUser } = useUserStore();
if (user.value) {
return { user: user.value };
}

try {
const { $config } = useNuxtApp();
// ✅ sends request to the backend [ nest ]
const response = await axios.get(`${$config.public.backendServer}/api/auth/verify`, { withCredentials: true });
user.value = response.data.user;
return { user: response.data.user };
} catch (error) {
return { user: null };
}
}
// backend - nest

@Get('verify')
async verifyToken(@Req() req: Request, @Res() res: Response) {
try {
const token = req.headers.cookie.split('=')[1]; // ❌ finds no .cookie? and goes into catch()
if (!token) {
return res.status(401).json({ message: 'Not authenticated' });
}

const decoded = this.jwtService.verify(token);
const user: Account | null = await this.accountsService.findUserByUsername(decoded.username);

if (!user) {
return res.status(401).json({ message: 'User not found' });
}

return res.status(200).json({ user });
} catch (error) {
return res.status(401).json({ message: 'Invalid token' });
}
}
// backend - nest

@Get('verify')
async verifyToken(@Req() req: Request, @Res() res: Response) {
try {
const token = req.headers.cookie.split('=')[1]; // ❌ finds no .cookie? and goes into catch()
if (!token) {
return res.status(401).json({ message: 'Not authenticated' });
}

const decoded = this.jwtService.verify(token);
const user: Account | null = await this.accountsService.findUserByUsername(decoded.username);

if (!user) {
return res.status(401).json({ message: 'User not found' });
}

return res.status(200).json({ user });
} catch (error) {
return res.status(401).json({ message: 'Invalid token' });
}
}
7 replies
NNuxt
Created by Spctr on 10/30/2024 in #❓・help
Production Port in Pterodactyl [ SOLVED ]
That doesn't work for Pterodactyl but I've found a workaround. Just put this file in the /home/container :
// index.js

// set environment variable for the port
process.env.PORT = '<port>';

// import the main startup file for the nuxt project
import('./.output/server/index.mjs')
.then(() => {
console.log(`Server is running on port ${process.env.PORT}`);
})
.catch((err) => {
console.error("Error when starting the server:", err);
});
// index.js

// set environment variable for the port
process.env.PORT = '<port>';

// import the main startup file for the nuxt project
import('./.output/server/index.mjs')
.then(() => {
console.log(`Server is running on port ${process.env.PORT}`);
})
.catch((err) => {
console.error("Error when starting the server:", err);
});
5 replies
NNuxt
Created by Spctr on 10/15/2024 in #❓・help
Frontend middleware auth with backend auth
thank u so much
12 replies
NNuxt
Created by Spctr on 10/15/2024 in #❓・help
Frontend middleware auth with backend auth
just this small changes
12 replies
NNuxt
Created by Spctr on 10/15/2024 in #❓・help
Frontend middleware auth with backend auth
thank u
12 replies
NNuxt
Created by Spctr on 10/15/2024 in #❓・help
Frontend middleware auth with backend auth
holy .. that works for me
12 replies
NNuxt
Created by Spctr on 10/15/2024 in #❓・help
Frontend middleware auth with backend auth
where should I do this checks
12 replies
NNuxt
Created by Spctr on 10/15/2024 in #❓・help
Frontend middleware auth with backend auth
why does the user wont be stored has someone an idea or a hint
12 replies
NNuxt
Created by Spctr on 10/15/2024 in #❓・help
Frontend middleware auth with backend auth
i've tried to fix it .. can someone help
12 replies
NNuxt
Created by Spctr on 10/15/2024 in #❓・help
Frontend middleware auth with backend auth
If u need to see something just tell me
12 replies