I get an error when i try out my code 'Error: Unknown authentication strategy "spotify"'. I even tried googling this issue but can't didn't find an answer
Update: I updated my code to give answers to a person that is helping me
Code
const passport = require('passport')
const SpotifyStrategy = require('passport-spotify').Strategy
const userWebData = require('../model/userWebSchema')
passport.serializeUser((user, done) => {
const u = user
done(null, u)
})
passport.deserializeUser(async(spotifyID, done)=> {
try{
const data = await userWebData.findOne({ spotifyID: spotifyID})
const user = data
return user ? done( null, user) : done(null, null)
}catch(e){
console.log(e)
done(e, null)
}
})
passport.use(
new SpotifyStrategy({
clientID: 'Clients_ID_That_I_Wont_Show',
clientSecret: 'Clients_Secret_That_I_Wont_Show',
callbackURL: 'http://localhost:3001/',
scope: ["user-modify-playback-state", "user-read-private","user-library-read"]
}, async(accessToken, refreshToken, expires_in, profile, done)=>{
const userData = await userWebData.findOne({ spotifyID: profile.id})
if(userData){
console.log(`User ${profile.displayName} found`)
return done(err, userData);
}else{
let profiles = await userWebData.create(
{
spotifyID: profile.id,
spotifyName: profile.displayName,
spotifyFollowers: profile.followers,
}
)
profile.save()
console.log(`New User ${profile.displayName} Created`)
return done(err, userData);
}
}
)
)
You also have to import the passport-spotify
package before authenticating with it. First, install the package (npm i passport-spotify
) and then require it in your file:
const SpotifyStrategy = require('passport-spotify').Strategy;
Then, you have to call the passport.use()
function before you can authenticate with passport
:
passport.use(
new SpotifyStrategy(
{
clientID: client_id,
clientSecret: client_secret,
callbackURL: 'http://localhost:8888/auth/spotify/callback'
},
function(accessToken, refreshToken, expires_in, profile, done) {
User.findOrCreate({ spotifyId: profile.id }, function(err, user) {
return done(err, user);
});
}
)
);
Finally, you can use it as an Express middleware. Your modified code would look something like:
const express = require('express')
const app = express()
const passport = require('passport')
const SpotifyStrategy = require('passport-spotify').Strategy;
passport.use(
new SpotifyStrategy(
{
clientID: client_id,
clientSecret: client_secret,
callbackURL: 'http://localhost:8888/auth/spotify/callback'
},
function(accessToken, refreshToken, expires_in, profile, done) {
User.findOrCreate({ spotifyId: profile.id }, function(err, user) {
return done(err, user);
});
}
)
);
app.get('/', passport.authenticate('spotify'), (req, res)=>{
res.redirect('http://localhost:3001/user')
})
app.get('/user', (req, res) => {
if(req.user == undefined){res.status(401).redirect('http://localhost:3001/')}else{res.send(req.user)}
})
module.exports = app
Refer to http://www.passportjs.org/packages/passport-spotify/