Skip to content

Instantly share code, notes, and snippets.

@emilsedgh
Last active May 15, 2017 17:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emilsedgh/52b136fb096cf2fae3860706e750e3a0 to your computer and use it in GitHub Desktop.
Save emilsedgh/52b136fb096cf2fae3860706e750e3a0 to your computer and use it in GitHub Desktop.
function login (socket, access_token, cb) {
Token.get(access_token).nodeify(function (err, token) {
if (err)
return cb(err)
if (!token)
return cb(Error.Unauthorized('Invalid credentials'))
if (token.expire_date) {
const expirey = new Date(token.expire_date)
if (expirey < (new Date()).getTime()) {
return cb(Error.Unauthorized('Token expired'))
}
}
if (token.type !== 'access')
return cb(Error.Unauthorized('Invalid credentials'))
User.get(token.user_id, function (err, user) {
if (err)
return cb(err)
if (!user)
return cb(Error.ResourceNotFound('Unknown user'))
process.domain.user = user
socket.user = user
socket.client_id = token.client_id
joinRooms(socket, cb)
})
})
}
const nodeify = promise => {
let callback
const resolve = res => {
callback(null, res)
}
const reject = err => {
callback(err)
}
promise
.then(resolve)
.catch(reject)
return cb => {
callback = cb
}
}
Promise.prototype.nodeify = function(cb) {
return nodeify(this)(cb)
}
Token.get = async token => {
const res = await db.query.promise('token/get', [token])
if (res.rows.length < 1)
throw Error.ResourceNotFound(`Token ${token} not found`)
return res.rows[0]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment