Skip to content
This repository has been archived by the owner on Sep 27, 2022. It is now read-only.

Commit

Permalink
Upgrade Guardian to 1.0 (#11)
Browse files Browse the repository at this point in the history
* Implements RealWorldWeb.Guardian
* Implements RealWorldWeb.GuardedController
* Changes all the function call as defined on the new version
* Upgrade Guardian to 1.0.0 (was 0.14.5), Mime to 1.2.0 (was 1.1.0) and Uuid to 1.1.8 (was 1.1.7)
  • Loading branch information
Rafael Soares dos Santos authored and lbighetti committed Jan 20, 2018
1 parent 50d1971 commit 46ab9c7
Show file tree
Hide file tree
Showing 18 changed files with 108 additions and 65 deletions.
10 changes: 5 additions & 5 deletions config/config.exs
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,14 @@ config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:request_id]

config :guardian, Guardian,
allowed_algos: ["HS256"],
config :real_world, RealWorldWeb.Guardian,
issuer: "RealWorld",
secret_key: "MDLMflIpKod5YCnkdiY7C4E3ki2rgcAAMwfBl0+vyC5uqJNgoibfQmAh7J3uZWVK",
# optional
allowed_algos: ["HS256"],
ttl: { 30, :days },
allowed_drift: 2000,
verify_issuer: true, # optional
secret_key: "MDLMflIpKod5YCnkdiY7C4E3ki2rgcAAMwfBl0+vyC5uqJNgoibfQmAh7J3uZWVK",
serializer: RealWorld.GuardianSerializer
verify_issuer: true

# Configure bcrypt for passwords
config :comeonin, :bcrypt_log_rounds, 4
Expand Down
14 changes: 0 additions & 14 deletions lib/real_world/guardian_serializer.ex

This file was deleted.

25 changes: 12 additions & 13 deletions lib/real_world_web/controllers/article_controller.ex
Original file line number Diff line number Diff line change
@@ -1,32 +1,31 @@
defmodule RealWorldWeb.ArticleController do
use RealWorldWeb, :controller
use Guardian.Phoenix.Controller
use RealWorldWeb.GuardedController

alias RealWorld.{Blog, Repo}
alias RealWorld.Blog.{Article, Favorite}

action_fallback RealWorldWeb.FallbackController

plug Guardian.Plug.EnsureAuthenticated,
%{handler: RealWorldWeb.SessionController} when action in [
:create, :update, :delete, :favorite
]
plug Guardian.Plug.EnsureAuthenticated when action in [
:create, :update, :delete, :favorite
]

def index(conn, _params, user, _full_claims) do
def index(conn, _params, user) do
articles = Blog.list_articles()
|> Repo.preload([:author, :favorites])
|> Blog.load_favorites(user)
render(conn, "index.json", articles: articles)
end

def feed(conn, _params, user, _full_claims) do
def feed(conn, _params, user) do
articles = user
|> Blog.feed
|> Repo.preload([:author, :favorites])
render(conn, "index.json", articles: articles)
end

def create(conn, %{"article" => params}, user, _full_claims) do
def create(conn, %{"article" => params}, user) do
with {:ok, %Article{} = article} <- Blog.create_article(create_params(params, user)) do
article = article
|> Repo.preload([:author, :favorites])
Expand All @@ -43,7 +42,7 @@ defmodule RealWorldWeb.ArticleController do
|> Map.merge(%{"user_id" => user.id})
end

def show(conn, %{"id" => slug}, user, _full_claims) do
def show(conn, %{"id" => slug}, user) do
article = slug
|> Blog.get_article_by_slug!
|> Repo.preload([:author, :favorites])
Expand All @@ -52,7 +51,7 @@ defmodule RealWorldWeb.ArticleController do
render(conn, "show.json", article: article)
end

def update(conn, %{"id" => id, "article" => article_params}, user, _full_claims) do
def update(conn, %{"id" => id, "article" => article_params}, user) do
article = id
|> Blog.get_article!
|> Repo.preload([:author, :favorites])
Expand All @@ -63,7 +62,7 @@ defmodule RealWorldWeb.ArticleController do
end
end

def favorite(conn, %{"slug" => slug}, user, _) do
def favorite(conn, %{"slug" => slug}, user) do
article = slug
|> Blog.get_article_by_slug!

Expand All @@ -76,7 +75,7 @@ defmodule RealWorldWeb.ArticleController do
end
end

