Also allow lookup by email

This commit is contained in:
Max Wofford 2025-03-03 14:51:01 -05:00
parent 466f05c389
commit 0f3f423b27
2 changed files with 26 additions and 1 deletions

View file

@ -4,6 +4,7 @@ PORT=4000
SLACK_CLIENT_ID=your_client_id_here
SLACK_CLIENT_SECRET=your_client_secret_here
SLACK_SIGNING_SECRET=your_signing_secret_here
SLACK_USER_OAUTH_TOKEN=your_user_oauth_token_here
# Sailors' log slack app
SLACK_SAILORS_LOG_SIGNING_SECRET=your_signing_secret_here

View file

@ -10,7 +10,13 @@ class Api::V1::StatsController < ApplicationController
query = Heartbeat
query = query.where(time: start_date..end_date)
query = query.where(user_id: params[:user_id]) if params[:user_id].present?
if params[:user_id].present? || params[:user_email].present?
user_id = params[:user_id] || find_by_email(params[:user_email])
return render plain: "User not found", status: :not_found unless user_id.present?
query = query.where(user_id: params[:user_id]) if params[:user_id].present?
end
render plain: query.duration_seconds
end
@ -23,4 +29,22 @@ class Api::V1::StatsController < ApplicationController
render plain: "Unauthorized", status: :unauthorized unless token == ENV["STATS_API_KEY"]
end
def find_by_email(email)
cache_key = "user_id_by_email/#{email}"
slack_id = Rails.cache.fetch(cache_key, expires_in: 1.week) do
response = HTTP
.auth("Bearer #{ENV["SLACK_USER_OAUTH_TOKEN"]}")
.get("https://slack.com/api/users.lookupByEmail", params: { email: email })
JSON.parse(response.body)["user"]["id"]
rescue => e
Rails.logger.error("Error finding user by email: #{e}")
nil
end
Rails.cache.delete(cache_key) if slack_id.nil?
slack_id
end
end