Last active
March 27, 2017 07:51
-
-
Save samueljmurray/c6d2a2c858e865cb30eb5d75cd07bbbf to your computer and use it in GitHub Desktop.
Login with auth0 token
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
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 -> | |
unauthorized(conn, %{}) | |
end | |
end | |
end | |
defp get_user_auth(decoded_jwt) do | |
phone_number = decoded_jwt["phone_number"] | |
auth0_id = decoded_jwt["sub"] | |
case Repo.get_by(UserAuth, method: "phone_number", remote_id: phone_number) do | |
user_auth = %UserAuth{} -> Repo.preload(user_auth, :user) | |
_ -> | |
# No user auth found, so create one | |
# If a user has this phone number, assign them to the new user_auth | |
user = Repo.get_by(User, phone_number: phone_number) | |
changeset = %UserAuth{} | |
|> UserAuth.changeset(%{method: "phone_number", remote_id: phone_number, auth0_id: auth0_id}) | |
|> Ecto.Changeset.put_assoc(:user, user) | |
case Repo.insert(changeset) do | |
{:ok, user_auth} -> user_auth |> Repo.preload(:user) | |
{:error, _} -> nil | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment