Skip to content

Instantly share code, notes, and snippets.

@samueljmurray
samueljmurray / passwordless_start_options.json
Created March 22, 2017 20:36
Passwordless start options
{
"client_id": "<CLIENT_ID>",
"connection": "sms",
"phone_number": "<PHONE_NUMBER>"
}
@samueljmurray
samueljmurray / session_create_action.ex
Last active March 22, 2017 20:40
Session create action
def create(conn, %{"jwt" => jwt}) do
auth0_pk = Application.get_env(:backend, :auth0)[:public_key]
case Guardian.decode_and_verify(jwt, %{secret: auth0_pk}) do
{:ok, decoded_jwt} -> login_with_auth0_token(conn, decoded_jwt)
{:error, _} -> unauthorized(conn, %{})
end
end
@samueljmurray
samueljmurray / login_with_auth0_token.ex
Last active March 27, 2017 07:51
Login with auth0 token
defp login_with_auth0_token(conn, decoded_jwt) do
case get_user_auth(decoded_jwt) do
nil -> server_error(conn)
user_auth ->
cond do
UserAuth.anon?(user_auth) ->
authorized_anon(conn, user_auth)
User.enabled?(user_auth.user) ->
authorized_employee(conn, user_auth)
true ->
@samueljmurray
samueljmurray / user_schema.ex
Last active March 27, 2017 10:53
User schema
schema "users" do
field :phone_number, :string
field :first_name, :string
field :last_name, :string
field :display_name, :string
field :employee_id, :string
field :disabled_at, Ecto.DateTime
field :disabled, :boolean, virtual: true
has_one :user_auth, UserAuth, on_replace: :delete
@samueljmurray
samueljmurray / user_auth_schema.ex
Last active March 27, 2017 10:52
UserAuth schema
schema "user_auths" do
field :method, :string
field :remote_id, :string
field :auth0_id, :string
belongs_to :user, User
has_many :devices, Device
timestamps
end
def anon?(%__MODULE__{user_id: nil}), do: true
def anon?(_), do: false
@samueljmurray
samueljmurray / authorized_anon.ex
Last active March 27, 2017 10:53
Authorized anon
defp authorized_anon(conn, user_auth) do
conn = Guardian.Plug.api_sign_in(conn, user_auth, :access)
jwt = Guardian.Plug.current_token(conn)
conn
|> put_status(201)
|> render(UserAuthView, "show.json", jwt: jwt)
end
@samueljmurray
samueljmurray / authorized_employee.ex
Last active March 27, 2017 10:54
Authorized employee
defp authorized_employee(conn, user_auth) do
conn = Guardian.Plug.api_sign_in(conn, user_auth, :access, perms: %{employee: [:full]})
jwt = Guardian.Plug.current_token(conn)
conn
|> put_status(201)
|> render(UserView, "show.json", user: user_auth.user, jwt: jwt)
end
@samueljmurray
samueljmurray / api_router.ex
Last active April 6, 2017 15:14
API router
defmodule YayCorp.Router do
use YayCorp.Web, :router
pipeline :api do
plug :accepts, ["json"]
end
pipeline :authenticated_api do
plug Guardian.Plug.VerifyHeader, realm: "Bearer"
plug Guardian.Plug.LoadResource
@samueljmurray
samueljmurray / guardian_db_config.ex
Last active April 6, 2017 15:13
GuardianDB config
config :guardian_db, GuardianDb,
repo: YayCorp.Repo,
sweep_interval: 60