balena-cli/lib/resin/auth/auth.coffee

40 lines
1003 B
CoffeeScript
Raw Normal View History

2014-11-14 09:51:59 -04:00
async = require('async')
2014-11-17 14:40:32 -04:00
_ = require('lodash')
2014-11-14 09:51:59 -04:00
2014-11-26 13:02:22 -04:00
token = require('../token/token')
server = require('../server/server')
2014-11-14 09:51:59 -04:00
exports.authenticate = (credentials, callback) ->
2014-11-26 13:02:22 -04:00
server.post '/login_', credentials, (error, response) ->
return callback(error, response?.body)
exports.login = (credentials, callback) ->
2014-11-14 09:51:59 -04:00
async.waterfall([
(callback) ->
exports.authenticate(credentials, callback)
(authToken, callback) ->
2014-11-26 13:02:22 -04:00
token.saveToken(authToken, callback)
2014-11-14 09:51:59 -04:00
], callback)
# Handy aliases
2014-11-26 13:02:22 -04:00
exports.isLoggedIn = token.hasToken
exports.getToken = token.getToken
2014-11-14 09:51:59 -04:00
# TODO: Maybe we should post to /logout or something
# like that to invalidate the token on the server?
2014-11-26 13:02:22 -04:00
exports.logout = token.clearToken
2014-11-17 14:40:32 -04:00
2014-11-18 12:11:20 -04:00
exports.parseCredentials = (credentials, callback) ->
2014-11-17 14:40:32 -04:00
result = credentials.split(':')
if result.length isnt 2
2014-11-18 12:11:20 -04:00
error = new Error('Invalid credentials. The expected input is username:password.')
return callback?(error)
2014-11-17 14:40:32 -04:00
2014-11-18 12:11:20 -04:00
callback? null,
2014-11-17 14:40:32 -04:00
username: _.first(result)
password: _.last(result)