forked from twitchdev/authentication-node-sample
/
index.js
executable file
·111 lines (92 loc) · 3.97 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*
Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
// Define our dependencies
var express = require('express');
var session = require('express-session');
var passport = require('passport');
var OAuth2Strategy = require('passport-oauth').OAuth2Strategy;
var request = require('request');
var handlebars = require('handlebars');
// Define our constants, you will change these with your own
const TWITCH_CLIENT_ID = '<YOUR CLIENT ID HERE>';
const TWITCH_SECRET = '<YOUR CLIENT SECRET HERE>';
const SESSION_SECRET = '<SOME SECRET HERE>';
const CALLBACK_URL = '<YOUR REDIRECT URL HERE>'; // You can run locally with - http://localhost:3000/auth/twitch/callback
// Initialize Express and middlewares
var app = express();
app.use(session({secret: SESSION_SECRET, resave: false, saveUninitialized: false}));
app.use(express.static('public'));
app.use(passport.initialize());
app.use(passport.session());
// Override passport profile function to get user profile from Twitch API
OAuth2Strategy.prototype.userProfile = function(accessToken, done) {
var options = {
url: 'https://api.twitch.tv/helix/users',
method: 'GET',
headers: {
'Client-ID': TWITCH_CLIENT_ID,
'Accept': 'application/vnd.twitchtv.v5+json',
'Authorization': 'Bearer ' + accessToken
}
};
request(options, function (error, response, body) {
if (response && response.statusCode == 200) {
done(null, JSON.parse(body));
} else {
done(JSON.parse(body));
}
});
}
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
passport.use('twitch', new OAuth2Strategy({
authorizationURL: 'https://id.twitch.tv/oauth2/authorize',
tokenURL: 'https://id.twitch.tv/oauth2/token',
clientID: TWITCH_CLIENT_ID,
clientSecret: TWITCH_SECRET,
callbackURL: CALLBACK_URL,
state: true
},
function(accessToken, refreshToken, profile, done) {
profile.accessToken = accessToken;
profile.refreshToken = refreshToken;
// Securely store user profile in your DB
//User.findOrCreate(..., function(err, user) {
// done(err, user);
//});
done(null, profile);
}
));
// Set route to start OAuth link, this is where you define scopes to request
app.get('/auth/twitch', passport.authenticate('twitch', { scope: 'user_read' }));
// Set route for OAuth redirect
app.get('/auth/twitch/callback', passport.authenticate('twitch', { successRedirect: '/', failureRedirect: '/' }));
// Define a simple template to safely generate HTML with values from user's profile
var template = handlebars.compile(`
<html><head><title>Twitch Auth Sample</title></head>
<table>
<tr><th>Access Token</th><td>{{accessToken}}</td></tr>
<tr><th>Refresh Token</th><td>{{refreshToken}}</td></tr>
<tr><th>Display Name</th><td>{{display_name}}</td></tr>
<tr><th>Bio</th><td>{{bio}}</td></tr>
<tr><th>Image</th><td>{{logo}}</td></tr>
</table></html>`);
// If user has an authenticated session, display it, otherwise display link to authenticate
app.get('/', function (req, res) {
if(req.session && req.session.passport && req.session.passport.user) {
res.send(template(req.session.passport.user));
} else {
res.send('<html><head><title>Twitch Auth Sample</title></head><a href="/auth/twitch"><img src="http://ttv-api.s3.amazonaws.com/assets/connect_dark.png"></a></html>');
}
});
app.listen(3000, function () {
console.log('Twitch auth sample listening on port 3000!')
});