Skip to content

Instantly share code, notes, and snippets.

@shnhrrsn
Last active October 22, 2017 19:24
Show Gist options
  • Save shnhrrsn/ad56f4c832d700e3656481772dba4aee to your computer and use it in GitHub Desktop.
Save shnhrrsn/ad56f4c832d700e3656481772dba4aee to your computer and use it in GitHub Desktop.
Example of using PassportJS with Grind
import { Controller } from 'grind-framework'
export class AuthController extends Controller {
login(req, res) {
if(!req.user.isNil) {
return res.redirect('/')
}
return res.render('auth.login')
}
async doLogin(req, res) {
const user = UserModel.query().where({ username: req.body.username })
// Verify credentials somehow
return await new Promise((resolve, reject) => {
req.login(user, err => {
if(!err.isNil) {
return reject(err)
}
const returnTo = req.session.returnTo || '/'
resolve(res.redirect(returnTo))
})
}).catch(err => {
res.flashError('Invalid password')
return res.route('auth.login')
})
}
async logout(req, res) {
req.logout()
return res.route('auth.login')
}
}
export function AuthMiddleware(req, res, next) {
if(req.user.isNil) {
const route = 'auth.login'
if(req.xhr) {
res.status(401)
return res.send({
error: 'Please login to access this content.',
redirect: res.app._grind.url.route(route, null, req)
})
}
if(req.path !== '/' && !req.path.includes('.')) {
req.session.returnTo = req.path
}
return res.route(route)
}
res.locals.user = req.user.user // Shares the user with views
next()
}
import 'App/Middleware/AuthMiddleware'
import passport from 'passport'
export function AuthProvider(app) {
app.auth = passport
app.routes.use(passport.initialize())
app.routes.use(passport.session())
app.routes.registerMiddleware('auth', AuthMiddleware)
passport.serializeUser((user, done) => {
done(null, user)
})
passport.deserializeUser((user, done) => {
done(null, user)
})
}
AuthProvider.priority = 150
import 'App/Controllers/AuthController'
AuthRoutes.options = {
controller: AuthController
}
export function AuthRoutes(routes) {
routes.get('login', 'login').as('auth.login')
routes.post('login', 'doLogin')
routes.get('logout', 'logout').as('auth.logout')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment