Skip to content

Instantly share code, notes, and snippets.

defmodule Sling.SessionController do
use Sling.Web, :controller
def create(conn, params) do
case authenticate(params) do
{:ok, user} ->
new_conn = Guardian.Plug.api_sign_in(conn, user, :access)
jwt = Guardian.Plug.current_token(new_conn)
new_conn
defmodule Sling.SessionView do
use Sling.Web, :view
def render("show.json", %{user: user, jwt: jwt}) do
%{
data: render_one(user, Sling.UserView, "user.json"),
meta: %{token: jwt}
}
end
defmodule Sling.UserView do
use Sling.Web, :view
def render("user.json", %{user: user}) do
%{
id: user.id,
username: user.username,
email: user.email,
}
end
defmodule Sling.UserController do
use Sling.Web, :controller
alias Sling.User
def create(conn, params) do
changeset = User.registration_changeset(%User{}, params)
case Repo.insert(changeset) do
{:ok, user} ->
defmodule Sling.Router do
use Sling.Web, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
plug :put_secure_browser_headers
end
defmodule Sling.GuardianSerializer do
@behaviour Guardian.Serializer
alias Sling.Repo
alias Sling.User
def for_token(user = %User{}), do: {:ok, "User:#{user.id}"}
def for_token(_), do: {:error, "Unknown resource type"}
def from_token("User:" <> id), do: {:ok, Repo.get(User, String.to_integer(id))}
config :guardian, Guardian,
secret_key: System.get_env("GUARDIAN_SECRET_KEY")
@bnhansn
bnhansn / dev.exs
Last active October 20, 2016 22:07
config :guardian, Guardian,
secret_key: "LG17BzmhBeq81Yyyn6vH7GVdrCkQpLktol2vdXlBzkRRHpYsZwluKMG9r6fnu90m"
# content above
config :guardian, Guardian,
issuer: "Sling",
ttl: {30, :days},
verify_issuer: true,
serializer: Sling.GuardianSerializer
import_config "#{Mix.env}.exs"
defmodule Sling.User do
use Sling.Web, :model
schema "users" do
field :username, :string
field :email, :string
field :password_hash, :string
field :password, :string, virtual: true
timestamps()