19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
# File 'app/controllers/collavre_slack/slack_auth_controller.rb', line 19
def callback
unless params[:code].present?
render json: { error: I18n.t("collavre_slack.errors.missing_oauth_code") }, status: :unprocessable_entity
return
end
unless params[:state].present?
render json: { error: I18n.t("collavre_slack.errors.missing_oauth_state") }, status: :unprocessable_entity
return
end
begin
state_data = message_verifier.verify(params[:state]).with_indifferent_access
Rails.logger.info("[SlackAuth] State data: #{state_data.inspect}")
if state_data[:exp] && Time.at(state_data[:exp]) < Time.current
render json: { error: I18n.t("collavre_slack.errors.invalid_oauth_state") }, status: :unprocessable_entity
return
end
user = ::User.find(state_data[:user_id])
Rails.logger.info("[SlackAuth] Verified user_id=#{user.id} from signed state")
rescue ActiveSupport::MessageVerifier::InvalidSignature => e
Rails.logger.warn("[SlackAuth] Invalid state signature: #{e.message}")
render json: { error: I18n.t("collavre_slack.errors.invalid_oauth_state") }, status: :unprocessable_entity
return
rescue ActiveRecord::RecordNotFound
Rails.logger.warn("[SlackAuth] User not found from state")
render json: { error: I18n.t("collavre_slack.errors.user_not_found") }, status: :unprocessable_entity
return
end
oauth_response = slack_client.oauth_access(code: params[:code], redirect_uri: slack_client.redirect_uri)
if oauth_response[:ok] != true
render json: { error: oauth_response[:error] || I18n.t("collavre_slack.errors.oauth_failed") }, status: :unprocessable_entity
return
end
Rails.logger.info("[SlackAuth] OAuth response: team=#{oauth_response.dig(:team, :id)}, user=#{user&.id}")
account = SlackAccount.find_or_initialize_by(team_id: oauth_response.dig(:team, :id))
account.user ||= user
account.team_name = oauth_response.dig(:team, :name)
account.access_token = oauth_response[:access_token]
account.authed_user_id = oauth_response.dig(:authed_user, :id)
account.scopes = oauth_response[:scope]
if account.save
render template: "collavre_slack/slack_auth/callback_success", layout: false
else
Rails.logger.error("[SlackAuth] Failed to save account: #{account.errors.full_messages.join(', ')}")
render json: { error: I18n.t("collavre_slack.errors.save_failed", errors: account.errors.full_messages.join(", ")) }, status: :unprocessable_entity
end
end
|