diff --git a/apps/api/src/controllers/auth.ts b/apps/api/src/controllers/auth.ts index dffec2a84..f98b646c7 100644 --- a/apps/api/src/controllers/auth.ts +++ b/apps/api/src/controllers/auth.ts @@ -2,17 +2,16 @@ import axios from "axios"; import bcrypt from "bcrypt"; import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"; import jwt from "jsonwebtoken"; +import { LRUCache } from "lru-cache"; +import { generators } from "openid-client"; +import { AuthorizationCode } from "simple-oauth2"; +import { getOAuthProvider, getOidcConfig } from "../lib/auth"; import { track } from "../lib/hog"; -import { checkToken } from "../lib/jwt"; import { forgotPassword } from "../lib/nodemailer/auth/forgot-password"; import { checkSession } from "../lib/session"; -import { prisma } from "../prisma"; -import { getOidcConfig, getOAuthProvider } from "../lib/auth"; -import { getOidcClient } from "../lib/utils/oidc_client"; import { getOAuthClient } from "../lib/utils/oauth_client"; -import { AuthorizationCode } from "simple-oauth2"; -import { generators } from "openid-client"; -import { LRUCache } from "lru-cache"; +import { getOidcClient } from "../lib/utils/oidc_client"; +import { prisma } from "../prisma"; const options = { max: 500, // Maximum number of items in cache @@ -75,8 +74,6 @@ export function authRoutes(fastify: FastifyInstance) { }, }, async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - let { email, password, admin, name } = request.body as { email: string; password: string; @@ -84,50 +81,45 @@ export function authRoutes(fastify: FastifyInstance) { name: string; }; - if (bearer) { - const token = checkToken(bearer); - if (token) { - const requester = await checkSession(bearer); + const requester = await checkSession(request); - if (!requester?.isAdmin) { - return reply.code(401).send({ - message: "Unauthorized", - }); - } + if (!requester?.isAdmin) { + return reply.code(401).send({ + message: "Unauthorized", + }); + } - // Checks if email already exists - let record = await prisma.user.findUnique({ - where: { email }, - }); + // Checks if email already exists + let record = await prisma.user.findUnique({ + where: { email }, + }); - // if exists, return 400 - if (record) { - return reply.code(400).send({ - message: "Email already exists", - }); - } + // if exists, return 400 + if (record) { + return reply.code(400).send({ + message: "Email already exists", + }); + } - const user = await prisma.user.create({ - data: { - email, - password: await bcrypt.hash(password, 10), - name, - isAdmin: admin, - }, - }); + const user = await prisma.user.create({ + data: { + email, + password: await bcrypt.hash(password, 10), + name, + isAdmin: admin, + }, + }); - const hog = track(); + const hog = track(); - hog.capture({ - event: "user_registered", - distinctId: user.id, - }); + hog.capture({ + event: "user_registered", + distinctId: user.id, + }); - reply.send({ - success: true, - }); - } - } + reply.send({ + success: true, + }); } ); @@ -149,8 +141,6 @@ export function authRoutes(fastify: FastifyInstance) { }, }, async (request: FastifyRequest, reply: FastifyReply) => { - // const bearer = request.headers.authorization!.split(" ")[1]; - let { email, password, name, language } = request.body as { email: string; password: string; @@ -694,28 +684,21 @@ export function authRoutes(fastify: FastifyInstance) { } ); - // saml api callback route - // Delete a user fastify.delete( "/api/v1/auth/user/:id", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); + const { id } = request.params as { id: string }; - if (token) { - const { id } = request.params as { id: string }; + await prisma.notes.deleteMany({ where: { userId: id } }); + await prisma.session.deleteMany({ where: { userId: id } }); + await prisma.notifications.deleteMany({ where: { userId: id } }); - await prisma.notes.deleteMany({ where: { userId: id } }); - await prisma.session.deleteMany({ where: { userId: id } }); - await prisma.notifications.deleteMany({ where: { userId: id } }); - - await prisma.user.delete({ - where: { id }, - }); + await prisma.user.delete({ + where: { id }, + }); - reply.send({ success: true }); - } + reply.send({ success: true }); } ); @@ -723,60 +706,52 @@ export function authRoutes(fastify: FastifyInstance) { fastify.get( "/api/v1/auth/profile", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - - const token = checkToken(bearer); + let session = await prisma.session.findUnique({ + where: { + sessionToken: request.headers.authorization!.split(" ")[1], + }, + }); - if (token) { - let session = await prisma.session.findUnique({ - where: { - sessionToken: request.headers.authorization!.split(" ")[1], - }, - }); + let user = await prisma.user.findUnique({ + where: { id: session!.userId }, + }); - let user = await prisma.user.findUnique({ - where: { id: session!.userId }, + if (!user) { + return reply.code(401).send({ + message: "Invalid user", }); + } - if (!user) { - return reply.code(401).send({ - message: "Invalid user", - }); - } + const config = await prisma.config.findFirst(); - const config = await prisma.config.findFirst(); + const notifcations = await prisma.notifications.findMany({ + where: { userId: user!.id }, + orderBy: { + createdAt: "desc", + }, + }); - const notifcations = await prisma.notifications.findMany({ - where: { userId: user!.id }, - orderBy: { - createdAt: "desc", - }, - }); + const data = { + id: user!.id, + email: user!.email, + name: user!.name, + isAdmin: user!.isAdmin, + language: user!.language, + ticket_created: user!.notify_ticket_created, + ticket_status_changed: user!.notify_ticket_status_changed, + ticket_comments: user!.notify_ticket_comments, + ticket_assigned: user!.notify_ticket_assigned, + sso_status: config!.sso_active, + version: config!.client_version, + notifcations, + external_user: user!.external_user, + }; - const data = { - id: user!.id, - email: user!.email, - name: user!.name, - isAdmin: user!.isAdmin, - language: user!.language, - ticket_created: user!.notify_ticket_created, - ticket_status_changed: user!.notify_ticket_status_changed, - ticket_comments: user!.notify_ticket_comments, - ticket_assigned: user!.notify_ticket_assigned, - sso_status: config!.sso_active, - version: config!.client_version, - notifcations, - external_user: user!.external_user, - }; - - await tracking("user_profile", {}); + await tracking("user_profile", {}); - reply.send({ - user: data, - }); - } else { - throw new Error("Invalid token"); - } + reply.send({ + user: data, + }); } ); @@ -789,32 +764,25 @@ export function authRoutes(fastify: FastifyInstance) { }; const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); - if (token) { - let session = await prisma.session.findUnique({ - where: { - sessionToken: bearer, - }, - }); + let session = await prisma.session.findUnique({ + where: { + sessionToken: bearer, + }, + }); - const hashedPass = await bcrypt.hash(password, 10); + const hashedPass = await bcrypt.hash(password, 10); - await prisma.user.update({ - where: { id: session?.userId }, - data: { - password: hashedPass, - }, - }); + await prisma.user.update({ + where: { id: session?.userId }, + data: { + password: hashedPass, + }, + }); - reply.send({ - success: true, - }); - } else { - reply.send({ - success: false, - }); - } + reply.send({ + success: true, + }); } ); @@ -827,45 +795,35 @@ export function authRoutes(fastify: FastifyInstance) { user: string; }; - console.log(user); - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); + let session = await prisma.session.findUnique({ + where: { + sessionToken: bearer, + }, + }); - if (token) { - let session = await prisma.session.findUnique({ - where: { - sessionToken: bearer, - }, - }); + const check = await prisma.user.findUnique({ + where: { id: session?.userId }, + }); - const check = await prisma.user.findUnique({ - where: { id: session?.userId }, + if (check?.isAdmin === false) { + return reply.code(401).send({ + message: "Unauthorized", }); + } - if (check?.isAdmin === false) { - return reply.code(401).send({ - message: "Unauthorized", - }); - } - - const hashedPass = await bcrypt.hash(password, 10); + const hashedPass = await bcrypt.hash(password, 10); - await prisma.user.update({ - where: { id: user }, - data: { - password: hashedPass, - }, - }); + await prisma.user.update({ + where: { id: user }, + data: { + password: hashedPass, + }, + }); - reply.send({ - success: true, - }); - } else { - reply.send({ - success: false, - }); - } + reply.send({ + success: true, + }); } ); @@ -875,39 +833,30 @@ export function authRoutes(fastify: FastifyInstance) { async (request: FastifyRequest, reply: FastifyReply) => { const bearer = request.headers.authorization!.split(" ")[1]; - //checks if token is valid and returns valid token - const token = checkToken(bearer); - - if (token) { - let session = await prisma.session.findUnique({ - where: { - sessionToken: bearer, - }, - }); + let session = await prisma.session.findUnique({ + where: { + sessionToken: bearer, + }, + }); - const { name, email, language } = request.body as { - name: string; - email: string; - language: string; - }; + const { name, email, language } = request.body as { + name: string; + email: string; + language: string; + }; - let user = await prisma.user.update({ - where: { id: session?.userId }, - data: { - name: name, - email: email, - language: language, - }, - }); + let user = await prisma.user.update({ + where: { id: session?.userId }, + data: { + name: name, + email: email, + language: language, + }, + }); - reply.send({ - user, - }); - } else { - reply.send({ - sucess: false, - }); - } + reply.send({ + user, + }); } ); @@ -916,42 +865,32 @@ export function authRoutes(fastify: FastifyInstance) { "/api/v1/auth/profile/notifcations/emails", async (request: FastifyRequest, reply: FastifyReply) => { const bearer = request.headers.authorization!.split(" ")[1]; + let session = await prisma.session.findUnique({ + where: { + sessionToken: bearer, + }, + }); - //checks if token is valid and returns valid token - const token = checkToken(bearer); - - if (token) { - let session = await prisma.session.findUnique({ - where: { - sessionToken: bearer, - }, - }); - - const { - notify_ticket_created, - notify_ticket_assigned, - notify_ticket_comments, - notify_ticket_status_changed, - } = request.body as any; + const { + notify_ticket_created, + notify_ticket_assigned, + notify_ticket_comments, + notify_ticket_status_changed, + } = request.body as any; - let user = await prisma.user.update({ - where: { id: session?.userId }, - data: { - notify_ticket_created: notify_ticket_created, - notify_ticket_assigned: notify_ticket_assigned, - notify_ticket_comments: notify_ticket_comments, - notify_ticket_status_changed: notify_ticket_status_changed, - }, - }); + let user = await prisma.user.update({ + where: { id: session?.userId }, + data: { + notify_ticket_created: notify_ticket_created, + notify_ticket_assigned: notify_ticket_assigned, + notify_ticket_comments: notify_ticket_comments, + notify_ticket_status_changed: notify_ticket_status_changed, + }, + }); - reply.send({ - user, - }); - } else { - reply.send({ - sucess: false, - }); - } + reply.send({ + user, + }); } ); @@ -959,17 +898,13 @@ export function authRoutes(fastify: FastifyInstance) { fastify.get( "/api/v1/auth/user/:id/logout", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); - if (token) { - const { id } = request.params as { id: string }; + const { id } = request.params as { id: string }; - await prisma.session.deleteMany({ - where: { userId: id }, - }); + await prisma.session.deleteMany({ + where: { userId: id }, + }); - reply.send({ success: true }); - } + reply.send({ success: true }); } ); @@ -977,32 +912,28 @@ export function authRoutes(fastify: FastifyInstance) { fastify.put( "/api/v1/auth/user/role", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); - if (token) { - const { id, role } = request.body as { id: string; role: boolean }; - // check for atleast one admin on role downgrade - if (role === false) { - const admins = await prisma.user.findMany({ - where: { isAdmin: true }, + const { id, role } = request.body as { id: string; role: boolean }; + // check for atleast one admin on role downgrade + if (role === false) { + const admins = await prisma.user.findMany({ + where: { isAdmin: true }, + }); + if (admins.length === 1) { + reply.code(400).send({ + message: "Atleast one admin is required", + success: false, }); - if (admins.length === 1) { - reply.code(400).send({ - message: "Atleast one admin is required", - success: false, - }); - return; - } + return; } - await prisma.user.update({ - where: { id }, - data: { - isAdmin: role, - }, - }); - - reply.send({ success: true }); } + await prisma.user.update({ + where: { id }, + data: { + isAdmin: role, + }, + }); + + reply.send({ success: true }); } ); @@ -1010,22 +941,18 @@ export function authRoutes(fastify: FastifyInstance) { fastify.post( "/api/v1/auth/user/:id/first-login", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); - if (token) { - const { id } = request.params as { id: string }; + const { id } = request.params as { id: string }; - await prisma.user.update({ - where: { id }, - data: { - firstLogin: false, - }, - }); + await prisma.user.update({ + where: { id }, + data: { + firstLogin: false, + }, + }); - await tracking("user_first_login", {}); + await tracking("user_first_login", {}); - reply.send({ success: true }); - } + reply.send({ success: true }); } ); } diff --git a/apps/api/src/controllers/clients.ts b/apps/api/src/controllers/clients.ts index d2c92adc5..393312be6 100644 --- a/apps/api/src/controllers/clients.ts +++ b/apps/api/src/controllers/clients.ts @@ -1,6 +1,5 @@ import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"; import { track } from "../lib/hog"; -import { checkToken } from "../lib/jwt"; import { prisma } from "../prisma"; export function clientRoutes(fastify: FastifyInstance) { @@ -9,32 +8,27 @@ export function clientRoutes(fastify: FastifyInstance) { "/api/v1/client/create", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); - - if (token) { - const { name, email, number, contactName }: any = request.body; - - const client = await prisma.client.create({ - data: { - name, - contactName, - email, - number: String(number), - }, - }); - - const hog = track(); - - hog.capture({ - event: "client_created", - distinctId: client.id, - }); - - reply.send({ - success: true, - }); - } + const { name, email, number, contactName }: any = request.body; + + const client = await prisma.client.create({ + data: { + name, + contactName, + email, + number: String(number), + }, + }); + + const hog = track(); + + hog.capture({ + event: "client_created", + distinctId: client.id, + }); + + reply.send({ + success: true, + }); } ); @@ -43,26 +37,21 @@ export function clientRoutes(fastify: FastifyInstance) { "/api/v1/client/update", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); - - if (token) { - const { name, email, number, contactName, id }: any = request.body; - - await prisma.client.update({ - where: { id: id }, - data: { - name, - contactName, - email, - number: String(number), - }, - }); - - reply.send({ - success: true, - }); - } + const { name, email, number, contactName, id }: any = request.body; + + await prisma.client.update({ + where: { id: id }, + data: { + name, + contactName, + email, + number: String(number), + }, + }); + + reply.send({ + success: true, + }); } ); @@ -71,17 +60,12 @@ export function clientRoutes(fastify: FastifyInstance) { "/api/v1/clients/all", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); + const clients = await prisma.client.findMany({}); - if (token) { - const clients = await prisma.client.findMany({}); - - reply.send({ - success: true, - clients: clients, - }); - } + reply.send({ + success: true, + clients: clients, + }); } ); @@ -90,20 +74,15 @@ export function clientRoutes(fastify: FastifyInstance) { "/api/v1/clients/:id/delete-client", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); - - if (token) { - const { id }: any = request.params; + const { id }: any = request.params; - await prisma.client.delete({ - where: { id: id }, - }); + await prisma.client.delete({ + where: { id: id }, + }); - reply.send({ - success: true, - }); - } + reply.send({ + success: true, + }); } ); } diff --git a/apps/api/src/controllers/config.ts b/apps/api/src/controllers/config.ts index 375e32858..80f8fb7ad 100644 --- a/apps/api/src/controllers/config.ts +++ b/apps/api/src/controllers/config.ts @@ -4,14 +4,13 @@ // SSO Provider // Portal Locale // Feature Flags -import { OAuth2Client } from "google-auth-library"; import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"; +import { OAuth2Client } from "google-auth-library"; const nodemailer = require("nodemailer"); -import { checkToken } from "../lib/jwt"; -import { prisma } from "../prisma"; -import { createTransportProvider } from "../lib/nodemailer/transport"; import { track } from "../lib/hog"; +import { createTransportProvider } from "../lib/nodemailer/transport"; +import { prisma } from "../prisma"; async function tracking(event: string, properties: any) { const client = track(); @@ -29,28 +28,23 @@ export function configRoutes(fastify: FastifyInstance) { "/api/v1/config/authentication/check", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); + const config = await prisma.config.findFirst(); - if (token) { - const config = await prisma.config.findFirst(); - - //@ts-expect-error - const { sso_active, sso_provider } = config; - - if (sso_active) { - reply.send({ - success: true, - sso: sso_active, - provider: sso_provider, - }); - } + //@ts-expect-error + const { sso_active, sso_provider } = config; + if (sso_active) { reply.send({ success: true, sso: sso_active, + provider: sso_provider, }); } + + reply.send({ + success: true, + sso: sso_active, + }); } ); @@ -59,51 +53,46 @@ export function configRoutes(fastify: FastifyInstance) { "/api/v1/config/authentication/oidc/update", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); + const { clientId, clientSecret, redirectUri, issuer, jwtSecret }: any = + request.body; + + const conf = await prisma.config.findFirst(); - if (token) { - const { clientId, clientSecret, redirectUri, issuer, jwtSecret }: any = - request.body; + await prisma.config.update({ + where: { id: conf!.id }, + data: { + sso_active: true, + sso_provider: "oidc", + }, + }); - const conf = await prisma.config.findFirst(); + const existingProvider = await prisma.openIdConfig.findFirst(); - await prisma.config.update({ - where: { id: conf!.id }, + if (existingProvider === null) { + await prisma.openIdConfig.create({ data: { - sso_active: true, - sso_provider: "oidc", + clientId: clientId, + redirectUri: redirectUri, + issuer: issuer, }, }); - - const existingProvider = await prisma.openIdConfig.findFirst(); - - if (existingProvider === null) { - await prisma.openIdConfig.create({ - data: { - clientId: clientId, - redirectUri: redirectUri, - issuer: issuer, - }, - }); - } else { - await prisma.openIdConfig.update({ - where: { id: existingProvider.id }, - data: { - clientId: clientId, - redirectUri: redirectUri, - issuer: issuer, - }, - }); - } - - await tracking("oidc_provider_updated", {}); - - reply.send({ - success: true, - message: "OIDC config Provider updated!", + } else { + await prisma.openIdConfig.update({ + where: { id: existingProvider.id }, + data: { + clientId: clientId, + redirectUri: redirectUri, + issuer: issuer, + }, }); } + + await tracking("oidc_provider_updated", {}); + + reply.send({ + success: true, + message: "OIDC config Provider updated!", + }); } ); @@ -112,65 +101,60 @@ export function configRoutes(fastify: FastifyInstance) { "/api/v1/config/authentication/oauth/update", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); - - if (token) { - const { - name, - clientId, - clientSecret, - redirectUri, - tenantId, - issuer, - jwtSecret, - }: any = request.body; - - const conf = await prisma.config.findFirst(); - - // Update config to true - await prisma.config.update({ - where: { id: conf!.id }, + const { + name, + clientId, + clientSecret, + redirectUri, + tenantId, + issuer, + jwtSecret, + }: any = request.body; + + const conf = await prisma.config.findFirst(); + + // Update config to true + await prisma.config.update({ + where: { id: conf!.id }, + data: { + sso_active: true, + sso_provider: "oauth", + }, + }); + + // Check if the provider exists + const existingProvider = await prisma.oAuthProvider.findFirst(); + + if (existingProvider === null) { + await prisma.oAuthProvider.create({ data: { - sso_active: true, - sso_provider: "oauth", + name: name, + clientId: clientId, + clientSecret: clientSecret, + redirectUri: redirectUri, + scope: "", // Add appropriate scope if needed + authorizationUrl: "", // Add appropriate URL if needed + tokenUrl: "", // Add appropriate URL if needed + userInfoUrl: "", // Add appropriate URL if needed }, }); - - // Check if the provider exists - const existingProvider = await prisma.oAuthProvider.findFirst(); - - if (existingProvider === null) { - await prisma.oAuthProvider.create({ - data: { - name: name, - clientId: clientId, - clientSecret: clientSecret, - redirectUri: redirectUri, - scope: "", // Add appropriate scope if needed - authorizationUrl: "", // Add appropriate URL if needed - tokenUrl: "", // Add appropriate URL if needed - userInfoUrl: "", // Add appropriate URL if needed - }, - }); - } else { - await prisma.oAuthProvider.update({ - where: { id: existingProvider.id }, - data: { - clientId: clientId, - clientSecret: clientSecret, - redirectUri: redirectUri, - }, - }); - } - - await tracking("oauth_provider_updated", {}); - - reply.send({ - success: true, - message: "SSO Provider updated!", + } else { + await prisma.oAuthProvider.update({ + where: { id: existingProvider.id }, + data: { + clientId: clientId, + clientSecret: clientSecret, + redirectUri: redirectUri, + }, }); } + + await tracking("oauth_provider_updated", {}); + + reply.send({ + success: true, + message: "SSO Provider updated!", + }); } ); @@ -179,31 +163,26 @@ export function configRoutes(fastify: FastifyInstance) { "/api/v1/config/authentication", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); - - if (token) { - const conf = await prisma.config.findFirst(); - - // Update config to false - await prisma.config.update({ - where: { id: conf!.id }, - data: { - sso_active: false, - sso_provider: "", - }, - }); - - // Delete the OAuth provider - await prisma.oAuthProvider.deleteMany({}); - - await tracking("sso_provider_deleted", {}); - - reply.send({ - success: true, - message: "SSO Provider deleted!", - }); - } + const conf = await prisma.config.findFirst(); + + // Update config to false + await prisma.config.update({ + where: { id: conf!.id }, + data: { + sso_active: false, + sso_provider: "", + }, + }); + + // Delete the OAuth provider + await prisma.oAuthProvider.deleteMany({}); + + await tracking("sso_provider_deleted", {}); + + reply.send({ + success: true, + message: "SSO Provider deleted!", + }); } ); @@ -213,51 +192,42 @@ export function configRoutes(fastify: FastifyInstance) { async (request: FastifyRequest, reply: FastifyReply) => { const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); - - if (token) { - // GET EMAIL SETTINGS - const config = await prisma.email.findFirst({ - select: { - active: true, - host: true, - port: true, - reply: true, - user: true, - }, - }); - - if (config && config?.active) { - const provider = await createTransportProvider(); - - await new Promise((resolve, reject) => { - provider.verify(function (error: any, success: any) { - if (error) { - console.log("ERROR", error); - reply.send({ - success: true, - active: true, - email: config, - verification: error, - }); - } else { - console.log("SUCCESS", success); - console.log("Server is ready to take our messages"); - reply.send({ - success: true, - active: true, - email: config, - verification: success, - }); - } - }); - }); - } else { - reply.send({ - success: true, - active: false, + // GET EMAIL SETTINGS + const config = await prisma.email.findFirst({ + select: { + active: true, + host: true, + port: true, + reply: true, + user: true, + }, + }); + + if (config && config?.active) { + const provider = await createTransportProvider(); + + await new Promise((resolve, reject) => { + provider.verify(function (error: any, success: any) { + if (error) { + console.log("ERROR", error); + reply.send({ + success: true, + active: true, + email: config, + verification: error, + }); + } else { + console.log("SUCCESS", success); + console.log("Server is ready to take our messages"); + reply.send({ + success: true, + active: true, + email: config, + verification: success, + }); + } }); - } + }); } } ); @@ -267,86 +237,81 @@ export function configRoutes(fastify: FastifyInstance) { "/api/v1/config/email", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); - - if (token) { - const { - host, - active, - port, - reply: replyto, - username, - password, - serviceType, - clientId, - clientSecret, - redirectUri, - }: any = request.body; + const { + host, + active, + port, + reply: replyto, + username, + password, + serviceType, + clientId, + clientSecret, + redirectUri, + }: any = request.body; + + const email = await prisma.email.findFirst(); + + if (email === null) { + await prisma.email.create({ + data: { + host: host, + port: port, + reply: replyto, + user: username, + pass: password, + active: true, + clientId: clientId, + clientSecret: clientSecret, + serviceType: serviceType, + redirectUri: redirectUri, + }, + }); + } else { + await prisma.email.update({ + where: { id: email.id }, + data: { + host: host, + port: port, + reply: replyto, + user: username, + pass: password, + active: active, + clientId: clientId, + clientSecret: clientSecret, + serviceType: serviceType, + redirectUri: redirectUri, + }, + }); + } + if (serviceType === "gmail") { const email = await prisma.email.findFirst(); - if (email === null) { - await prisma.email.create({ - data: { - host: host, - port: port, - reply: replyto, - user: username, - pass: password, - active: true, - clientId: clientId, - clientSecret: clientSecret, - serviceType: serviceType, - redirectUri: redirectUri, - }, - }); - } else { - await prisma.email.update({ - where: { id: email.id }, - data: { - host: host, - port: port, - reply: replyto, - user: username, - pass: password, - active: active, - clientId: clientId, - clientSecret: clientSecret, - serviceType: serviceType, - redirectUri: redirectUri, - }, - }); - } - - if (serviceType === "gmail") { - const email = await prisma.email.findFirst(); - - const google = new OAuth2Client( - //@ts-expect-error - email?.clientId, - email?.clientSecret, - email?.redirectUri - ); - - const authorizeUrl = google.generateAuthUrl({ - access_type: "offline", - scope: "https://mail.google.com", - prompt: "consent", - }); + const google = new OAuth2Client( + //@ts-expect-error + email?.clientId, + email?.clientSecret, + email?.redirectUri + ); - reply.send({ - success: true, - message: "SSO Provider updated!", - authorizeUrl: authorizeUrl, - }); - } + const authorizeUrl = google.generateAuthUrl({ + access_type: "offline", + scope: "https://mail.google.com", + prompt: "consent", + }); reply.send({ success: true, message: "SSO Provider updated!", + authorizeUrl: authorizeUrl, }); } + + reply.send({ + success: true, + message: "SSO Provider updated!", + }); } ); @@ -355,54 +320,49 @@ export function configRoutes(fastify: FastifyInstance) { "/api/v1/config/email/oauth/gmail", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); - - if (token) { - const { code }: any = request.query; - - const email = await prisma.email.findFirst(); - - const google = new OAuth2Client( - //@ts-expect-error - email?.clientId, - email?.clientSecret, - email?.redirectUri - ); - - const r = await google.getToken(code); - - await prisma.email.update({ - where: { id: email?.id }, - data: { - refreshToken: r.tokens.refresh_token, - accessToken: r.tokens.access_token, - expiresIn: r.tokens.expiry_date, - serviceType: "gmail", - }, - }); + const { code }: any = request.query; - const provider = nodemailer.createTransport({ - service: "gmail", - host: "smtp.gmail.com", - port: 465, - secure: true, - auth: { - type: "OAuth2", - user: email?.user, - clientId: email?.clientId, - clientSecret: email?.clientSecret, - refreshToken: r.tokens.refresh_token, - accessToken: r.tokens.access_token, - expiresIn: r.tokens.expiry_date, - }, - }); + const email = await prisma.email.findFirst(); - reply.send({ - success: true, - message: "SSO Provider updated!", - }); - } + const google = new OAuth2Client( + //@ts-expect-error + email?.clientId, + email?.clientSecret, + email?.redirectUri + ); + + const r = await google.getToken(code); + + await prisma.email.update({ + where: { id: email?.id }, + data: { + refreshToken: r.tokens.refresh_token, + accessToken: r.tokens.access_token, + expiresIn: r.tokens.expiry_date, + serviceType: "gmail", + }, + }); + + const provider = nodemailer.createTransport({ + service: "gmail", + host: "smtp.gmail.com", + port: 465, + secure: true, + auth: { + type: "OAuth2", + user: email?.user, + clientId: email?.clientId, + clientSecret: email?.clientSecret, + refreshToken: r.tokens.refresh_token, + accessToken: r.tokens.access_token, + expiresIn: r.tokens.expiry_date, + }, + }); + + reply.send({ + success: true, + message: "SSO Provider updated!", + }); } ); @@ -411,17 +371,12 @@ export function configRoutes(fastify: FastifyInstance) { "/api/v1/config/email", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); + await prisma.email.deleteMany({}); - if (token) { - await prisma.email.deleteMany({}); - - reply.send({ - success: true, - message: "Email settings deleted!", - }); - } + reply.send({ + success: true, + message: "Email settings deleted!", + }); } ); } diff --git a/apps/api/src/controllers/data.ts b/apps/api/src/controllers/data.ts index dc07d860e..ecf621ae1 100644 --- a/apps/api/src/controllers/data.ts +++ b/apps/api/src/controllers/data.ts @@ -1,5 +1,4 @@ import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"; -import { checkToken } from "../lib/jwt"; import { prisma } from "../prisma"; export function dataRoutes(fastify: FastifyInstance) { @@ -8,16 +7,11 @@ export function dataRoutes(fastify: FastifyInstance) { "/api/v1/data/tickets/all", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); + const result = await prisma.ticket.count({ + where: { hidden: false }, + }); - if (token) { - const result = await prisma.ticket.count({ - where: { hidden: false }, - }); - - reply.send({ count: result }); - } + reply.send({ count: result }); } ); @@ -26,16 +20,11 @@ export function dataRoutes(fastify: FastifyInstance) { "/api/v1/data/tickets/completed", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); - - if (token) { - const result = await prisma.ticket.count({ - where: { isComplete: true, hidden: false }, - }); + const result = await prisma.ticket.count({ + where: { isComplete: true, hidden: false }, + }); - reply.send({ count: result }); - } + reply.send({ count: result }); } ); @@ -44,16 +33,11 @@ export function dataRoutes(fastify: FastifyInstance) { "/api/v1/data/tickets/open", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); + const result = await prisma.ticket.count({ + where: { isComplete: false, hidden: false }, + }); - if (token) { - const result = await prisma.ticket.count({ - where: { isComplete: false, hidden: false }, - }); - - reply.send({ count: result }); - } + reply.send({ count: result }); } ); @@ -62,16 +46,11 @@ export function dataRoutes(fastify: FastifyInstance) { "/api/v1/data/tickets/unassigned", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); - - if (token) { - const result = await prisma.ticket.count({ - where: { userId: null, hidden: false, isComplete: false }, - }); + const result = await prisma.ticket.count({ + where: { userId: null, hidden: false, isComplete: false }, + }); - reply.send({ count: result }); - } + reply.send({ count: result }); } ); } diff --git a/apps/api/src/controllers/notebook.ts b/apps/api/src/controllers/notebook.ts index 44c03e974..71aa66e50 100644 --- a/apps/api/src/controllers/notebook.ts +++ b/apps/api/src/controllers/notebook.ts @@ -1,8 +1,7 @@ import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"; -import { checkToken } from "../lib/jwt"; +import { track } from "../lib/hog"; import { checkSession } from "../lib/session"; import { prisma } from "../prisma"; -import { track } from "../lib/hog"; async function tracking(event: string, properties: any) { const client = track(); @@ -23,27 +22,21 @@ export function notebookRoutes(fastify: FastifyInstance) { async (request: FastifyRequest, reply: FastifyReply) => { const { content, title }: any = request.body; + const user = await checkSession(request); - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); - - if (token) { - const user = await checkSession(bearer); + const data = await prisma.notes.create({ + data: { + title, + note: content, + userId: user!.id, + }, + }); - const data = await prisma.notes.create({ - data: { - title, - note: content, - userId: user!.id, - }, - }); + await tracking("note_created", {}); - await tracking("note_created", {}); + const { id } = data; - const { id } = data; - - reply.status(200).send({ success: true, id }); - } + reply.status(200).send({ success: true, id }); } ); @@ -52,18 +45,13 @@ export function notebookRoutes(fastify: FastifyInstance) { "/api/v1/notebooks/all", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); - - if (token) { - const user = await checkSession(bearer); + const user = await checkSession(request); - const notebooks = await prisma.notes.findMany({ - where: { userId: user!.id }, - }); + const notebooks = await prisma.notes.findMany({ + where: { userId: user!.id }, + }); - reply.status(200).send({ success: true, notebooks: notebooks }); - } + reply.status(200).send({ success: true, notebooks: notebooks }); } ); @@ -72,67 +60,60 @@ export function notebookRoutes(fastify: FastifyInstance) { "/api/v1/notebooks/note/:id", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); - - if (token) { - const user = await checkSession(bearer); + const user = await checkSession(request); - const { id }: any = request.params; + const { id }: any = request.params; - const note = await prisma.notes.findUnique({ - where: { userId: user!.id, id: id }, - }); + const note = await prisma.notes.findUnique({ + where: { userId: user!.id, id: id }, + }); - reply.status(200).send({ success: true, note }); - } + reply.status(200).send({ success: true, note }); } ); // Delete an entry fastify.delete( - "/api/v1/documents/:id", - + "/api/v1/notebooks/note/:id", async (request: FastifyRequest, reply: FastifyReply) => { + const user = await checkSession(request); const { id }: any = request.params; - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); + await prisma.notes.delete({ + where: { + id: id, + userId: user!.id + }, + }); - if (token) { - await prisma.notes.delete({ - where: { id: id }, - }); + await tracking("note_deleted", {}); - reply.status(200).send({ success: true }); - } + reply.status(200).send({ success: true }); } ); // Update an entry fastify.put( "/api/v1/notebooks/note/:id/update", - async (request: FastifyRequest, reply: FastifyReply) => { + const user = await checkSession(request); const { id }: any = request.params; const { content, title }: any = request.body; - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); - - if (token) { - await checkSession(bearer); + await prisma.notes.update({ + where: { + id: id, + userId: user!.id + }, + data: { + title: title, + note: content, + }, + }); - await prisma.notes.update({ - where: { id: id }, - data: { - title: title, - note: content, - }, - }); + await tracking("note_updated", {}); - reply.status(200).send({ success: true }); - } + reply.status(200).send({ success: true }); } ); } diff --git a/apps/api/src/controllers/queue.ts b/apps/api/src/controllers/queue.ts index 146bfbfaf..68f1b4373 100644 --- a/apps/api/src/controllers/queue.ts +++ b/apps/api/src/controllers/queue.ts @@ -1,9 +1,8 @@ import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"; -import { checkToken } from "../lib/jwt"; -import { prisma } from "../prisma"; import { OAuth2Client } from "google-auth-library"; import { track } from "../lib/hog"; +import { prisma } from "../prisma"; async function tracking(event: string, properties: any) { const client = track(); @@ -23,12 +22,21 @@ export function emailQueueRoutes(fastify: FastifyInstance) { "/api/v1/email-queue/create", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); - - if (token) { - const { - name, + const { + name, + username, + password, + hostname, + tls, + serviceType, + clientId, + clientSecret, + redirectUri, + }: any = request.body; + + const mailbox = await prisma.emailQueue.create({ + data: { + name: name, username, password, hostname, @@ -37,64 +45,46 @@ export function emailQueueRoutes(fastify: FastifyInstance) { clientId, clientSecret, redirectUri, - }: any = request.body; - - const mailbox = await prisma.emailQueue.create({ - data: { - name: name, - username, - password, - hostname, - tls, - serviceType, - clientId, - clientSecret, - redirectUri, - }, - }); - - // generate redirect uri - switch (serviceType) { - case "gmail": - const google = new OAuth2Client( - clientId, - clientSecret, - redirectUri - ); - - const authorizeUrl = google.generateAuthUrl({ - access_type: "offline", - scope: "https://mail.google.com", - prompt: "consent", - state: mailbox.id, - }); - - tracking("gmail_provider_created", { - provider: "gmail", - }); - - reply.send({ - success: true, - message: "Gmail imap provider created!", - authorizeUrl: authorizeUrl, - }); - break; - case "other": - tracking("imap_provider_created", { - provider: "other", - }); - - reply.send({ - success: true, - message: "Other service type created!", - }); - break; - default: - reply.send({ - success: false, - message: "Unsupported service type", - }); - } + }, + }); + + // generate redirect uri + switch (serviceType) { + case "gmail": + const google = new OAuth2Client(clientId, clientSecret, redirectUri); + + const authorizeUrl = google.generateAuthUrl({ + access_type: "offline", + scope: "https://mail.google.com", + prompt: "consent", + state: mailbox.id, + }); + + tracking("gmail_provider_created", { + provider: "gmail", + }); + + reply.send({ + success: true, + message: "Gmail imap provider created!", + authorizeUrl: authorizeUrl, + }); + break; + case "other": + tracking("imap_provider_created", { + provider: "other", + }); + + reply.send({ + success: true, + message: "Other service type created!", + }); + break; + default: + reply.send({ + success: false, + message: "Unsupported service type", + }); } } ); @@ -104,44 +94,39 @@ export function emailQueueRoutes(fastify: FastifyInstance) { "/api/v1/email-queue/oauth/gmail", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); - - if (token) { - const { code, mailboxId }: any = request.query; - - const mailbox = await prisma.emailQueue.findFirst({ - where: { - id: mailboxId, - }, - }); - - const google = new OAuth2Client( - //@ts-expect-error - mailbox?.clientId, - mailbox?.clientSecret, - mailbox?.redirectUri - ); - - console.log(google); - - const r = await google.getToken(code); - - await prisma.emailQueue.update({ - where: { id: mailbox?.id }, - data: { - refreshToken: r.tokens.refresh_token, - accessToken: r.tokens.access_token, - expiresIn: r.tokens.expiry_date, - serviceType: "gmail", - }, - }); - - reply.send({ - success: true, - message: "Mailbox updated!", - }); - } + const { code, mailboxId }: any = request.query; + + const mailbox = await prisma.emailQueue.findFirst({ + where: { + id: mailboxId, + }, + }); + + const google = new OAuth2Client( + //@ts-expect-error + mailbox?.clientId, + mailbox?.clientSecret, + mailbox?.redirectUri + ); + + console.log(google); + + const r = await google.getToken(code); + + await prisma.emailQueue.update({ + where: { id: mailbox?.id }, + data: { + refreshToken: r.tokens.refresh_token, + accessToken: r.tokens.access_token, + expiresIn: r.tokens.expiry_date, + serviceType: "gmail", + }, + }); + + reply.send({ + success: true, + message: "Mailbox updated!", + }); } ); @@ -150,30 +135,25 @@ export function emailQueueRoutes(fastify: FastifyInstance) { "/api/v1/email-queues/all", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); - - if (token) { - const queues = await prisma.emailQueue.findMany({ - select: { - id: true, - name: true, - serviceType: true, - active: true, - teams: true, - username: true, - hostname: true, - tls: true, - clientId: true, - redirectUri: true, - }, - }); - - reply.send({ - success: true, - queues: queues, - }); - } + const queues = await prisma.emailQueue.findMany({ + select: { + id: true, + name: true, + serviceType: true, + active: true, + teams: true, + username: true, + hostname: true, + tls: true, + clientId: true, + redirectUri: true, + }, + }); + + reply.send({ + success: true, + queues: queues, + }); } ); @@ -182,22 +162,17 @@ export function emailQueueRoutes(fastify: FastifyInstance) { "/api/v1/email-queue/delete", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); - - if (token) { - const { id }: any = request.body; + const { id }: any = request.body; - await prisma.emailQueue.delete({ - where: { - id: id, - }, - }); + await prisma.emailQueue.delete({ + where: { + id: id, + }, + }); - reply.send({ - success: true, - }); - } + reply.send({ + success: true, + }); } ); } diff --git a/apps/api/src/controllers/users.ts b/apps/api/src/controllers/users.ts index 8b6843aad..8689dba12 100644 --- a/apps/api/src/controllers/users.ts +++ b/apps/api/src/controllers/users.ts @@ -1,9 +1,8 @@ import bcrypt from "bcrypt"; import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"; -import { checkToken } from "../lib/jwt"; -import { prisma } from "../prisma"; import { track } from "../lib/hog"; +import { prisma } from "../prisma"; export function userRoutes(fastify: FastifyInstance) { // All users @@ -11,37 +10,25 @@ export function userRoutes(fastify: FastifyInstance) { "/api/v1/users/all", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - - if (bearer) { - const token = checkToken(bearer); - if (token) { - const users = await prisma.user.findMany({ - where: { - external_user: false, - }, - select: { - id: true, - name: true, - email: true, - isAdmin: true, - createdAt: true, - updatedAt: true, - language: true, - }, - }); - - reply.send({ - users, - success: true, - }); - } - } else { - reply.send({ - success: false, - message: "No token provided", - }); - } + const users = await prisma.user.findMany({ + where: { + external_user: false, + }, + select: { + id: true, + name: true, + email: true, + isAdmin: true, + createdAt: true, + updatedAt: true, + language: true, + }, + }); + + reply.send({ + users, + success: true, + }); } ); @@ -50,46 +37,33 @@ export function userRoutes(fastify: FastifyInstance) { "/api/v1/user/new", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const { email, password, name, admin }: any = request.body; const e = email.toLowerCase(); - if (bearer) { - const token = checkToken(bearer); - if (token) { - const hash = await bcrypt.hash(password, 10); - - await prisma.user.create({ - data: { - name, - email: e, - password: hash, - isAdmin: admin, - }, - }); - - - const client = track(); - - client.capture({ - event: "user_created", - distinctId: "uuid", - }); - - client.shutdownAsync(); - - reply.send({ - success: true, - }); - } - } else { - reply.send({ - success: false, - message: "No token provided", - }); - } + const hash = await bcrypt.hash(password, 10); + + await prisma.user.create({ + data: { + name, + email: e, + password: hash, + isAdmin: admin, + }, + }); + + const client = track(); + + client.capture({ + event: "user_created", + distinctId: "uuid", + }); + + client.shutdownAsync(); + + reply.send({ + success: true, + }); } ); @@ -98,30 +72,18 @@ export function userRoutes(fastify: FastifyInstance) { "/api/v1/user/reset-password", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const { password, id }: any = request.body; - if (bearer) { - const token = checkToken(bearer); - if (token) { - const hashedPass = await bcrypt.hash(password, 10); - await prisma.user.update({ - where: { id: id }, - data: { - password: hashedPass, - }, - }); - reply - .status(201) - .send({ message: "password updated success", failed: false }); - } - } else { - reply.send({ - success: false, - message: "No token provided", - }); - } + const hashedPass = await bcrypt.hash(password, 10); + await prisma.user.update({ + where: { id: id }, + data: { + password: hashedPass, + }, + }); + reply + .status(201) + .send({ message: "password updated success", failed: false }); } ); @@ -130,23 +92,18 @@ export function userRoutes(fastify: FastifyInstance) { "/api/v1/user/notifcation/:id", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); - const { id }: any = request.params; - if (token) { - await prisma.notifications.update({ - where: { id: id }, - data: { - read: true, - }, - }); - - reply.send({ - success: true, - }); - } + await prisma.notifications.update({ + where: { id: id }, + data: { + read: true, + }, + }); + + reply.send({ + success: true, + }); } ); } diff --git a/apps/api/src/controllers/webhooks.ts b/apps/api/src/controllers/webhooks.ts index 0a8590985..07a92d95d 100644 --- a/apps/api/src/controllers/webhooks.ts +++ b/apps/api/src/controllers/webhooks.ts @@ -1,7 +1,6 @@ import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"; -import { checkToken } from "../lib/jwt"; -import { prisma } from "../prisma"; import { track } from "../lib/hog"; +import { prisma } from "../prisma"; export function webhookRoutes(fastify: FastifyInstance) { // Create a new webhook @@ -9,33 +8,28 @@ export function webhookRoutes(fastify: FastifyInstance) { "/api/v1/webhook/create", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); - - if (token) { - const { name, url, type, active, secret }: any = request.body; - await prisma.webhooks.create({ - data: { - name, - url, - type, - active, - secret, - createdBy: "375f7799-5485-40ff-ba8f-0a28e0855ecf", - }, - }); - - const client = track(); - - client.capture({ - event: "webhook_created", - distinctId: "uuid", - }); - - client.shutdownAsync(); - - reply.status(200).send({ message: "Hook created!", success: true }); - } + const { name, url, type, active, secret }: any = request.body; + await prisma.webhooks.create({ + data: { + name, + url, + type, + active, + secret, + createdBy: "375f7799-5485-40ff-ba8f-0a28e0855ecf", + }, + }); + + const client = track(); + + client.capture({ + event: "webhook_created", + distinctId: "uuid", + }); + + client.shutdownAsync(); + + reply.status(200).send({ message: "Hook created!", success: true }); } ); @@ -44,36 +38,25 @@ export function webhookRoutes(fastify: FastifyInstance) { "/api/v1/webhooks/all", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); - - if (token) { - const webhooks = await prisma.webhooks.findMany({}); + const webhooks = await prisma.webhooks.findMany({}); - reply.status(200).send({ webhooks: webhooks, success: true }); - } + reply.status(200).send({ webhooks: webhooks, success: true }); } ); // Delete a webhook - fastify.delete( "/api/v1/admin/webhook/:id/delete", async (request: FastifyRequest, reply: FastifyReply) => { - const bearer = request.headers.authorization!.split(" ")[1]; - const token = checkToken(bearer); - - if (token) { - const { id }: any = request.params; - await prisma.webhooks.delete({ - where: { - id: id, - }, - }); - - reply.status(200).send({ success: true }); - } + const { id }: any = request.params; + await prisma.webhooks.delete({ + where: { + id: id, + }, + }); + + reply.status(200).send({ success: true }); } ); } diff --git a/apps/api/src/lib/session.ts b/apps/api/src/lib/session.ts index 8ff52e97a..c302e7795 100644 --- a/apps/api/src/lib/session.ts +++ b/apps/api/src/lib/session.ts @@ -1,7 +1,9 @@ import { prisma } from "../prisma"; // Checks session token and returns user object -export async function checkSession(token: any) { +export async function checkSession(request: any) { + const token = request.headers.authorization!.split(" ")[1]; + let session = await prisma.session.findUnique({ where: { sessionToken: token, diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts index be66fe11b..4a3cafd60 100644 --- a/apps/api/src/main.ts +++ b/apps/api/src/main.ts @@ -7,14 +7,15 @@ import fs from "fs"; import { exec } from "child_process"; import { track } from "./lib/hog"; import { getEmails } from "./lib/imap"; +import { checkToken } from "./lib/jwt"; import { prisma } from "./prisma"; import { registerRoutes } from "./routes"; // Ensure the directory exists -const logFilePath = './logs.log'; // Update this path to a writable location +const logFilePath = "./logs.log"; // Update this path to a writable location // Create a writable stream -const logStream = fs.createWriteStream(logFilePath, { flags: 'a' }); +const logStream = fs.createWriteStream(logFilePath, { flags: "a" }); // Initialize Fastify with logger const server: FastifyInstance = Fastify({ @@ -26,7 +27,7 @@ const server: FastifyInstance = Fastify({ }); server.register(cors, { origin: "*", - + methods: ["GET", "POST", "PUT", "DELETE"], allowedHeaders: ["Content-Type", "Authorization", "Accept"], }); @@ -82,6 +83,19 @@ server.get("/", async function (request, response) { response.send({ healthy: true }); }); +// JWT authentication hook +server.addHook("preHandler", async function (request: any, reply: any) { + try { + const bearer = request.headers.authorization!.split(" ")[1]; + return checkToken(bearer); + } catch (err) { + reply.send({ + message: "Unauthorized", + success: false, + }); + } +}); + const start = async () => { try { // Run prisma generate and migrate commands before starting the server