Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Trakt TV Node Authentication
// Open a file in disk with promise
const getJson = (filename) => {
return new Promise((resolve, reject) => {
jsonfile.readFile(filename, function(err, obj) {
if (err) { reject(err); }
resolve(obj);
});
});
};
// Save a File in disk with promise
const saveJson = (obj, fileName) => {
return new Promise((resolve, reject) => {
jsonfile.writeFile(fileName, obj, {spaces: 2, EOL: '\r\n'}, function(err) {
if (err) { reject(err); }
resolve(obj);
});
});
};
// try to get token from json file from disk
getJson("myToken.json")
.then(token => {
// If token is empty, get a new one using Trakt Device Authentication
if (_.isEmpty(token)) {
return trakt.get_codes().then(poll => {
console.log("Please visit in a browser: " + poll.verification_url);
console.log("Use de code: " + poll.user_code);
console.log("I'll wait for you ;)");
// verify if app was authorized
return trakt.poll_access(poll);
});
}
// injects back stored token on new session.
return trakt.import_token(token);
}).then(newTokens => {
// Contains token, refreshed if needed (store it back)
return saveJson(newTokens, "myToken.json");
}).then(() => {
// Get my user to check Trakt is logged in
return trakt.users.profile({
username: 'me',
extended: 'full'
});
}).then(profile => {
_debug("MyTrakt: Logged in");
console.log("Welcome " + profile.data.username);
// console.log(profile);
}).catch(console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment