Skip to content
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

fix example, document requirements to run example #6

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
__pycache__/
Flask_Firebase.egg-info
1 change: 1 addition & 0 deletions CHANGES.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
v1.8, 2023-04-10 -- Handle expired jwt token
v1.7, 2018-05-15 -- Allow setting of auth domain.
v1.6, 2017-10-26 -- Only verify last two domain levels on redirect.
v1.5, 2017-09-15 -- Use Firebase User.getIdToken().
Expand Down
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Philipp Keller

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
48 changes: 36 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ depends on the `Flask.debug` variable.

## Configuration

- `FIREBASE_API_KEY`: The API key.
- `FIREBASE_PROJECT_ID`: The project identifier, eg. `foobar`.
- `FIREBASE_API_KEY`: The API key. Get this from Firebase -> Project settings -> web api key
- `FIREBASE_PROJECT_ID`: The project identifier, eg. `foobar`. Project settings -> Project ID
- `FIREBASE_AUTH_SIGN_IN_OPTIONS`: Comma-separated list of enabled providers.

## Providers
Expand All @@ -22,17 +22,30 @@ depends on the `Flask.debug` variable.
- `google`
- `twitter`

## Sample code
## Working example

To get the example below working:

- ensure you have sqlite installed
- pip install the following packages into your virtualenv: `flask`, `requests`, `flask_login`, `flask_sqlalchemy` and `pyjwt`
- run the server with `export FLASK_DEBUG=1 && venv/bin/flask run --with-threads --cert adhoc` (<-- needs SSL as the social login provider would choke otherwise)
- allow self-signed certificate on localhost: in chrome go to chrome://flags/#allow-insecure-localhost and enable the setting
- replace all REPLACE_ME in the code below

```python
from flask import Flask, request
from flask import Flask, request, redirect
from flask_firebase import FirebaseAuth
from flask_login import LoginManager, UserMixin, login_user, logout_user
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user
from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)
app.config.from_object(...)
app.debug = False # to disable local testing
app.config['FIREBASE_API_KEY'] = 'REPLACE_ME'
app.config['FIREBASE_PROJECT_ID'] = 'REPLACE_ME'
app.config['FIREBASE_AUTH_SIGN_IN_OPTIONS'] = 'google,facebook' # <-- coma separated list, see Providers above
app.config['SECRET_KEY'] = 'REPLACE_ME' # <-- random string
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/firebase_users.db'

db = SQLAlchemy(app)
auth = FirebaseAuth(app)
Expand All @@ -45,13 +58,22 @@ class Account(UserMixin, db.Model):

__tablename__ = 'accounts'

account_id = db.Column(db.Integer, primary_key=True)
firebase_user_id = db.Column(db.Text, unique=True)
account_id = db.Column(db.Integer)
firebase_user_id = db.Column(db.Text, unique=True, primary_key=True)
email = db.Column(db.Text, unique=True, nullable=False)
email_verified = db.Column(db.Boolean, default=False, nullable=False)
name = db.Column(db.Text)
photo_url = db.Column(db.Text)

def get_id(self):
return self.firebase_user_id

def __repr__(self):
return str(dict(firebase_user_id=self.firebase_user_id, email=self.email, name=self.name))


db.create_all() # <-- don't use this in production! This creates the account table in your sqlite
db.session.commit()

@auth.production_loader
def production_sign_in(token):
Expand All @@ -72,18 +94,20 @@ def production_sign_in(token):
def development_sign_in(email):
login_user(Account.query.filter_by(email=email).one())


@auth.unloader
def sign_out():
logout_user()


@login_manager.user_loader
def load_user(account_id):
return Account.query.get(account_id)


@login_manager.unauthorized_handler
def authentication_required():
return auth.url_for('widget', mode='select', next=request.url)
return redirect(auth.url_for('widget', mode='select', next=request.url))

@app.route("/")
@login_required
def index():
return f"<p>Hello, {current_user.name}!</p>"
```
17 changes: 10 additions & 7 deletions flask_firebase/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,13 +105,16 @@ def sign_in(self):
with self.lock:
self.refresh_keys()
key = self.keys[header['kid']]
token = jwt.decode(
request.data,
key=key,
audience=self.project_id,
algorithms=['RS256'])
self.production_load_callback(token)
return 'OK'
try:
token = jwt.decode(
request.data,
key=key,
audience=self.project_id,
algorithms=['RS256'])
self.production_load_callback(token)
return 'OK'
except jwt.exceptions.ExpiredSignatureError as e:
abort(401, 'jwt signature expired')

def sign_out(self):
self.unload_callback()
Expand Down
1 change: 1 addition & 0 deletions flask_firebase/templates/firebase_auth/widget_base.html
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
ui.start("#firebaseui-auth-container", {
queryParameterForSignInSuccessUrl: "next",
signInOptions: [ {{ firebase_auth.provider_ids }} ],
signInFlow: 'popup',
callbacks: {
signInSuccess: function(user, credential, redirectUrl) {
user.getIdToken().then(function(token) {
Expand Down