balena-cli/lib/auth/auth.coffee

39 lines
990 B
CoffeeScript
Raw Normal View History

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