@auth/core
Version:
Authentication for the Web.
75 lines (74 loc) • 2.49 kB
JavaScript
import { html, text } from "../lib/utils/email.js";
/**
* Add Mailgun login to your page.
*
* ### Setup
*
* #### Configuration
*```ts
* import { Auth } from "@auth/core"
* import Mailgun from "@auth/core/providers/mailgun"
*
* const request = new Request(origin)
* const response = await Auth(request, {
* providers: [
* Mailgun({
* from: MAILGUN_DOMAIN,
* region: "EU", // Optional
* }),
* ],
* })
* ```
*
* ### Resources
*
* - [Mailgun documentation](https://documentation.mailgun.com/docs/mailgun)
*
* :::info **Disclaimer**
*
* If you think you found a bug in the default configuration, you can [open an issue](https://authjs.dev/new/provider-issue).
*
* Auth.js strictly adheres to the specification and it cannot take responsibility for any deviation from
* the spec by the provider. You can open an issue, but if the problem is non-compliance with the spec,
* we might not pursue a resolution. You can ask for more help in [Discussions](https://authjs.dev/new/github-discussions).
*
* :::
*/
export default function MailGun(config) {
const { region = "US" } = config;
const servers = {
US: "api.mailgun.net",
EU: "api.eu.mailgun.net",
};
const apiServer = servers[region];
return {
id: "mailgun",
type: "email",
name: "Mailgun",
from: "Auth.js <no-reply@authjs.dev>",
maxAge: 24 * 60 * 60,
async sendVerificationRequest(params) {
const { identifier: to, provider, url, theme } = params;
const { host } = new URL(url);
const domain = provider.from?.split("@").at(1);
if (!domain)
throw new Error("malformed Mailgun domain");
const form = new FormData();
form.append("from", `${provider.name} <${provider.from}>`);
form.append("to", to);
form.append("subject", `Sign in to ${host}`);
form.append("html", html({ host, url, theme }));
form.append("text", text({ host, url }));
const res = await fetch(`https://${apiServer}/v3/${domain}/messages`, {
method: "POST",
headers: {
Authorization: `Basic ${btoa(`api:${provider.apiKey}`)}`,
},
body: form,
});
if (!res.ok)
throw new Error("Mailgun error: " + (await res.text()));
},
options: config,
};
}