This repository has been archived by the owner on Sep 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
_facebook-session-cookie.coffee
75 lines (63 loc) · 2.13 KB
/
_facebook-session-cookie.coffee
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
crypto = require 'crypto'
class FBSession
constructor: (@app_id, @app_secret, @domain) ->
@state = 'logged_out'
initialize: (req) =>
@req = req
@_eatCookie req
req.fb_session = if @isLoggedIn() then this else null
getId: => @params?.uid
getAccessToken: => @params?.access_token
getParams: => @params
# TODO this doesn't log the user out of facebook so
# for now let's keep the logout shit on the client side
# logout: () =>
# res.setCookie 'fbs_'+@app_id, '',
# domain: @domain,
# expires: new Date( new Date().getTime() - 30 * 24 * 60 * 60 * 1000 )
isLoggedIn: -> @state is 'logged_in'
_getSignature: (params) =>
hash = crypto.createHash 'md5'
keys = Object.keys(params).sort()
payload = ""
payload += "#{key}=#{value}" for key, value of params
payload += @app_secret
hash.update payload
return hash.digest 'hex'
_verifyFBSession: (session) =>
verify_signature = session.sig
delete session.sig
return verify_signature is @_getSignature(session)
# taken from connect's cookieDecoder middleware.
_getCookies: (req) =>
cookies = {}
header = req.headers.cookie
return cookies unless header
pairs = header.split /[;,] */
for pair in pairs
eqlIndex = pair.indexOf '='
key = pair.substr(0, eqlIndex).trim().toLowerCase()
val = pair.substr(++eqlIndex, pair.length).trim()
if val[0] is '"'
val = val.slice(1, -1)
if cookies[key] is undefined
cookies[key] = require('querystring').unescape(val, true)
return cookies
_eatCookie: (req) =>
cookies = req.cookies or @_getCookies req
cookie = cookies["fbs_#{@app_id}"]
return false unless cookie
params = require('querystring').parse cookie
if @_verifyFBSession(params)
@state = 'logged_in'
@params = params
return true
else return false
# Hook up this middleware and you're set
module.exports = (fb_app_id, fb_app_secret, domain) ->
return ((req, res, next) ->
fb_session = new FBSession(fb_app_id, fb_app_secret, domain)
fb_session.initialize req
next()
)
module.exports.FBSession = FBSession