]>
git.r.bdr.sh - rbdr/dasein/blob - lib/handlers/auth.js
d16e15de24b17a3dfe2ce998bd05a0f80f5d69d6
3 const Co
= require('co');
4 const TwitterHelper
= require('../twitter_helper');
5 const JsonWebToken
= require('jsonwebtoken');
6 const Pify
= require('pify');
10 internals
.kRedirectUrl
= 'https://api.twitter.com/oauth/authenticate?oauth_token=';
11 internals
.kMainLocation
= '/';
13 internals
.signJsonWebToken
= Pify(JsonWebToken
.sign
);
15 module
.exports
= internals
.AuthHandler
= class AuthHandler
{
19 this._twitterHelper
= new TwitterHelper(config
.twitter
);
20 this._jwtConfig
= config
.jwt
;
21 this._hostname
= config
.hostname
;
26 const twitterHelper
= this._twitterHelper
;
28 return function *handleLogin() {
30 if (this.state
.user
) {
31 return this.redirect(internals
.kMainLocation
);
34 const requestToken
= yield twitterHelper
.getRequestToken();
35 this.redirect(`${internals.kRedirectUrl}${requestToken.oAuthToken}`);
43 return function *handleCallback() {
45 if (this.request
.query
.denied
) {
46 return this.throw(401);
49 const oAuthToken
= this.request
.query
.oauth_token
;
50 const oAuthVerifier
= this.request
.query
.oauth_verifier
;
54 const accessToken
= yield self
._twitterHelper
.getAccessToken(oAuthToken
, oAuthVerifier
);
55 user
= yield self
._twitterHelper
.getUser(accessToken
.oAuthAccessToken
, accessToken
.oAuthAccessTokenSecret
);
58 console
.error(err
.stack
|| err
.message
|| err
);
59 return this.throw(401);
62 yield self
._setJWT(user
, this);
64 this.redirect(internals
.kMainLocation
);
72 return function * () {
74 this.cookies
.set(self
._jwtConfig
.cookieName
, null);
75 this.redirect(internals
.kMainLocation
);
79 // Sets a JSON Web Token Cookie
80 _setJWT(payload
, context
) {
84 return Co(function * () {
86 const token
= yield internals
.signJsonWebToken(payload
, self
._jwtConfig
.secret
, {
87 expiresIn: self
._jwtConfig
.duration
90 context
.cookies
.set(self
._jwtConfig
.cookieName
, token
, {
91 maxAge: self
._jwtConfig
.duration
* 1000,
93 domain: self
._hostname
,