-
Notifications
You must be signed in to change notification settings - Fork 32
Verify user's ID token generated via firebase client. Bump version 0.2.1 #8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
aniruddhasd
wants to merge
3
commits into
scripbox:master
Choose a base branch
from
aniruddhasd:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+153
−1
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -210,6 +210,44 @@ iex(4)> FirebaseAdminEx.Auth.generate_sign_in_with_email_link(action_code_settin | |
"{\n \"kind\": \"identitytoolkit#GetOobConfirmationCodeResponse\",\n \"email\": \"[email protected]\",\n \"oobLink\": \"https://YOUR-FIREBASE-CLIENT.firebaseapp.com/__/auth/action?mode=signIn&oobCode=xcdwelFRvfbtghHjswvw2f3g46hh6j8&apiKey=Fgae35h6j78_vbsddgs34th6h6hhekj97gfj&lang=en&continueUrl=www.test.com/sign-in\"\n}\n"} | ||
``` | ||
|
||
* Verify user's ID token | ||
|
||
```ex | ||
# Fetch the id_token generated by firebase client for the user and pass to to verify_token(id_token, allow_unverified \\ true). It checks for valid certificate, issuer, audience, expiry and optionally if the user has a verified email address. | ||
#Returns user object with token details on successful verification. | ||
|
||
#Valid id token | ||
iex(5)> id_token = "eyJhbGciOiJSUzI1NiIsImtpZCI6ImQ1OThkYjVjZjE1ZWNhOTI0OWJhZTUzMDYzOWVkYzUzNmMzYzViYjUiLCJ0eXAiOiJKV1QifQ" | ||
iex(6)> FirebaseAdminEx.Auth.verify_token(id_token) | ||
{:ok, | ||
%{ | ||
"aud" => "YOUR-FIREBASE-PROJECT", | ||
"auth_time" => 1577079586, | ||
"email" => "[email protected]", | ||
"email_verified" => false, | ||
"exp" => 1577087136, | ||
"firebase" => %{ | ||
"identities" => %{"email" => ["[email protected]"]}, | ||
"sign_in_provider" => "password" | ||
}, | ||
"iat" => 1577083536, | ||
"iss" => "https://securetoken.google.com/YOUR-FIREBASE-PROJECT", | ||
"sub" => "xxxxxxxxxxxxxxxxxxxx", | ||
"user_id" => "USER-UID-ON-FIREBASE" | ||
}} | ||
|
||
#Expired id_token | ||
iex(7)> id_token = "eyJhbGciOiJSUzI1NiIsImtpZCI6ImQ1OThkYjVjZjE1ZWNhOTI0OWJhZTUzMDYzOWVkYzUzNmMzYzViYjUiLCJ0eXAiOiJKtyerdf" | ||
iex(8)> FirebaseAdminEx.Auth.verify_token(id_token) | ||
{:error, "Token has passed it's expiry time"} | ||
|
||
#Force check for verified email address | ||
iex(9)> id_token = "eyJhbGciOiJSUzI1NiIsImtpZCI6ImQ1OThkYjVjZjE1ZWNhOTI0OWJhZTUzMDYzOWVkYzUzNmMzYzViYjUiLCJ0eXAiOiJKV1QifQ" | ||
iex(10)> FirebaseAdminEx.Auth.verify_token(id_token,false) | ||
{:error, "Email is not verified"} | ||
``` | ||
|
||
|
||
## Firebase Documentation | ||
|
||
* [Setup Guide](https://firebase.google.com/docs/admin/setup/) | ||
|
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,6 +5,7 @@ defmodule FirebaseAdminEx.Auth do | |
@auth_endpoint "https://www.googleapis.com/identitytoolkit/v3/relyingparty/" | ||
@auth_endpoint_account "https://identitytoolkit.googleapis.com/v1/projects/" | ||
@auth_scope "https://www.googleapis.com/auth/cloud-platform" | ||
@auth_cert_url "https://www.googleapis.com/robot/v1/metadata/x509/[email protected]" | ||
|
||
@doc """ | ||
Get a user's info by UID | ||
|
@@ -36,6 +37,20 @@ defmodule FirebaseAdminEx.Auth do | |
def delete_user(uid, client_email \\ nil), | ||
do: do_request("deleteAccount", %{localId: uid}, client_email) | ||
|
||
@doc """ | ||
Update an existing user by UID | ||
Pick one or more fields that require updation. | ||
Passing the firebase UID as local_id is mandatory, force check this in the client before using update_user api. | ||
iex(9)> request_body = %{email_verified: true, local_id: "iD1vovu1QsOcOFrkB2XBw2F4jsZ2"} | ||
%{email_verified: true, local_id: "iD1vovu1QsOcOFrkB2XBw2F4jsZ2"} | ||
iex(10)> FirebaseAdminEx.Auth.update_user(request_body) | ||
{:ok, _UPDATED_USER_BODY_RESPONSE} | ||
|
||
""" | ||
@spec update_user(map, String.t() | nil) :: tuple() | ||
def update_user(request_body, client_email \\ nil), | ||
do: do_request("setAccountInfo", request_body, client_email) | ||
|
||
# TODO: Add other commands: | ||
# list_users | ||
# create_user | ||
|
@@ -67,6 +82,105 @@ defmodule FirebaseAdminEx.Auth do | |
end | ||
end | ||
|
||
@doc """ | ||
Fetch environment specific Firebase project_id | ||
""" | ||
def firebase_project_id() do | ||
Goth.Config.get(:project_id) |> elem(1) | ||
end | ||
|
||
@doc """ | ||
Verify id token based on certificate, token issuer and timestamp | ||
""" | ||
@spec verify_token(String.t(), boolean()) :: tuple() | ||
def verify_token(id_token, allow_unverified \\ true) do | ||
with {:ok, fields} <- resolve_token_firebase(id_token, @auth_cert_url), | ||
{true,_} <- check_payload_email_verified(fields["email_verified"],allow_unverified), | ||
{true,_} <- check_payload_audience(fields["aud"]), | ||
{true,_} <- check_payload_issuer(fields["iss"]), | ||
{true,_} <- check_payload_expiry(fields["exp"]) do | ||
{:ok, fields} | ||
else | ||
{:error, reason} -> {:error, reason} | ||
{false, reason} -> {:error, reason} | ||
end | ||
end | ||
|
||
@doc """ | ||
Resolve id token based on certificate into firebase user data | ||
""" | ||
@spec resolve_token_firebase(String.t(), String.t()) :: tuple() | ||
def resolve_token_firebase(id_token, cert_url) do | ||
with true <- !is_nil(id_token), | ||
{:ok, response} <- HTTPoison.get(cert_url), | ||
%{body: body} = response, | ||
certs = Poison.Parser.parse!(body, %{}), | ||
{:ok, header} <- Joken.peek_header(id_token), | ||
jwks = JOSE.JWK.from_firebase(certs), | ||
true <- !is_nil(jwks[header["kid"]]), | ||
jwk = jwks[header["kid"]] |> JOSE.JWK.to_map |> elem(1), | ||
{true, jose_jwt, _} = JOSE.JWT.verify(jwk, id_token) do | ||
fields = JOSE.JWT.to_map(jose_jwt) |> elem(1) | ||
{:ok, fields} | ||
else | ||
false -> {:error, "id_token is nil"} | ||
{:error, _} -> {:error, "Unable to resolve id_token error"} | ||
{false,_} -> {:error, "Unable to resolve id_token due to certificate mismatch"} | ||
end | ||
end | ||
|
||
@doc """ | ||
Check if the email in the payload is verified. If client allows unverified users, | ||
set allow_unverified to true | ||
""" | ||
@spec check_payload_email_verified(String.t(), boolean()) :: tuple() | ||
def check_payload_email_verified(field_value, allow_unverified) do | ||
if field_value || allow_unverified do | ||
{true, "Email is verified"} | ||
else | ||
{false, "Email is not verified"} | ||
end | ||
end | ||
|
||
@doc """ | ||
Check if the issuer in the payload matches client's firebase project | ||
""" | ||
@spec check_payload_issuer(String.t()) :: tuple() | ||
def check_payload_issuer(field_value) do | ||
firebase_project_id = firebase_project_id() | ||
if field_value == "https://securetoken.google.com/" <> firebase_project_id do | ||
{true, "Issuer matches client's firebase project"} | ||
else | ||
{false, "Token issuer does not match client's firebase project"} | ||
end | ||
end | ||
|
||
@doc """ | ||
Check if the audience in the payload matches client's firebase project | ||
""" | ||
@spec check_payload_audience(String.t()) :: tuple() | ||
def check_payload_audience(field_value) do | ||
firebase_project_id = firebase_project_id() | ||
if field_value == firebase_project_id do | ||
{true, "Audience matches client's firebase project"} | ||
else | ||
{false, "Token aud does not match client's firebase project"} | ||
end | ||
end | ||
|
||
@doc """ | ||
Check that the token expiry time has not passed. | ||
""" | ||
@spec check_payload_expiry(integer()) :: tuple() | ||
def check_payload_expiry(field_value) do | ||
current_datetime = DateTime.utc_now |> DateTime.to_unix | ||
if field_value > current_datetime do | ||
{true, "Token is valid"} | ||
else | ||
{false, "Token has passed it's expiry time"} | ||
end | ||
end | ||
|
||
defp do_request(url_suffix, payload, client_email, project_id) do | ||
with {:ok, response} <- | ||
Request.request( | ||
|
This file contains hidden or 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
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
i worked on something similar, can you check this code, maybe you can use it
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@bernardd @nitinstp23