Quantcast
Channel: 一言多いプログラマーの独り言
Viewing all articles
Browse latest Browse all 846

「Phoenix」フレームワークでユーザー認証(ヘルパー)

$
0
0
Phoenix」フレームワークでユーザー認証ヘルパーです。ログインユーザー情報をテンプレート上で扱えるようになります。ソースを見れば、何となく分かるのですが、書き方がエレガントすぎて、ついていけません(笑)。

/web/models/session.ex(モデル)

def current_user(conn) do
id = Plug.Conn.get_session(conn, :current_user)
if id, do: HelloPhoenix.Repo.get(User, id)
end

def logged_in?(conn), do: !!current_user(conn)
/web/web.ex

def view do
quote do
import HelloPhoenix.Session, only: [current_user: 1, logged_in?: 1]
end
end
/web/templates/layout/app.html.eex(テンプレート)

<%= if logged_in?(@conn) do %>
<p><%= current_user(@conn).email %></p>
<p><%= link "ログアウト", to: session_path(@conn, :delete), method: :delete %></p>
<% else %>
<p><%= link "ログイン", to: "/login" %></p>
<p><%= link "会員登録", to: registration_path(@conn, :new) %></p>
<% end %>

参考サイト
User Authentication from Scratch in Elixir and Phoenix(Nithin Bekalさん)

Viewing all articles
Browse latest Browse all 846

Trending Articles