How to implement Gmail Authentication

697 views
Skip to first unread message

Moiz Nagpurwala

unread,
Mar 18, 2015, 12:50:15 PM3/18/15
to web...@googlegroups.com
Hello,

I'm developing an application for internal use in my company (hosted locally).

I want to enable authentication using Gmail e.g. my colleagues use there exiting gmail id for authentication.

I have implemented this code provided in "SMTP and Gmail" found here http://web2py.com/books/default/chapter/29/09/access-control#Other-login-methods-and-login-forms
in my db.py

from gluon.contrib.login_methods.email_auth import *
auth.settings.login_methods.append(email_auth("smtp.gmail.com:587","@gmail.com"))


Nothing seem to happen.

Please help.

Leonel Câmara

unread,
Mar 18, 2015, 1:12:50 PM3/18/15
to web...@googlegroups.com
You need to allow "insecure" applications to connect to your gmail account for that to work.

I would not use email_auth for that reason alone.

Moiz Nagpurwala

unread,
Mar 18, 2015, 6:00:50 PM3/18/15
to web...@googlegroups.com
I'm clueless here. I thought that this code would allow any user with valid gmail I'd to login in my app.

Michele Comitini

unread,
Mar 18, 2015, 6:46:59 PM3/18/15
to web...@googlegroups.com
Why not use OAuth2 with google?  It should work with the gmail account

2015-03-18 18:33 GMT+01:00 Moiz Nagpurwala <moi...@gmail.com>:
I'm clueless here. I thought that this code would allow any user with valid gmail I'd to login in my app.

--
Resources:
- http://web2py.com
- http://web2py.com/book (Documentation)
- http://github.com/web2py/web2py (Source code)
- https://code.google.com/p/web2py/issues/list (Report Issues)
---
You received this message because you are subscribed to the Google Groups "web2py-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to web2py+un...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Moiz Nagpurwala

unread,
Mar 19, 2015, 2:50:50 AM3/19/15
to web...@googlegroups.com
Any working example of OAuth2 with Google please.

The documentation only describes Facebook integration.

Thanks.

Moiz Nagpurwala

unread,
Apr 7, 2015, 10:01:22 AM4/7/15
to web...@googlegroups.com
Hello,

Still waiting for a working example of OAuth2 with Google.

It is very crucial for my application to integrate Google authentication in order to succeed.

Hope this great community won't let me down.

Thanks and regards.

Willoughby

unread,
Apr 8, 2015, 9:04:16 AM4/8/15
to web...@googlegroups.com
Web2PySlices has two examples of OAuth2 being used - have you looked at those?

piero crisci

unread,
Apr 9, 2015, 8:30:46 AM4/9/15
to web...@googlegroups.com
First of all you need to get the google_auth.json file to use OAuth
To get that you need to register your Google account as a webdeveloper
You can find how get the information on Google :)
 
Then u can change ur auth table  in this way
 
In the model.py
 
from gluon.tools import Auth, Crud, Service, PluginManager, prettydate
auth = Auth(db,secure=True)
crud, service, plugins = Crud(db), Service(), PluginManager()
## ------------TABELLE USER ------------------- ##
## create all tables needed by auth if not custom tables
auth.settings.extra_fields['auth_user']= [
  Field('phone', type='string', label='Telefono'),
  Field('country',type='string', label='Nazione'),
  Field('city',type='string', label='Città'),
  Field('address',type='string', label='Indirizzo'),
  Field('auth_login', type='string', default='basic', label='Tipo Login',readable=False, writable=False),
  Field('url_img', requires=IS_EMPTY_OR(IS_URL()), label='Link Immagine Profile',readable=False, writable=False),
  Field('nickname',  type='string', label='Nickname'),
  Field('birthdate',  type='date', label='Data Di nascita'),
  Field('gender', type = 'string', label='Genere' ,requires = IS_IN_SET(['M','F']), default = 'M'),
  Field('facebook_id', type='string', label='Username di Facebook',readable=False, writable=False),
  Field('twitter_id',  type='string', label='Username di Twitter',readable=False, writable=False),
  Field('google_id',  type='string', label='Username di Google',readable=False, writable=False ),
  Field('linkedin_id',  type='string', label='Username di Linkedin',readable=False, writable=False),
  ]
auth.define_tables(username=False, signature=True)
 
In The Controller
 
Import AccountAccess
def google():
    if auth.is_logged_in():
        redirect(URL(r=request, c='default', f='index'))
    folder = request.folder
    google_access = AccountAccess.GoogleAccount(folder)
    auth.settings.login_form=google_access
 
    return auth.login(next=URL(r=request, c='default', f='index'))
 
 
In the Module section
Create the AccountAccess module

import oauth2 as oauth
from gluon.contrib.login_methods.oauth10a_account import OAuthAccount as OAuthAccount10a
from gluon.contrib.login_methods.oauth20_account import OAuthAccount
from oauthtwitter_account import OAuthAccount as OauthAccountTwitter
import os
import storage
import urllib2
from oauth2 import Client, Consumer, Token