def unfavorite(conn, %{"slug" => slug}, user, _) do
def unfavorite(conn, %{"slug" => slug}, user) do
article = slug
|> Blog.get_article_by_slug!

Expand All @@ -89,7 +88,7 @@ defmodule RealWorldWeb.ArticleController do
end
end

def delete(conn, %{"id" => slug}, _user, _full_claims) do
def delete(conn, %{"id" => slug}, _user) do
Blog.delete_article(slug)
send_resp(conn, :no_content, "")
end
Expand Down
14 changes: 7 additions & 7 deletions lib/real_world_web/controllers/comment_controller.ex
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
defmodule RealWorldWeb.CommentController do
use RealWorldWeb, :controller
use Guardian.Phoenix.Controller
use RealWorldWeb.GuardedController

alias RealWorld.Blog
alias RealWorld.Blog.Comment

action_fallback RealWorldWeb.FallbackController

plug Guardian.Plug.EnsureAuthenticated, %{handler: RealWorldWeb.SessionController} when action in [:create, :update, :delete]
plug Guardian.Plug.EnsureAuthenticated when action in [:create, :update, :delete]

def index(conn, %{"article_id" => slug}, _user, _full_claims) do
def index(conn, %{"article_id" => slug}, _user) do
article = Blog.get_article_by_slug!(slug)
comments = Blog.list_comments(article)

comments =
comments
|> RealWorld.Repo.preload(:author)
render(conn, "index.json", comments: comments)
end

def create(conn, %{"article_id" => slug, "comment" => comment_params}, user, _full_claims) do
def create(conn, %{"article_id" => slug, "comment" => comment_params}, user) do
article = Blog.get_article_by_slug!(slug)
with {:ok, %Comment{} = comment} <- Blog.create_comment(comment_params |> Map.merge(%{"user_id" => user.id}) |> Map.merge(%{"article_id" => article.id})) do
conn
Expand All @@ -28,15 +28,15 @@ defmodule RealWorldWeb.CommentController do
end
end

def update(conn, %{"id" => id, "comment" => comment_params}, user, _full_claims) do
def update(conn, %{"id" => id, "comment" => comment_params}, _user) do
comment = Blog.get_comment!(id)

with {:ok, %Comment{} = comment} <- Blog.update_comment(comment, comment_params) do
render(conn, "show.json", comment: comment)
end
end

def delete(conn, %{"id" => id}, _user, _full_claims) do
def delete(conn, %{"id" => id}, _user) do
comment = Blog.get_comment!(id)
with {:ok, %Comment{}} <- Blog.delete_comment(comment) do
send_resp(conn, :no_content, "")
Expand Down
10 changes: 5 additions & 5 deletions lib/real_world_web/controllers/profile_controller.ex
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
defmodule RealWorldWeb.ProfileController do
use RealWorldWeb, :controller
use Guardian.Phoenix.Controller
use RealWorldWeb.GuardedController

alias RealWorld.Accounts.{Users, User}

action_fallback RealWorldWeb.FallbackController

plug Guardian.Plug.EnsureAuthenticated, %{handler: RealWorldWeb.SessionController} when action in [:follow, :unfollow]
plug Guardian.Plug.EnsureAuthenticated when action in [:follow, :unfollow]

def show(conn, %{"username" => username}, current_user, _) do
def show(conn, %{"username" => username}, current_user) do
case Users.get_by_username(username) do
user = %User{} ->
conn
Expand All @@ -21,7 +21,7 @@ defmodule RealWorldWeb.ProfileController do
end
end

def follow(conn, %{"username" => username}, current_user, _) do
def follow(conn, %{"username" => username}, current_user) do
case Users.get_by_username(username) do
followee = %User{} ->
current_user
Expand All @@ -37,7 +37,7 @@ defmodule RealWorldWeb.ProfileController do
end
end

def unfollow(conn, %{"username" => username}, current_user, _) do
def unfollow(conn, %{"username" => username}, current_user) do
case Users.get_by_username(username) do
followee = %User{} ->
current_user
Expand Down
4 changes: 2 additions & 2 deletions lib/real_world_web/controllers/session_controller.ex
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ defmodule RealWorldWeb.SessionController do
def create(conn, params) do
case Auth.find_user_and_check_password(params) do
{:ok, user} ->
{:ok, jwt, _full_claims} = user |> Guardian.encode_and_sign(:token)
{:ok, jwt, _full_claims} = user |> RealWorldWeb.Guardian.encode_and_sign(%{}, token_type: :token)

