Skip to content

Instantly share code, notes, and snippets.

@ray-sh
Last active September 30, 2017 02:17
Show Gist options
  • Save ray-sh/1fad2650b8bc8434a7ab113ca81b352b to your computer and use it in GitHub Desktop.
Save ray-sh/1fad2650b8bc8434a7ab113ca81b352b to your computer and use it in GitHub Desktop.
Auth functions
#Function used in auth
#1>Save the user id in session and current_user in conn.assign which will exposed as @current_user for all template
#Deliver pass port to user, user will carry the :user_id in next request
def deliver_passport_to_user(conn,user) do
conn
|>assign(:current_user, user)
|>put_session(:user_id,user.id)
|>configure_session(renew: true) #Renew the session to keep our safe
end
#2>Try to identify the real user, we will use plug module and plug it within the plug pipeline
defmodule Blog.Auth do
import Plug.Conn
def init(ops) do
ops
end
def call(conn, ops) do
user_id = get_session(conn,:user_id)
IO.puts "user ID #{user_id}"
current_user = user_id && Blog.Repo.get(Blog.User, user_id)
assign(conn,:current_user, current_user)
end
end
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
plug :put_secure_browser_headers
plug Blog.Auth
end
#3, We will do check in different controler by define check funcion and plug it
defp auth(conn, _params) do
if conn.assigns.current_user do
conn
else
conn
|>put_flash(:error, "you must login")
|>redirect(to: page_path(conn,:index))
|>halt() #Then next plug will pass through conn and will not handle it
end
end
plug :auth when action in [:index, :show]
#4 Log out, use will leave and the system will get back the pass port to the user
def recycle_passport_back(conn) do
conn
|>configure_session( drop: true)
|> redirect(to: page_path(conn,:index))
end
#Summary, all there function are plugs, we plug them to the whole plug pipeline to implement our function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment