Created
March 29, 2023 13:55
-
-
Save notchris/93c78db75e4cf8e9388c1b63ef8408e8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import express from "express"; | |
import payload from "payload"; | |
import { PayloadRequest } from "payload/dist/express/types"; | |
import cors from "cors"; | |
require("dotenv").config(); | |
const app = express(); | |
const router = express.Router(); | |
app.use(express.json()); | |
app.use( | |
cors({ | |
origin: [ | |
"http://localhost:4200", | |
], | |
credentials: true, | |
}) | |
); | |
// Tells express to server files in /client as static | |
app.use(express.static("/var/www/beta.safsonline.com/client/")); | |
// Initialize Payload | |
payload.init({ | |
secret: process.env.PAYLOAD_SECRET, | |
mongoURL: process.env.MONGODB_URI, | |
express: app, | |
onInit: () => { | |
payload.logger.info(`Payload Admin URL: ${payload.getAdminURL()}`); | |
router.use(payload.authenticate); | |
}, | |
}); | |
// router.use(payload.authenticate); (undefined) | |
// Sets the entry index for the client | |
router.get("/", (_, res) => { | |
res.sendFile("/var/www/beta.safsonline.com/client/index.html"); | |
}); | |
// Login Route | |
router.post("/login", async (req, res) => { | |
const { email, password } = req.body; | |
// Attempt Payload login with user credentials | |
try { | |
const result = await payload.login({ | |
collection: "users", | |
data: { | |
email, | |
password, | |
}, | |
req: req as PayloadRequest<any>, | |
res: res, | |
locale: "en", | |
}); | |
// Payload returns authenticated | |
if (result) { | |
res.json({ | |
ok: true, | |
error: false, | |
}); | |
} else { | |
throw new Error("Invalid result from payload."); | |
} | |
} catch (error) { | |
// Invalid credentials | |
if (error.status === 401) { | |
res.json({ | |
ok: false, | |
error: | |
"Your email or password is incorrect, or you may not have verified your email address.", | |
}); | |
// Other error | |
} else { | |
res.json({ | |
ok: false, | |
error: "Server error.", | |
}); | |
} | |
} | |
}); | |
app.use("/", router); | |
app.listen(3000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment