|
| 1 | +defmodule CodeCorpsWeb.UserSlimView do |
| 2 | + @moduledoc false |
| 3 | + alias CodeCorps.Presenters.ImagePresenter |
| 4 | + |
| 5 | + use CodeCorpsWeb, :view |
| 6 | + use JaSerializer.PhoenixView |
| 7 | + |
| 8 | + def type, do: "user" |
| 9 | + |
| 10 | + attributes [ |
| 11 | + :biography, :cloudinary_public_id, :email, :first_name, |
| 12 | + :github_avatar_url, :github_id, :github_username, :intercom_user_hash, |
| 13 | + :inserted_at, :last_name, :name, :photo_large_url, :photo_thumb_url, |
| 14 | + :sign_up_context, :state, :state_transition, :twitter, :username, |
| 15 | + :website, :updated_at |
| 16 | + ] |
| 17 | + |
| 18 | + def photo_large_url(user, _conn), do: ImagePresenter.large(user) |
| 19 | + |
| 20 | + def photo_thumb_url(user, _conn), do: ImagePresenter.thumbnail(user) |
| 21 | + |
| 22 | + @doc """ |
| 23 | + Returns the user email or an empty string, depending on the user |
| 24 | + being rendered is the authenticated user, or some other user. |
| 25 | +
|
| 26 | + Users can only see their own emails. Everyone else's are private. |
| 27 | + """ |
| 28 | + def email(user, %Plug.Conn{assigns: %{current_user: current_user}}) do |
| 29 | + if user.id == current_user.id, do: user.email, else: "" |
| 30 | + end |
| 31 | + def email(_user, _conn), do: "" |
| 32 | + |
| 33 | + @intercom_secret_key Application.get_env(:code_corps, :intercom_identity_secret_key) || "RANDOM_KEY" |
| 34 | + |
| 35 | + def intercom_user_hash(%{id: id}, _conn) when is_number(id) do |
| 36 | + id |> Integer.to_string |> do_intercom_user_hash |
| 37 | + end |
| 38 | + # def intercom_user_hash(_user, _conn), do: nil |
| 39 | + |
| 40 | + defp do_intercom_user_hash(id_string) do |
| 41 | + :crypto.hmac(:sha256, @intercom_secret_key, id_string) |
| 42 | + |> Base.encode16 |
| 43 | + |> String.downcase |
| 44 | + end |
| 45 | + |
| 46 | + @doc """ |
| 47 | + Returns the user's full name when both first and last name are present. |
| 48 | + Returns the only user's first name or last name when the other is missing, |
| 49 | + otherwise returns nil. |
| 50 | + """ |
| 51 | + def name(%{first_name: first_name, last_name: last_name}, _conn) do |
| 52 | + "#{first_name} #{last_name}" |> String.trim |> normalize_name |
| 53 | + end |
| 54 | + |
| 55 | + defp normalize_name(name) when name in ["", nil], do: nil |
| 56 | + defp normalize_name(name), do: name |
| 57 | +end |
0 commit comments