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

Added login #11

Merged
merged 3 commits into from
Jul 9, 2024
Merged
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
2 changes: 1 addition & 1 deletion api/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@ COPY . .

RUN pipenv install --ignore-pipfile --system --dev

CMD python wsgi.py
CMD python setup.py && python wsgi.py
1 change: 1 addition & 0 deletions api/Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ flask-bcrypt = "*"
python-dotenv = "*"
psycopg2-binary = "*"
flask-sqlalchemy = "*"
flask-login = "*"

[dev-packages]
pylint = "*"
Expand Down
11 changes: 9 additions & 2 deletions api/Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions api/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,7 @@
class Config(object):
SECRET_KEY = os.getenv('SECRET_KEY')
SQLALCHEMY_DATABASE_URI = os.getenv('SQLALCHEMY_DATABASE_URI')
SESSION_COOKIE_SECURE = True
REMEMBER_COOKIE_NAME = 'Pollination_token'
FLASK_ENV = 'development'
DEBUG = True
4 changes: 3 additions & 1 deletion api/pollination/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from flask_cors import CORS
from flask_bcrypt import Bcrypt
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from sqlalchemy.orm import DeclarativeBase
from config import Config

Expand All @@ -13,7 +14,8 @@
CORS(app)
app.config.from_object(Config)
app.app_context().push()

login_manager = LoginManager()
login_manager.init_app(app)
bcrypt = Bcrypt(app)


Expand Down
33 changes: 18 additions & 15 deletions api/pollination/models.py
Original file line number Diff line number Diff line change
@@ -1,41 +1,41 @@
'''
Contains the table representations of the database
'''
import string
import random
from uuid import uuid4
from flask_login import UserMixin
from pollination import db
from pollination import login_manager


# BELOW THIS ARE EXAMPLES
@login_manager.user_loader
def load_user(user_id):
'''Sets up the login manager to use the alt id'''
return db.session.scalars(db.select(User).filter_by(alt_id=user_id)).first()


def get_uuid():
'''Returns a unique id in hex'''
return uuid4().hex


def get_basic_id():
'''Returns a unique id of easy typeable string'''
return ''.join(random.choices(string.ascii_uppercase
+ string.ascii_lowercase, k=6))


class User(db.Model):
class User(db.Model, UserMixin):
'''
Only allows people with the team id to create an account
'''
__tablename__ = "User"
id = db.Column(db.String(32), primary_key=True,
unique=True, default=get_uuid)
alt_id = db.Column(db.String(6), unique=True, default=get_basic_id)
username = db.Column(db.Text, unique=True)
email = db.Column(db.Text, unique=True)
alt_id = db.Column(db.String(32), unique=True, default=get_uuid)
username = db.Column(db.Text, unique=True, nullable=False)
password = db.Column(db.String(72), nullable=False)
file = db.Relationship('File', back_populates='user',
cascade='all, delete', passive_deletes=True)
# Determine what access level the function is at

def get_id(self):
return str(self.alt_id)

def __repr__(self):
return f"Team('{self.name}','{ self.alt_id }')"
return f"User('{self.username}','{ self.alt_id }')"


class File(db.Model):
Expand Down Expand Up @@ -68,3 +68,6 @@ class Species(db.Model):
native = db.Column(db.Boolean)
location = db.Column(db.Text)
image_location = db.Column(db.Text)

def __repr__(self):
return f"Species('{self.name}', '{self.plant}', '{self.native}')"
71 changes: 68 additions & 3 deletions api/pollination/routes/__init__.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,78 @@
'''
Contains the initial api routes
'''
# from flask import request, jsonify
from pollination import app # , bcrypt, db
from flask import request, jsonify
from flask_login import login_user, current_user, logout_user
from flask_login import login_required, fresh_login_required
from pollination import app, bcrypt, login_manager, db
from pollination.models import User, File, Species


@login_manager.unauthorized_handler
def unauthorized():
'''
Unauthorized
'''
return jsonify({"Invalid": "Unauthorized"}), 401


@app.route('/api/login', methods=['POST'])
def login():
'''
User Login and sets a cookie to be authenticated in the future
'''
data = request.json

if (data is None):
return jsonify({"Invalid": "Incorrect username or password"}), 401
if (data.get('username') is None):
return jsonify({"Invalid": "Incorrect username or password"}), 401
if (data.get('password') is None):
return jsonify({"Invalid": "Incorrect username or password"}), 401

user = db.session.scalars(db.select(User)
.filter_by(username=data['username'])).one()

if (user is None or user.password is None):
# save value as a cookie
return jsonify({"Invalid": "Incorrect username or password"}), 401
# return "Invalid"

pass_check = bcrypt.check_password_hash(user.password, data['password'])
if (pass_check is False):
return jsonify({"Invalid": "Incorrect username or password"}), 401
# return "Invalid"

# Check remember me token if the user wants a cookie
login_user(user, remember=True)
# user.verified = True
return jsonify({"Success": "User is authenticated"}), 200


@app.route('/api/verify', methods=['GET'])
@login_required
def verify():
'''
Verifies the User
'''
return jsonify({"Success": "User is authenticated"}), 200


@app.route('/api/change-password', methods=['POST'])
@fresh_login_required
def change_password():
'''
Change password of the User
ADD BELOW
'''
return jsonify({"Success": "User password changed"}), 200


@app.route('/api/test', methods=['GET', 'POST'])
@login_required
def test():
'''
test
'''
return "This works"
user: User = current_user
return user.username
6 changes: 3 additions & 3 deletions api/setup.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
# pylint: skip-file
from pollination import db
from pollination import db, bcrypt
from pollination.models import User

if __name__ == "__main__":
db.drop_all()
db.create_all()

user = User(username="moo", email="testing@gmail.com")
hash = bcrypt.generate_password_hash("moo").decode('utf-8')
user = User(username="moo", password=hash)
db.session.add(user)
db.session.commit()
Loading