conn
|> put_status(:created)
Expand All @@ -20,7 +20,7 @@ defmodule RealWorldWeb.SessionController do
end
end

def unauthenticated(conn, _params) do
def auth_error(conn, {_type, _reason}, _opts) do
conn
|> put_status(:forbidden)
|> render(RealWorldWeb.UserView, "error.json", message: "Not Authenticated")
Expand Down
16 changes: 8 additions & 8 deletions lib/real_world_web/controllers/user_controller.ex
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
defmodule RealWorldWeb.UserController do
use RealWorldWeb, :controller
use Guardian.Phoenix.Controller
use RealWorldWeb.GuardedController

alias RealWorld.Accounts.{Auth, Users}

action_fallback RealWorldWeb.FallbackController

plug Guardian.Plug.EnsureAuthenticated, %{handler: RealWorldWeb.SessionController} when action in [:current_user, :update]
plug Guardian.Plug.EnsureAuthenticated when action in [:current_user, :update]

def create(conn, %{"user" => user_params}, _, _) do
def create(conn, %{"user" => user_params}, _) do
case Auth.register(user_params) do
{:ok, user} ->
{:ok, jwt, _full_claims} = user |> Guardian.encode_and_sign(:token)
{:ok, jwt, _full_claims} = user |> RealWorldWeb.Guardian.encode_and_sign(%{}, token_type: :token)

conn
|> put_status(:created)
Expand All @@ -21,8 +21,8 @@ defmodule RealWorldWeb.UserController do
end
end

def current_user(conn, _params, user, _) do
jwt = Guardian.Plug.current_token(conn)
def current_user(conn, _params, user) do
jwt = RealWorldWeb.Guardian.Plug.current_token(conn)

if user != nil do
render(conn, "show.json", jwt: jwt, user: user)
Expand All @@ -37,8 +37,8 @@ defmodule RealWorldWeb.UserController do
|> render("show.json", jwt: jwt, user: user)
end

def update(conn, %{"user" => user_params}, user, _) do
jwt = Guardian.Plug.current_token(conn)
def update(conn, %{"user" => user_params}, user) do
jwt = RealWorldWeb.Guardian.Plug.current_token(conn)

case Users.update_user(user, user_params) do
{:ok, user} ->
Expand Down
36 changes: 36 additions & 0 deletions lib/real_world_web/guarded_controller.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
defmodule RealWorldWeb.GuardedController do
@moduledoc """
Use this module in a controller to take the advantage of having
the subject of authentication (eg.: an authenticated user) injected
in the action as the third argument.
## Usage example
defmodule RealWorldWeb.MyController do
use RealWorldWeb, :controller
use RealWorldWeb.GuardedController
plug Guardian.Plug.EnsureAuthenticated
def index(conn, params, current_user) do
# ..code..
end
end
"""

defmacro __using__(_opts \\ []) do
quote do
def action(conn, _opts) do
apply(
__MODULE__,
action_name(conn),
[
conn,
conn.params,
RealWorldWeb.Guardian.Plug.current_resource(conn)
]
)
end
end
end
end
20 changes: 20 additions & 0 deletions lib/real_world_web/guardian.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
defmodule RealWorldWeb.Guardian do
@moduledoc """
This module is required by Guardian, to implements all type or configuration for
the auth token.
Also, is used to retrieve and deliver the authentication subject to Guardian.
More details here: https://github.com/ueberauth/guardian#installation
"""

use Guardian, otp_app: :real_world

alias RealWorld.{Repo, Accounts.User}

def subject_for_token(%User{} = user, _claims), do: {:ok, to_string(user.id)}
def subject_for_token(_, _), do: {:error, "Unknown resource type"}

def resource_from_claims(%{"sub" => user_id}), do: {:ok, Repo.get(User, user_id)}
def resource_from_claims(_claims), do: {:error, "Unknown resource type"}
end
4 changes: 3 additions & 1 deletion lib/real_world_web/router.ex
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ defmodule RealWorldWeb.Router do
pipeline :api do
plug :accepts, ["json"]
plug ProperCase.Plug.SnakeCaseParams
plug Guardian.Plug.Pipeline, error_handler: RealWorldWeb.SessionController,
module: RealWorldWeb.Guardian
plug Guardian.Plug.VerifyHeader, realm: "Token"
plug Guardian.Plug.LoadResource
plug Guardian.Plug.LoadResource, allow_blank: true
end

