ExPetOauth is a simple library wich uses Ueberauth and Ueberauth Google to implements Google Oauth 2.0 in Petlove apps.
ExPetOauth already provides the authentication routes, controllers, session control and to permits access only to users with email from @petlove.com.br
.
-
Setup your application at Google Developer Console.
-
Add :ex_pet_oauth to your list of dependencies in mix.exs:
def deps do
[
{:ex_pet_oauth, "~> 1.0", git: "[email protected]:petlove/ex_pet_oauth.git"}
]
end
- Add Google provider to your Überauth configuration:
config :ueberauth, Ueberauth,
providers: [
google: {Ueberauth.Strategy.Google, [hd: "petlove.com.br", prompt: "consent", default_scope: "email profile"]}
]
- Add the project Google credentials:
config :ueberauth, Ueberauth.Strategy.Google.OAuth,
client_id: System.get_env("GOOGLE_CLIENT_ID"),
client_secret: System.get_env("GOOGLE_CLIENT_SECRET")
- Add ExPetOauth configuration to your project:
config :ex_pet_oauth,
web_module: MyAppWeb,
user_schema: MyApp.User,
repo: MyApp.Repo,
layout_view: MyAppWeb.LayoutView
- Add ExPetOauth routes and pipelines to your
router.ex
require ExPetOauthWeb.Router
ExPetOauthWeb.Router.pipelines()
ExPetOauthWeb.Router.auth_routes()
The ExPetOauthWeb.Router.pipelines()
will enable you to use the pipeline authentication
in your routes to authenticate your user before requests.
This pipeline gets the user from session and assign then to the current_user
in your connection, it means that you can access the current_user
in your controller methods with a pattern match like this:
def index(%{assigns: %{current_user: current_user}} = conn, params) do
# Do your action
end
In your views you can access the current_user simply by: @current_user
constant.
NOTE If you want to get the current_user in a route wich doesn't use the pipelineauthentication
, you must call the get_session(conn, :current_user)
in your controller and assign
then to conn
, like this:
def index(conn, _params) do
current_user = get_session(conn, :current_user)
conn = assign(conn, :current_user, current_user)
render(conn, "index.html")
end
- Now you can create your login and logout button in your Frontend to the authentication route, like this:
<%= button "Sign in with Google", to: Routes.auth_path(@conn, :request, "google") %>
<%= button "Logout", to: Routes.auth_path(@conn, :delete), method: :delete %>
It's done! Now your users can make login with Google =)