Skip to content

Commit

Permalink
better error messages for linking mastodon accounts
Browse files Browse the repository at this point in the history
  • Loading branch information
pushcx committed Feb 3, 2024
1 parent f6455c1 commit 5e38360
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
7 changes: 5 additions & 2 deletions app/controllers/settings_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -191,8 +191,11 @@ def mastodon_authentication

def mastodon_auth
app = MastodonApp.find_or_register(params[:mastodon_instance_name])
redirect_to settings_path if app.nil?
redirect_to app.oauth_auth_url, allow_other_host: true
if app.persisted?
redirect_to app.oauth_auth_url, allow_other_host: true
else
redirect_to settings_path, flash: {error: app.errors.full_messages.join(" ")}
end
end

def mastodon_callback
Expand Down
18 changes: 14 additions & 4 deletions app/models/mastodon_app.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ def redirect_uri
"https://#{Rails.application.domain}/settings/mastodon_callback?instance=#{name}"
end

def register_app
# this (if needed) adds errors to the model or saves on success because calling .save after it
# runs will clear these errors
def register_app!
raise "already registered, delete and recreate" if client_id.present?

s = Sponge.new
Expand All @@ -30,13 +32,21 @@ def register_app
scopes: "read:accounts",
website: "https://#{Rails.application.domain}"
)
if res.nil? || res.body.blank?
errors.add :base, "App registration failed, is #{name} a Mastodon instance?"
return
end
js = JSON.parse(res.body)
if js && js["client_id"].present? && js["client_secret"].present?
self.client_id = js["client_id"]
self.client_secret = js["client_secret"]
return save!
end
raise "registration failed, response was #{res.body}"
errors.add :base, "Mastodon instance didn't return a client_id and client_secret"
rescue OpenSSL::SSL::SSLError
errors.add :base, "#{name} isn't a working SSL server"
rescue JSON::ParserError
errors.add :base, "#{name} responded with non-parseable JSON"
end

def token_and_user_from_code(code)
Expand All @@ -51,6 +61,7 @@ def token_and_user_from_code(code)
code: code,
scope: "read:account"
)
raise "mastodon getting user token failed, response from #{name} was nil" if res.nil?
ps = JSON.parse(res.body)
tok = ps["access_token"]

Expand Down Expand Up @@ -98,8 +109,7 @@ def self.find_or_register(instance_name)
return existing if existing.present?

app = new name: name
app.register_app
app.save!
app.register_app!
app
end

Expand Down

0 comments on commit 5e38360

Please sign in to comment.