Skip to content

Instantly share code, notes, and snippets.

@jpbecotte
Last active June 22, 2016 17:15
Show Gist options
  • Save jpbecotte/e59392e09f0ff5dce232c90f897d54a4 to your computer and use it in GitHub Desktop.
Save jpbecotte/e59392e09f0ff5dce232c90f897d54a4 to your computer and use it in GitHub Desktop.
Elixir code exemple with unsafe (user) variable to be ported for version 1.3
def create(conn, %{"fb_token" => fb_token, "version" => version}) do #from API
if ! version_check(conn, version) do
send_bad_version(conn)
else
Facebook.Config.appsecret "xxxxxxxx"
Facebook.Config.graph_url "https://graph.facebook.com/"
{:json, data} = Facebook.me("email,name", fb_token)
Logger.debug "FB API CALL returns: #{inspect(data)}"
user = Repo.get_by(User, facebook_id: data["id"])
if user == nil do
changeset = User.changeset_fb(%User{}, %{
name: data["name"],
email: data["email"],
facebook_id: data["id"]
})
if changeset.valid? do
{:ok, user} = Repo.insert changeset
end
end
if user != nil do
conn
|> put_session(:current_user, user.id)
|> json(%{
status: "authorized",
id: user.id,
email: user.email,
name: user.name,
socket_token: Phoenix.Token.sign(conn, "user", user.id)
})
else
conn
|> json(%{status: "something went wrong"})
end
end
end
@frahugo
Copy link

frahugo commented Jun 22, 2016

def create(conn, %{"fb_token" => fb_token, "version" => "1"}) do #from API
  result = 
    fetch_facebook_data
    |> fetch_or_create_user

  case result
    {:ok, user} ->
      conn
      |> put_session(:current_user, user.id)
      |> as_json(user)
    {:error, _error} ->
      conn |> json(%{status: "something went wrong"})
  end
end
def create(conn, %{"version" => _}), do: send_bad_version(conn)

defp facebook_data do
  try do
    Facebook.Config.appsecret "xxxxxxxx"
    Facebook.Config.graph_url "https://graph.facebook.com/"

    case Facebook.me("email,name", fb_token) do
      {:json, data} ->
        Logger.debug "FB API CALL returns: #{inspect(data)}"
        data
      {:error, error} -> {:error, error} # is this the tuple returned by Facebook.me when error?
    end
  rescue
    e in RuntimeError -> {:error, e}
  end
end

defp fetch_or_create_user({:ok, facebook_data}) do
  Repo.get_by(User, facebook_id: facebook_data["id"])
  |> create_user(facebook_data)
end
defp fetch_or_create_user({:error, facebook_error}), do: {:error, facebook_error}

defp create_user(nil, facebook_data) do
  attributes = Map.take(facebook_data, ["name", "email", "id"]) 

  %User{}
  |> User.changeset_fb(attributes)
  |> Repo.insert
end
defp create_user(user, data), do: {:ok, user}

defp as_json(conn, user) do
  data = %{
    status: "authorized",
    id: user.id,
    email: user.email,
    name: user.name,
    socket_token: Phoenix.Token.sign(conn, "user", user.id)
  }

  json(conn, data)
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment