Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/pull-request-check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ env:
DATABASE_NAME: vektor-database
PORT: 8080
HOSTING_URL: localhost
GOOGLE_FROM_EMAIL: ${{ secrets.GOOGLE_FROM_EMAIL }}
GOOGLE_CLIENT_ID: ${{ secrets.GOOGLE_CLIENT_ID }}
GOOGLE_CLIENT_SECRET: ${{ secrets.GOOGLE_CLIENT_SECRET }}
GOOGLE_REFRESH_TOKEN: ${{ secrets.GOOGLE_REFRESH_TOKEN }}

on:
push:
Expand Down
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,26 @@ i `.env`.

For å kjøre appen og migrere databasen, se [scripts](#database).


### Email setup

The API sends email through Gmail using OAuth 2.0. Add the following values to your `.env` file:

```.env
GOOGLE_FROM_EMAIL=vektorbot@vektorprogrammet.no
GOOGLE_CLIENT_ID=*Google OAuth client ID*
GOOGLE_CLIENT_SECRET=*Google OAuth client secret*
GOOGLE_REFRESH_TOKEN=*OAuth refresh token for the sender account*
```

`GOOGLE_FROM_EMAIL` is the email address used as the sender. `GOOGLE_CLIENT_ID` and
`GOOGLE_CLIENT_SECRET` identify the OAuth client, and `GOOGLE_REFRESH_TOKEN` lets
the API obtain access to Gmail without storing the account password. All four
values are required for the API to start. Keep the client secret and refresh token
private, and do not commit them to the repository.



## Recommended Extensions

### Imports Autocomplete
Expand Down
7 changes: 7 additions & 0 deletions lib/global-variables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,10 @@ export const MAX_TEXT_LENGTH = 2500 as const;
export const DEFAULT_QUERY_LIMIT = 10 as const;

export const DEFAULT_QUERY_SORT_OPTION = "desc" as const;

export const VALID_CONTACT_EMAIL_ADDRESSES: readonly string[] = [
"hovedstyret@vektorprogrammet.no",
"styret.ntnu@vektorprogrammet.no",
"uib@vektorprogrammet.no",
"nmbu@vektorprogrammet.no",
];
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"drizzle-zod": "^0.5.1",
"express": "^5.1.0",
"express-zod-safe": "^1.3.3",
"nodemailer": "^9.0.5",
"pg": "^8.14.1",
"swagger-jsdoc": "^6.2.8",
"validator": "^13.15.0",
Expand All @@ -42,6 +43,7 @@
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
"@types/node": "^22.14.0",
"@types/nodemailer": "^8.0.1",
"@types/pg": "^8.11.11",
"@types/supertest": "^6.0.3",
"@types/swagger-jsdoc": "^6.0.4",
Expand Down
19 changes: 19 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 23 additions & 0 deletions src/enviroment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,26 @@ if (!hostOptionsResult.success) {
}

export const hostOptions = hostOptionsResult.data;

const mailOptionsResult = z
.object({
GOOGLE_FROM_EMAIL: z.string().email(),
GOOGLE_CLIENT_ID: z.string().nonempty(),
GOOGLE_CLIENT_SECRET: z.string().nonempty(),
GOOGLE_REFRESH_TOKEN: z.string().nonempty(),
})
.transform((schema) => ({
fromEmail: schema.GOOGLE_FROM_EMAIL,
clientId: schema.GOOGLE_CLIENT_ID,
clientSecret: schema.GOOGLE_CLIENT_SECRET,
refreshToken: schema.GOOGLE_REFRESH_TOKEN,
}))
.safeParse(env);

if (!mailOptionsResult.success) {
console.error("Error when parsing environment variables.");
console.error(fromZodError(mailOptionsResult.error).message);
process.exit(1);
}

export const mailOptions = mailOptionsResult.data;
1 change: 1 addition & 0 deletions src/error/error-messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ const HTTP_CLIENT_ERROR_MESSAGES = [
"Failed to execute the database command",
"Error parsing database response",
"Database error",
"Nice try!",
] as const;
const HTTP_SERVER_ERROR_MESSAGES = [
"Internal server error occurred",
Expand Down
3 changes: 3 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
assistantApplicationRouter,
teamApplicationRouter,
} from "@/src/routers/applications";
import { contactRouter } from "@/src/routers/contact";
import { expensesRouter } from "@/src/routers/expenses";
import { sponsorsRouter } from "@/src/routers/sponsors";
import { teamsRouter } from "@/src/routers/teams";
Expand Down Expand Up @@ -45,6 +46,8 @@ api.use("/assistantapplications", assistantApplicationRouter);

api.use("/teams", teamsRouter);

api.use("/contact", contactRouter);

// Error handling
api.use(
jsonParsingErrorHandler,
Expand Down
82 changes: 82 additions & 0 deletions src/routers/contact.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { VALID_CONTACT_EMAIL_ADDRESSES } from "@/lib/global-variables";
import { clientError, serverError } from "@/src/error/http-errors";
import { sendEmail } from "@/src/services/mail-service";
import { Router, json } from "express";
import { z } from "zod";

export const contactRouter = Router();
contactRouter.use(json());

/**
* @openapi
* /contact:
* post:
* tags: [contact]
* summary: Send a contact email
* description: Send an email to contact, using the configured mail service.
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - receivingEmail
* - replyTo
* - about
* properties:
* receivingEmail:
* type: string
* format: email
* description: Recipient email address
* replyTo:
* type: string
* format: email
* nullable: true
* description: Optional reply-to address
* about:
* type: string
* description: Email subject
* text:
* type: string
* nullable: true
* description: Plain text email body
* responses:
* 200:
* description: Email sent successfully
* content:
* application/json:
* schema:
* type: string
* example: Successfully sent the email!
* 400:
* description: Invalid request format
*/
contactRouter.post("/", async (req, res, next) => {
const contactSchema = z.object({
receivingEmail: z.string().email(),
replyTo: z.string().email(),
about: z.string().min(1),
text: z.string().optional(),
});

const result = contactSchema.safeParse(req.body);

if (!result.success) {
return next(clientError(400, "Invalid request format", result.error));
}

const { receivingEmail, replyTo, about, text } = result.data;

if (!VALID_CONTACT_EMAIL_ADDRESSES.includes(receivingEmail)) {
return next(clientError(418, "Nice try!"));
}

const emailResult = await sendEmail(receivingEmail, replyTo, about, text);

if (!emailResult.success) {
return next(serverError(500, "Data processing error", emailResult.error));
}

return res.json("Successfully sent the email!");
});
43 changes: 43 additions & 0 deletions src/services/mail-service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import type { Result } from "@/lib/types";
import { mailOptions } from "@/src/enviroment";
import nodemailer from "nodemailer";

const transporter = nodemailer.createTransport({
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
secure: true,
// biome-ignore lint/style/useNamingConvention: Nodemailer requires the `requireTLS` option name.
requireTLS: true,
service: "gmail",
auth: {
type: "OAuth2",
user: mailOptions.fromEmail,
clientId: mailOptions.clientId,
clientSecret: mailOptions.clientSecret,
refreshToken: mailOptions.refreshToken,
},
});

export async function sendEmail(
to: string,
replyTo: string,
subject: string,
text?: string,
html?: string,
): Promise<Result<void, Error>> {
try {
await transporter.sendMail({
from: `"Vektorprogrammet" <${mailOptions.fromEmail}>`,
to,
replyTo,
subject,
text,
html,
});

return { success: true, data: undefined };
} catch (error: unknown) {
return {
success: false,
error: new Error("Failed to send email", { cause: error }),
};
}
}
Loading