Guide: Implement AMC auth into your app

  1. Install the packages
yarn init -y
yarn add express passport-discourse passport express-session session-file-store https://github.com/markus-li/passport-discourse.git
  1. Implement this logic into your app
const express = require("express");
const app = express();
const passportDiscourse = require("passport-discourse").Strategy
const passport = require('passport');
const session = require("express-session")
const FileStore = require('session-file-store')(session);

app.use(session({
    secret: '...', // PLEASE replace this with something random
    store: new FileStore({}),
    resave: false,
    saveUninitialized: true,
    cookie: { secure: false }
}));
app.use(passport.initialize());
app.use(passport.session());

passport.use(new passportDiscourse({
    secret: "...", /* Generate a random string and give this to an admin */
    discourse_url: "https://amcforum.wiki",
    callback_url: "http://localhost:3000/goalpost", // replace with your url and also give to an admin
    debug: false
}, function (req, accessToken, refreshToken, profile, done) {
    done(null, profile);
}))

passport.serializeUser(function (user, done) {
    done(null, user);
});

passport.deserializeUser(function (user, done) {
    done(null, user);
});
app.get("/login", passport.authenticate("discourse"));
app.get("/goalpost", passport.authenticate("discourse", {
    successRedirect: "/finish",
    failureRedirect: "/login"
}));
/**
 * @typedef {Object} User
 * @property {string} provider - The provider of the user authentication.
 * @property {string} username - The username of the user.
 * @property {string} email - The email of the user.
 * @property {string} displayName - The display name of the user.
 * @property {string} avatar - The URL of the user's avatar.
 * @property {string} groups - The groups the user belongs to.
 */
app.get("/finish", async function (req, res) {
    /** @type {User} */
    const user = req.user
   // Why the comments? This should give you intellisense :)
    if (!req.isAuthenticated()) res.redirect("/login")
    res.send(`hurray! hi ${req.user.username}`)
});
app.listen(3000)
  1. You’re done! Enjoy AMC auth :slight_smile:
2 Likes

This topic was automatically closed after 2 minutes. New replies are no longer allowed.