fixed 'added 'refreshToken', converted to 'httpOnly', added SSL

fixed 'gql-types' generator
This commit is contained in:
lnn0q 2025-04-06 19:57:14 +03:00
parent d179b8c7c8
commit c190d368de
20 changed files with 314 additions and 179 deletions

View file

@ -7,7 +7,7 @@ import jwt from 'jsonwebtoken';
export async function LoginResolver(
_: any,
{ input }: MutationLoginArgs,
{ identity }: IdentityContext
{ req, res, identity }: IdentityContext
): Promise<Session> {
const error = 'Invalid password or email';
@ -36,14 +36,21 @@ export async function LoginResolver(
data: { refreshToken }
});
res.cookie('jwt', refreshToken, {
httpOnly: true,
sameSite: 'none',
secure: true,
maxAge: 24 * 60 * 60 * 1000
});
return {
accessToken,
refreshToken: {
token: refreshToken,
httpOnly: true,
secure: true,
maxAge: 24 * 60 * 60 * 1000,
sameSite: 'None'
}
accessToken
// refreshToken: {
// token: refreshToken,
// httpOnly: true,
// secure: true,
// maxAge: 24 * 60 * 60 * 1000,
// sameSite: 'None'
// }
};
}

View file

@ -0,0 +1,36 @@
import { IdentityContext } from '@app/server/identity';
import { prisma } from '@app/server/prisma/client';
import { Session } from '@generated/types';
import jwt from 'jsonwebtoken';
export async function RefreshTokenResolver(
_: any,
{ req, res, identity }: IdentityContext
): Promise<Session> {
const accessTokenSecret = process.env.ACCESS_TOKEN_SECRET;
const refreshTokenSecret = process.env.REFRESH_TOKEN_SECRET;
if (accessTokenSecret == null || refreshTokenSecret == null) throw new Error('No secrets found.');
const cookie: { jwt?: string | null } = req.cookies;
if (cookie == null || cookie.jwt == null) throw new Error('Unauthorized.');
const refreshToken = cookie.jwt;
const user = await prisma.user.findUniqueOrThrow({
where: { refreshToken },
select: { id: true }
});
const decoded = jwt.verify(refreshToken, accessTokenSecret) as {
userId: string;
iat: number;
exp: number;
};
if (user.id !== decoded.userId) throw new Error('Invalid token.');
const accessToken = jwt.sign({ userId: user.id }, accessTokenSecret, {
expiresIn: '30s'
});
return { accessToken };
}

View file

@ -1,11 +1,11 @@
import { IdentityContext } from '@app/server/identity';
import { prisma, uuid } from '@app/server/prisma/client';
import { MutationRegisterArgs } from '@generated/types';
import { MutationSignUpArgs } from '@generated/types';
import bcrypt from 'bcrypt';
export async function SignUpResolver(
_: any,
{ input }: MutationRegisterArgs,
{ input }: MutationSignUpArgs,
{ identity }: IdentityContext
): Promise<void> {
const existingUsername = await prisma.user.findUnique({

View file

@ -19,6 +19,6 @@ export async function BooksManyResolver(
__: any,
{ identity }: IdentityContext
): Promise<Book[]> {
if (identity == null) throw Error('Unauthorized');
if (identity == null) throw new Error('Unauthorized');
return books;
}

View file

@ -7,7 +7,7 @@ type Query {
type Mutation {
login(input: LoginInput!): Session!
signUp(input: RegisterInput!): Void
signUp(input: SignUpInput!): Void
}
input LoginInput {
@ -15,7 +15,7 @@ input LoginInput {
password: String!
}
input RegisterInput {
input SignUpInput {
email: String!
username: String!
password: String!
@ -23,7 +23,6 @@ input RegisterInput {
type Session {
accessToken: String!
refreshToken: RefreshToken!
}
type RefreshToken {

View file

@ -5,6 +5,8 @@ import { prisma } from './prisma/client';
import { Session } from '@generated/types';
export interface IdentityContext {
req: Request;
res: Response;
identity?: {
id: string;
username: string;
@ -19,11 +21,10 @@ export async function getIdentityContext({
res: Response;
}): Promise<IdentityContext> {
const authHeaders = req.headers.authorization;
if (authHeaders == null) return {};
if (authHeaders == null) return { req, res };
const session: Session = JSON.parse(authHeaders);
console.log(session);
const accessToken = session.accessToken;
const { accessToken } = session;
const accessTokenSecret = process.env.ACCESS_TOKEN_SECRET;
if (accessTokenSecret == null) throw new Error('No `accessToken`.');
@ -43,5 +44,14 @@ export async function getIdentityContext({
}
});
if (identity == null) throw new Error("Couldn't find the user.");
return { identity };
return { req, res, identity };
}
/* throw new GraphQLError('User is not authenticated', {
extensions: {
code: 'UNAUTHENTICATED',
http: { status: 401 }
}
}); */
// throw new GraphQLError(`${error}`);

View file

@ -5,20 +5,25 @@ import cors from 'cors';
import 'dotenv/config';
import express from 'express';
import fs from 'fs';
import http from 'http';
import https from 'https';
import path from 'path';
import ViteExpress from 'vite-express';
import { Mutation, Query } from './graphql/graphql';
import { getIdentityContext, IdentityContext } from './identity';
import { Mutation, Query } from './graphql/graphql';
const MODE = process.env.VITE_MODE || 'prod';
const isProd = MODE === 'prod';
const __dirname = import.meta.dirname;
const HOST = process.env.VITE_HOST || 'localhost';
const PORT = parseInt(process.env.VITE_PORT || '3000');
const MOTD = `\n\n\n\x1b[35m-server is listening at...-\x1b[0m\n\nhttp://${HOST}:${PORT}\nhttp://localhost:${PORT}\n\n\n`;
const key = fs.readFileSync(path.join(__dirname + '../../../certs/selfsigned.key'));
const cert = fs.readFileSync(path.join(__dirname + '../../../certs/selfsigned.crt'));
const app = express();
const server = http.createServer(app);
const server = https.createServer({ key, cert }, app);
const typeDefs = fs.readFileSync(path.join(__dirname, 'graphql', 'schema.graphql'), 'utf8');
@ -31,12 +36,12 @@ const resolvers = {
const apollo = new ApolloServer<IdentityContext>({
typeDefs,
resolvers,
introspection: !isProd,
plugins: [ApolloServerPluginDrainHttpServer({ httpServer: server })],
formatError: (formattedError, error) => {
formatError: formattedError => {
process.stdout.write('\n```\n');
console.error(`${error}`);
console.error(formattedError);
process.stdout.write('\n```\n');
return formattedError;
}
});

View file

@ -14,7 +14,7 @@ model User {
username String @unique @db.VarChar(255)
password String
refreshToken String? @db.VarChar(255)
refreshToken String? @unique @db.VarChar(255)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt