Farmbot-Web-App/app/lib/session_token.rb

57 lines
2.2 KiB
Ruby
Raw Normal View History

# Generates a JSON Web Token (JWT) for a given user. Typically placed in the
# `Authorization` header, or used a password to gain access to the MQTT server.
2016-12-01 13:19:00 -07:00
class SessionToken < AbstractJwtToken
2019-03-11 16:54:39 -06:00
MUST_VERIFY = "Verify account first"
MQTT = ENV.fetch("MQTT_HOST")
2018-02-20 09:15:45 -07:00
# No beta URL provided? Then provide the latest stable.
2019-03-11 16:54:39 -06:00
DEFAULT_BETA_URL =
2018-02-20 09:15:45 -07:00
"https://api.github.com/repos/FarmBot/farmbot_os/releases/latest"
2017-10-05 15:42:46 -06:00
# If you are not using the standard MQTT broker (eg: you use a 3rd party
# MQTT vendor), you will need to change this line.
2019-03-11 16:54:39 -06:00
DEFAULT_MQTT_WS =
"#{ENV["FORCE_SSL"] ? "wss://" : "ws://"}#{ENV.fetch("MQTT_HOST")}:3002/ws"
2019-03-11 16:54:39 -06:00
MQTT_WS = ENV["MQTT_WS"] || DEFAULT_MQTT_WS
EXPIRY = 40.days
VHOST = ENV.fetch("MQTT_VHOST") { "/" }
2019-04-04 07:37:52 -06:00
BETA_OS_URL = ENV["BETA_OTA_URL"] || DEFAULT_BETA_URL
DEFAULT_OS = "https://api.github.com/repos/farmbot/farmbot_os/releases" +
"/latest"
2019-03-11 16:54:39 -06:00
# Originally imported from `CalculateVersion` mutation (check source control
# for context) - RC
2019-04-04 07:37:52 -06:00
OS_RELEASE_SERVER = ENV.fetch("OS_UPDATE_SERVER", DEFAULT_OS)
2019-03-11 16:54:39 -06:00
2016-03-24 09:02:48 -06:00
def self.issue_to(user,
iat: Time.now.to_i,
exp: EXPIRY.from_now.to_i,
2017-10-04 13:10:29 -06:00
iss: $API_URL,
aud: AbstractJwtToken::UNKNOWN_AUD,
fbos_version:) # Gem::Version
2017-08-30 09:43:06 -06:00
unless user.verified?
Rollbar.info("Verification Error", email: user.email)
raise Errors::Forbidden, MUST_VERIFY
2017-08-30 09:43:06 -06:00
end
2018-03-28 15:28:21 -06:00
jti = SecureRandom.uuid
TokenIssuance.create!(device_id: user.device.id, exp: exp, jti: jti)
2019-03-11 16:54:39 -06:00
self.new([{ aud: aud,
sub: user.id,
iat: iat,
jti: jti,
iss: iss,
exp: exp,
mqtt: MQTT,
bot: "device_#{user.device.id}",
vhost: VHOST,
mqtt_ws: MQTT_WS,
os_update_server: OS_RELEASE_SERVER,
beta_os_update_server: BETA_OS_URL }])
end
2020-03-25 13:56:43 -06:00
def self.as_json(user, aud, fbos_version, exp = EXPIRY.from_now.to_i)
{ token: SessionToken.issue_to(user, iss: $API_URL,
aud: aud,
2020-03-25 13:56:43 -06:00
exp: exp,
fbos_version: fbos_version),
2019-03-11 16:54:39 -06:00
user: user }
end
end