[
  {
    "path": ".env_sample",
    "content": "export GOOGLE_CLIENT_ID=YourAppsClientId.apps.googleusercontent.com\nexport GOOGLE_CLIENT_SECRET=SuperSecret\n# export GOOGLE_SCOPE=optional see README.md\n"
  },
  {
    "path": ".formatter.exs",
    "content": "# Used by \"mix format\"\n[\n  inputs: [\"{mix,.formatter}.exs\", \"{config,lib,test}/**/*.{ex,exs}\"]\n]\n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "version: 2\nupdates:\n- package-ecosystem: mix\n  directory: \"/\"\n  schedule:\n    interval: monthly\n    time: \"17:00\"\n    timezone: Europe/London\n"
  },
  {
    "path": ".github/workflows/ci.yml",
    "content": "name: Elixir CI\n\non:\n  push:\n    branches: [ main ]\n  pull_request:\n    branches: [ main ]\n\njobs:\n  build:\n    name: Build and test\n    runs-on: ubuntu-latest\n    steps:\n    - uses: actions/checkout@v2\n    - name: Set up Elixir\n      uses: erlef/setup-beam@v1\n      with:\n        elixir-version: '1.14.2' # Define the elixir version [required]\n        otp-version: '25.1.2' # Define the OTP version [required]\n    - name: Restore dependencies cache\n      uses: actions/cache@v4\n      with:\n        path: deps\n        key: ${{ runner.os }}-mix-${{ hashFiles('**/mix.lock') }}\n        restore-keys: ${{ runner.os }}-mix-\n    - name: Install dependencies\n      run: mix deps.get\n    - name: Run Tests\n      run: mix coveralls.json\n      env:\n        MIX_ENV: test\n    - name: Upload coverage to Codecov\n      uses: codecov/codecov-action@v1\n\n"
  },
  {
    "path": ".gitignore",
    "content": "/_build\n/cover\n/deps\n/doc\n/.fetch\nerl_crash.dump\n*.ez\n*.beam\n/config/*.secret.exs\n.elixir_ls\n.env\nelixir_auth_google.iml\n.idea"
  },
  {
    "path": ".travis.yml",
    "content": "language: elixir\nmatrix:\n  include:\n    - elixir: 1.12.3\n      otp_release: 24.0.2\nenv:\n  MIX_ENV=test\nscript:\n  - mix coveralls.json\nafter_success:\n  - bash <(curl -s https://codecov.io/bash) # send coverage report\ncache:\n  directories:\n    - _build\n    - deps\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 2, June 1991\n\n Copyright (C) 1989, 1991 Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The licenses for most software are designed to take away your\nfreedom to share and change it.  By contrast, the GNU General Public\nLicense is intended to guarantee your freedom to share and change free\nsoftware--to make sure the software is free for all its users.  This\nGeneral Public License applies to most of the Free Software\nFoundation's software and to any other program whose authors commit to\nusing it.  (Some other Free Software Foundation software is covered by\nthe GNU Lesser General Public License instead.)  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthis service if you wish), that you receive source code or can get it\nif you want it, that you can change the software or use pieces of it\nin new free programs; and that you know you can do these things.\n\n  To protect your rights, we need to make restrictions that forbid\nanyone to deny you these rights or to ask you to surrender the rights.\nThese restrictions translate to certain responsibilities for you if you\ndistribute copies of the software, or if you modify it.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must give the recipients all the rights that\nyou have.  You must make sure that they, too, receive or can get the\nsource code.  And you must show them these terms so they know their\nrights.\n\n  We protect your rights with two steps: (1) copyright the software, and\n(2) offer you this license which gives you legal permission to copy,\ndistribute and/or modify the software.\n\n  Also, for each author's protection and ours, we want to make certain\nthat everyone understands that there is no warranty for this free\nsoftware.  If the software is modified by someone else and passed on, we\nwant its recipients to know that what they have is not the original, so\nthat any problems introduced by others will not reflect on the original\nauthors' reputations.\n\n  Finally, any free program is threatened constantly by software\npatents.  We wish to avoid the danger that redistributors of a free\nprogram will individually obtain patent licenses, in effect making the\nprogram proprietary.  To prevent this, we have made it clear that any\npatent must be licensed for everyone's free use or not licensed at all.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                    GNU GENERAL PUBLIC LICENSE\n   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n  0. This License applies to any program or other work which contains\na notice placed by the copyright holder saying it may be distributed\nunder the terms of this General Public License.  The \"Program\", below,\nrefers to any such program or work, and a \"work based on the Program\"\nmeans either the Program or any derivative work under copyright law:\nthat is to say, a work containing the Program or a portion of it,\neither verbatim or with modifications and/or translated into another\nlanguage.  (Hereinafter, translation is included without limitation in\nthe term \"modification\".)  Each licensee is addressed as \"you\".\n\nActivities other than copying, distribution and modification are not\ncovered by this License; they are outside its scope.  The act of\nrunning the Program is not restricted, and the output from the Program\nis covered only if its contents constitute a work based on the\nProgram (independent of having been made by running the Program).\nWhether that is true depends on what the Program does.\n\n  1. You may copy and distribute verbatim copies of the Program's\nsource code as you receive it, in any medium, provided that you\nconspicuously and appropriately publish on each copy an appropriate\ncopyright notice and disclaimer of warranty; keep intact all the\nnotices that refer to this License and to the absence of any warranty;\nand give any other recipients of the Program a copy of this License\nalong with the Program.\n\nYou may charge a fee for the physical act of transferring a copy, and\nyou may at your option offer warranty protection in exchange for a fee.\n\n  2. You may modify your copy or copies of the Program or any portion\nof it, thus forming a work based on the Program, and copy and\ndistribute such modifications or work under the terms of Section 1\nabove, provided that you also meet all of these conditions:\n\n    a) You must cause the modified files to carry prominent notices\n    stating that you changed the files and the date of any change.\n\n    b) You must cause any work that you distribute or publish, that in\n    whole or in part contains or is derived from the Program or any\n    part thereof, to be licensed as a whole at no charge to all third\n    parties under the terms of this License.\n\n    c) If the modified program normally reads commands interactively\n    when run, you must cause it, when started running for such\n    interactive use in the most ordinary way, to print or display an\n    announcement including an appropriate copyright notice and a\n    notice that there is no warranty (or else, saying that you provide\n    a warranty) and that users may redistribute the program under\n    these conditions, and telling the user how to view a copy of this\n    License.  (Exception: if the Program itself is interactive but\n    does not normally print such an announcement, your work based on\n    the Program is not required to print an announcement.)\n\nThese requirements apply to the modified work as a whole.  If\nidentifiable sections of that work are not derived from the Program,\nand can be reasonably considered independent and separate works in\nthemselves, then this License, and its terms, do not apply to those\nsections when you distribute them as separate works.  But when you\ndistribute the same sections as part of a whole which is a work based\non the Program, the distribution of the whole must be on the terms of\nthis License, whose permissions for other licensees extend to the\nentire whole, and thus to each and every part regardless of who wrote it.\n\nThus, it is not the intent of this section to claim rights or contest\nyour rights to work written entirely by you; rather, the intent is to\nexercise the right to control the distribution of derivative or\ncollective works based on the Program.\n\nIn addition, mere aggregation of another work not based on the Program\nwith the Program (or with a work based on the Program) on a volume of\na storage or distribution medium does not bring the other work under\nthe scope of this License.\n\n  3. You may copy and distribute the Program (or a work based on it,\nunder Section 2) in object code or executable form under the terms of\nSections 1 and 2 above provided that you also do one of the following:\n\n    a) Accompany it with the complete corresponding machine-readable\n    source code, which must be distributed under the terms of Sections\n    1 and 2 above on a medium customarily used for software interchange; or,\n\n    b) Accompany it with a written offer, valid for at least three\n    years, to give any third party, for a charge no more than your\n    cost of physically performing source distribution, a complete\n    machine-readable copy of the corresponding source code, to be\n    distributed under the terms of Sections 1 and 2 above on a medium\n    customarily used for software interchange; or,\n\n    c) Accompany it with the information you received as to the offer\n    to distribute corresponding source code.  (This alternative is\n    allowed only for noncommercial distribution and only if you\n    received the program in object code or executable form with such\n    an offer, in accord with Subsection b above.)\n\nThe source code for a work means the preferred form of the work for\nmaking modifications to it.  For an executable work, complete source\ncode means all the source code for all modules it contains, plus any\nassociated interface definition files, plus the scripts used to\ncontrol compilation and installation of the executable.  However, as a\nspecial exception, the source code distributed need not include\nanything that is normally distributed (in either source or binary\nform) with the major components (compiler, kernel, and so on) of the\noperating system on which the executable runs, unless that component\nitself accompanies the executable.\n\nIf distribution of executable or object code is made by offering\naccess to copy from a designated place, then offering equivalent\naccess to copy the source code from the same place counts as\ndistribution of the source code, even though third parties are not\ncompelled to copy the source along with the object code.\n\n  4. You may not copy, modify, sublicense, or distribute the Program\nexcept as expressly provided under this License.  Any attempt\notherwise to copy, modify, sublicense or distribute the Program is\nvoid, and will automatically terminate your rights under this License.\nHowever, parties who have received copies, or rights, from you under\nthis License will not have their licenses terminated so long as such\nparties remain in full compliance.\n\n  5. You are not required to accept this License, since you have not\nsigned it.  However, nothing else grants you permission to modify or\ndistribute the Program or its derivative works.  These actions are\nprohibited by law if you do not accept this License.  Therefore, by\nmodifying or distributing the Program (or any work based on the\nProgram), you indicate your acceptance of this License to do so, and\nall its terms and conditions for copying, distributing or modifying\nthe Program or works based on it.\n\n  6. Each time you redistribute the Program (or any work based on the\nProgram), the recipient automatically receives a license from the\noriginal licensor to copy, distribute or modify the Program subject to\nthese terms and conditions.  You may not impose any further\nrestrictions on the recipients' exercise of the rights granted herein.\nYou are not responsible for enforcing compliance by third parties to\nthis License.\n\n  7. If, as a consequence of a court judgment or allegation of patent\ninfringement or for any other reason (not limited to patent issues),\nconditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot\ndistribute so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you\nmay not distribute the Program at all.  For example, if a patent\nlicense would not permit royalty-free redistribution of the Program by\nall those who receive copies directly or indirectly through you, then\nthe only way you could satisfy both it and this License would be to\nrefrain entirely from distribution of the Program.\n\nIf any portion of this section is held invalid or unenforceable under\nany particular circumstance, the balance of the section is intended to\napply and the section as a whole is intended to apply in other\ncircumstances.\n\nIt is not the purpose of this section to induce you to infringe any\npatents or other property right claims or to contest validity of any\nsuch claims; this section has the sole purpose of protecting the\nintegrity of the free software distribution system, which is\nimplemented by public license practices.  Many people have made\ngenerous contributions to the wide range of software distributed\nthrough that system in reliance on consistent application of that\nsystem; it is up to the author/donor to decide if he or she is willing\nto distribute software through any other system and a licensee cannot\nimpose that choice.\n\nThis section is intended to make thoroughly clear what is believed to\nbe a consequence of the rest of this License.\n\n  8. If the distribution and/or use of the Program is restricted in\ncertain countries either by patents or by copyrighted interfaces, the\noriginal copyright holder who places the Program under this License\nmay add an explicit geographical distribution limitation excluding\nthose countries, so that distribution is permitted only in or among\ncountries not thus excluded.  In such case, this License incorporates\nthe limitation as if written in the body of this License.\n\n  9. The Free Software Foundation may publish revised and/or new versions\nof the General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\nEach version is given a distinguishing version number.  If the Program\nspecifies a version number of this License which applies to it and \"any\nlater version\", you have the option of following the terms and conditions\neither of that version or of any later version published by the Free\nSoftware Foundation.  If the Program does not specify a version number of\nthis License, you may choose any version ever published by the Free Software\nFoundation.\n\n  10. If you wish to incorporate parts of the Program into other free\nprograms whose distribution conditions are different, write to the author\nto ask for permission.  For software which is copyrighted by the Free\nSoftware Foundation, write to the Free Software Foundation; we sometimes\nmake exceptions for this.  Our decision will be guided by the two goals\nof preserving the free status of all derivatives of our free software and\nof promoting the sharing and reuse of software generally.\n\n                            NO WARRANTY\n\n  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\nFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\nOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\nPROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\nOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\nTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\nPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\nREPAIR OR CORRECTION.\n\n  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\nREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\nINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\nOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\nTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\nYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\nPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGES.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nconvey the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software; you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License along\n    with this program; if not, write to the Free Software Foundation, Inc.,\n    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf the program is interactive, make it output a short notice like this\nwhen it starts in an interactive mode:\n\n    Gnomovision version 69, Copyright (C) year name of author\n    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, the commands you use may\nbe called something other than `show w' and `show c'; they could even be\nmouse-clicks or menu items--whatever suits your program.\n\nYou should also get your employer (if you work as a programmer) or your\nschool, if any, to sign a \"copyright disclaimer\" for the program, if\nnecessary.  Here is a sample; alter the names:\n\n  Yoyodyne, Inc., hereby disclaims all copyright interest in the program\n  `Gnomovision' (which makes passes at compilers) written by James Hacker.\n\n  <signature of Ty Coon>, 1 April 1989\n  Ty Coon, President of Vice\n\nThis General Public License does not permit incorporating your program into\nproprietary programs.  If your program is a subroutine library, you may\nconsider it more useful to permit linking proprietary applications with the\nlibrary.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.\n"
  },
  {
    "path": "README.md",
    "content": "<div align=\"center\">\n\n# `elixir-auth-google`\n\nThe _easiest_ way to add Google OAuth authentication to your Elixir Apps.\n\n![sign-in-with-google-buttons](https://user-images.githubusercontent.com/194400/69637172-07a67900-1050-11ea-9e25-2b9e84a49d91.png)\n\n![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/dwyl/elixir-auth-google/ci.yml?label=build&style=flat-square&branch=main)\n[![codecov.io](https://img.shields.io/codecov/c/github/dwyl/elixir-auth-google/master.svg?style=flat-square)](http://codecov.io/github/dwyl/elixir-auth-google?branch=main)\n[![Hex.pm](https://img.shields.io/hexpm/v/elixir_auth_google?color=brightgreen&style=flat-square)](https://hex.pm/packages/elixir_auth_google)\n[![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat-square)](https://github.com/dwyl/elixir-auth-google/issues)\n[![HitCount](http://hits.dwyl.com/dwyl/elixir-auth-google.svg)](http://hits.dwyl.com/dwyl/elixir-auth-google)\n<!-- [![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-brightgreen.svg?style=flat-square)](https://GitHub.com/TutorialsAndroid/GButton) -->\n\n</div>\n\n# _Why_? 🤷\n\nWe needed a **_much_ simpler**\nand **_extensively_ documented** way\nto add \"_**Sign-in** with **Google**_\"\ncapability to our Elixir App(s). <br />\n\n# _What_? 💭\n\nAn Elixir package that seamlessly handles\nGoogle OAuth2 Authentication/Authorization\nin as few steps as possible. <br />\nFollowing best practices for security & privacy\nand avoiding complexity\nby having sensible defaults for all settings.\n\n\n> We built a lightweight solution\nthat only does _one_ thing\nand is easy for complete beginners to understand/use. <br />\nThere were already _several_ available options\nfor adding Google Auth to apps on\n[hex.pm/packages?search=google](https://hex.pm/packages?search=google) <br />\nthat all added _far_ too many implementation steps (complexity)\nand had incomplete docs (**`@doc false`**) and tests. <br />\ne.g:\n[github.com/googleapis/elixir-google-api](https://github.com/googleapis/elixir-google-api)\nwhich is a\n[\"_generated_\"](https://github.com/googleapis/elixir-google-api/blob/master/scripts/generate_client.sh)\nclient and is considered \"experimental\". <br />\nWe have drawn inspiration from several sources\nincluding code from other programming languages to build this package.\nThis result is _much_ simpler\nthan anything else\nand has both step-by-step instructions\nand a _complete working example_ App\nincluding how to encrypt tokens for secure storage\nto help you ship your app _fast_.\n\n\n# _Who_? 👥\n\nThis module is for people building apps using Elixir/Phoenix\nwho want to ship the \"Sign-in with Google\" feature _faster_\nand more maintainably.\n\nIt's targetted at _complete_ beginners\nwith no prior experience/knowledge\nof auth \"schemes\" or \"strategies\". <br />\nJust follow the detailed instructions\nand you'll be up-and running in 5 minutes.\n\n\n# _How_? ✅\n\nYou can add Google Authentication to your Elixir App\nusing **`elixir_auth_google`** <br />\nin under **5 minutes**\nby following these **5 _easy_ steps**:\n\n## 1. Add the hex package to `deps` 📦\n\nOpen your project's **`mix.exs`** file\nand locate the **`deps`** (dependencies) section. <br />\nAdd a line for **`:elixir_auth_google`** in the **`deps`** list:\n\n```elixir\ndef deps do\n  [\n    {:elixir_auth_google, \"~> 1.6.9\"}\n  ]\nend\n```\n\nOnce you have added the line to your **`mix.exs`**,\nremember to run the **`mix deps.get`** command\nin your terminal\nto _download_ the dependencies.\n\n\n## 2. Create Google APIs Application OAuth2 Credentials 🆕\n\nCreate a Google Application if you don't already have one,\ngenerate the OAuth2 Credentials for the application\nand save the credentials as environment variables\naccessible by your app, or put them in your config file.\n\n> **Note**: There are a few steps for creating a set of Google APIs credentials,\nso if you don't already have a Google App,\nwe created the following step-by-step guide\nto make it quick and _relatively_ painless:\n[create-google-app-guide.md](https://github.com/dwyl/elixir-auth-google/blob/master/create-google-app-guide.md) <br />\nDon't be intimidated by all the buzz-words;\nit's quite straightforward.\nAnd if you get stuck, ask for\n[help!](https://github.com/dwyl/elixir-auth-google/issues)\n\n\n## 3. Setup CLIENT_ID and CLIENT_SECRET in your project\n\nYou may either add those keys as environment variables or put them in the config:\n\n```\nexport GOOGLE_CLIENT_ID=631770888008-6n0oruvsm16kbkqg6u76p5cv5kfkcekt.apps.googleusercontent.com\nexport GOOGLE_CLIENT_SECRET=MHxv6-RGF5nheXnxh1b0LNDq\n```\nOr add the following in the config file:\n\n```elixir\nconfig :elixir_auth_google,\n  client_id: \"631770888008-6n0oruvsm16kbkqg6u76p5cv5kfkcekt.apps.googleusercontent.com\",\n  client_secret: \"MHxv6-RGF5nheXnxh1b0LNDq\"\n\n```\n> ⚠️ Don't worry, these keys aren't valid.\nThey are just here for illustration purposes.\n\n\n## 4. Create a `GoogleAuthController` in your Project 📝\n\nCreate a new file called\n[`lib/app_web/controllers/google_auth_controller.ex`](https://github.com/dwyl/elixir-auth-google-demo/blob/master/lib/app_web/controllers/google_auth_controller.ex)\nand add the following code:\n\n```elixir\ndefmodule AppWeb.GoogleAuthController do\n  use AppWeb, :controller\n\n  @doc \"\"\"\n  `index/2` handles the callback from Google Auth API redirect.\n  \"\"\"\n  def index(conn, %{\"code\" => code}) do\n    {:ok, token} = ElixirAuthGoogle.get_token(code, MyAppWeb.Endpoint.url())\n    {:ok, profile} = ElixirAuthGoogle.get_user_profile(token.access_token)\n    conn\n    |> put_view(AppWeb.PageView)\n    |> render(:welcome, profile: profile)\n  end\nend\n```\nThis code does 3 things:\n+ Create a one-time auth `token` based on the response `code` sent by Google\nafter the person authenticates.\n+ Request the person's profile data from Google based on the `access_token`\n+ Render a `:welcome` view displaying some profile data\nto confirm that login with Google was successful.\n\n\n## 5. Create the `/auth/google/callback` Endpoint 📍\n\nOpen your **`router.ex`** file\nand locate the section that looks like `scope \"/\", AppWeb do`\n\nAdd the following line:\n\n```elixir\nget \"/auth/google/callback\", GoogleAuthController, :index\n```\n\nSample: [lib/app_web/router.ex#L20](https://github.com/dwyl/elixir-auth-google-demo/blob/4bb616dd134f498b84f079104c0f3345769517c4/lib/app_web/router.ex#L20)\n\n### Different callback url?\n\nYou can specify the env var\n\n```\nexport GOOGLE_CALLBACK_PATH=/myauth/google_callback\n```\n\nor add it in the configuration\n\nOr add the following in the config file:\n\n```elixir\nconfig :elixir_auth_google,\n  # ...\n  callback_path: \"/myauth/google_callback\"\n```\n\n## 6. Add the \"Login with Google\" Button to your Template ✨\n\nIn order to display the \"Sign-in with Google\" button in the UI,\nwe need to _generate_ the URL for the button in the relevant controller,\nand pass it to the template.\n\nOpen the `lib/app_web/controllers/page_controller.ex` file\nand update the `index` function:\n\nFrom:\n```elixir\ndef index(conn, _params) do\n  render(conn, \"index.html\")\nend\n```\n\nTo:\n```elixir\ndef index(conn, _params) do\n  oauth_google_url = ElixirAuthGoogle.generate_oauth_url(conn)\n  render(conn, \"index.html\",[oauth_google_url: oauth_google_url])\nend\n```\n\nYou can add extra features the the generated url by passing the state as a string,\nor any other query as a map of key/value pairs.\n\n```elixir\noauth_google_url = ElixirAuthGoogle.generate_oauth_url(conn, state)\n```\n\nWill result in Google Sign In link with `&state=state` added.\nAnd something like:\n\n```elixir\noauth_google_url = ElixirAuthGoogle.generate_oauth_url(conn, %{lang: 'pt-BR'})\n```\n\nWill return a url with `lang=pt-BR` included in the sign in request.\n\n#### _Alternatively_ pass the `url` of your `App` into `generate_oauth_url/1`\n\nWe have noticed that on `fly.io` \nwhere the `Phoenix` App is proxied,\npassing the `conn` struct \nto `ElixirAuthGoogle.generate_oauth_url/2`\nis not effective.\nSee [dwyl/elixir-auth-google/issues/94](https://github.com/dwyl/elixir-auth-google/issues/94)\n\nSo we added an alternative way \nof invoking `generate_oauth_url/2`\npassing in the `url` of your `App`:\n\n```elixir\ndef index(conn, _params) do\n  base_url = MyAppWeb.Endpoint.url()\n  oauth_google_url = ElixirAuthGoogle.generate_oauth_url(base_url)\n  render(conn, \"index.html\",[oauth_google_url: oauth_google_url])\nend\n```\n\nThis uses \n[Phoenix.Endpoint.url/0](https://hexdocs.pm/phoenix/Phoenix.Endpoint.html#c:url/0) \nwhich is available in any `Phoenix` App.\n\nJust remember to replace `MyAppWeb` with the name of your `App`. 😉\n\n<br />\n\n### 6.1 Update the `page/index.html.eex` Template\n\nOpen the `/lib/app_web/templates/page/index.html.eex` file\nand type the following code:\n\n```html\n<section class=\"phx-hero\">\n  <h1>Welcome to Awesome App!</h1>\n  <p>To get started, login to your Google Account: </p>\n  <a href={@oauth_google_url}>\n    <img src=\"https://i.imgur.com/Kagbzkq.png\" alt=\"Sign in with Google\" />\n  </a>\n</section>\n```\n\n# _Done_! 🚀\n\nThe home page of the app now has a big \"Sign in with Google\" button:\n\n![sign-in-button](https://user-images.githubusercontent.com/194400/70202961-3c32c880-1713-11ea-9737-9121030ace06.png)\n\nWhen the person clicks the button,\nand authenticates with their Google Account,\nthey will be returned to your App\nwhere you can display a \"login success\" message:\n\n![welcome](https://user-images.githubusercontent.com/194400/70201692-494db880-170f-11ea-9776-0ffd1fdf5a72.png)\n\n\n### _Optional_: Scopes\n\nMost of the time you will only want/need\nthe person's email address and profile data\nwhen authenticating with your App.\nIn the cases where you need more specific access\nto a Google service, you will need to specify the exact scopes.\nSee:\nhttps://developers.google.com/identity/protocols/oauth2/scopes\n\nOnce you know the scope(s) your App needs access to,\nsimply define them using an environment variable, e.g:\n\n```\nGOOGLE_SCOPE=\"email contacts photoslibrary\"\n```\nThose double-quotes (`\"`) encapsulating the environment variable `String` are important. \nWithout them your system will only assign the first word to the `GOOGLE_SCOPE`.\ne.g: `email` and ignore the remaining scopes you need.\n***or*** you can set them as a config variable if you prefer:\n\n```\nconfig :elixir_auth_google,\n  :google_scope: \"email contacts photoslibrary\"\n```\n\nWith that configured, your App will gain access to the requested services\nonce the person authenticates/authorizes.\n\n<br /> <br />\n\n\n## _Optimised_ SVG+CSS Button\n\nIn **step 6.1** above, we suggest using an `<img>`\nfor the `Sign in with GitHub` button.\n\nBut even though this image appears small **`389 × 93 px`**\nhttps://i.imgur.com/Kagbzkq.png it is \"only\" **`8kb`**:\n\n![google-button-8kb](https://user-images.githubusercontent.com/194400/73607428-cd0c1000-45ad-11ea-8639-ffc3e9a0e0a2.png)\n\nWe could spend some time in a graphics editor optimising the image,\nbut we _know_ we can do better by using our `CSS` skills! 💡\n\n> **Note**: This is the _official_ button provided by Google:\n[developers.google.com/identity/images/signin-assets.zip](developers.google.com/identity/images/signin-assets.zip) <br />\nSo if there was any optimisation they could squeeze out of it,\nthey probably would have done it before publishing the zip!\n\nThe following code re-creates the `<img>`\nusing the GitHub logo **`SVG`**\nand `CSS` for layout/style:\n\n```html\n<div style=\"display:flex; flex-direction:column; width:368px; margin-left:133px;\">\n  <link href=\"https://fonts.googleapis.com/css?family=Roboto&display=swap\">\n\n  <a href=\"<%= @oauth_google_url %>\"\n    style=\"display:inline-flex; align-items:center; min-height:50px;\n      background-color:#4285F4; font-family:'Roboto',sans-serif;\n      font-size:28px; color:white; text-decoration:none;\n      margin-top: 12px\">\n      <div style=\"background-color: white; margin:2px; padding-top:18px; padding-bottom:6px; min-height:59px; width:72px\">\n      <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 533.5 544.3\"\n        width=\"52px\" height=\"35\" style=\"display:inline-flex; align-items:center;\" >\n        <path d=\"M533.5 278.4c0-18.5-1.5-37.1-4.7-55.3H272.1v104.8h147c-6.1 33.8-25.7 63.7-54.4 82.7v68h87.7c51.5-47.4 81.1-117.4 81.1-200.2z\" fill=\"#4285f4\"/>\n        <path d=\"M272.1 544.3c73.4 0 135.3-24.1 180.4-65.7l-87.7-68c-24.4 16.6-55.9 26-92.6 26-71 0-131.2-47.9-152.8-112.3H28.9v70.1c46.2 91.9 140.3 149.9 243.2 149.9z\" fill=\"#34a853\"/>\n        <path d=\"M119.3 324.3c-11.4-33.8-11.4-70.4 0-104.2V150H28.9c-38.6 76.9-38.6 167.5 0 244.4l90.4-70.1z\" fill=\"#fbbc04\"/>\n        <path d=\"M272.1 107.7c38.8-.6 76.3 14 104.4 40.8l77.7-77.7C405 24.6 339.7-.8 272.1 0 169.2 0 75.1 58 28.9 150l90.4 70.1c21.5-64.5 81.8-112.4 152.8-112.4z\" fill=\"#ea4335\"/>\n      </svg>\n    </div>\n    <div style=\"margin-left: 27px;\">\n      Sign in with Google\n    </div>\n  </a>\n</div>\n```\n\n> We created this from scratch using the SVG of the Google logo\nand some basic CSS. <br />\nFor the \"making of\" journey see:\nhttps://github.com/dwyl/elixir-auth-google/issues/25\n\nThe result looks _better_ than the `<img>` button:\n\n![img-vs-svg-8kb-1kb](https://user-images.githubusercontent.com/194400/73607841-54a84d80-45b3-11ea-9d0c-a81005a0bfde.png)\n\nIt can be scaled to any screen size so it will _always_ look great! <br />\nUsing http://bytesizematters.com we see that our SVG+CSS button is only **`1kb`**:\n![bytesize-matters-google-button](https://user-images.githubusercontent.com/194400/73607378-4fe09b00-45ad-11ea-9ab1-3b383c1d4516.png)\n\n\nThat is an **87.5%** bandwidth saving\non the **`8kb`** of the\n[**`.png`** button](https://github.com/dwyl/elixir-auth-google/issues/25).\nAnd what's _more_ it reduces the number of HTTP requests\nwhich means the page loads _even_ faster.\n\nThis is used in the Demo app:\n[`lib/app_web/templates/page/index.html.eex`](https://github.com/dwyl/elixir-auth-google-demo/blob/4fdbeada2f13f4dd27d2372a916764ec7aad24e7/lib/app_web/templates/page/index.html.eex#L5-L26)\n\n\n### `i18n`\n\nThe _biggest_ advantage of having an SVG+CSS button\nis that you can _translate_ the button text! <br />\nSince the text/copy of the button is now _just_ text in standard HTML,\nthe user's web browser can _automatically_ translate it! <br />\ne.g: _French_ 🇬🇧 > 🇫🇷\n\n![google-login-french-translation](https://user-images.githubusercontent.com/194400/73607961-c03eea80-45b4-11ea-9840-5d5f02ff8a13.png)\n\nThis is _much_ better UX for the **80%** of people in the world\nwho do _not_ speak English _fluently_.\nThe _single_ biggest engine for growth in startup companies\nis [_translating_](https://youtu.be/T9ikpoF2GH0?t=463)\ntheir user interface into more languages.\nObviously don't focus on translations\nwhile you're building your MVP,\nbut if it's no extra _work_\nto use this SVG+CSS button\nand it means the person's web browser\ncan _automatically_ localise your App!\n\n### _Accessibility_\n\nThe `SVG+CSS` button is more accessible than the image.\nEven thought the `<img>` had an `alt` attribute\nwhich is a lot better than nothing,\nthe `SVG+CSS` button can be re-interpreted\nby a non-screen device and more easily transformed.\n\n\n<br /> <br />\n\n## _Even_ More Detail 💡\n\nIf you want to dive a bit deeper into _understanding_ how this package works,\nYou can read and grok the code in under 10 minutes:\n[`/lib/elixir_auth_google.ex`](https://github.com/dwyl/elixir-auth-google/blob/master/lib/elixir_auth_google.ex)\n\nWe created a _basic_ demo Phoenix App,\nto show you _exactly_ how you can implement\nthe **`elixir_auth_google`** package:\nhttps://github.com/dwyl/elixir-auth-google-demo\nIt's deployed to Heroku: https://elixir-auth-google-demo.herokuapp.com <br />\n(_no data is saved so you can play with it - and try to break it!_)\n\nAnd if you want/need a more complete real-world example\nincluding creating sessions and saving profile data to a database,\ntake a look at our MVP:\nhttps://github.com/dwyl/app-mvp-phoenix\n\n\n<br /><br />\n\n## Notes 📝\n\n+ Official Docs for Google Identity Platform:\nhttps://developers.google.com/identity/choose-auth\n  + Web specific sample code (JS):\n  https://developers.google.com/identity/sign-in/web\n+ Google Sign-In for server-side apps:\nhttps://developers.google.com/identity/sign-in/web/server-side-flow\n+ Using OAuth 2.0 for Web Server Applications:\nhttps://developers.google.com/identity/protocols/OAuth2WebServer\n+ Google Auth Branding Guidelines:\nhttps://developers.google.com/identity/branding-guidelines <br />\nOnly two colors are permitted for the button:\n**white** `#FFFFFF` and **blue** `#4285F4`\n\n![two-colors-of-google-auth-button](https://user-images.githubusercontent.com/194400/69634312-d9be3600-1049-11ea-9354-cdaa53f5c42b.png)\n\n\n### Fun Facts 📈📊\n\nUnlike other \"social media\" companies,\nGoogle/Alphabet does not report it's\n_Monthly_ Active Users (MAUs)\nor _Daily_ Active Users (DAUs)\nhowever they do release stats in drips\nin their Google IO or YouTube events.\nThe following is a quick list of facts\nthat make adding Google Auth to your App\na compelling business case:\n\n+ As of May 2019, there are over\n[2.5 Billion](https://www.theverge.com/2019/5/7/18528297/google-io-2019-android-devices-play-store-total-number-statistic-keynote)\n_active_ Android devices;\n[87%](https://www.idc.com/promo/smartphone-market-share/os) global market share.\nAll these people have Google Accounts in order to use Google services.\n+ YouTube has\n[2 billion](https://www.businessofapps.com/data/youtube-statistics/)\nmonthly active YouTube users (_signed in with a Google Account_).\n+ Gmail has\n[1.5 Billion](https://www.thenewsminute.com/article/googles-gmail-turns-15-now-has-over-15-billion-monthly-active-users-99275)\nmonthly active users a\n[27% share](https://seotribunal.com/blog/google-stats-and-facts)\n of the global email client market.\n+ [65%](https://techjury.net/stats-about/gmail-statistics)\nof Small and Medium sized businesses use Google Apps for business.\n+ [90%+](https://techjury.net/stats-about/gmail-statistics)\nof startups use Gmail. This is a good _proxy_ for \"early adopters\".\n+ [68%](https://eu.azcentral.com/story/opinion/op-ed/joannaallhands/2017/10/09/google-classroom-changing-teachers-students-education/708246001/)\nof schools in the US use Google Classroom and related G-suite products. <br />\nSo the _next_ generation of internet/app users have Google accounts.\n+ Google has\n[90.46%](https://seotribunal.com/blog/google-stats-and-facts/)\nof the search engine market share worldwide. 95.4% on Mobile.\n\nOf the 4.5 billion internet users (58% of the world population),\naround 3.2 billion (72%) have a Google account.\n90%+ of tech \"early adopters\" use Google Apps\nwhich means that adding Google OAuth Sign-in\nis the _logical_ choice for _most_ Apps.\n\n### Privacy Concerns? 🔐\n\nA _common misconception_ is that adding Google Auth Sign-in\nsends a user's application data to Google.\nThis is **`false`** and App developers have 100% control\nover what data is sent to (stored by) Google.\nAn App can use Google Auth to _authenticate_ a person\n(_identify them and get read-only access\n  to their personal details like **first name** and **email address**_)\nwithout sending any data to Google.\nYes, it will mean that Google \"knows\" that the person is _using_ your App,\nbut it will not give Google any insight into _how_ they are using it\nor what types of data they are storing in the App. Privacy is maintained.\nSo if you use the @dwyl app to plan your wedding or next holiday,\nGoogle will not have _any_ of that data\nand will not serve any annoying ads based on your project/plans.\n"
  },
  {
    "path": "config/config.exs",
    "content": "import Config\n\nif Mix.env() == :test do\n  import_config \"test.exs\"\nend\n"
  },
  {
    "path": "config/test.exs",
    "content": "import Config\n\nconfig :elixir_auth_google,\n  client_id: \"631770888008-6n0oruvsm16kbkqg6u76p5cv5kfkcekt.apps.googleusercontent.com\",\n  client_secret: \"MHxv6-RGF5nheXnxh1b0LNDq\",\n  httpoison_mock: true\n\nSystem.put_env(\n  \"GOOGLE_CLIENT_ID\",\n  \"631770888008-6n0oruvsm16kbkqg6u76p5cv5kfkcekt.apps.googleusercontent.com\"\n)\n"
  },
  {
    "path": "create-google-app-guide.md",
    "content": "# Creating a Google Application for OAuth2 Authentication\n\nThis is a step-by-step guide\nfor creating a Google App from scratch\nso that you can obtain the API keys\nto add Google OAuth2 Authentication\nto your Elixir App\nand save the credentials to environment variables.<br />\nOur guide follows the _official_ docs:\nhttps://developers.google.com/identity/sign-in/web/server-side-flow <br />\nWe've added detail and screenshots to the steps\nbecause some people have found the official Google API docs confusing. <br />\n_This_ guide is checked periodically by the @dwyl team/community,\nbut Google are known to occasionally change their UI/Workflow,\nso if anything has changed, or there are extra/fewer steps,\n[please let us know!](https://github.com/dwyl/elixir-auth-google/issues)\n\n## 1. Create a New Project\n\nIn your preferred web browser,\nvisit:\nhttps://console.developers.google.com\nand ensure you are authenticated with your Google Account\nso you can see your \"API & Services Dashboard\":\n\n<img width=\"972\" alt=\"elixir-auth-google-create-new-app\" src=\"https://user-images.githubusercontent.com/194400/69722359-c7f29680-110e-11ea-90ae-da11ba42cc4a.png\">\n\nIf you don't already have a Google APIs project for your Elixir App,\nclick the **CREATE** button on the dashboard.\n\n\n## 2. Define the Details for your New Project (App)\n\nEnter the details for your App's **Project name**\nand where appropriate input any additional/relevant info:\n\n<img width=\"972\" alt=\"elixir-auth-google-app-details\" src=\"https://user-images.githubusercontent.com/194400/69722801-ead17a80-110f-11ea-9bc9-d145b29baac6.png\">\n\nClick the **CREATE** button to create your project.\n\n\n## 3. OAuth Consent Screen\n\nAfter creating the New Project,\nthe UI will return to the APIs dashboard\nand the name of your app will appear in the top menu.\n\nClick the **OAuth Consent Screen** from the left side menu:\n\n<img width=\"959\" alt=\"elixir-auth-google-consent-screen\" src=\"https://user-images.githubusercontent.com/194400/69727668-e78fbc00-111a-11ea-8b39-124a4b045b02.png\">\n\nMake the Application **`Public`** (_the default option_) and\ninput the same name as you used for your application in step 1.\nUpload an image if you have one (_e.g: the icon/logo for your app_):\n\n<img width=\"1226\" alt=\"OAuth-consent-screen-1of2\" src=\"https://user-images.githubusercontent.com/194400/69727443-76500900-111a-11ea-9425-bff972afe565.png\">\n\nLeave the \"**Scopes for Google APIs**\" set to the default\n**email**, **profile** and **openid**.\n\nNo other data is required at this point, so skip the rest.\n\nScroll down to the bottom and click \"**Save**\":\n<img width=\"1277\" alt=\"OAuth-consent-screen-2of2\" src=\"https://user-images.githubusercontent.com/194400/69727445-76e89f80-111a-11ea-860d-fd41939dd10f.png\">\n\nThis will take you to the API Credentials page.\n\n## 4. Create Credentials\n\nClick the **Create Credentials** button:\n<img width=\"960\" alt=\"Screenshot 2019-11-26 at 23 24 28\" src=\"https://user-images.githubusercontent.com/194400/69725288-b2cd3600-1115-11ea-9601-04054cac6f5b.png\">\nThat will popup a menu from which you will select **OAuth Client ID**.\n\nYou will see a form that allows you to specify\nthe details of your App for the credentials.\n\n<img width=\"971\" alt=\"Screenshot 2019-11-27 at 02 13 55\" src=\"https://user-images.githubusercontent.com/194400/69728313-296d3200-111c-11ea-8da0-85c1ade89d8a.png\">\n\n+ Application Type: Web application\n+ Name: Elixir Auth Server\n+ Authorized JavaScript origins:\nhttp://localhost:4000\n(_the default for a Phoenix app on your local dev machine.\n  you can add your \"production\" URL later._)\n+ Authorized redirect URIs:  \nhttp://localhost:4000/auth/google/callback\n(_the endpoint to redirect to once authentication is successful.\n  again, add your production URL once you have auth working on `localhost`_)\n\n> Ensure you hit the enter key after pasting/typing\nthe URIs to ensure they are saved.\nA common stumbling block is that URIs aren't saved. See:\nhttps://stackoverflow.com/questions/24363041/redirect-uri-in-google-cloud-console-doesnt-save\n\nOnce you have input the relevant data click the **Create** button.\n\n> This form/step can be confusing at first,\nbut essentially you can have multiple credentials\nfor the same project,\ne.g: if you had a Native Android App\nyou would create a new set of credentials\nto ensure a separation of concerns between\nserver and client implementations.\nFor now just create the server (Elixir) credentials.\n\n\n## 5. Download the OAuth Client Credentials\n\nAfter you click the **Create** button\nin the **Create OAuth client ID** form (_step 4 above_),\nyou will be shown your OAuth client Credentials:\n\n<img width=\"970\" alt=\"elixir-auth-google-oauth-client-credentials\" src=\"https://user-images.githubusercontent.com/194400/69730648-5cb1c000-1120-11ea-8ad4-0ef62cfb6a0a.png\">\n\nDownload the credentials, e.g:\n\n+ Client ID: 631770888008-6n0oruvsm16kbkqg6u76p5cv5kfkcekt.apps.googleusercontent.com\n+ Client Secret: MHxv6-RGF5nheXnxh1b0LNDq\n\n> ⚠️ Don't worry, these keys aren't valid.\nWe deleted them immediately after capturing the screenshot\nto avoid any security issues.\nObviously treat your credentials\nlike you would the username+password for your bank account;\nnever share a **real** Client ID or secret on GitHub\nor any other public/insecure forum!\n\nYou can also download the OAuth credentials as a json file:\n\n<img width=\"821\" alt=\"elixir-auth-google-json\" src=\"https://user-images.githubusercontent.com/194400/69736916-57a63e00-112b-11ea-8b28-6f137f00106b.png\">\n\nExample:\n```json\n{\n  \"web\": {\n    \"client_id\": \"631770888008-6n0oruvsm16kbkqg6u76p5cv5kfkcekt.apps.googleusercontent.com\",\n    \"project_id\": \"elixir-auth-demo\",\n    \"auth_uri\": \"https://accounts.google.com/o/oauth2/auth\",\n    \"token_uri\": \"https://oauth2.googleapis.com/token\",\n    \"auth_provider_x509_cert_url\": \"https://www.googleapis.com/oauth2/v1/certs\",\n    \"client_secret\": \"MHxv6-RGF5nheXnxh1b0LNDq\",\n    \"redirect_uris\": [\n      \"http://localhost:4000/auth/google/callback\"\n    ],\n    \"javascript_origins\": [\n      \"http://localhost:4000\"\n    ]\n  }\n}\n```\n\n> Again, for security reasons,\nthese credentials were\ninvalidated _immediately_ after downloading. <br />\nBut this is what the file looks like.\n\n\nReturn to step 3 of the\n[README.md](https://github.com/dwyl/elixir-auth-google/blob/master/README.md)\n\n\n<br />\n\n# Note\n\nWhen you ship your app to your Production environment,\nyou will need to re-visit steps 3 & 4\nto update your app settings URL & callback\nto reflect the URl where you are deploying your app e.g:\n\n![add-heroku-app](https://user-images.githubusercontent.com/194400/70204921-32f92a00-171a-11ea-83b2-34e5eeea777b.png)\n\nIn our case\nhttps://elixir-auth-google-demo.herokuapp.com\nand\nhttps://elixir-auth-google-demo.herokuapp.com/auth/google/callback\n"
  },
  {
    "path": "lib/elixir_auth_google.ex",
    "content": "defmodule ElixirAuthGoogle do\n  @moduledoc \"\"\"\n  Minimalist Google OAuth Authentication for Elixir Apps.\n  Extensively tested, documented, maintained and in active use in production.\n  \"\"\"\n  @google_auth_url \"https://accounts.google.com/o/oauth2/v2/auth?response_type=code\"\n  @google_token_url \"https://oauth2.googleapis.com/token\"\n  @google_user_profile \"https://www.googleapis.com/oauth2/v3/userinfo\"\n  @default_scope \"profile email\"\n  @default_callback_path \"/auth/google/callback\"\n\n  @httpoison (Application.compile_env(:elixir_auth_google, :httpoison_mock) &&\n                ElixirAuthGoogle.HTTPoisonMock) || HTTPoison\n\n  @type conn :: map\n  @type url :: String.t()\n\n  @doc \"\"\"\n  `inject_poison/0` injects a TestDouble of HTTPoison in Test\n  so that we don't have duplicate mock in consuming apps.\n  see: github.com/dwyl/elixir-auth-google/issues/35\n  \"\"\"\n  def inject_poison, do: @httpoison\n\n  @doc \"\"\"\n  `get_baseurl_from_conn/1` derives the base URL from the conn struct\n  \"\"\"\n  @spec get_baseurl_from_conn(conn) :: String.t()\n  def get_baseurl_from_conn(%{host: h, port: p, scheme: s}) when p != 80 do\n    \"#{Atom.to_string(s)}://#{h}:#{p}\"\n  end\n\n  def get_baseurl_from_conn(%{host: h, scheme: s}) do\n    \"#{Atom.to_string(s)}://#{h}\"\n  end\n\n  def get_baseurl_from_conn(%{host: h} = conn) do\n    scheme =\n      case h do\n        \"localhost\" -> :http\n        _ -> :https\n      end\n\n    get_baseurl_from_conn(Map.put(conn, :scheme, scheme))\n  end\n\n  @doc \"\"\"\n  `generate_redirect_uri/1` generates the Google redirect uri based on `conn`\n  or the `url`. If the `App.Endpoint.url()`\n  e.g: auth.dwyl.com or https://gcal.fly.dev\n  is passed into `generate_redirect_uri/1`,\n  return that `url` with the callback appended to it.\n  See: github.com/dwyl/elixir-auth-google/issues/94\n  \"\"\"\n  @spec generate_redirect_uri(url) :: String.t()\n  def generate_redirect_uri(url) when is_binary(url) do\n    scheme =\n      cond do\n        # url already contains scheme return empty\n        String.contains?(url, \"https\") -> \"\"\n        # url contains \":\" is localhost:4000 no need for scheme\n        String.contains?(url, \":\") -> \"\"\n        # Default to https if scheme not set e.g: app.fly.dev -> https://app.fly.fev\n        true -> \"https://\"\n      end\n\n    \"#{scheme}#{url}\" <> get_app_callback_url()\n  end\n\n  @spec generate_redirect_uri(conn) :: String.t()\n  def generate_redirect_uri(conn) do\n    get_baseurl_from_conn(conn) <> get_app_callback_url()\n  end\n\n  @doc \"\"\"\n  `generate_oauth_url/1` creates the Google OAuth2 URL with client_id, scope and\n  redirect_uri which is the URL Google will redirect to when auth is successful.\n  This is the URL you need to use for your \"Login with Google\" button.\n  See step 5 of the instructions.\n  \"\"\"\n  @spec generate_oauth_url(String.t()) :: String.t()\n  def generate_oauth_url(url) when is_binary(url) do\n    query = [\n      client_id: google_client_id(),\n      redirect_uri: generate_redirect_uri(url),\n      scope: google_scope()\n    ]\n\n    params = URI.encode_query(query, :rfc3986)\n\n    \"#{@google_auth_url}&#{params}\"\n  end\n\n  @spec generate_oauth_url(conn) :: String.t()\n  def generate_oauth_url(conn) when is_map(conn) do\n    query = [\n      client_id: google_client_id(),\n      redirect_uri: generate_redirect_uri(conn),\n      scope: google_scope()\n    ]\n\n    params = URI.encode_query(query, :rfc3986)\n\n    \"#{@google_auth_url}&#{params}\"\n  end\n\n  @doc \"\"\"\n  Same as `generate_oauth_url/1` with `state` query parameter,\n  or a `map` of key/pair values to be included in the urls query string.\n  \"\"\"\n  @spec generate_oauth_url(conn, String.t() | map) :: String.t()\n  def generate_oauth_url(conn, state) when is_binary(state) do\n    params = URI.encode_query(%{state: state}, :rfc3986)\n    generate_oauth_url(conn) <> \"&#{params}\"\n  end\n\n  def generate_oauth_url(conn, query) when is_map(query) do\n    query = URI.encode_query(query, :rfc3986)\n    generate_oauth_url(conn) <> \"&#{query}\"\n  end\n\n  @doc \"\"\"\n  `get_token/2` encodes the secret keys and authorization code returned by Google\n  and issues an HTTP request to get a person's profile data.\n\n  **TODO**: we still need to handle the various failure conditions >> issues/16\n  \"\"\"\n  @spec get_token(String.t(), conn) :: {:ok, map} | {:error, any}\n  def get_token(code, conn) when is_map(conn) do\n    redirect_uri = generate_redirect_uri(conn)\n\n    inject_poison().post(@google_token_url, req_body(code, redirect_uri))\n    |> parse_body_response()\n  end\n\n  @spec get_token(String.t(), url) :: {:ok, map} | {:error, any}\n  def get_token(code, url) when is_binary(url) do\n    redirect_uri = generate_redirect_uri(url)\n\n    inject_poison().post(@google_token_url, req_body(code, redirect_uri))\n    |> parse_body_response()\n  end\n\n  defp req_body(code, redirect_uri) do\n    Jason.encode!(%{\n      client_id: google_client_id(),\n      client_secret: google_client_secret(),\n      redirect_uri: redirect_uri,\n      grant_type: \"authorization_code\",\n      code: code\n    })\n  end\n\n  @doc \"\"\"\n  `get_user_profile/1` requests the Google User's userinfo profile data\n  providing the access_token received in the `get_token/1` above.\n  invokes `parse_body_response/1` to decode the JSON data.\n\n  **TODO**: we still need to handle the various failure conditions >> issues/16\n  At this point the types of errors we expect are HTTP 40x/50x responses.\n  \"\"\"\n  @spec get_user_profile(String.t()) :: {:ok, map} | {:error, any}\n  def get_user_profile(token) do\n    params = URI.encode_query(%{access_token: token}, :rfc3986)\n\n    \"#{@google_user_profile}?#{params}\"\n    |> inject_poison().get()\n    |> parse_body_response()\n  end\n\n  @doc \"\"\"\n  `parse_body_response/1` parses the response returned by Google\n  so your app can use the resulting JSON.\n  \"\"\"\n  @spec parse_body_response({atom, String.t()} | {:error, any}) :: {:ok, map} | {:error, any}\n  def parse_body_response({:error, err}), do: {:error, err}\n\n  def parse_body_response({:ok, response}) do\n    body = Map.get(response, :body)\n    # make keys of map atoms for easier access in templates\n    if body == nil do\n      {:error, :no_body}\n    else\n      {:ok, str_key_map} = Jason.decode(body)\n      atom_key_map = for {key, val} <- str_key_map, into: %{}, do: {String.to_atom(key), val}\n      {:ok, atom_key_map}\n    end\n\n    # https://stackoverflow.com/questions/31990134\n  end\n\n  def google_client_id do\n    System.get_env(\"GOOGLE_CLIENT_ID\") || Application.get_env(:elixir_auth_google, :client_id)\n  end\n\n  defp google_client_secret do\n    System.get_env(\"GOOGLE_CLIENT_SECRET\") ||\n      Application.get_env(:elixir_auth_google, :client_secret)\n  end\n\n  defp google_scope do\n    System.get_env(\"GOOGLE_SCOPE\") || Application.get_env(:elixir_auth_google, :google_scope) ||\n      @default_scope\n  end\n\n  defp get_app_callback_url do\n    System.get_env(\"GOOGLE_CALLBACK_PATH\") ||\n      Application.get_env(:elixir_auth_google, :callback_path) || @default_callback_path\n  end\nend\n"
  },
  {
    "path": "lib/httpoison_mock.ex",
    "content": "defmodule ElixirAuthGoogle.HTTPoisonMock do\n  @moduledoc \"\"\"\n  This is a TestDouble for HTTPoison which returns a predictable response.\n  Please see: https://github.com/dwyl/elixir-auth-google/issues/35\n  \"\"\"\n\n  @doc \"\"\"\n  get/1 passing in the wrong_token is used to test failure in the auth process.\n  Obviously, don't invoke it from your App unless you want people to see fails.\n  \"\"\"\n  def get(\"https://www.googleapis.com/oauth2/v3/userinfo?access_token=wrong_token\") do\n    {:error, :bad_request}\n  end\n\n  # get/1 using a dummy _url to test body decoding.\n  def get(_url) do\n    {:ok,\n     %{\n       body:\n         Jason.encode!(%{\n           email: \"nelson@gmail.com\",\n           email_verified: true,\n           family_name: \"Correia\",\n           given_name: \"Nelson\",\n           locale: \"en\",\n           name: \"Nelson Correia\",\n           picture: \"https://lh3.googleusercontent.com/a-/AAuE7mApnYb260YC1JY7a\",\n           sub: \"940732358705212133793\"\n         })\n     }}\n  end\n\n  @doc \"\"\"\n  post/2 passing in dummy _url & _body to test return of access_token.\n  \"\"\"\n  def post(_url, _body) do\n    {:ok, %{body: Jason.encode!(%{access_token: \"token1\"})}}\n  end\nend\n"
  },
  {
    "path": "mix.exs",
    "content": "defmodule ElixirAuthGoogle.MixProject do\n  use Mix.Project\n\n  @description \"Minimalist Google OAuth Authentication for Elixir Apps\"\n  @version \"1.6.11\"\n\n  def project do\n    [\n      app: :elixir_auth_google,\n      version: @version,\n      elixir: \">= 1.11.0\",\n      start_permanent: Mix.env() == :prod,\n      deps: deps(),\n      description: @description,\n      package: package(),\n      aliases: aliases(),\n      # coverage\n      test_coverage: [tool: ExCoveralls]\n    ]\n  end\n\n  def cli do\n    [\n      preferred_envs: [\n        c: :test,\n        coveralls: :test,\n        \"coveralls.json\": :test,\n        \"coveralls.html\": :test,\n        t: :test\n      ]\n    ]\n  end\n\n  # Run \"mix help compile.app\" to learn about applications.\n  def application do\n    [\n      extra_applications: [:logger]\n    ]\n  end\n\n  # Run \"mix help deps\" to learn about dependencies.\n  defp deps do\n    [\n      {:credo, \"~> 1.5\", only: [:dev, :test], runtime: false},\n      {:httpoison, \"~> 2.3\"},\n      {:jason, \"~> 1.2\"},\n\n      # Track test coverage: github.com/parroty/excoveralls\n      {:excoveralls, \"~> 0.18.0\", only: [:test, :dev]},\n\n      # Mock stuffs in test: github.com/jjh42/mock\n      {:mock, \"~> 0.3.0\", only: :test},\n\n      # documentation\n      {:ex_doc, \"~> 0.40.0\", only: :dev}\n    ]\n  end\n\n  defp package do\n    [\n      maintainers: [\"dwyl\"],\n      licenses: [\"GPL-2.0-or-later\"],\n      links: %{github: \"https://github.com/dwyl/elixir-auth-google\"},\n      files: ~w(lib LICENSE mix.exs README.md .formatter.exs)\n    ]\n  end\n\n  defp aliases do\n    [\n      t: [\"test\"],\n      c: [\"coveralls.html\"]\n    ]\n  end\nend\n"
  },
  {
    "path": "test/elixir_auth_google_test.exs",
    "content": "defmodule ElixirAuthGoogleTest do\n  use ExUnit.Case, async: true\n  doctest ElixirAuthGoogle\n\n  import Mock\n\n  test \"get_baseurl_from_conn(conn) detects the URL based on conn.host HTTP\" do\n    conn = %{\n      host: \"localhost\",\n      port: 4000,\n      scheme: :http\n    }\n\n    assert ElixirAuthGoogle.get_baseurl_from_conn(conn) == \"http://localhost:4000\"\n  end\n\n  test \"get_baseurl_from_conn(conn) detects the URL based on conn.host HTTPS\" do\n    conn = %{\n      host: \"localhost\",\n      port: 4000,\n      scheme: :https\n    }\n\n    assert ElixirAuthGoogle.get_baseurl_from_conn(conn) == \"https://localhost:4000\"\n  end\n\n  test \"get_baseurl_from_conn(conn) detects the URL for production HTTPS\" do\n    conn = %{\n      host: \"dwyl.com\",\n      port: 80,\n      scheme: :https\n    }\n\n    assert ElixirAuthGoogle.get_baseurl_from_conn(conn) == \"https://dwyl.com\"\n  end\n\n  test \"get_baseurl_from_conn(conn) detects the URL for production HTTP\" do\n    conn = %{\n      host: \"dwyl.com\",\n      port: 80,\n      scheme: :http\n    }\n\n    assert ElixirAuthGoogle.get_baseurl_from_conn(conn) == \"http://dwyl.com\"\n  end\n\n  test \"get_baseurl_from_conn(conn) detects the URL for production HTTPS, non-standard port\" do\n    conn = %{\n      host: \"dwyl.com\",\n      port: 8080,\n      scheme: :https\n    }\n\n    assert ElixirAuthGoogle.get_baseurl_from_conn(conn) == \"https://dwyl.com:8080\"\n  end\n\n  test \"get Google login url\" do\n    conn = %{\n      host: \"localhost\",\n      port: 4000\n    }\n\n    assert ElixirAuthGoogle.generate_oauth_url(conn) =~\n             \"https://accounts.google.com/o/oauth2/v2/auth?response_type=code\"\n  end\n\n  test \"get Google login url (config redirect uri)\" do\n    conn = %{\n      host: \"localhost\",\n      port: 4000\n    }\n\n    url = ElixirAuthGoogle.generate_oauth_url(conn)\n    assert url =~ \"https://accounts.google.com/o/oauth2/v2/auth?response_type=code\"\n    assert url =~ \"http%3A%2F%2Flocalhost%3A4000\"\n  end\n\n  test \"get Google login url with state\" do\n    conn = %{\n      host: \"localhost\",\n      port: 4000\n    }\n\n    url = ElixirAuthGoogle.generate_oauth_url(conn, \"state1\")\n    id = System.get_env(\"GOOGLE_CLIENT_ID\")\n    id_from_config = Application.get_env(:elixir_auth_google, :client_id)\n\n    assert id == id_from_config\n\n    expected =\n      \"https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=\" <>\n        id <>\n        \"&redirect_uri=http%3A%2F%2Flocalhost%3A4000%2Fauth%2Fgoogle%2Fcallback&scope=profile%20email&state=state1\"\n\n    assert url == expected\n  end\n\n  test \"get Google login with language parameters\" do\n    conn = %{\n      host: \"localhost\",\n      port: 4000\n    }\n\n    url = ElixirAuthGoogle.generate_oauth_url(conn, %{hl: \"es-MX\"})\n    id = System.get_env(\"GOOGLE_CLIENT_ID\")\n    id_from_config = Application.get_env(:elixir_auth_google, :client_id)\n\n    assert id == id_from_config\n\n    expected =\n      \"https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=\" <>\n        id <>\n        \"&redirect_uri=http%3A%2F%2Flocalhost%3A4000%2Fauth%2Fgoogle%2Fcallback&scope=profile%20email&hl=es-MX\"\n\n    assert url == expected\n  end\n\n  test \"get Google token\" do\n    conn = %{\n      host: \"localhost\",\n      port: 4000\n    }\n\n    {:ok, res} = ElixirAuthGoogle.get_token(\"ok_code\", conn)\n    assert res == %{access_token: \"token1\"}\n  end\n\n  test \"get Google token with url as second param #94\" do\n    {:ok, res} = ElixirAuthGoogle.get_token(\"ok_code\", \"gcal.fly.dev\")\n    assert res == %{access_token: \"token1\"}\n  end\n\n  test \"get Google token (config redirect uri)\" do\n    conn = %{\n      host: \"localhost\",\n      port: 4000\n    }\n\n    {:ok, res} = ElixirAuthGoogle.get_token(\"ok_code\", conn)\n    assert res == %{access_token: \"token1\"}\n  end\n\n  test \"get_user_profile/1\" do\n    res = %{\n      email: \"nelson@gmail.com\",\n      email_verified: true,\n      family_name: \"Correia\",\n      given_name: \"Nelson\",\n      locale: \"en\",\n      name: \"Nelson Correia\",\n      picture: \"https://lh3.googleusercontent.com/a-/AAuE7mApnYb260YC1JY7a\",\n      sub: \"940732358705212133793\"\n    }\n\n    assert ElixirAuthGoogle.get_user_profile(\"123\") == {:ok, res}\n  end\n\n  test \"return error with incorrect token\" do\n    assert ElixirAuthGoogle.get_user_profile(\"wrong_token\") == {:error, :bad_request}\n  end\n\n  test \"generate_redirect_uri(conn) generate correct callback url\" do\n    conn = %{\n      host: \"foobar.com\",\n      port: 80\n    }\n\n    assert ElixirAuthGoogle.generate_redirect_uri(conn) ==\n             \"https://foobar.com/auth/google/callback\"\n  end\n\n  test \"generate_oauth_url(url) passing in App.Endpoint.url() #94\" do\n    url = \"gcal.fly.dev\"\n    client_id = ElixirAuthGoogle.google_client_id()\n    https = \"https%3A%2F%2F#{url}\"\n\n    auth_url =\n      \"https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=#{client_id}&redirect_uri=#{https}%2Fauth%2Fgoogle%2Fcallback&scope=profile%20email\"\n\n    assert ElixirAuthGoogle.generate_oauth_url(url) =~ auth_url\n  end\n\n  test \"generate_oauth_url(url) with scheme e.g. https://gcal.fly.dev #94\" do\n    no_scheme = \"gcal.fly.dev\"\n    url = \"https://#{no_scheme}\"\n    client_id = ElixirAuthGoogle.google_client_id()\n    https = \"https%3A%2F%2F#{no_scheme}\"\n\n    auth_url =\n      \"https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=#{client_id}&redirect_uri=#{https}%2Fauth%2Fgoogle%2Fcallback&scope=profile%20email\"\n\n    assert ElixirAuthGoogle.generate_oauth_url(url) =~ auth_url\n  end\n\n  test \"generate_redirect_uri(conn) generate correct callback url with custom url path from application environment variable\" do\n    conn = %{\n      host: \"foobar.com\",\n      port: 80\n    }\n\n    mock_get_env = fn :elixir_auth_google, :callback_path -> \"/special/callback\" end\n\n    with_mock Application, get_env: mock_get_env do\n      assert ElixirAuthGoogle.generate_redirect_uri(conn) ==\n               \"https://foobar.com/special/callback\"\n    end\n  end\n\n  test \"generate_redirect_uri(conn) generate correct callback url with custom url path from system environment variable\" do\n    conn = %{\n      host: \"foobar.com\",\n      port: 80\n    }\n\n    mock_get_env = fn \"GOOGLE_CALLBACK_PATH\" -> \"/very/special/callback\" end\n\n    with_mock System, get_env: mock_get_env do\n      assert ElixirAuthGoogle.generate_redirect_uri(conn) ==\n               \"https://foobar.com/very/special/callback\"\n    end\n  end\nend\n"
  },
  {
    "path": "test/test_helper.exs",
    "content": "ExUnit.start()\n"
  }
]