Skip to content

Instantly share code, notes, and snippets.

scope "/", OauthTutorialWeb do
pipe_through :browser
get "/", PageController, :index
resources "/todos", TodoController
end
schema "todos" do
field :content, :string
belongs_to :user, OauthTutorial.Accounts.User
timestamps()
end
schema "users" do
field :email, :string
field :provider, :string
field :token, :string
has_many :todos, OauthTutorial.Todos.Todo
timestamps()
end
<ul>
<li><a href="https://hexdocs.pm/phoenix/overview.html">Get Started</a></li>
<%= if function_exported?(Routes, :live_dashboard_path, 2) do %>
<li><%= link "LiveDashboard", to: Routes.live_dashboard_path(@conn, :home) %></li>
<% end %>
<%= if @conn.assigns[:user] do %>
<li><%= link "Logout", to: Routes.auth_path(@conn, :signout) %></li>
<% else %>
<li>
<%= link "Sign in with Github", to: Routes.auth_path(@conn, :request, "github") %>
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, {OauthTutorialWeb.LayoutView, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
plug OauthTutorial.Plugs.SetUser
end
defmodule OauthTutorial.Plugs.SetUser do
import Plug.Conn
import Phoenix.Controller
alias OauthTutorial.Repo
alias OauthTutorial.Accounts.User
def init(opts), do: opts
def call(conn, _opts) do
get "/signout", AuthController, :signout
def signout(conn, _params) do
conn
|> configure_session(drop: true)
|> redirect(to: Routes.page_path(conn, :index))
end
def callback(%{assigns: %{ueberauth_auth: auth}} = conn, params) do
user_data = %{token: auth.credentials.token, email: auth.info.email, provider: "github"}
case findOrCreateUser(user_data) do
{:ok, user} ->
conn
|> put_flash(:info, "Welcome to OAuth Tutorial!")
|> put_session(:user_id, user.id)
|> redirect(to: "/")
{:error, changeset} ->
defp findOrCreateUser(user_data) do
changeset = User.changeset(%User{}, user_data)
case Repo.get_by(User, email: changeset.changes.email) do
nil ->
IO.puts("User not found, creating new one")
Repo.insert(changeset)
user -> {:ok, user}
end
end