-
-
Save hassox/b2a14a9003508bee7bcb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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