const express = require("express") const passport = require("../middleware/passport") const router = express.Router() function saveReferer(req, res, next) { if (req.session != null) { req.session.loginReferrer = req.get("Referer") req.session.save() } next() } // Perform the login, after login Auth0 will redirect to callback router.get("/login", saveReferer, passport.authenticate("auth0", {scope: "openid username profile"}), (req, res) => { res.redirect("/") }) router.get("/callback", function (req, res, next) { passport.authenticate("auth0", function (err, user, info) { if (err) { return next(err) } if (!user) { console.log(err, user, info); return res.redirect("/auth/login") } req.logIn(user, function (err) { if (err) { return next(err) } res.redirect(req.session.loginReferrer || "/"); }) })(req, res, next); }) router.get("/user", (req, res) => { if (req.user == null) { return res.status(401).json({error: {message: "Unauthorized"}}) } const name = req.user._json.name // TODO: Grab data from rpdata-api user database res.json({data: { name }}) }) router.get("/logout", saveReferer, (req, res) => { req.logout() res.redirect(req.session.loginReferrer || "/"); }) module.exports = router