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

@ -3,12 +3,13 @@ import { gql } from '@apollo/client';
export const sessionFragment = gql`
fragment Session on Session {
accessToken
refreshToken {
token
maxAge
secure
httpOnly
sameSite
}
}
`;
// refreshToken {
// token
// maxAge
// secure
// httpOnly
// sameSite
// }

View file

@ -1,3 +1,3 @@
interface UseIdentityProps {}
// interface UseIdentityProps {}
export function useIdentity(props: UseIdentityProps) {}
// export function useIdentity(props: UseIdentityProps) {}

View file

@ -1,4 +1,5 @@
import { ApolloClient, ApolloProvider, InMemoryCache } from '@apollo/client';
import { ApolloClient, ApolloProvider, HttpLink, InMemoryCache, from } from '@apollo/client';
import { onError } from '@apollo/client/link/error';
import '@client/assets/styles/index.css';
import '@client/assets/styles/nerd-fonts-icons.css';
import { Provider } from '@client/components/ui/provider';
@ -8,8 +9,8 @@ import { StrictMode, createContext, useState } from 'react';
import ReactDOM from 'react-dom/client';
// TanStackRouter - Import the generated route tree
import { routeTree } from './routeTree.gen';
import { Session } from 'inspector';
import { routeTree } from './routeTree.gen';
// Create a new router instance
const router = createRouter({ routeTree });
@ -22,25 +23,43 @@ declare module '@tanstack/react-router' {
}
// Environment
const MODE = import.meta.env.VITE_MODE || 'prod';
const isProd = MODE === 'prod';
const HOST = import.meta.env.VITE_HOST || 'localhost';
const PORT = import.meta.env.VITE_PORT || '3000';
const uri = `http://${HOST}:${PORT}/graphql`;
const uri = `https://${HOST}:${PORT}/graphql`;
// Auth context
export const AuthContext = createContext<any>(null);
function App() {
const sessionRaw = localStorage.getItem('session');
const session: Session | null = sessionRaw !== null ? JSON.parse(sessionRaw) : null;
const [authHeaders, setAuthHeaders] = useState<Session | null>(session);
const [authHeaders, setAuthHeaders] = useState<Session | null>(null);
const AuthProvider = AuthContext.Provider;
// if (authHeaders == null) refreshToken();
const httpLink = new HttpLink({
uri,
credentials: 'include',
headers: authHeaders != null ? { authorization: JSON.stringify(authHeaders) } : undefined
});
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.forEach(({ message, locations, path }) =>
console.error(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`)
);
if (networkError) console.error(`[Network error]: ${networkError}`);
});
const client = new ApolloClient({
uri,
link: isProd ? undefined : from([errorLink, httpLink]),
cache: new InMemoryCache(),
connectToDevTools: true,
headers: authHeaders != null ? { authorization: JSON.stringify(authHeaders) } : undefined
connectToDevTools: !isProd,
credentials: 'include'
});
return (
@ -49,7 +68,6 @@ function App() {
value={{
authHeaders,
setHeaders: (session: Session) => {
localStorage.setItem('session', JSON.stringify(session));
setAuthHeaders(session);
}
}}

View file

@ -109,7 +109,7 @@ function SignUpForm() {
}
const mutation = gql`
mutation AuthSignUp($input: RegisterInput!) {
mutation AuthSignUp($input: SignUpInput!) {
signUp(input: $input)
}
`;

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