Fakultas Ilmu Komputer UI

google_auth.ex 1.61 KB
Newer Older
1
2
3
defmodule DiskuyWeb.Auth.GoogleAuth do
  alias DiskuyWeb.Auth.Guardian
  alias Diskuy.Account
4
5
  alias Diskuy.Utility.Utility

6
7
8
9
10
11
12
13
14
15
  def get_access_token(code, conn) do
    case ElixirAuthGoogle.get_token(code, conn) do
      {:ok, profile} ->
        {:ok, profile}
      _ ->
        {:error, :bad_request}
    end
  end

  def create_local_token(token) do
16
    {:ok, profile} = ElixirAuthGoogle.get_user_profile(token)
17
18
19
20
    {email, username, picture} = {profile[:email], profile[:name], profile[:picture]}
    case Account.get_by_email(email) do
      {:ok, user} ->
        Guardian.create_token(user)
21
22
23
24
25
26
27
28
29
      {:error, :not_found} ->
        create_user(username, email, picture)
    end
  end

  defp create_user(username, email, picture) do
    case Account.get_by_username(username) do
      {:ok, _user} ->
        new_username = create_username(username)
30
31
32
        {:ok, user} = Account.create_user(%{username: new_username,
                                            email: email,
                                            picture: picture, role: "reguler"})
33
        Guardian.create_token(user)
34
      {:error, :not_found} ->
35
36
37
        {:ok, user} = Account.create_user(%{username: username,
                                            email: email,
                                            picture: picture, role: "reguler"})
38
39
40
        Guardian.create_token(user)
    end
  end
41
42
43
44
45
46
47
48
49
50
51

  defp create_username(username) do
    new_username = "#{username}-#{Utility.random_string(6)}"
    case Account.get_by_username(new_username) do
      {:ok, _user} ->
        create_username(username)
      {:error, :not_found} ->
        new_username
    end
  end

52
end