Skip to content

Instantly share code, notes, and snippets.

@hassox hassox/api_login_controller.ex Secret
Last active Dec 20, 2015

Embed
What would you like to do?
defmodule Server.Api.LoginController do
use Server.Web, :controller
use Guardian.Phoenix.Controller
alias Server.User
alias Server.Repo
def login(conn, params, _user, _claims) do
user = Repo.get_by(User, email: params["email"])
case User.check_password(user, params["password"]) do
{:ok, user} ->
conn = Guardian.Plug.api_sign_in(conn, user, :api)
jwt = Guardian.Plug.current_token(conn)
conn
|> put_resp_header("authorization", "Bearer #{jwt}")
|> render("user.json", user: user, jwt: jwt)
{:error, reason} ->
conn
|> put_status(401)
|> render("unauthenticated.json")
end
end
end
defmodule Server.Api.UserController do
use Server.Web, :controller
use Guardian.Phoenix.Controller
alias Server.User
alias Guardian.Plug.EnsureAuthenticated
alias Guardian.Plug.EnsurePermissions
plug EnsureAuthenticated, handler: __MODULE__
plug EnsurePermissions, handler: __MODULE__, default: [:write_profile]
def index(conn, _params, current_user, _claims) do
users = Repo.all(User)
json(conn, %{ data: users, current_user: current_user })
end
def unauthenticated(conn, _params) do
# handle unauthenticated
end
def unauthorized(conn, _params) do
# handle incorrect permissions
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.