I am trying to implement user registration and login system on Flask, which will accept traditional email registration along with OAuth 2.0 (Google and Facebook) registration and login.
For registration using email, its clear for me: I am collecting data using forms and writting into respective table.
user = Account(email=form.email.data.lower(), username=form.username.data.lower(), password=form.password.data)
In order to login into the system I ask for username and respective password. When it comes to OAuth Google login, after requesting the service and receiving the response from Google, I need to write received data into the table. For that purpose I have added extra column OAuth_ID, where I store user id received from Google.
if userinfo_response.json().get("email_verified"):
unique_id = userinfo_response.json()["sub"]
users_email = userinfo_response.json()["email"]
picture = userinfo_response.json()["picture"]
users_name = userinfo_response.json()["given_name"]
else:
return "User email not available or not verified by Google.", 400
user = Account.query.filter_by(email=users_email).first()
if user is None:
user = Account(email=users_email.lower(), oauth_id=unique_id, username=users_name.lower(), password='test-password')
db.session.add(user)
db.session.commit()
Please advice regarding the following: What shall I do with password field, which is mandatory (nullable=False) in database and required when registering using email. Above, I have inserted password manually for testing purpose which is wrong approach.
user = Account(email=users_email.lower(), oauth_id=unique_id, username=users_name.lower(), password='test-password')
How can I deal with passwords when I use OAuth? Second: What shall I do with username? Through Google OAuth I cant receive it.
Database model:
class Account(UserMixin, db.Model):
__tablename__ = 'accounts'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(30), nullable=False, unique=True, index=True)
password_hash = db.Column(db.String(128), nullable=False)
email = db.Column(db.String(50), nullable=False, unique=True)
activated = db.Column(db.Boolean, nullable=False, default=False)
activated_on = db.Column(db.Date)
last_seen = db.Column(db.DateTime(), default=datetime.utcnow)
oauth_id=db.Column(db.Integer(), unique=True, index=True)
role_id = db.Column(db.Integer(), db.ForeignKey('roles.id'))
user_login = db.relationship("User", uselist=False, backref="accounts")
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(50, collation='NOCASE'), nullable=False)
last_name = db.Column(db.String(50, collation='NOCASE'), nullable=False)
phone = db.Column(db.String(15), nullable=False)
login_id = db.Column(db.Integer, db.ForeignKey('accounts.id'))
Thank you in advance!