This repository has been archived on 2024-04-29. You can view files and clone it, but cannot push or open issues or pull requests.
node-fftcg/backend/session.coffee

63 lines
1.6 KiB
CoffeeScript
Raw Normal View History

# node libraries
redis = (require 'redis')
crypto = (require 'crypto')
logger = (require 'logging').default 'session'
2019-05-08 16:45:24 +00:00
# expiry times in days
EXPIRY =
2019-02-16 18:03:21 +00:00
# games expire 1 week after creation
2019-05-08 16:45:24 +00:00
game: 7
# logins expire 1 month after last action
2019-05-08 16:45:24 +00:00
login: 30
2019-02-16 18:15:49 +00:00
class FFTCGSESSION
constructor: ->
@db = redis.createClient
host: 'redis'
port: 6379
2019-02-19 20:36:14 +00:00
@db.on 'error', (err) =>
2019-02-16 18:15:49 +00:00
logger.error err.message
start: (data) ->
new Promise (resolve) =>
# hash data
hmac = crypto.createHmac 'sha256', Math.random().toString()
hmac.update (JSON.stringify data)
digest = hmac.digest 'base64'
logger.debug 'digest', digest
# push (hash, data) into DB for the configured timespan
2019-05-08 16:45:24 +00:00
@db.setex digest, EXPIRY.login * 86400, (JSON.stringify data), (err) ->
2019-02-19 18:57:22 +00:00
logger.info "OK '#{digest}' created"
2019-05-08 16:45:24 +00:00
# return cookie data
resolve
value: digest
properties:
expires: EXPIRY.login
2019-02-16 18:15:49 +00:00
2019-05-07 20:15:18 +00:00
destroy: (digest) ->
new Promise (resolve, reject) =>
# delete hash immediately
@db.del digest, (err, res) ->
if res == 0
reject null
else
logger.info "OK '#{digest}' deleted"
resolve null
2019-02-16 18:15:49 +00:00
check: (digest) ->
new Promise (resolve, reject) =>
# refresh expiry timer on digest
2019-05-08 16:45:24 +00:00
@db.expire digest, EXPIRY.login * 86400, (err, res) =>
2019-02-16 18:15:49 +00:00
if res == 0
reject null
else
@db.get digest, (err, res) ->
2019-02-19 18:57:22 +00:00
logger.info "OK '#{digest}' resumed"
2019-05-07 15:37:07 +00:00
resolve digest
2019-02-19 18:57:22 +00:00
module.exports = new FFTCGSESSION