fp/services/bright/lib/bright_web/controllers/auth_controller.ex

93 lines
2.2 KiB
Elixir

defmodule BrightWeb.AuthController do
@moduledoc """
Auth controller responsible for handling Ueberauth responses
"""
require Logger
use BrightWeb, :controller
plug Ueberauth
alias Ueberauth.Strategy.Helpers
alias Bright.UserFromAuth
alias Bright.User
def delete(conn, _params) do
conn
|> put_flash(:info, "You have been logged out!")
|> clear_session()
|> redirect(to: "/")
end
def callback(%{assigns: %{ueberauth_failure: _fails}} = conn, _params) do
conn
|> put_flash(:error, "Failed to authenticate.")
|> redirect(to: "/")
end
# def callback(conn, %{"provider" => provider}) do
# end
def callback(conn = %{assigns: %{ueberauth_auth: auth}}, _params) do
if user = User.get_by_ueberauth(auth) do
sign_in_and_redirect(conn, user, ~p"/~")
else
conn
|> put_flash(:success, "Almost there! Please complete your profile now.")
|> redirect(to: ~p"/join?#{params_from_ueberauth(auth)}")
end
end
defp sign_in_and_redirect(conn, user, route) do
user
|> User.sign_in_changes()
|> Repo.update()
conn
|> assign(:current_user, user)
|> put_flash(:success, "Welcome!")
|> put_session("id", user.id)
|> configure_session(renew: true)
|> redirect(to: route)
end
defp params_from_ueberauth(%{provider: :github, info: info}) do
%{name: info.name, handle: info.nickname, github_handle: info.nickname}
end
defp params_from_ueberauth(%{provider: :patreon, info: info}) do
%{name: info.name, handle: info.nickname, patreon_handle: info.nickname}
end
# case Ueberauth.Auth.fetch!(conn) do
# {:ok, auth} ->
# Logger.info("auth is as follows: #{inspect(auth)}")
# {:error, reason} ->
# conn
# |> put_flash(:error, "Auth failed! #{reason}")
# |> redirect(to: ~p"/")
# end
# case UserFromAuth.find_or_create(auth) do
# {:ok, user} ->
# conn
# |> put_flash(:info, "Successfully authenticated #{inspect(user)}")
# |> put_session(:current_user, user)
# |> configure_session(renew: true)
# |> redirect(to: "/")
# {:error, reason} ->
# conn
# |> put_flash(:error, reason)
# |> redirect(to: "/")
# end
end