Я пишу приложение, которое, по сути, будет перечислять товары и позволяет пользователям оформить заказ.Но я застрял с этой проблемой при использовании паспорта для аутентификации пользователя.Моя аутентификация на Facebook работает отлично и фиксирует адрес электронной почты пользователя и т. Д. Я боролся с Twitter, и Google перенаправляет bacxk на localhost (в настоящее время работает на моем ноутбуке).При перенаправлении на localhost я получаю следующую ошибку:
TypeError: Невозможно прочитать свойство '0' из неопределенного
мой файл паспорта facebook.js выглядит ниже и работает отличноfine
'use strict'
const passport = require('passport')
, FacebookStrategy = require('passport-facebook').Strategy
const User = require('../models/user')
let check = x => x === undefined ? 'empty' : x
passport.use(new FacebookStrategy({
clientID: 'xxxxxxxxxxxxx',
clientSecret: 'xxxxxxxxxxxxxxxxxxxxxxx',
callbackURL: "http://localhost:3000/auth/facebook/callback"
},
function(accessToken, refreshToken, profile, done) {
User.findOrCreate({
id: profile.id,
name: profile.displayName,
photo: "https://graph.facebook.com/"+profile.id+"/picture",
email: check(profile._json.email)
}, function(err, user) {
return done( err, user)
})
}
))
А мои файлы twitter.js и google.js выглядят следующим образом:
'use strict'
const passport = require('passport')
, TwitterStrategy = require('passport-twitter').Strategy
const User = require('../models/user')
passport.use(new TwitterStrategy({
consumerKey: 'xxxxxxxxxxxxxxxxx',
consumerSecret: 'xxxxxxxxxxxxxxxxxxxxxxxxx',
callbackURL: "http://localhost:3000/auth/twitter/callback",
includeEmail: true
},
function(token, tokenSecret, profile, done) {
User.findOrCreate({
id: profile.id,
name: profile.displayName,
photo: profile.photos[0].value,
email: profile.emails[0].value
}, function(err, user) {
return done(err, user)
})
}
))
'use strict'
const passport = require('passport')
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy
const User = require('../models/user')
passport.use(new GoogleStrategy({
clientID: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx',
clientSecret: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx',
callbackURL: "http://localhost:3000/auth/google/callback",
profileFields: ['id', 'displayName', 'photos', 'email']
},
function(accessToken, refreshToken, profile, done) {
User.findOrCreate({
id: profile.id,
name: profile.displayName,
photo: profile.photos[0].value,
email: profile.emails[0].value
}, function (err, user) {
return done(err, user)
})
}
))
мой app.js выглядит следующим образом:
'use strict'
const express = require('express')
const bodyParser = require('body-parser')
const favicon = require('serve-favicon')
const path = require('path')
const app = express()
const{mongoose} = require('./db/index')
const passport = require('passport')
const session = require('express-session')
const MongoStore = require('connect-mongo')(session)
//================ROUTES
const userRouter = require('./routes/index')
const adminRouter = require('./routes/admin')
const productRouter = require('./routes/products')
//=================MODELS
const Category = require('./models/category')
const Product = require('./models/product')
const User = require('./models/user')
app.set('view engine', 'ejs')
const logger = require('./log')
const morgan = require('morgan')
app.use(express.static(path.join(__dirname,'public')))
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')))
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
app.use(morgan('dev'))
app.use(morgan('combined',{'stream': logger.stream}))
//==================SESSIONS
app.use(session({
secret: 'secret',
saveUninitialized: false,
resave: false,
store: new MongoStore({url: 'mongodb://localhost/e-commerce'})
}))
app.use(passport.initialize())
app.use(passport.session())
//==================Navbar
app.use((req,res,next) => {
Category.find().then(data => {
res.locals.ctg = data
next()
}, (e) => {throw new Error('Unable to find category')})
})
//==================Use Routes
app.use(userRouter)
app.use(adminRouter)
app.use(productRouter)
//======================PASSPORT
passport.serializeUser(function (user, done) {
done(null, user._id)
})
passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
done(err, user)
})
})
//==================Errors
app.use(function(req,res,next){
const err = new Error('Not found')
err.status = 404
next(err)
})
app.use(function(err,req,res,next){
res.locals.error = req.app.get('env') === 'development' ? err : {}
res.status(err.status || 500)
res.render('error')
})
//app.set('port',(process.env.PORT || 3000))
const PORT = process.env.PORT || 3000
app.listen(PORT,() => logger.info(`${String.fromCodePoint(9749)} is ready on port ${PORT}`))
// app.listen(app.get('port'),function(){
// console.log('running on port',app.get('port'))
// })
module.exports ={app}
и мой products.js выглядит следующим образом, где я добавил маршруты:
'use strict'
const router = require('express').Router()
const logger = require('../log')
const Category = require('../models/category')
const Product = require('../models/product')
router.get('/navbar', (req,res) => {
const perPage = 8
const page = req.query.page || 1
const ctg = req.query.name
Product.find({category: req.query.name})
.skip((perPage * page) - perPage)
.limit(perPage)
.then(products => {
Product.count({category: req.query.name})
.then(count => {
res.render('product', {
navbar: products,
current: page,
pages: Math.ceil(count / perPage),
category: ctg
})
}, (e) => {throw new Error('Unable to count!')})
}, (e) => {throw new Error('Unable to find this product!')})
})
router.get('/single', (req,res) => {
if (req.isAuthenticated()){
console.log(req.user)
res.send('ok')
}
})
module.exports = router
Консоль выдает следующую ошибку при попытке использовать Twitter:
GET /auth/twitter 302 855.274 ms - 0
{"message":"::1 - - [25/Mar/2019:14:24:58 +0000] \"GET /auth/twitter HTTP/1.1\" 302 0 \"http://localhost:3000/login\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36\"\n","level":"info"}
GET /auth/twitter/callback?oauth_token=xxxxxxxxxxxxxxxxxx&oauth_verifier=xxxxxxxxxxxxxxxxxx 500 1393.641 ms - 1775
{"message":"::1 - - [25/Mar/2019:14:25:00 +0000] \"GET /auth/twitter/callback?oauth_token=xxxxxxxxxxxxxxxxxx&oauth_verifier=xxxxxxxxxxxxxxxxxx HTTP/1.1\" 500 1775 \"-\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36\"\n","level":"info"}
GET /auth/twitter/style.css 404 11.922 ms - 1735
{"message":"::1 - - [25/Mar/2019:14:25:00 +0000] \"GET /auth/twitter/style.css HTTP/1.1\" 404 1735 \"http://localhost:3000/auth/twitter/callback?oauth_token=xxxxxxxxxxxxxxxxxx&oauth_verifier=xxxxxxxxxxxxxxxxxx\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36\"\n","level":"info"}
и при попытке с Google я получаю следующее:
GET /auth/google 302 7.842 ms - 0
{"message":"::1 - - [25/Mar/2019:14:05:38 +0000] \"GET /auth/google HTTP/1.1\" 302 0 \"http://localhost:3000/login\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36\"\n","level":"info"}
GET /auth/google/callback?code=xxxxxxxxxxxxxxxxxxxxxxxxxxxx&scope=profile%20https://www.googleapis.com/auth/userinfo.profile%20https://www.googleapis.com/auth/profile.emails.read 500 1031.758 ms - 1775
{"message":"::1 - - [25/Mar/2019:14:05:54 +0000] \"GET /auth/google/callback?code=xxxxxxxxxxxxxxxxxxxxxxxxxxxx&scope=profile%20https://www.googleapis.com/auth/userinfo.profile%20https://www.googleapis.com/auth/profile.emails.read HTTP/1.1\" 500 1775 \"-\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36\"\n","level":"info"}
GET /auth/google/style.css 404 13.095 ms - 1735
{"message":"::1 - - [25/Mar/2019:14:05:54 +0000] \"GET /auth/google/style.css HTTP/1.1\" 404 1735 \"http://localhost:3000/auth/google/callback?code=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&scope=profile%20https://www.googleapis.com/auth/userinfo.profile%20https://www.googleapis.com/auth/profile.emails.read\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36\"\n","level":"info"}
GET /auth/google/favicon.ico 404 4.848 ms - 1735
{"message":"::1 - - [25/Mar/2019:14:05:54 +0000] \"GET /auth/google/favicon.ico HTTP/1.1\" 404 1735 \"http://localhost:3000/auth/google/callback?code=4/xxxxxxxxxxxxxxxxxxxxxxxxx&scope=profile%20https://www.googleapis.com/auth/userinfo.profile%20https://www.googleapis.com/auth/profile.emails.read\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36\"\n","level":"info"}
Пожалуйста, дайте мне знать, если вам понадобится какая-либо дополнительная информация, чтобы помочь мне определить проблему с моим кодом здесь.