class GoogleAccount(OAuthAccount):
    "OAuth 2.0 for Google"
    def __init__(self,db,session,request,response,folder):
        with open(os.path.join(folder, 'private/google_auth.json'), 'rb') as f:
            gai = storage.Storage(json.load(f)['web'])
        self.db = db
        self.request = request
        self.response = response
        self.session = session
        g = dict(
                request=request,
                response=response,
                session=session,
                )
        OAuthAccount.__init__(self,g, gai.client_id, gai.client_secret,
                              gai.auth_uri, gai.token_uri,
                              scope='https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/plus.login',
                              approval_prompt='auto',
                              access_type = 'offline',
                              state="auth_provider=google")
    def get_user(self):
        token = self.accessToken()
        if not token:
            return None
        uinfo_url = 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=%s' % urllib2.quote(token, safe='')
        uinfo = None
        try:
            uinfo_stream = urllib2.urlopen(uinfo_url)
        except:
            session.token = None
            return None
        data = uinfo_stream.read()
        uinfo = json.loads(data)
        username = uinfo['id']
        if uinfo:
            gender = 'M'
            if uinfo['gender'][0].lower() == 'f':
                gender = 'F'
            existent = self.db(self.db.auth_user.email == uinfo["email"]).select(self.db.auth_user.id,self.db.auth_user.auth_login).first()
            if existent:
                if existent.auth_login <> 'Google':
                    diz_account = dict(
                         username = uinfo['email'],
                         gender = gender,
                         auth_login = 'Google',
                         url_img = uinfo.get('picture', ''),
                         google_id = uinfo['id'],
                         registration_id = uinfo['id']
                    )
                    existent.update_record(**diz_account)
                return dict(first_name = uinfo.get('given_name', uinfo["name"].split()[0]),
                            last_name = uinfo.get('family_name', uinfo["name"].split()[-1]),
                            username = uinfo['email'],
                            email = uinfo['email'],
                            gender = gender,
                            auth_login = 'Google',
                            birthdate = uinfo.get('birthday', ''),
                            url_img = uinfo.get('picture', ''),
                            google_id = uinfo['id'],
                            registration_id = uinfo['id']
                            )
            else:
#                self.db.auth.send_welcome_email(user)
                return dict(first_name = uinfo.get('given_name', uinfo["name"].split()[0]),
                            last_name = uinfo.get('family_name', uinfo["name"].split()[-1]),
                            username = uinfo['email'],
                            email = uinfo['email'],
                            gender = gender,
                            auth_login = 'Google',
                            birthdate = uinfo.get('birthday', ''),
                            url_img = uinfo.get('picture', ''),
                            google_id = uinfo['id'],
                            registration_id = uinfo['id']
                            )
    def call_api(self):
        api_return = urllib.urlopen("https://www.googleapis.com/oauth2/v1/userinfo?access_token=%s" % self.accessToken())
        user = json.loads(api_return.read())
        if user:
            return user
        else:
            session.token = None
            return None
 
 
It worked for me

Moiz Nagpurwala

unread,
Apr 9, 2015, 9:44:38 AM4/9/15
to web...@googlegroups.com
Thanks a lot.

I will surely give it a try.

Do-Yang Kim

unread,
Jul 11, 2015, 9:24:03 AM7/11/15
to web...@googlegroups.com
Hi. I'm a newbie trying web2py. I get this error when I try above code

Cannot import module 'applications.admin.modules.oauth2'

I'm assuming that I don't have oauth2 library set up in the module section. How can I fix this?

Massimo Di Pierro

unread,
Jul 12, 2015, 5:15:07 AM7/12/15
to web...@googlegroups.com, pla...@gmail.com
You have to run web2py from source and run 

pip install oath2

Michele Comitini

unread,
Jul 13, 2015, 5:28:52 AM7/13/15
to web...@googlegroups.com, pla...@gmail.com
The code for Google OAuth2 does not need to import oauth2.
If you use OAuth2 there is no need to use any external library for oauth.

While OAuth1.1 need the oauth2 python external python module (pip install oauth2 as Massimo says). 
I know it is ridiculous but the confusion arises from the python oauth2 library which is indeed for OAuth1.1.  A very poor naming choice...
Anyway OAuth1.1 is being phased out almost everywhere.

mic



--

Do-Yang Kim

unread,
Jul 14, 2015, 8:21:42 AM7/14/15
to web...@googlegroups.com, pla...@gmail.com
Thank you. I got the code to compile by running web2py from source but the suggested code above did not exactly work. I found a working solution from stackoverflow.
http://stackoverflow.com/questions/30072099/the-correct-way-to-implement-login-with-google-account
Reply all
Reply to author
Forward
0 new messages