Tuesday, July 3, 2018

python your oauth server login using google account integration

from flask import flash, redirect, url_for, session, request, jsonify
from flask_oauthlib.client import OAuth
from app.models.company_models import Company, CompanyInfo, Branch
from app.models.shared_models import Sphere, Business
from app import instance, oauth as my_oauth, my_mail
from app.models.auth_models import User
from flask_login import login_user, logout_user, current_user, login_required
import urllib
from app.helpers.url_helper import base_url
from app.libraries.odo.odo_common import uuid_generator

GOOGLE_CLIENT_ID = '1059700860469-sdfaasdf.apps.googleusercontent.com'
GOOGLE_CLIENT_SECRET = 'asdf'
# one of the Redirect URIs from Google APIs console
AUTH_REDIRECT_URI = '/googleauth/callback'

google_oauth = OAuth(instance)

google = google_oauth.remote_app(
'google',
consumer_key=GOOGLE_CLIENT_ID,
consumer_secret=GOOGLE_CLIENT_SECRET,
request_token_params={
'scope': 'email'
},
base_url='https://www.googleapis.com/oauth2/v1/',
request_token_url=None,
access_token_method='POST',
access_token_url='https://accounts.google.com/o/oauth2/token',
authorize_url='https://accounts.google.com/o/oauth2/auth',
)


@instance.route('/googleauth', methods=['GET', 'POST'])
def googleauth_index():
return redirect(url_for('googleauth_login', **request.args))


@instance.route('/googleauth/login')
def googleauth_login():
session['x_response_type'] = request.args['response_type']
session['x_client_id'] = request.args['client_id']
session['x_redirect_uri'] = request.args['redirect_uri']
session['x_scope'] = request.args['scope']

if 'google_token' in session:
token = session['google_token']
if not token is None:
googleauth_revoke()
session.pop('google_token')

return google.authorize(callback=url_for('googleauth_authorized', _external=True))


@instance.route('/googleauth/logout')
def googleauth_logout():

if 'google_token' in session:
token = session['google_token']
if token:
googleauth_revoke()
session.pop('google_token')

return redirect(base_url('order'))


@instance.route(AUTH_REDIRECT_URI)
def googleauth_authorized():

resp = google.authorized_response()

# try to revoke
if resp is None:
return 'Access denied: reason=%s error=%s' % (
request.args['error_reason'],
request.args['error_description']
)

session['google_token'] = (resp['access_token'], '')
google_user = google.get('userinfo').data
user = User.query.filter_by(email=google_user['email']).first()

if not user:
new_password = uuid_generator()

user = User()
user.username = google_user['email']
user.email = google_user['email']
user.password = new_password
user.role_id = 6 # new user is admin for your self
try:
user.save()

body = "Google хэрэглэгчээр системд бүртгүүлсэн нууц үг: " + new_password + ""
my_mail.Send("Таны систем дээрх нууц үг", body, [user.email])
except Exception as e:
flash('Хэрэглэгч бүртгэхэд алдаа гарлаа! ' +
str(e), category='error')

if login_user(user):
response_type = session['x_response_type']
client_id = session['x_client_id']
redirect_uri = session['x_redirect_uri']
scope = session['x_scope']
return redirect(url_for('googleauth_confirm_authorization', response_type=response_type, client_id=client_id, redirect_uri=redirect_uri, scope=scope))


@instance.route('/googleauth/confirm', methods=['GET', 'POST'])
@login_required
def googleauth_confirm_authorization():
return my_oauth.confirm_authorization_request()


@google.tokengetter
def googleauth_get_google_oauth_token():
return session.get('google_token')


def googleauth_revoke():
if 'google_token' in session:
token = session['google_token']
if not token is None:
try:
request = urllib.request.Request(
"https://accounts.google.com/o/oauth2/revoke?token=" + token[0])
request.add_header(
"Content-type", "application/x-www-form-urlencoded")
urllib.request.urlopen(request).read()
except Exception as e:
print(e)