|
@@ -0,0 +1,82 @@
|
|
|
+const passport = require('passport');
|
|
|
+const { BasicStrategy } = require('passport-http');
|
|
|
+const { Strategy: BearerStrategy } = require('passport-http-bearer');
|
|
|
+const { Strategy: JwtStrategy, ExtractJwt } = require('passport-jwt');
|
|
|
+
|
|
|
+const { masterKey, jwtSecret } = require('../../config');
|
|
|
+const { getAllUsersDataFromDB } = require('../../utils/data-handlers');
|
|
|
+
|
|
|
+const { User } = require('../../routes/users/model');
|
|
|
+
|
|
|
+const password = () => (req, res, next) =>
|
|
|
+ passport.authenticate('password', { session: false }, (err, user) => {
|
|
|
+ if (err && err.param) {
|
|
|
+ return res.status(400).json(err)
|
|
|
+ } else if (err || !user) {
|
|
|
+ return res.status(401).json(err)
|
|
|
+ }
|
|
|
+ req.logIn(user, { session: false }, (err) => {
|
|
|
+ if (err) return res.status(401).end()
|
|
|
+ next()
|
|
|
+ })
|
|
|
+ })(req, res, next)
|
|
|
+
|
|
|
+const master = () =>
|
|
|
+ passport.authenticate('master', { session: false })
|
|
|
+
|
|
|
+const token = ({ required } = {}) => (req, res, next) =>
|
|
|
+ passport.authenticate('token', { session: false }, (err, user) => {
|
|
|
+ if (err || (required && !user)) {
|
|
|
+ return res.status(401).end()
|
|
|
+ }
|
|
|
+ req.logIn(user, { session: false }, (err) => {
|
|
|
+ if (err) return res.status(401).end()
|
|
|
+ next()
|
|
|
+ })
|
|
|
+ })(req, res, next)
|
|
|
+
|
|
|
+passport.use('password', new BasicStrategy((email, password, done) => {
|
|
|
+ const allUsers = getAllUsersDataFromDB();
|
|
|
+
|
|
|
+ const userRecord = allUsers.find(el => el.email === email);
|
|
|
+ if (!userRecord) return done({ message: 'Wrong credentials' });
|
|
|
+
|
|
|
+ const user = new User(userRecord, false);
|
|
|
+ const isPasswordValid = user.authenticate(password);
|
|
|
+ if (!isPasswordValid) return done({ message: 'Wrong credentials' });
|
|
|
+
|
|
|
+ return done(null, user);
|
|
|
+}))
|
|
|
+
|
|
|
+passport.use('master', new BearerStrategy((token, done) => {
|
|
|
+ if (token === masterKey) {
|
|
|
+ done(null, {})
|
|
|
+ } else {
|
|
|
+ done(null, false)
|
|
|
+ }
|
|
|
+}))
|
|
|
+
|
|
|
+passport.use('token', new JwtStrategy({
|
|
|
+ secretOrKey: jwtSecret,
|
|
|
+ jwtFromRequest: ExtractJwt.fromExtractors([
|
|
|
+ ExtractJwt.fromUrlQueryParameter('access_token'),
|
|
|
+ ExtractJwt.fromBodyField('access_token'),
|
|
|
+ ExtractJwt.fromAuthHeaderWithScheme('Bearer')
|
|
|
+ ])
|
|
|
+}, ({ id }, done) => {
|
|
|
+ const allUsers = getAllUsersDataFromDB();
|
|
|
+
|
|
|
+ const userRecord = allUsers.find(el => el.id === id);
|
|
|
+ if (!userRecord) return done({ message: 'Invalid token' });
|
|
|
+
|
|
|
+ const user = new User(userRecord, false);
|
|
|
+ return done(null, user)
|
|
|
+}))
|
|
|
+
|
|
|
+
|
|
|
+module.exports = {
|
|
|
+ password,
|
|
|
+ master,
|
|
|
+ token,
|
|
|
+ passport
|
|
|
+}
|