Home > other >  Mongo DB: Mongoose
Mongo DB: Mongoose

Time:07-01

I'm trying to figure out how exactly I should do when it comes to Spotify API and OAuth2.

The refresh token needs to be stored in a database as the bot cycles and lose the token otherwise. So first time when I start the bot the token it generates a URL that contains an authentication code, this code needs to be inserted to the code, and then when I deploy it again it will get me the refresh token and everything I need.

I'm using Mongoose and have managed to get the token stored to Mongo DB. Though I'm too much of a beginner to figure out how to fetch the token from the databas, and I also don't want to run the authentication again, except a function that refreshed the token.

I have a separate file containing this:

const mongoose = require('mongoose');

const tokenSchema = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  token: String
});

module.exports = mongoose.model("RefreshToken", tokenSchema);

The code below might be a bit heavy. And probably contains a lot of faults. But this is what I'm currently working with (and struggles with).

var generateRandomString = function(length) {
var text = '';
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

  for (var i = 0; i < length; i  ) {
    text  = possible.charAt(Math.floor(Math.random() * possible.length));
  }
  return text;
};

var scopes = ['user-read-private', 'user-read-email', 'playlist-read-private', 'playlist-modify-private', 'playlist-modify-public'],
  redirectUri = '<my uri>',
  clientId = '<my client id>',
  clientSecret = '<my client secret>',
  state = generateRandomString(16);

var spotifyApi = new SpotifyWebApi({
  redirectUri: redirectUri,
  clientId: clientId,
  clientSecret: clientSecret
});

// Create the authorization URL
var authorizeURL = spotifyApi.createAuthorizeURL(scopes, state);

var credentials = {
  clientId: '<my client id>',
  clientSecret: '<my client secret>',
  redirectUri: '<my uri>'
};

var spotifyApi = new SpotifyWebApi(credentials);

var app = express();

app.get('/login', function(req, res) {
  res.redirect(authorizeURL);
});

// The code that's returned as a query parameter to the redirect URI
var code = '<authentication code>';

// Retrieve an access token and a refresh token
client.on('ready', async () => {
  await mongoose.connect(process.env.MONGODB_SPECTRUM, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    // useFindAndModify: false,
    keepAlive: true
  }).then(()=>{
    console.log('Connected to the Spectrum Database');
  }).catch((err) => {
    console.log(err);
  });

  
spotifyApi.authorizationCodeGrant(code).then(
  function(data) {
    console.log('The token expires in '   data.body['expires_in']);
    console.log('The access token is '   data.body['access_token']);
    console.log('The refresh token is '   data.body['refresh_token']);

    // Set the access token on the API object to use it in later calls
    spotifyApi.setAccessToken(data.body['access_token']);

    // SAVE REFRESH TOKEN TO DB
    const refreshToken = new RefreshToken({
      _id: mongoose.Types.ObjectId(),
      token: data.body['refresh_token']
    });
    refreshToken.save()
    .then(result => console.log(result))
    .catch(err => console.log(err));
    spotifyApi.setRefreshToken(refreshToken.token);
  },
  function(err) {
    console.log('Something went wrong!', err);
  }
);
// --------------------------------------------------
// clientId, clientSecret and refreshToken has been set on the api object previous to this call.
function refreshSpotifyToken() {
spotifyApi.refreshAccessToken().then(
  function(data) {
    console.log('The access token has been refreshed!');

    // Save the access token so that it's used in future calls
    spotifyApi.setAccessToken(data.body['access_token']);
    console.log('The access token is '   data.body['access_token']);
    console.log('The token expires in '   data.body['expires_in']);
  },
  function(err) {
    console.log('Could not refresh access token', err);
  });
};

  refreshSpotifyToken();
  setInterval(refreshSpotifyToken, 1000 * 60 * 59);
})

CodePudding user response:

You wanted to get the token from the database? is these token for every person? if so you might add memberID from your schema then fetch the token in your command as of following:

const mongoose = require('mongoose');

const tokenSchema = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId, //Sometimes, you dont need to add this it will automatically generate on the mongodb.
  memberID: String
  token: String
});

module.exports = mongoose.model("RefreshToken", tokenSchema);

Then fetch it to your command.

const token = require('path_of_file')

const token_user = await token.findOne({
   memberID: message.author.id
})

then get your token.

console.log(token_user.token) //These how you get the token using memberID

EDIT:

You might can use _id: mongoose.Schema.Types.ObjectId

const token = require('path_of_file')

const token_user = await token.findOne({
   _id: "Your _id from the database" //Copy paste it here
})

console.log(token_user.token)
  • Related