An IndieWeb engine for a self-hostable website. https://koype.net/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.3KB

  1. # Koype: a IndieWeb-focused, single-tenant website engine for people.
  2. #
  3. # Copyright © 2019 Jacky Alciné <jacky.is@black.af>
  4. #
  5. # This file belongs to the Koype project.
  6. #
  7. # This program is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU Affero General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU Affero General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Affero General Public License
  18. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  19. defmodule Koype.Web.AuthenticationHelpers do
  20. alias Koype.Guardian.Plug, as: KGPlug
  21. alias IndieWeb.Auth.Scope
  22. def is_signed_in?(conn, type) do
  23. KGPlug.authenticated?(conn, key: type)
  24. end
  25. def is_signed_out?(conn, type), do: !is_signed_in?(conn, type)
  26. def owner_sign_in(conn) do
  27. conn
  28. |> KGPlug.sign_in(
  29. Koype.host(),
  30. %{"id" => Koype.host() |> URI.parse() |> IndieWeb.URL.canonalize() |> URI.to_string()},
  31. ttl: {1, :week},
  32. key: :owner
  33. )
  34. |> KGPlug.remember_me(Koype.host(), key: :owner)
  35. end
  36. def owner_sign_out(conn) do
  37. conn
  38. |> KGPlug.sign_out()
  39. end
  40. def indie_sign_in(client_id, scopes)
  41. def indie_sign_in(client_id, scopes) when is_binary(scopes),
  42. do: indie_sign_in(client_id, Scope.from_string(scopes))
  43. def indie_sign_in(client_id, scopes) when is_list(scopes) do
  44. claims = %{scope: Scope.to_string(scopes)}
  45. {:ok, token, _claims} =
  46. Koype.Guardian.encode_and_sign(
  47. client_id,
  48. claims,
  49. key: :indie,
  50. token_type: :access
  51. )
  52. token
  53. end
  54. def indie_current_token(conn) do
  55. case KGPlug.current_token(conn, key: :indie) do
  56. nil -> {:error, :no_token}
  57. token -> {:ok, token}
  58. end
  59. end
  60. def indie_current_resource(conn) do
  61. case KGPlug.current_resource(conn, key: :indie) do
  62. nil -> {:error, :no_resource}
  63. resource -> {:ok, resource}
  64. end
  65. end
  66. def revoke_token(token) do
  67. Koype.Guardian.revoke(token)
  68. end
  69. end