re-implemented JWT auth
This commit is contained in:
parent
c190d368de
commit
b47b0f3752
18 changed files with 390 additions and 174 deletions
74
app/server/config.ts
Normal file
74
app/server/config.ts
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
import cors from 'cors';
|
||||
import 'dotenv/config';
|
||||
|
||||
interface AppConfig {
|
||||
readonly isProd: boolean;
|
||||
readonly host: string;
|
||||
readonly port: number;
|
||||
readonly limit: { readonly limit: string };
|
||||
readonly origin: string[];
|
||||
readonly corsOptions: cors.CorsOptions;
|
||||
readonly greeting: string;
|
||||
readonly accessToken: TokenConfig;
|
||||
readonly refreshToken: RefreshTokenConfig;
|
||||
}
|
||||
|
||||
interface TokenConfig {
|
||||
readonly secret: string;
|
||||
readonly expiresIn: number;
|
||||
}
|
||||
|
||||
interface RefreshTokenConfig extends TokenConfig {
|
||||
readonly maxAge: number;
|
||||
}
|
||||
|
||||
export function toAppConfig(): AppConfig {
|
||||
const MODE = process.env.VITE_MODE || 'prod';
|
||||
const isProd = MODE === 'prod';
|
||||
|
||||
const host = process.env.VITE_HOST || 'localhost';
|
||||
const port = parseInt(process.env.VITE_PORT || '3000');
|
||||
|
||||
const urlRemote = `https://${host}:${port}`;
|
||||
const urlLocal = host !== 'localhost' ? `https://localhost:${port}` : undefined;
|
||||
|
||||
const limit = { limit: '50mb' };
|
||||
|
||||
const origin = urlLocal != null ? [urlLocal, urlRemote] : [urlRemote];
|
||||
const corsOptions: cors.CorsOptions = {
|
||||
origin,
|
||||
credentials: true
|
||||
};
|
||||
|
||||
const accessTokenExpiresIn = 24 * 60 * 60;
|
||||
const refreshTokenExpiresIn = 15 * 24 * 60 * 60;
|
||||
|
||||
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 accessToken: TokenConfig = {
|
||||
secret: accessTokenSecret,
|
||||
expiresIn: accessTokenExpiresIn
|
||||
};
|
||||
|
||||
const refreshToken: RefreshTokenConfig = {
|
||||
secret: refreshTokenSecret,
|
||||
expiresIn: refreshTokenExpiresIn,
|
||||
maxAge: refreshTokenExpiresIn * 1000
|
||||
};
|
||||
|
||||
const greeting = `\n\n\n\x1b[35m-server is listening at...-\x1b[0m\n\n${urlRemote}\n${urlLocal}\n\n\n`;
|
||||
|
||||
return {
|
||||
isProd,
|
||||
host,
|
||||
port,
|
||||
limit,
|
||||
origin,
|
||||
corsOptions,
|
||||
accessToken,
|
||||
refreshToken,
|
||||
greeting
|
||||
};
|
||||
}
|
||||
51
app/server/express/auth/refreshToken.ts
Normal file
51
app/server/express/auth/refreshToken.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import { config } from '@app/server/main';
|
||||
import { prisma } from '@app/server/prisma/client';
|
||||
import { Session } from '@generated/types';
|
||||
import 'dotenv/config';
|
||||
import { Request, Response } from 'express';
|
||||
import jwt from 'jsonwebtoken';
|
||||
|
||||
export async function refreshTokenController(req: Request, res: Response) {
|
||||
try {
|
||||
const cookie: { jwt?: string | null } = req.cookies;
|
||||
|
||||
if (cookie == null || cookie.jwt == null) {
|
||||
res.sendStatus(401);
|
||||
return;
|
||||
}
|
||||
|
||||
const refreshToken = cookie.jwt;
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { refreshToken },
|
||||
select: { id: true }
|
||||
});
|
||||
|
||||
if (user == null) {
|
||||
res.statusMessage = 'User not found.';
|
||||
res.status(401).end();
|
||||
return;
|
||||
}
|
||||
|
||||
const decoded = jwt.verify(refreshToken, config.refreshToken.secret) as {
|
||||
userId: string;
|
||||
iat: number;
|
||||
exp: number;
|
||||
};
|
||||
|
||||
if (user.id !== decoded.userId) {
|
||||
res.statusMessage = 'Invalid token.';
|
||||
res.status(401).end();
|
||||
return;
|
||||
}
|
||||
|
||||
const accessToken = jwt.sign({ userId: user.id }, config.accessToken.secret, {
|
||||
expiresIn: config.accessToken.expiresIn
|
||||
});
|
||||
|
||||
const session: Session = { accessToken };
|
||||
res.json(session);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,22 +1,24 @@
|
|||
/* gql imports */
|
||||
import { QueryResolvers } from '@generated/types';
|
||||
import { MutationResolvers, QueryResolvers } from '@generated/types';
|
||||
|
||||
/* Query */
|
||||
import { BooksManyResolver } from './resolvers/booksManyResolver';
|
||||
import { BookOneResolver } from './resolvers/bookOneResolver';
|
||||
|
||||
/* Mutation */
|
||||
import { LoginResolver } from './resolvers/auth/login';
|
||||
import { SignUpResolver } from './resolvers/auth/signUp';
|
||||
import { LoginResolver } from './resolvers/auth/login';
|
||||
import { LogoutResolver } from './resolvers/auth/logout';
|
||||
|
||||
export const Query: QueryResolvers = {
|
||||
booksMany: BooksManyResolver,
|
||||
bookOne: BookOneResolver
|
||||
};
|
||||
|
||||
export const Mutation = {
|
||||
export const Mutation: MutationResolvers = {
|
||||
signUp: SignUpResolver,
|
||||
login: LoginResolver,
|
||||
signUp: SignUpResolver
|
||||
logout: LogoutResolver
|
||||
};
|
||||
|
||||
export const Subscription = {};
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { prisma } from '@app/server/prisma/client';
|
|||
import { MutationLoginArgs, Session } from '@generated/types';
|
||||
import bcrypt from 'bcrypt';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { config } from '@app/server/main';
|
||||
|
||||
export async function LoginResolver(
|
||||
_: any,
|
||||
|
|
@ -19,16 +20,11 @@ export async function LoginResolver(
|
|||
const match = await bcrypt.compare(input.password, user.password);
|
||||
if (!match) throw new Error(error);
|
||||
|
||||
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 accessToken = jwt.sign({ userId: user.id }, accessTokenSecret, {
|
||||
expiresIn: '30s'
|
||||
const accessToken = jwt.sign({ userId: user.id }, config.accessToken.secret, {
|
||||
expiresIn: config.accessToken.expiresIn
|
||||
});
|
||||
const refreshToken = jwt.sign({ userId: user.id }, refreshTokenSecret, {
|
||||
expiresIn: '1d'
|
||||
const refreshToken = jwt.sign({ userId: user.id }, config.refreshToken.secret, {
|
||||
expiresIn: config.refreshToken.expiresIn
|
||||
});
|
||||
|
||||
await prisma.user.update({
|
||||
|
|
@ -40,17 +36,10 @@ export async function LoginResolver(
|
|||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
secure: true,
|
||||
maxAge: 24 * 60 * 60 * 1000
|
||||
maxAge: config.refreshToken.maxAge
|
||||
});
|
||||
|
||||
return {
|
||||
accessToken
|
||||
// refreshToken: {
|
||||
// token: refreshToken,
|
||||
// httpOnly: true,
|
||||
// secure: true,
|
||||
// maxAge: 24 * 60 * 60 * 1000,
|
||||
// sameSite: 'None'
|
||||
// }
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,32 @@
|
|||
import { IdentityContext } from '@app/server/identity';
|
||||
import { prisma } from '@app/server/prisma/client';
|
||||
|
||||
export async function LogoutResolver(
|
||||
_: any,
|
||||
__: any,
|
||||
{ req, res, identity }: IdentityContext
|
||||
): Promise<void> {
|
||||
const cookie: { jwt?: string | null } = req.cookies;
|
||||
if (cookie == null || cookie.jwt == null) return;
|
||||
|
||||
const refreshToken = cookie.jwt;
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { refreshToken },
|
||||
select: { id: true }
|
||||
});
|
||||
|
||||
if (user == null) {
|
||||
res.clearCookie('jwt', { httpOnly: true });
|
||||
return;
|
||||
}
|
||||
|
||||
await prisma.user.update({
|
||||
where: {
|
||||
id: user.id
|
||||
},
|
||||
data: { refreshToken: null }
|
||||
});
|
||||
|
||||
res.clearCookie('jwt', { httpOnly: true });
|
||||
}
|
||||
|
|
@ -1,36 +0,0 @@
|
|||
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 };
|
||||
}
|
||||
|
|
@ -6,7 +6,7 @@ import bcrypt from 'bcrypt';
|
|||
export async function SignUpResolver(
|
||||
_: any,
|
||||
{ input }: MutationSignUpArgs,
|
||||
{ identity }: IdentityContext
|
||||
{ req, res, identity }: IdentityContext
|
||||
): Promise<void> {
|
||||
const existingUsername = await prisma.user.findUnique({
|
||||
where: { username: input.username },
|
||||
|
|
|
|||
|
|
@ -17,8 +17,9 @@ export const books = [
|
|||
export async function BooksManyResolver(
|
||||
_: any,
|
||||
__: any,
|
||||
{ identity }: IdentityContext
|
||||
{ req, res, identity }: IdentityContext
|
||||
): Promise<Book[]> {
|
||||
if (identity == null) throw new Error('Unauthorized');
|
||||
|
||||
return books;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,13 +6,9 @@ type Query {
|
|||
}
|
||||
|
||||
type Mutation {
|
||||
login(input: LoginInput!): Session!
|
||||
signUp(input: SignUpInput!): Void
|
||||
}
|
||||
|
||||
input LoginInput {
|
||||
email: String!
|
||||
password: String!
|
||||
login(input: LoginInput!): Session!
|
||||
logout: Void
|
||||
}
|
||||
|
||||
input SignUpInput {
|
||||
|
|
@ -21,16 +17,13 @@ input SignUpInput {
|
|||
password: String!
|
||||
}
|
||||
|
||||
type Session {
|
||||
accessToken: String!
|
||||
input LoginInput {
|
||||
email: String!
|
||||
password: String!
|
||||
}
|
||||
|
||||
type RefreshToken {
|
||||
token: String!
|
||||
maxAge: Int!
|
||||
secure: Boolean!
|
||||
httpOnly: Boolean!
|
||||
sameSite: String!
|
||||
type Session {
|
||||
accessToken: String!
|
||||
}
|
||||
|
||||
type Book {
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
import { Session } from '@generated/types';
|
||||
import 'dotenv/config';
|
||||
import { Request, Response } from 'express';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { config } from './main';
|
||||
import { prisma } from './prisma/client';
|
||||
import { Session } from '@generated/types';
|
||||
import { GraphQLError } from 'graphql';
|
||||
|
||||
export interface IdentityContext {
|
||||
req: Request;
|
||||
|
|
@ -20,38 +22,42 @@ export async function getIdentityContext({
|
|||
req: Request;
|
||||
res: Response;
|
||||
}): Promise<IdentityContext> {
|
||||
const authHeaders = req.headers.authorization;
|
||||
if (authHeaders == null) return { req, res };
|
||||
try {
|
||||
const authHeaders = req.headers.authorization;
|
||||
if (authHeaders == null) return { req, res };
|
||||
|
||||
const session: Session = JSON.parse(authHeaders);
|
||||
const { accessToken } = session;
|
||||
const session: Session = JSON.parse(authHeaders);
|
||||
const { accessToken } = session;
|
||||
|
||||
const accessTokenSecret = process.env.ACCESS_TOKEN_SECRET;
|
||||
if (accessTokenSecret == null) throw new Error('No `accessToken`.');
|
||||
const decoded = jwt.verify(accessToken, config.accessToken.secret) as {
|
||||
userId: string;
|
||||
iat: number;
|
||||
exp: number;
|
||||
};
|
||||
|
||||
const decoded = jwt.verify(accessToken, accessTokenSecret) as {
|
||||
userId: string;
|
||||
iat: number;
|
||||
exp: number;
|
||||
};
|
||||
|
||||
const identity = await prisma.user.findUnique({
|
||||
where: { id: decoded.userId },
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
username: true
|
||||
}
|
||||
});
|
||||
if (identity == null) throw new Error("Couldn't find the user.");
|
||||
return { req, res, identity };
|
||||
}
|
||||
|
||||
/* throw new GraphQLError('User is not authenticated', {
|
||||
const identity = await prisma.user.findUnique({
|
||||
where: { id: decoded.userId },
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
username: true
|
||||
}
|
||||
});
|
||||
if (identity == null) throw new Error("Couldn't find the user.");
|
||||
return { req, res, identity };
|
||||
} catch (error) {
|
||||
if (error instanceof Error)
|
||||
throw new GraphQLError(error.message, {
|
||||
extensions: {
|
||||
code: 'UNAUTHENTICATED',
|
||||
http: { status: 401 }
|
||||
}
|
||||
});
|
||||
throw new GraphQLError(typeof error === 'string' ? error : 'Unknown error', {
|
||||
extensions: {
|
||||
code: 'UNAUTHENTICATED',
|
||||
http: { status: 401 }
|
||||
}
|
||||
}); */
|
||||
|
||||
// throw new GraphQLError(`${error}`);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { ApolloServer } from '@apollo/server';
|
||||
import { expressMiddleware } from '@apollo/server/express4';
|
||||
import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';
|
||||
import cookies from 'cookie-parser';
|
||||
import cors from 'cors';
|
||||
import 'dotenv/config';
|
||||
import express from 'express';
|
||||
|
|
@ -8,17 +9,14 @@ import fs from 'fs';
|
|||
import https from 'https';
|
||||
import path from 'path';
|
||||
import ViteExpress from 'vite-express';
|
||||
import { toAppConfig } from './config';
|
||||
import { refreshTokenController } from './express/auth/refreshToken';
|
||||
import { Mutation, Query } from './graphql/graphql';
|
||||
import { getIdentityContext, IdentityContext } from './identity';
|
||||
|
||||
const MODE = process.env.VITE_MODE || 'prod';
|
||||
const isProd = MODE === 'prod';
|
||||
export const config = toAppConfig();
|
||||
|
||||
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'));
|
||||
|
||||
|
|
@ -36,7 +34,7 @@ const resolvers = {
|
|||
const apollo = new ApolloServer<IdentityContext>({
|
||||
typeDefs,
|
||||
resolvers,
|
||||
introspection: !isProd,
|
||||
introspection: !config.isProd,
|
||||
plugins: [ApolloServerPluginDrainHttpServer({ httpServer: server })],
|
||||
formatError: formattedError => {
|
||||
process.stdout.write('\n```\n');
|
||||
|
|
@ -48,17 +46,21 @@ const apollo = new ApolloServer<IdentityContext>({
|
|||
|
||||
await apollo.start();
|
||||
|
||||
app.use(cors<cors.CorsRequest>(config.corsOptions));
|
||||
app.use(express.json(config.limit));
|
||||
app.use(cookies());
|
||||
app.get('/api/refreshAccessToken', refreshTokenController);
|
||||
app.use(
|
||||
'/graphql',
|
||||
cors<cors.CorsRequest>(),
|
||||
express.json(),
|
||||
expressMiddleware(apollo, {
|
||||
context: getIdentityContext
|
||||
})
|
||||
);
|
||||
|
||||
await new Promise<void>(resolve => server.listen({ hostname: HOST, port: PORT }, resolve));
|
||||
await new Promise<void>(resolve =>
|
||||
server.listen({ hostname: config.host, port: config.port }, resolve)
|
||||
);
|
||||
|
||||
process.stdout.write(MOTD);
|
||||
process.stdout.write(config.greeting);
|
||||
|
||||
ViteExpress.bind(app, server);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue