2018-10-11 15:37:39 +00:00
|
|
|
defmodule MobilizonWeb.Guardian do
|
2018-01-14 16:56:50 +00:00
|
|
|
@moduledoc """
|
|
|
|
Handles the JWT tokens encoding and decoding
|
|
|
|
"""
|
2018-07-27 08:45:35 +00:00
|
|
|
use Guardian,
|
2018-10-11 15:37:39 +00:00
|
|
|
otp_app: :mobilizon,
|
2018-07-27 08:45:35 +00:00
|
|
|
permissions: %{
|
|
|
|
superuser: [:moderate, :super],
|
|
|
|
user: [:base]
|
|
|
|
}
|
2017-12-09 13:58:37 +00:00
|
|
|
|
2018-10-11 15:37:39 +00:00
|
|
|
alias Mobilizon.Actors
|
|
|
|
alias Mobilizon.Actors.User
|
2017-12-09 13:58:37 +00:00
|
|
|
|
2018-01-14 16:56:50 +00:00
|
|
|
def subject_for_token(%User{} = user, _claims) do
|
2017-12-09 13:58:37 +00:00
|
|
|
{:ok, "User:" <> to_string(user.id)}
|
|
|
|
end
|
|
|
|
|
|
|
|
def subject_for_token(_, _) do
|
|
|
|
{:error, :unknown_resource}
|
|
|
|
end
|
|
|
|
|
|
|
|
def resource_from_claims(%{"sub" => "User:" <> uid_str}) do
|
|
|
|
try do
|
|
|
|
case Integer.parse(uid_str) do
|
|
|
|
{uid, ""} ->
|
2018-11-12 17:17:53 +00:00
|
|
|
{:ok, Actors.get_user_with_actors!(uid)}
|
2018-07-27 08:45:35 +00:00
|
|
|
|
2017-12-09 13:58:37 +00:00
|
|
|
_ ->
|
|
|
|
{:error, :invalid_id}
|
|
|
|
end
|
|
|
|
rescue
|
|
|
|
Ecto.NoResultsError -> {:error, :no_result}
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2018-01-14 16:56:50 +00:00
|
|
|
def resource_from_claims(_) do
|
2017-12-09 13:58:37 +00:00
|
|
|
{:error, :reason_for_error}
|
|
|
|
end
|
|
|
|
|
2018-01-13 22:33:03 +00:00
|
|
|
def after_encode_and_sign(resource, claims, token, _options) do
|
|
|
|
with {:ok, _} <- Guardian.DB.after_encode_and_sign(resource, claims["typ"], claims, token) do
|
|
|
|
{:ok, token}
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def on_verify(claims, token, _options) do
|
|
|
|
with {:ok, _} <- Guardian.DB.on_verify(claims, token) do
|
|
|
|
{:ok, claims}
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def on_revoke(claims, token, _options) do
|
|
|
|
with {:ok, _} <- Guardian.DB.on_revoke(claims, token) do
|
|
|
|
{:ok, claims}
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
# def build_claims(claims, _resource, opts) do
|
|
|
|
# claims = claims
|
|
|
|
# |> encode_permissions_into_claims!(Keyword.get(opts, :permissions))
|
|
|
|
# {:ok, claims}
|
|
|
|
# end
|
2018-01-14 16:56:50 +00:00
|
|
|
end
|