scope "/", RealWorldWeb do
Expand Down
2 changes: 1 addition & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ defmodule RealWorld.Mixfile do
{:proper_case, "~> 1.0.0"},
{:cowboy, "~> 1.1"},
{:comeonin, "~> 3.2"},
{:guardian, "~> 0.14.5"},
{:guardian, "~> 1.0"},
{:excoveralls, "~> 0.7", only: [:dev, :test]},
{:credo, "~> 0.8.5", only: [:dev, :test]},
{:ex_machina, "~> 2.0", only: :test},
Expand Down
6 changes: 3 additions & 3 deletions mix.lock
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@
"exjsx": {:hex, :exjsx, "4.0.0", "60548841e0212df401e38e63c0078ec57b33e7ea49b032c796ccad8cde794b5c", [:mix], [{:jsx, "~> 2.8.0", [hex: :jsx, repo: "hexpm", optional: false]}], "hexpm"},
"fs": {:hex, :fs, "0.9.2", "ed17036c26c3f70ac49781ed9220a50c36775c6ca2cf8182d123b6566e49ec59", [:rebar], [], "hexpm"},
"gettext": {:hex, :gettext, "0.13.1", "5e0daf4e7636d771c4c71ad5f3f53ba09a9ae5c250e1ab9c42ba9edccc476263", [:mix], []},
"guardian": {:hex, :guardian, "0.14.5", "6d4e89b673accdacbc092ad000dc7494019426bd898eebf699caf1d19000cdcd", [:mix], [{:jose, "~> 1.8", [hex: :jose, repo: "hexpm", optional: false]}, {:phoenix, "~> 1.2 and < 1.4.0", [hex: :phoenix, repo: "hexpm", optional: true]}, {:plug, "~> 1.3", [hex: :plug, repo: "hexpm", optional: false]}, {:poison, ">= 1.3.0 and < 4.0.0", [hex: :poison, repo: "hexpm", optional: false]}, {:uuid, ">=1.1.1", [hex: :uuid, repo: "hexpm", optional: false]}], "hexpm"},
"guardian": {:hex, :guardian, "1.0.0", "21bae2a8c0b4ed5943d9da0c6aeb16e52874c1f675de5d7920ae35471c6263f9", [:mix], [{:jose, "~> 1.8", [hex: :jose, repo: "hexpm", optional: false]}, {:phoenix, "~> 1.0 or ~> 1.2 or ~> 1.3", [hex: :phoenix, repo: "hexpm", optional: true]}, {:plug, "~> 1.3.3 or ~> 1.4", [hex: :plug, repo: "hexpm", optional: true]}, {:poison, "~> 2.2 or ~> 3.0", [hex: :poison, repo: "hexpm", optional: false]}, {:uuid, ">= 1.1.1", [hex: :uuid, repo: "hexpm", optional: false]}], "hexpm"},
"hackney": {:hex, :hackney, "1.9.0", "51c506afc0a365868469dcfc79a9d0b94d896ec741cfd5bd338f49a5ec515bfe", [:rebar3], [{:certifi, "2.0.0", [hex: :certifi, repo: "hexpm", optional: false]}, {:idna, "5.1.0", [hex: :idna, repo: "hexpm", optional: false]}, {:metrics, "1.0.1", [hex: :metrics, repo: "hexpm", optional: false]}, {:mimerl, "1.0.2", [hex: :mimerl, repo: "hexpm", optional: false]}, {:ssl_verify_fun, "1.1.1", [hex: :ssl_verify_fun, repo: "hexpm", optional: false]}], "hexpm"},
"idna": {:hex, :idna, "5.1.0", "d72b4effeb324ad5da3cab1767cb16b17939004e789d8c0ad5b70f3cea20c89a", [:rebar3], [{:unicode_util_compat, "0.3.1", [hex: :unicode_util_compat, repo: "hexpm", optional: false]}], "hexpm"},
"jose": {:hex, :jose, "1.8.4", "7946d1e5c03a76ac9ef42a6e6a20001d35987afd68c2107bcd8f01a84e75aa73", [:mix, :rebar3], [{:base64url, "~> 0.0.1", [hex: :base64url, repo: "hexpm", optional: false]}], "hexpm"},
"jsx": {:hex, :jsx, "2.8.2", "7acc7d785b5abe8a6e9adbde926a24e481f29956dd8b4df49e3e4e7bcc92a018", [:mix, :rebar3], []},
"metrics": {:hex, :metrics, "1.0.1", "25f094dea2cda98213cecc3aeff09e940299d950904393b2a29d191c346a8486", [:rebar3], []},
"mime": {:hex, :mime, "1.1.0", "01c1d6f4083d8aa5c7b8c246ade95139620ef8effb009edde934e0ec3b28090a", [:mix], []},
"mime": {:hex, :mime, "1.2.0", "78adaa84832b3680de06f88f0997e3ead3b451a440d183d688085be2d709b534", [:mix], [], "hexpm"},
"mimerl": {:hex, :mimerl, "1.0.2", "993f9b0e084083405ed8252b99460c4f0563e41729ab42d9074fd5e52439be88", [:rebar3], []},
"phoenix": {:hex, :phoenix, "1.3.0", "1c01124caa1b4a7af46f2050ff11b267baa3edb441b45dbf243e979cd4c5891b", [:mix], [{:cowboy, "~> 1.0", [hex: :cowboy, repo: "hexpm", optional: true]}, {:phoenix_pubsub, "~> 1.0", [hex: :phoenix_pubsub, repo: "hexpm", optional: false]}, {:plug, "~> 1.3.3 or ~> 1.4", [hex: :plug, repo: "hexpm", optional: false]}, {:poison, "~> 2.2 or ~> 3.0", [hex: :poison, repo: "hexpm", optional: false]}], "hexpm"},
"phoenix_ecto": {:hex, :phoenix_ecto, "3.2.3", "450c749876ff1de4a78fdb305a142a76817c77a1cd79aeca29e5fc9a6c630b26", [:mix], [{:ecto, "~> 2.1", [hex: :ecto, optional: false]}, {:phoenix_html, "~> 2.9", [hex: :phoenix_html, optional: true]}, {:plug, "~> 1.0", [hex: :plug, optional: false]}]},
Expand All @@ -37,4 +37,4 @@
"ranch": {:hex, :ranch, "1.3.2", "e4965a144dc9fbe70e5c077c65e73c57165416a901bd02ea899cfd95aa890986", [:rebar3], []},
"ssl_verify_fun": {:hex, :ssl_verify_fun, "1.1.1", "28a4d65b7f59893bc2c7de786dec1e1555bd742d336043fe644ae956c3497fbe", [:make, :rebar], []},
"unicode_util_compat": {:hex, :unicode_util_compat, "0.3.1", "a1f612a7b512638634a603c8f401892afbf99b8ce93a45041f8aaca99cadb85e", [], [], "hexpm"},
"uuid": {:hex, :uuid, "1.1.7", "007afd58273bc0bc7f849c3bdc763e2f8124e83b957e515368c498b641f7ab69", [:mix], []}}
"uuid": {:hex, :uuid, "1.1.8", "e22fc04499de0de3ed1116b770c7737779f226ceefa0badb3592e64d5cfb4eb9", [:mix], [], "hexpm"}}
2 changes: 1 addition & 1 deletion test/real_world/blog_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ defmodule RealWorld.BlogTest do
setup do
user = insert(:user)
article = insert(:article, author: user)
{:ok, jwt, _full_claims} = Guardian.encode_and_sign(user)
{:ok, jwt, _full_claims} = RealWorldWeb.Guardian.encode_and_sign(user)
{:ok, %{author: user, article: article, jwt: jwt}}
end

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ defmodule RealWorldWeb.ArticleControllerTest do
setup do
user = insert(:user)
article = insert(:article, author: user)
{:ok, jwt, _full_claims} = Guardian.encode_and_sign(user)
{:ok, jwt, _full_claims} = RealWorldWeb.Guardian.encode_and_sign(user)
{:ok, %{article: article, user: user, jwt: jwt}}
end

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ defmodule RealWorldWeb.CommentControllerTest do
user = insert(:user)
article = insert(:article, author: user)
comment = insert(:comment, author: user, article: article)
{:ok, jwt, _full_claims} = Guardian.encode_and_sign(user)
{:ok, jwt, _full_claims} = RealWorldWeb.Guardian.encode_and_sign(user)
{:ok, %{comment: comment, user: user, article: article, jwt: jwt}}
end

Expand Down

0 comments on commit 46ab9c7

Please sign in to comment.