Skip to content

Instantly share code, notes, and snippets.

@m5r
Last active October 14, 2021 20:08
Show Gist options
  • Save m5r/4845f651610bdac9f8071f7c00bb1d64 to your computer and use it in GitHub Desktop.
Save m5r/4845f651610bdac9f8071f7c00bb1d64 to your computer and use it in GitHub Desktop.
Magic login link generation and verification
import jwt from "jsonwebtoken";
import { User } from "./entities/user";
export function generateSignInUrl(user: User) {
const token = generateSignInToken(user);
return `${process.env.APP_URL}/auth/verify?token=${token}`;
}
function generateSignInToken(user: User) {
const payload = {
type: "magic",
id: user.id,
email: user.email,
};
return jwt.sign(
payload,
process.env.JWT_SECRET,
{
issuer: "capsulecorp.dev",
algorithm: "HS256",
expiresIn: "30m",
},
);
}
export function verifyToken(token: string) {
return jwt.verify(
token,
process.env.JWT_SECRET,
{
issuer: "capsulecorp.dev",
algorithms: ["HS256"],
},
) as Pick<User, "id" | "email">;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment