def oauthLogin(provider_name): authomatic = Authomatic(AUTHOMATIC_CONFIG, 'your secret string', report_errors=True) response = make_response() result = authomatic.login(WerkZeug(request,response),provider_name) if result: if result.user: result.user.update() appuser = dict(username = result.user.username, email = result.user.email,password="******") logging.debug(appuser) user = User() uid = user.get_id(appuser['username']) if uid is not None: log_user_in(appuser['username'],uid) else: # call register user message = register_user(appuser) if message is None: return log_user_in(appuser['username'],uid) return str(message) # query db and see if result.user.email is there, # if the answer is yes, get username and all stuff for this user # log him in with the data from our database # if he is not there then add result.user.email, result.user.stuff # generate password for him and log him in with that #log_user_in(appuser.username,appuser.uid) #,True,result.user.email) return redirect(url_for('startpage',n=0)) return response
def init_app(self, app): if app.config.get("MODULE_USER_ACCOUNT_ENABLE_OAUTH_LOGIN"): secret = app.config.get("SECRET_KEY") providers = app.config.get("MODULE_USER_ACCOUNT_OAUTH_PROVIDERS") config = {} auth_providers = [] for provider, conf in list(providers.items()): if hasattr(oauth2, provider): cls = getattr(oauth2, provider) conf[ "class_"] = conf["class_"] if "class_" in conf else cls elif hasattr(oauth1, provider): cls = getattr(oauth1, provider) conf[ "class_"] = conf["class_"] if "class_" in conf else cls else: continue conf["id"] = provider_id() _provider = provider.lower() auth_providers.append(_provider) config[_provider] = conf self.oauth = Authomatic(config=config, secret=secret, session=session, report_errors=True) Juice.g(OAUTH_PROVIDERS=auth_providers)
def login_with(provider_name): """ The below is login page action using OAuth with Google :param provider_name: The provider name. google by default """ response = make_response() authomatic = Authomatic(app.config['SOCIAL_LOGIN'], app.secret_key) result = authomatic.login( WerkzeugAdapter(request, response), provider_name, None, session=session, session_saver=lambda: app.save_session(session, response)) if result and result.user and result.user.credentials: response = result.provider.access( authomatic.config.get(provider_name).get('url')) if response.status == 200: """ Create a new user if the provided email is not exists. Otherwise, update the current user """ user = User.first_or_new(email=response.data.get('email')) user.name = response.data.get('name') user.save() login_user(user) return redirect(url_for('index')) return response
def login_provider(provider=None): """ Login handler, must accept both GET and POST to be able to use OpenID. """ authomatic = Authomatic(config=config.config, secret=config.SECRET_KEY, report_errors=True, logging_level=log.level) response = make_response(redirect(redirect_url())) result = authomatic.login(WerkzeugAdapter(request, response), provider) if result: user = result.user if user: user.update() verified = mongoUtils.verify_user(user, provider=provider) if not verified: verified = mail.send_activation_email(email=user.email) flash("Welcome to SoFly! An email has been sent to verify your email address.", category='info') session['user'] = dict( email = user.email, first_name = user.first_name, last_name = user.last_name, name = user.name, id = user.id, verified = verified ) log.debug(session['user']) return response
def login_with(provider_name): response = make_response() authomatic = Authomatic( { 'default': 'google', 'google': { 'class_': 'authomatic.providers.oauth2.Google', 'consumer_key': '426158043393-j1gnqba0dpucop2o5m9lo7m248vr1744' '.apps.googleusercontent.com', 'consumer_secret': 'd88vSFHyhZJ63O4ug6GrksTB', 'scope': ['profile', 'email'], 'url': 'https://www.googleapis.com/userinfo/v2/me', }, }, app.secret_key) result = authomatic.login( WerkzeugAdapter(request, response), provider_name, None, session=session, session_saver=lambda: app.save_session(session, response)) if result and result.user and result.user.credentials: response = result.provider.access( authomatic.config.get(provider_name).get('url')) if response.status == 200: user = User.first_or_new(email=response.data.get('email')) user.name = response.data.get('name') user.save() login_user(user) return redirect(url_for('index')) return response
def oauthLogin(provider_name): authomatic = Authomatic(AUTHOMATIC_CONFIG, 'your secret string', report_errors=True) response = make_response() result = authomatic.login(WerkZeug(request, response), provider_name) if result: if result.user: result.user.update() appuser = dict(username=result.user.username, email=result.user.email, password="******") logging.debug(appuser) user = User() uid = user.get_id(appuser['username']) if uid is not None: log_user_in(appuser['username'], uid) else: # call register user message = register_user(appuser) if message is None: return log_user_in(appuser['username'], uid) return str(message) # query db and see if result.user.email is there, # if the answer is yes, get username and all stuff for this user # log him in with the data from our database # if he is not there then add result.user.email, result.user.stuff # generate password for him and log him in with that #log_user_in(appuser.username,appuser.uid) #,True,result.user.email) return redirect(url_for('startpage', n=0)) return response
def __call__(self): cfg = authomatic_cfg() if cfg is None: return "Authomatic is not configured" if not ( ISiteRoot.providedBy(self.context) or INavigationRoot.providedBy(self.context) ): # callback url is expected on either navigationroot or site root # so bevor going on redirect root = api.portal.get_navigation_root(self.context) self.request.response.redirect( "{0}/authomatic-handler/{1}".format( root.absolute_url(), getattr(self, 'provider', '') ) ) return "redirecting" if not hasattr(self, 'provider'): return self.template() if self.provider not in cfg: return "Provider not supported" if not self.is_anon: if self.provider in self._provider_names: raise ValueError( 'Provider {0} is already connected to current ' 'user.'.format(self.provider) ) # TODO: some sort of CSRF check might be needed, so that # not an account got connected by CSRF. Research needed. pass auth = Authomatic( cfg, secret=authomatic_settings().secret.encode('utf8') ) result = auth.login( ZopeRequestAdapter(self), self.provider ) if not result: logger.info('return from view') # let authomatic do its work return if result.error: return result.error.message display = cfg[self.provider].get('display', {}) provider_name = display.get('title', self.provider) if not self.is_anon: # now we delegate to PAS plugin to add the identity self._add_identity(result, provider_name) self.request.response.redirect( "{0}".format(self.context.absolute_url()) ) else: # now we delegate to PAS plugin in order to login self._remember_identity(result, provider_name) self.request.response.redirect( "{0}/login_success".format(self.context.absolute_url()) ) return "redirecting"
def __call__(self): cfg = authomatic_cfg() if cfg is None: return "Authomatic is not configured" if not ( ISiteRoot.providedBy(self.context) or INavigationRoot.providedBy(self.context) ): # callback url is expected on either navigationroot or site root # so bevor going on redirect root = api.portal.get_navigation_root(self.context) self.request.response.redirect( "{0}/authomatic-handler/{1}".format( root.absolute_url(), getattr(self, 'provider', '') ) ) return "redirecting" if not hasattr(self, 'provider'): return self.template() if self.provider not in cfg: return "Provider not supported" if not self.is_anon: if self.provider in self._provider_names: raise ValueError( 'Provider {0} is already connected to current ' 'user.'.format(self.provider) ) # TODO: some sort of CSRF check might be needed, so that # not an account got connected by CSRF. Research needed. pass secret = authomatic_settings().secret if six.PY2 and isinstance(secret, six.text_type): secret = secret.encode('utf8') auth = Authomatic(cfg, secret=secret) result = auth.login(ZopeRequestAdapter(self), self.provider) if not result: logger.info('return from view') # let authomatic do its work return if result.error: return result.error.message display = cfg[self.provider].get('display', {}) provider_name = display.get('title', self.provider) if not self.is_anon: # now we delegate to PAS plugin to add the identity self._add_identity(result, provider_name) self.request.response.redirect( "{0}".format(self.context.absolute_url()) ) else: # now we delegate to PAS plugin in order to login self._remember_identity(result, provider_name) if api.env.plone_version() < '5.2': self.request.response.redirect( "{0}/login_success".format(self.context.absolute_url()) ) else: self.request.response.redirect(self.context.absolute_url()) return "redirecting"
def login(self, request): authomatic = Authomatic(self.config, self.key, report_errors=True) response = make_response() result = authomatic.login(WerkzeugAdapter(request, response), self.provider) return response, result
def login(): """Use Authomatic to log a user in. Once Authomatic has done its thing, check against valid users to allow or invalidate the login session. Note that this URL needs to be registered as an authorized redirect URI in the credentials for the webapp: Be logged in as the Google account that will own eMoL Go to: https://console.developers.google.com Select Credentials Create credentials for the app Authorize the Google+ API The client ID and client secret go into config.py as consumer_key and consumer_secret in the OAUTH2 section Set this URL (http://example.com/login) as an authorized redirect URI """ session.clear() response = make_response() authomatic = Authomatic( current_app.config['AUTHOMATIC_CONFIG'], current_app.config['AUTHOMATIC_SECRET'] ) result = authomatic.login( WerkzeugAdapter(request, response), 'google' ) if result: if result.user: result.user.update() # User is logged in, now check against our user table print(result.user) user = User.query.filter( User.email == result.user.email ).one_or_none() if user is None: # No. abort(401) else: # Yes! login_user(user) return redirect(url_for('home.index')) if request.method == 'POST': abort(500) else: return response
def __init__(self): self.authomatic_config = { 'google': { 'class_': oauth2.Google, 'consumer_key': app.config['GOOGLE_OAUTH_CLIENT_ID'], 'consumer_secret': app.config['GOOGLE_OAUTH_CONSUMER_SECRET'], 'scope': ['profile', 'email'] } } self.authomatic = Authomatic(self.authomatic_config, app.config['AUTHOMATIC_SALT'])
def oauth(request, provider): response = HttpResponse() authomatic = Authomatic( get_setting(settings.AUTHOMATIC_CONFIG, request), get_setting(settings.SECRET_KEY, request) ) result = authomatic.login(DjangoAdapter(request, response), provider) if result: if result.error: messages.error( request, 'There was an error signing you in. Please try again' ) return HttpResponseRedirect(reverse('sign_in')) if result.user: # Then user is being redirected back from provider with their data # # OAuth 2.0 and OAuth 1.0a provide only limited user data on login, # We need to update the user to get more info. if not (result.user.name and result.user.id): result.user.update() provider = result.provider.name user = KagisoUser.get_user_from_auth_db(result.user.email) if user: _social_login(request, user.email, provider) return HttpResponseRedirect('/') else: gender = result.user.gender if gender: # Form constants (region, gender) are in uppercase gender = gender.upper() data = { 'provider': provider, 'email': result.user.email, 'first_name': result.user.first_name, 'last_name': result.user.last_name, 'gender': gender, 'birth_date': result.user.birth_date, } request.session['oauth_data'] = data return HttpResponseRedirect(reverse('sign_up')) # If result.user is None then user will be redirected to provider # to authenticate themselves, prior to being redirected back to this view. return response
def login_view(self): log.debug('login_view') response = Response() dpconf = dict(class_=oauth2.Dataporten, consumer_key=self.settings.get('oauth_client_id', ''), consumer_secret=self.settings.get('oauth_client_secret', '')) authomatic = Authomatic(config=dict(dp=dpconf), secret='mumbojumbo') result = authomatic.login(WebObAdapter(self.request, response), 'dp') if result: # The login procedure is over log.debug('login_view - login complete') return self.login_complete(result) else: log.debug('login_view - login not complete') return response
def view_authomatic_(self, config, e): response = Response() provider_name = e.context.name logger.info('using provider %r' % provider_name) if not provider_name in config: msg = 'I got to the URL for provider %r even though it is not in the config.' % provider_name raise ValueError(msg) authomatic = Authomatic(config=config, secret='some random secret string') url_base_public = self.options.url_base_public url_base_internal = self.options.url_base_internal if not ((url_base_public is None) == (url_base_public is None)): msg = 'Only one of url_base_public and url_base_internal is specified.' raise Exception(msg) result = authomatic.login( MyWebObAdapter(e.request, response, url_base_internal, url_base_public), provider_name) if not result: return response # If there is result, the login procedure is over and we can write to response. response.write('<a href="..">Home</a>') if result.error: # Login procedure finished with an error. msg = result.error.message return self.show_error(e, msg, status=500) elif result.user: # OAuth 2.0 and OAuth 1.0a provide only limited user data on login, # We need to update the user to get more info. # if not (result.user.name and result.user.id): result.user.update() s = "user info: \n" for k, v in result.user.__dict__.items(): s += '\n %s : %s' % (k, v) logger.debug(s) next_location = config.get('next_location', e.root) handle_auth_success(self, e, provider_name, result, next_location) # # response.write('<pre>'+s+'</pre>') # # Welcome the user. # response.write(u'<h1>Hi {0}</h1>'.format(result.user.name)) # response.write(u'<h2>Your id is: {0}</h2>'.format(result.user.id)) # response.write(u'<h2>Your email is: {0}</h2>'.format(result.user.email)) # just regular login return response
def oauth(request, provider): response = HttpResponse() authomatic = Authomatic(get_setting(settings.AUTHOMATIC_CONFIG, request), get_setting(settings.SECRET_KEY, request)) result = authomatic.login(DjangoAdapter(request, response), provider) if result: if result.error: messages.error( request, 'There was an error signing you in. Please try again') return HttpResponseRedirect(reverse('sign_in')) if result.user: # Then user is being redirected back from provider with their data # # OAuth 2.0 and OAuth 1.0a provide only limited user data on login, # We need to update the user to get more info. if not (result.user.name and result.user.id): result.user.update() provider = result.provider.name user = KagisoUser.get_user_from_auth_db(result.user.email) if user: _social_login(request, user.email, provider) return HttpResponseRedirect('/') else: gender = result.user.gender if gender: # Form constants (region, gender) are in uppercase gender = gender.upper() data = { 'provider': provider, 'email': result.user.email, 'first_name': result.user.first_name, 'last_name': result.user.last_name, 'gender': gender, 'birth_date': result.user.birth_date, } request.session['oauth_data'] = data return HttpResponseRedirect(reverse('sign_up')) # If result.user is None then user will be redirected to provider # to authenticate themselves, prior to being redirected back to this view. return response
def init_app(self, app): if app.config.get("MODULE_USER_ACCOUNT_ENABLE_OAUTH_LOGIN"): secret = app.config.get("SECRET_KEY") providers = app.config.get("MODULE_USER_ACCOUNT_OAUTH_PROVIDERS") config = {} auth_providers = [] for provider, conf in providers.items(): if hasattr(oauth2, provider): cls = getattr(oauth2, provider) conf["class_"] = conf["class_"] if "class_" in conf else cls elif hasattr(oauth1, provider): cls = getattr(oauth1, provider) conf["class_"] = conf["class_"] if "class_" in conf else cls else: continue conf["id"] = provider_id() _provider = provider.lower() auth_providers.append(_provider) config[_provider] = conf self.oauth = Authomatic( config=config, secret=secret, session=session, report_errors=True ) Webmaster.g(OAUTH_PROVIDERS=auth_providers)
def get_authomatic(request): settings = request.registry.settings # authomatic social auth authomatic_conf = { # callback http://yourapp.com/social_auth/twitter 'twitter': { 'class_': oauth1.Twitter, 'consumer_key': settings.get('authomatic.pr.twitter.key', 'X'), 'consumer_secret': settings.get('authomatic.pr.twitter.secret', 'X'), }, # callback http://yourapp.com/social_auth/facebook 'facebook': { 'class_': oauth2.Facebook, 'consumer_key': settings.get('authomatic.pr.facebook.app_id', 'X'), 'consumer_secret': settings.get('authomatic.pr.facebook.secret', 'X'), 'scope': ['email'], }, # callback http://yourapp.com/social_auth/google 'google': { 'class_': oauth2.Google, 'consumer_key': settings.get('authomatic.pr.google.key', 'X'), 'consumer_secret': settings.get('authomatic.pr.google.secret', 'X'), 'scope': ['email'], } } return Authomatic(config=authomatic_conf, secret=settings['authomatic.secret'])
class GoogleOauthAuthenticator(AbstractUserAuthenticator): """ User authenticator class implementing Google OAuth. """ def __init__(self): self.authomatic_config = { 'google': { 'class_': oauth2.Google, 'consumer_key': app.config['GOOGLE_OAUTH_CLIENT_ID'], 'consumer_secret': app.config['GOOGLE_OAUTH_CONSUMER_SECRET'], 'scope': [ 'profile', 'email' ] } } self.authomatic = Authomatic( self.authomatic_config, app.config['AUTHOMATIC_SALT'] ) @property def auth_type(self): return 'google oauth' def log_in(self): response = flask.make_response() result = self.authomatic.login( WerkzeugAdapter(request, response), 'google', session=session, session_saver=lambda: app.save_session(session, response), secure_cookie=(True if request.is_secure else False) ) if result: if result.error: msg = 'Google auth failed with error: {0}' logging.error(msg.format(result.error.message)) return abort(403) # successful login if result.user: result.user.update() user = result.user self.set_expiration() self.set_current_user(email=user.email, first_name=user.first_name, last_name=user.last_name) # TODO: find a way to save the angular args? # authomatic adds url params google auth has stripped the # angular args anyway, so let's just redirect back to the # index. resp = self.redirect_to_index() self.set_csrf_token(resp) return resp # Authomatic will have put a redirect in our response here. return response
def includeme(config: Configurator) -> None: """Pyramid knob.""" settings = config.registry.settings # Pyramid requires an authorization policy to be active. config.set_authorization_policy(ACLAuthorizationPolicy()) # Enable JWT authentication. config.include("pyramid_jwt") config.set_jwt_authentication_policy( config.registry.settings["jwt.secret"], auth_type="Token" ) # Add API routes for auth config.add_route("user", "/api/user") config.add_route("login", "/login") # Add request.user shorthand config.add_request_method(get_user, "user", reify=True) # Add request.authomatic shorthand authomatic = Authomatic( config={ "github": { "class_": oauth2.GitHub, "consumer_key": settings["github.consumer_key"], "consumer_secret": settings["github.consumer_secret"], "access_headers": {"User-Agent": "getoffmylawn"}, } }, secret=settings["jwt.secret"], ) config.add_request_method(lambda self: authomatic, "authomatic", reify=True)
def login_view(self): log.debug('login_view') response = Response() dpconf = dict(class_=oauth2.Dataporten, consumer_key=self.settings.get('oauth_client_id', ''), consumer_secret=self.settings.get( 'oauth_client_secret', '')) authomatic = Authomatic(config=dict(dp=dpconf), secret='mumbojumbo') result = authomatic.login(WebObAdapter(self.request, response), 'dp') if result: # The login procedure is over log.debug('login_view - login complete') return self.login_complete(result) else: log.debug('login_view - login not complete') return response
def dipluginauthomaticlogin(request): platform = request.GET.get('platform') course_code = request.GET.get('course_code') group_id = request.GET.get('group_id') html_response = HttpResponse() if (platform in settings.DATAINTEGRATION_PLUGINS_INCLUDEAUTHOMATIC): di_plugin = settings.DATAINTEGRATION_PLUGINS[platform] authomatic = Authomatic(di_plugin.authomatic_config_json, di_plugin.authomatic_secretkey) result = authomatic.login(DjangoAdapter(request, html_response), di_plugin.authomatic_config_key, report_errors=True) # If there is no result, the login procedure is still pending. # Don't write anything to the response if there is no result! if result: # If there is result, the login procedure is over and we can write to response. html_response.write('<a href="..">Home</a>') if result.error: # Login procedure finished with an error. html_response.write('<h2>Error: {0}</h2>'.format(result.error.message)) elif result.user: # Hooray, we have the user! # OAuth 2.0 and OAuth 1.0a provide only limited user data on login, # We need to update the user to get more info. if not (result.user.name and result.user.id): result.user.update() # Welcome the user. html_response.write(u'<p>Hi {0}</p>'.format(result.user.name)) # response.write(u'<h2>Your id is: {0}</h2>'.format(result.user.id)) # response.write(u'<h2>Your email is: {0}</h2>'.format(result.user.email)) # If there are credentials (only by AuthorizationProvider), # we can _access user's protected resources. if result.user.credentials: if result.provider.name == 'fb': di_plugin.perform_import(group_id, course_code, result) post_smimport(course_code, "Facebook") html_response.write('Updating Facebook for ' + course_code) else: html_response.write('Auth Returned no Response.') return html_response
async def redirect_login_record_session_google(request): success_cb, error_cb, adapter, first_response = oauth_init(request) if adapter is None: return first_response authomatic = Authomatic(config=CONFIG, secret=SECRET_SALT) result = authomatic.login(adapter, 'fb', # session=session['authomatic'], session_saver=lambda: None) if result: if result.error: warning("FB login error", result.error) return response.redirect('%s?error=%s' % (error_cb, result.error)) elif result.user: debug("FB login success", result.user) result.user.update() user_dict = result.user.__dict__ debug("FB retrieving email", user_dict) rea = authomatic.access(result.user.credentials, 'https://graph.facebook.com/' + result.user.id + '?fields=email') user_email = json.loads(rea.read().decode('utf-8'))["email"] debug("FB login update success", result.user) return upsert_login_redirect(request, "facebook:" + user_email, {'email': user_email, 'id': user_dict['id'], 'username': user_dict['username'], 'name': user_dict['name'], 'first_name': user_dict['first_name'], 'last_name': user_dict['last_name'], 'nickname': user_dict['nickname'], 'link': user_dict['link'], 'gender': user_dict['gender'], 'timezone': user_dict['timezone'], 'locale': user_dict['locale'], 'birth_date': user_dict['birth_date'], 'country': user_dict['country'], 'city': user_dict['city'], 'location': user_dict['location'], 'postal_code': user_dict['postal_code'], 'picture': user_dict['picture'], 'phone': user_dict['phone'], }, success_cb, adapter) return adapter.response
def setup_authomatic(app): authomatic = Authomatic(app.config['OAUTH_CONFIG'], app.config['SECRET_KEY'], report_errors=True) def func(): g.authomatic = authomatic return func
def authomatic_setup(request): magpie_secret = get_constant("MAGPIE_SECRET", request, settings_name="magpie.secret") return Authomatic(config=authomatic_config(request), secret=magpie_secret, logger=AUTHOMATIC_LOGGER, report_errors=True, logging_level=AUTHOMATIC_LOGGER.level)
def __call__(self): cfg = authomatic_cfg() if cfg is None: return "Authomatic is not configured" if not (ISiteRoot.providedBy(self.context) or INavigationRoot.providedBy(self.context)): # callback url is expected on either navigationroot or site root # so bevor going on redirect root = api.portal.get_navigation_root(self.context) self.request.response.redirect("{}/authomatic-handler/{}".format( root.absolute_url(), getattr(self, "provider", ""))) return "redirecting" if not getattr(self, "provider", None): return self.template() if self.provider not in cfg: return "Provider not supported" if not self.is_anon: if self.provider in self._provider_names: logger.warn( "Provider %s is already connected to current " "user.", self.provider) return self._redirect() # TODO: some sort of CSRF check might be needed, so that # not an account got connected by CSRF. Research needed. pass secret = authomatic_settings().secret auth = Authomatic(cfg, secret=secret) result = auth.login(ZopeRequestAdapter(self), self.provider) if not result: logger.info("return from view") # let authomatic do its work return if result.error: return result.error.message display = cfg[self.provider].get("display", {}) provider_name = display.get("title", self.provider) if not self.is_anon: # now we delegate to PAS plugin to add the identity self._add_identity(result, provider_name) else: # now we delegate to PAS plugin in order to login self._remember_identity(result, provider_name) return self._redirect()
def __init__(self): print("Start server") self.printers = [] self.printer_class = {} self.db = pymongo.MongoClient('localhost', 27017)['SunAlert'] self.authomatic = Authomatic(CONFIG, 'your secret string', report_errors=False) self.app = Flask('SunAlert') self.start() self.app.config['TEMPLATES_AUTO_RELOAD'] = True self.app.config['TESTING'] = True self.app.config['DEBUG'] = True self.app.config['ENV'] = "development" self.app.run(host="0.0.0.0", port=9999)
def init_app(app): if app.config['AUTH_PROVIDERS'] is None: raise RuntimeError('You must configure the authentication providers. For more info look at the local.conf file') app.authomatic = Authomatic( app.config['AUTH_PROVIDERS'], app.config['APP_SECRET_KEY'], report_errors=False ) app.register_blueprint(mod)
def get_social_media_id(request): ''' Gets users social media IDs for use in signup for information integration. :param request: :return: ''' # TODO: Add social media functionality apart from facebook # We we need the response object for the adapter. html_response = HttpResponse() if (platform in settings.DATAINTEGRATION_PLUGINS_INCLUDEAUTHOMATIC): di_plugin = settings.DATAINTEGRATION_PLUGINS[platform] authomatic = Authomatic(di_plugin.authomatic_config_json, di_plugin.authomatic_secretkey) result = authomatic.login(DjangoAdapter(request, html_response), di_plugin.authomatic_config_key, report_errors=True) # If there is no result, the login procedure is still pending. # Don't write anything to the response if there is no result! if result: # If there is result, the login procedure is over and we can write to response. #html_response.write('<a href="..">Home</a>') if result.error: # Login procedure finished with an error. html_response.write('<p>Error: {0}</p>'.format(result.error.message)) elif result.user: # Hooray, we have the user! # OAuth 2.0 and OAuth 1.0a provide only limited user data on login, # We need to update the user to get more info. if not (result.user.name and result.user.id): result.user.update() # Welcome the user. # html_response.write(u'<p>Hi {0}</p>'.format(result.user.name)) html_response.write(u'<h2>Your Facebook id is: {0}</h2>'.format(result.user.id)) else: html_response.write('Auth Returned no Response.') return html_response
def login(provider_name): """ Login handler, must accept both GET and POST to be able to use OpenID. """ authomatic = Authomatic(current_app.config['AUTHOMATIC'], current_app.config['SECRET_KEY'], report_errors=False) # We need response object for the WerkzeugAdapter. response = make_response() # Log the user in, pass it the adapter and the provider name. result = authomatic.login(WerkzeugAdapter(request, response), provider_name) # If there is no LoginResult object, the login procedure is still pending. if result: if result.user: if not (result.user.first_name and result.user.last_name and result.user.id and result.user.email): # We need to update the user to get more info. result.user.update() if not result.user.email.endswith("@thenewmotion.com"): return current_app.login_manager.unauthorized() user = User.query.filter_by(email=result.user.email).first() if not user: user = User(result.user.email, first_name=result.user.first_name, last_name=result.user.last_name, active=True) db.session.add(user) db.session.commit() login_user(user) flash("Logged in successfully.", category="success") # The rest happens inside the template. return redirect(request.args.get('next') or url_for('public.home')) # Don't forget to return the response. return response
def login(provider_name): """ Login handler, must accept both GET and POST to be able to use OpenID. """ authomatic = Authomatic( current_app.config['AUTHOMATIC'], current_app.config['SECRET_KEY'], report_errors=False) # We need response object for the WerkzeugAdapter. response = make_response() # Log the user in, pass it the adapter and the provider name. result = authomatic.login(WerkzeugAdapter(request, response), provider_name) # If there is no LoginResult object, the login procedure is still pending. if result: if result.user: if not (result.user.first_name and result.user.last_name and result.user.id and result.user.email): # We need to update the user to get more info. result.user.update() if not result.user.email.endswith("@thenewmotion.com"): return current_app.login_manager.unauthorized() user = User.query.filter_by(email=result.user.email).first() if not user: user = User(result.user.email, first_name=result.user.first_name, last_name=result.user.last_name, active=True) db.session.add(user) db.session.commit() login_user(user) flash("Logged in successfully.", category="success") # The rest happens inside the template. return redirect(request.args.get('next') or url_for('public.home')) # Don't forget to return the response. return response
async def redirect_login_record_session_google(request): success_cb, error_cb, adapter, first_response = oauth_init(request) if adapter is None: return first_response authomatic = Authomatic(config=CONFIG, secret=SECRET_SALT) result = authomatic.login(adapter, 'google', # session=session['authomatic'], session_saver=lambda: None) if result: if result.error: warning("Google login error", result.error) return response.redirect('%s?error=%s' % (error_cb, result.error)) elif result.user: debug("Google login success", result.user) result.user.update() debug("Google login update success", result.user) userdict = result.user.to_dict() return upsert_login_redirect(request, "google:" + userdict['email'], result.user.to_dict(), success_cb, adapter) return adapter.response
def facebook_login_view(request): from pyramid.response import Response from authomatic.providers import oauth2 from authomatic.adapters import WebObAdapter from authomatic import Authomatic CONFIG = { 'fb': { 'class_': oauth2.Facebook, 'consumer_key': request.registry.settings['facebook.key'], 'consumer_secret': request.registry.settings['facebook.secret'], 'scope': ['public_profile', 'email'] } } authomatic = Authomatic(config=CONFIG, secret='mysecret') response = Response() result = authomatic.login(WebObAdapter(request, response), 'fb') if result: if result.error: response.write(result.error.message) elif result.user: if result.user.credentials: url = 'https://graph.facebook.com/me?fields=id,name,email,first_name,last_name' fb_response = result.provider.access(url) if fb_response.status == 200: data = fb_response.data response.write('facebook id: {} <br />'.format(data['id'])) response.write('facebook name: {} <br />'.format( data['name'])) response.write('facebook first name: {} <br />'.format( data['first_name'])) response.write('facebook last name: {} <br />'.format( data['last_name'])) response.write('facebook email: {} <br />'.format( data['email'])) return response
class OAuthomatic(object): oauth = None response = None def init_app(self, app): if app.config.get("MODULE_USER_ACCOUNT_ENABLE_OAUTH_LOGIN"): secret = app.config.get("SECRET_KEY") providers = app.config.get("MODULE_USER_ACCOUNT_OAUTH_PROVIDERS") config = {} auth_providers = [] for provider, conf in providers.items(): if hasattr(oauth2, provider): cls = getattr(oauth2, provider) conf["class_"] = conf["class_"] if "class_" in conf else cls elif hasattr(oauth1, provider): cls = getattr(oauth1, provider) conf["class_"] = conf["class_"] if "class_" in conf else cls else: continue conf["id"] = provider_id() _provider = provider.lower() auth_providers.append(_provider) config[_provider] = conf self.oauth = Authomatic( config=config, secret=secret, session=session, report_errors=True ) Webmaster.g(OAUTH_PROVIDERS=auth_providers) def login(self, provider): response = make_response() adapter = WerkzeugAdapter(request, response) login = self.oauth.login(adapter=adapter, provider_name=provider, session=session, session_saver=self._session_saver) self.response = response return login def _session_saver(self): session.modified = True
class OAuthomatic(object): oauth = None response = None def init_app(self, app): if app.config.get("MODULE_USER_ACCOUNT_ENABLE_OAUTH_LOGIN"): secret = app.config.get("SECRET_KEY") providers = app.config.get("MODULE_USER_ACCOUNT_OAUTH_PROVIDERS") config = {} auth_providers = [] for provider, conf in list(providers.items()): if hasattr(oauth2, provider): cls = getattr(oauth2, provider) conf[ "class_"] = conf["class_"] if "class_" in conf else cls elif hasattr(oauth1, provider): cls = getattr(oauth1, provider) conf[ "class_"] = conf["class_"] if "class_" in conf else cls else: continue conf["id"] = provider_id() _provider = provider.lower() auth_providers.append(_provider) config[_provider] = conf self.oauth = Authomatic(config=config, secret=secret, session=session, report_errors=True) Juice.g(OAUTH_PROVIDERS=auth_providers) def login(self, provider): response = make_response() adapter = WerkzeugAdapter(request, response) login = self.oauth.login(adapter=adapter, provider_name=provider, session=session, session_saver=self._session_saver) self.response = response return login def _session_saver(self): session.modified = True
def __init__(self): self.authomatic_config = { 'google': { 'class_': oauth2.Google, 'consumer_key': app.config['GOOGLE_OAUTH_CLIENT_ID'], 'consumer_secret': app.config['GOOGLE_OAUTH_CONSUMER_SECRET'], 'scope': [ 'profile', 'email' ] } } self.authomatic = Authomatic( self.authomatic_config, app.config['AUTHOMATIC_SALT'] )
def configure_oauth(settings): # pragma: no cover CONFIG = { 'fb': { 'class_': oauth2.Facebook, 'consumer_key': settings['facebook.key'], 'consumer_secret': settings['facebook.secret'], 'scope': ['email'] }, 'google': { 'class_': oauth2.Google, 'consumer_key': settings['google.key'], 'consumer_secret': settings['google.secret'], 'scope': ['email'] } } authomatic = Authomatic(config=CONFIG, secret="giftpacito") return authomatic
def setup_authomatic(app): authomatic = Authomatic( { 'fb': { 'consumer_key': app.config['CONSUMER_KEY'], 'consumer_secret': app.config['CONSUMER_SECRET'], 'class_': oauth2.Facebook, 'scope': [], } }, app.config['SECRET_KEY'], report_errors=False) def func(): g.authomatic = authomatic return func
def get_authomatic(request): settings = request.registry.settings # authomatic social auth authomatic_conf = { # callback http://yourapp.com/social_auth/twitter 'twitter': { 'class_': oauth1.Twitter, 'consumer_key': settings.get('authomatic.pr.twitter.key', ''), 'consumer_secret': settings.get('authomatic.pr.twitter.secret', ''), }, # callback http://yourapp.com/social_auth/facebook 'facebook': { 'class_': oauth2.Facebook, 'consumer_key': settings.get('authomatic.pr.facebook.app_id', ''), 'consumer_secret': settings.get('authomatic.pr.facebook.secret', ''), 'scope': ['email'], }, # callback http://yourapp.com/social_auth/google 'google': { 'class_': oauth2.Google, 'consumer_key': settings.get('authomatic.pr.google.key', ''), 'consumer_secret': settings.get('authomatic.pr.google.secret', ''), 'scope': ['profile', 'email'], }, 'github': { 'class_': oauth2.GitHub, 'consumer_key': settings.get('authomatic.pr.github.key', ''), 'consumer_secret': settings.get('authomatic.pr.github.secret', ''), 'scope': ['repo', 'public_repo', 'user:email'], 'access_headers': { 'User-Agent': 'AppEnlight' }, }, 'bitbucket': { 'class_': oauth1.Bitbucket, 'consumer_key': settings.get('authomatic.pr.bitbucket.key', ''), 'consumer_secret': settings.get('authomatic.pr.bitbucket.secret', '') } } return Authomatic(config=authomatic_conf, secret=settings['authomatic.secret'])
def init_app(self, app): if self._authomatic: return self._authomatic = Authomatic(config={ 'facebook': { 'class_': oauth2.Facebook, 'consumer_key': app.config['FB_CONSUMER_KEY'], 'consumer_secret': app.config['FB_CONSUMER_SECRET'], 'scope': ['public_profile', 'email'], }, 'google': { 'class_': oauth2.Google, 'consumer_key': app.config['GOOGLE_CONSUMER_KEY'], 'consumer_secret': app.config['GOOGLE_CONSUMER_SECRET'], 'scope': ['profile', 'email'], }, }, secret=app.config['SECRET_KEY'], debug=True, logger=app.logger)
def includeme(config): """ The authomatic config should look something like this: 'fb': { 'class_': authomatic.providers.oauth2.Facebook, # Facebook is an AuthorizationProvider too. 'consumer_key': '########################', 'consumer_secret': '########################', # But it is also an OAuth 2.0 provider and it needs scope. 'scope': ['user_about_me', 'email', 'publish_stream'], }, So we need to resolve the 'class_' part for whatever we have configured. For this project we'll also keep the secret within this file """ authomatic_file = config.registry.settings.get('kedja.authomatic', '') if authomatic_file: with open(authomatic_file, 'r') as f: auth_config = yaml.safe_load(f) secret = auth_config.pop('secret', None) if secret is None: logger.warning("'secret' is missing within the automatic configuration. A random secret will be used.") secret = str(uuid4()) # Fix all class names within the configuration for k, section in auth_config.items(): if 'class_' in section: section['class_'] = config.maybe_dotted(section['class_']) else: raise ConfigurationError("The section '%s' lacks the 'class_' key which is required." % k) authomatic = Authomatic(config=auth_config, secret=secret) config.registry.registerUtility(authomatic, IAuthomatic) logger.debug("Registered authomatic with providers: '%s'" % ", ".join(auth_config.keys())) else: logger.warning("'kedja.authomatic' is missing in the paster.ini file. " "It should point to a yaml file with Authomatic configuration. " "Login with authomatic will be disabled!")
def __init__(self, app, datastore, geoip=None, celery=None, message_cls=None, authomatic=None, views=None, schemas=None, add_api_routes=True): self.app = app self.datastore = datastore self.config = config = self.config_cls(app.config) self.request_utils = self.request_utils_cls(config, geoip) self.emails = self.emails_cls(config, message_cls, celery) self.authomatic = authomatic or Authomatic( config['AUTHOMATIC_CONFIG'], config['AUTHOMATIC_SECRET_KEY']) self.schemas = schemas or self.schemas self.views = views or self.views self.blueprint = Blueprint('userflow', 'flask_userflow', url_prefix=config['URL_PREFIX'], subdomain=config['SUBDOMAIN'], template_folder='templates') if add_api_routes: _add_api_routes(config, self.views, self.blueprint) app.register_blueprint(self.blueprint) self._init_login_manager() self._init_principal() self.auth_token_serializer = self._create_serializer('auth_token') self.register_confirm_serializer = self._create_serializer( 'register_confirm') self.restore_confirm_serializer = \ self._create_serializer('restore_confirm')
def get_authomatic(request): settings = request.registry.settings # authomatic social auth authomatic_conf = { # callback http://yourapp.com/social_auth/twitter "twitter": { "class_": oauth1.Twitter, "consumer_key": settings.get("authomatic.pr.twitter.key", ""), "consumer_secret": settings.get("authomatic.pr.twitter.secret", ""), }, # callback http://yourapp.com/social_auth/facebook "facebook": { "class_": oauth2.Facebook, "consumer_key": settings.get("authomatic.pr.facebook.app_id", ""), "consumer_secret": settings.get("authomatic.pr.facebook.secret", ""), "scope": ["email"], }, # callback http://yourapp.com/social_auth/google "google": { "class_": oauth2.Google, "consumer_key": settings.get("authomatic.pr.google.key", ""), "consumer_secret": settings.get("authomatic.pr.google.secret", ""), "scope": ["profile", "email"], }, "github": { "class_": oauth2.GitHub, "consumer_key": settings.get("authomatic.pr.github.key", ""), "consumer_secret": settings.get("authomatic.pr.github.secret", ""), "scope": ["repo", "public_repo", "user:email"], "access_headers": {"User-Agent": "AppEnlight"}, }, "bitbucket": { "class_": oauth1.Bitbucket, "consumer_key": settings.get("authomatic.pr.bitbucket.key", ""), "consumer_secret": settings.get("authomatic.pr.bitbucket.secret", ""), }, } return Authomatic(config=authomatic_conf, secret=settings["authomatic.secret"])
def worker(cls, self, methods): users = self.user if not isinstance(users, list): users = [users.get()] else: users = [user.get() for user in users] for method in methods: if method == 'APP': reg_ids = [] for user in users: if getattr(user, '%s_regid' % self.app_name, None): reg_ids.append(getattr(user, '%s_regid' % self.app_name)) if len(reg_ids) > 0: App_notification(self.app_name).sendNotice(reg_ids, self.message, self.url if self.url.startswith('http') else 'http://hanasee.com%s' % self.url) elif method == 'MAIL': for user in users: if type(user) == ndb.key.Key or getattr(user, 'email', None) is None: pass elif mail.is_email_valid(user.email): user_address = user.email sender_address = "Hanasee <*****@*****.**>" subject = '[Hanasee] %s' % self.message body = """ 하나시(Hanasee)에서 알려드립니다. \n\n %s \n\n 바로가기 : %s \n\n 항상 저희 점핑너츠의 하나시(Hanasee)를 이용해주시는 유저분들께 감사드립니다. """ % (self.message, self.url if self.url.startswith('http') else 'http://hanasee.com%s' % self.url) options = {} options['username'] = user.nickname options['uid'] = user.key.id() options['picture'] = user.picture options['message'] = self.message options['url'] = self.url if self.url.startswith('http') else 'http://hanasee.com%s' % self.url options['email'] = user.email template = JINJA_ENVIRONMENT.get_template('email.html') html = template.render(options) mail.send_mail(sender_address, user_address, subject, body, html=html) elif method == 'SNS': authomatic = Authomatic(config=CONFIG, secret='a-long-secret-string') for user in users: if type(user) == ndb.key.Key: pass elif getattr(user, 'fb', None): token = user.fb """ if self.action == 'regist' or self.action == 'write': url = 'https://graph.facebook.com/me/feed' body = u'message=%s&link=%s&caption=HANASEE' % (self.message, self.url if self.url.startswith('http') else 'http://hanasee.com%s' % self.url) else: url = 'https://graph.facebook.com/v2.0/me/og.likes' body = u'message=%s&object=%s' % (self.message, self.url if self.url.startswith('http') else 'http://hanasee.com%s' % self.url) """ url = 'https://graph.facebook.com/me/feed' body = u'message=%s&link=%s' % (self.message, self.url if self.url.startswith('http') else 'http://hanasee.com%s' % self.url) authomatic.access(token, url, method='POST', body=body) elif getattr(user, 'tw', None): token = user.tw url = 'https://api.twitter.com/1.1/statuses/update.json' #body = u'status=%s' % (self.message + self.url if self.url.startswith('http') else 'http://hanasee.com%s' % self.url) body = self.message + self.url if self.url.startswith('http') else 'http://hanasee.com%s' % self.url authomatic.access(token, url, method='POST', params=dict(status=body)) '''' authomatic.access(token, url='https://api.twitter.com/1.1/statuses/update.json', params=dict(status=(self.message + self.url if self.url.startswith('http') else 'http://hanasee.com%s' % self.url)), method='POST') ''' elif getattr(user, 'kakao', None): token = user.kakao self.url = self.url if self.url.startswith('http') else 'http://hanasee.com%s' % self.url urlInfo = {} urlInfo['url'] = self.url urlInfo['host'] = 'hanasee.com' if getattr(self, 'part', None): part = self.part.get() urlInfo['title'] = part.content elif getattr(self, 'hanasy', None): hanasy = self.hanasy.get() urlInfo['title'] = hanasy.title urlInfo['description'] = hanasy.description """ images = [] i = 0; for image in hanasy.images: if i > 2: break images.append(image) i = i+1 if len(images) > 0: urlInfo['image'] = images """ else: urlInfo['title'] = 'Hanasee' #urlInfo['image'] = ['https://lh5.ggpht.com/-8H5uPC3vLUCBhTLW0gWZQEMBQLWxsQ7mrkKbSEtvWl97OkPjoYxShx7zUKYICn19CA=w300-rw'] urlInfo = json.dumps(urlInfo) url = 'https://kapi.kakao.com/v1/api/story/post/link' body = u'link_info=%s&content=%s&android_exec_param=url=%s' % (urlInfo, self.message, self.url) authomatic.access(token, url, method='POST', body=body) elif getattr(user, 'google', None): pass pass else: pass
def login(provider): # after login url next_page = 'site.index' # check if provider is valid providers = OAuthProvider() if provider not in providers.get_slugs(): abort(404) # create authomatic and response objects authomatic = Authomatic(providers.credentials, app.config['SECRET_KEY'], report_errors=True) oauth_response = make_response() # try login provider_name = providers.get_name(provider) adapter = WerkzeugAdapter(request, oauth_response) result = authomatic.login(adapter, provider_name) if result: # flash error message if any if result.error and app.debug: session['remember_me'] = False session['provider'] = None msg = BeautifulSoup(result.error.message).findAll(text=True) flash({'type': 'alert', 'text': ' '.join(msg)}) # if success redir_resp = make_response(redirect(url_for(next_page))) if result.user: result.user.update() # check if api sent email address if not result.user.email: msg = '{} is refusing to send us your email address. ' msg += 'Please, try another log in provider.' flash({'type': 'error', 'text': msg.format(provider_name)}) next_page = 'site.login_options' # manage user data in db else: # convert all emails to lowercase (avoids duplicity in db) result.user.email = result.user.email.lower() # if existing user user = User.query.filter_by(email=result.user.email).first() if user: if provider != user.created_with: return redirect('/login/{}'.format(user.created_with)) user.last_seen = datetime.now() db.session.add(user) db.session.commit() # if new user else: now = datetime.now() roles = Group() if result.user.email in app.config['ADMIN']: role = roles.default('admin') else: role = roles.default() new_user = User(email=result.user.email, name=result.user.name, created_with=provider, created_at=now, last_seen=now, group=role) # check if email address is valid if not new_user.valid_email(): msg = 'The address “{}” provided by {} is not a valid ' msg += 'email. Please, try another log in provider.' flash({'type': 'error', 'text': msg.format(new_user.email, provider_name)}) next_page = 'site.login_options' # save user to db else: db.session.add(new_user) db.session.commit() new_query = User.query.filter_by(email=new_user.email) user = new_query.first() # login user if user and user.valid_email(): login_user(user) flash({'type': 'success', 'text': 'Welcome, {}'.format(result.user.name)}) # remember me remember_me = session.get('remember_me', False) if remember_me: session_provider = session.get('provider', False) if provider == session_provider: session['remember_me'] = False session['provider'] = None user.remember_me_token = user.get_token() db.session.add(user) db.session.commit() max_age = 60 * 60 * 24 * 30 redir_resp.set_cookie('remember_me', user.get_hash(), max_age=max_age) redir_resp.set_cookie('user_id', str(user.id), max_age=max_age) return redir_resp return oauth_response
def signin(self, **kwargs): logging.error("signin") result = { 'code': 400, 'message': 'bad request' } args_signin = ['email', 'password'] args_device = ['deviceId', 'appName'] args_oauth = ['type'] # check parameter validation if len(set(self.arguments) & set(args_device)) == len(args_device): # device signin device_key = ndb.Key('Devices', '%s|%s' % (self.arguments.get('appName'), self.arguments.get('deviceId'))) device = device_key.get() if device and getattr(device, 'user', None) is not None and getattr(device, 'user').get() is not None: user = getattr(device, 'user').get() self.session['user'] = user.to_obj(mine=True) setattr(user, '%s_regid' % self.arguments.get('appName'), device.regId) user.put() message = '로그인 하셨습니다' url = 'http://hanasee.com' Messages(user=user.key, action_user=user.key, action='signin', settings='system', app_name='hanasee', message=message, url=url) if hasattr(self.session, 'returnTo'): return self.redirect(self.session.pop('returnTo')) else: result['code'] = 200 result['message'] = 'OK' result['User'] = user.to_obj(mine=True) return self.createRes(200, result) # no information in device elif self.arguments.get('returnTo') is not None: options = { 'returnTo': self.arguments.get('returnTo'), 'appName': self.arguments.get('appName'), 'state': self.arguments.get('state') } template = JINJA_ENVIRONMENT.get_template('signin.html') return self.response.write(template.render(options)) else: result['code'] = 401 result['message'] = 'unauthorized' return self.createRes(401, result) elif len(set(self.arguments) & set(args_signin)) == len(args_signin): # email signin user = Users.find(self.arguments.get('email')) if not user: result['code'] = 401 result['message'] = 'invalid email address' + self.arguments.get('email') #return self.createRes(401, result) else: # check password md5password = md5.md5(self.arguments.get('password')).hexdigest() if md5password != user.password: result['code'] = 401 result['message'] = 'invalid password' #return self.createRes(401, result) else: # success to login # device info if ('deviceInfo' in self.session): deviceInfo = self.session['deviceInfo'] # save reg_id in user setattr(user, re.sub('\.', '', '%s_regid' % deviceInfo.get('appName')), deviceInfo.get('regId')) user.put() # save user in device device_key = ndb.Key('Devices', '%s|%s' % (deviceInfo.get('appName'), deviceInfo.get('deviceId'))) device = device_key.get() setattr(device, 'user', user.key) device.put() self.session.pop('deviceInfo') message = '로그인 하셨습니다' url = 'http://hanasee.com' Messages( user=user.key, action_user=user.key, action='signin', settings='system', app_name='hanasee', message=message, url=url) self.session['user'] = user.to_obj(mine=True) result['code'] = 200 result['message'] = 'OK' if result['code'] == 200: if self.session.get('returnTo', None): returnTo = self.session.pop('returnTo') return self.redirect(returnTo) else: result['code'] = 200 result['message'] = 'OK' result['User'] = user.to_obj(mine=True) return self.createRes(200, result) else: if self.session.get('returnTo', None): options = { 'returnTo': self.session.get('returnTo'), 'message': result['message'], 'state': self.session.get('state') }; template = JINJA_ENVIRONMENT.get_template('signin.html') return self.response.write(template.render(options)) else: return self.createRes(401, result) elif kwargs.get('type'): authomatic = Authomatic(config=CONFIG, secret='a-long-secret-string') results = authomatic.login(Webapp2Adapter(self), kwargs.get('type')) if results: if results.error: pass elif results.user: if not results.user.id: results.user.update() # find existed connection connection = Connections.get(id="%s|%s" % (results.provider.name, results.user.id)) user = None if type(connection) == ndb.key.Key: connection = Connections(id="%s|%s" % (results.provider.name, results.user.id)) if connection.user is not None: user = connection.user.get() elif getattr(results.user, 'email') is not None: user = Users.find(results.user.email) isNewUser = False if user is None: user = Users(auto_id=True) user.email = getattr(results.user, 'email') isNewUser = True connection.user = user.key if getattr(user, 'nickname') is None: if results.provider.name == 'kakao': try: user.nickname = results.user.data.get(u'properties').get(u'nickname') except KeyError, e: logging.error('kakao error : ' + e) if self.session.get('returnTo', None): template = JINJA_ENVIRONMENT.get_template('signin.html') options = { 'returnTo': self.arguments.get('returnTo'), 'appName': self.arguments.get('appName'), 'state': self.arguments.get('state') } options['message'] = 'internal error' return self.response.write(template.render(options)) else: result['code'] = 500 result['message'] = 'internal error' return self.createRes(500, result) else: user.nickname = results.user.name if getattr(user, 'picture') is None: if results.provider.name == 'kakao': try: user.picture = results.user.data.get(u'properties').get(u'profile_image') except KeyError, e: logging.error(results.user.data) elif results.provider.name == 'fb': url = 'https://graph.facebook.com/{}?fields=picture' url = url.format(results.user.id) response = results.provider.access(url) user.picture = response.data.get('picture').get('data').get('url') elif results.provider.name == 'tw': url = 'https://api.twitter.com/1.1/users/show.json?user_id={}' url = url.format(results.user.id) response = results.provider.access(url) user.picture = response.data.get('profile_image_url') elif results.provider.name == 'google': user.picture = results.user.picture # device info if ('deviceInfo' in self.session): deviceInfo = self.session['deviceInfo'] # save reg_id in user setattr(user, re.sub('\.', '', '%s_regid' % deviceInfo.get('appName')), deviceInfo.get('regId')) user.put() # save user in device device = ndb.Key(Devices, "%s|%s" % (deviceInfo.get('appName'), deviceInfo.get('deviceId'))).get() setattr(device, 'user', user.key) device.put() self.session.pop('deviceInfo') logging.error("qqqq") # registered: register message if isNewUser: logging.error("new user") message = '%s님이 하나시를 시작했습니다.' % user.nickname url = 'http://hanasee.com' Messages(user=user.key, action_user=user.key, action='regist', settings='system', app_name='hanasee', message=message, url=url).send(['MAIL','SNS']) # otherwise: sign-in message else: message = '로그인 하셨습니다' url = 'http://hanasee.com' Messages( user=user.key, action_user=user.key, action='signin', settings='system', app_name='hanasee', message=message, url=url) self.session['user'] = user.to_obj(mine=True) user.provider = results.provider.name setattr(user, results.provider.name, results.provider.credentials.serialize()) connection.put() user.put() if self.session.get('returnTo', None): returnTo = self.session.pop('returnTo') return self.redirect(returnTo) else: result['code'] = 200 result['message'] = 'OK' result['User'] = user.to_obj(mine=True) return self.createRes(200, result)
def get_social_media_id(request): ''' Gets users social media IDs for use in signup for information integration. :param request: :return: ''' # TODO: Add social media functionality apart from facebook # We we need the response object for the adapter. html_response = HttpResponse() if (request.GET.get('context') is not None): request.GET = request.GET.copy() state_dict = request.GET.pop('context') state_dict = state_dict[0] state_dict = json.loads(state_dict) #print str(state_dict) request.session['platform'] = state_dict['platform'] #request.session['course_code'] = state_dict['course_code'] #request.session['group_id'] = state_dict['group'] #print 'Data stored in session: %s, %s, %s' % (request.session['platform'], request.session['course_code'], request.session['group_id']) platform = request.session['platform'] #Facebook endpoints break on GET variables..... #platform = request.GET.get('platform') if (platform in settings.DATAINTEGRATION_PLUGINS_INCLUDEAUTHOMATIC): di_plugin = settings.DATAINTEGRATION_PLUGINS[platform] authomatic = Authomatic(di_plugin.authomatic_config_json, di_plugin.authomatic_secretkey) result = authomatic.login(DjangoAdapter(request, html_response), di_plugin.authomatic_config_key, report_errors=True) # If there is no result, the login procedure is still pending. # Don't write anything to the response if there is no result! if result: # If there is result, the login procedure is over and we can write to response. #html_response.write('<a href="..">Home</a>') if result.error: # Login procedure finished with an error. html_response.write('<p>Error: {0}</p>'.format(result.error.message)) elif result.user: # Hooray, we have the user! # OAuth 2.0 and OAuth 1.0a provide only limited user data on login, # We need to update the user to get more info. if not (result.user.name and result.user.id): result.user.update() # Welcome the user. # html_response.write(u'<p>Hi {0}</p>'.format(result.user.name)) html_response.write(u'<h2>Your Facebook id is: {0}</h2>'.format(result.user.id)) else: html_response.write('Auth Returned no Response.') return html_response
def dipluginauthomaticlogin(request): if request.GET.get('context') is not None: request.GET = request.GET.copy() state_dict = request.GET.pop('context') state_dict = state_dict[0] state_dict = json.loads(state_dict) request.session['platform'] = state_dict['platform'] request.session['unit'] = state_dict['unit'] request.session['group_id'] = state_dict['group'] platform = request.session['platform'] html_response = HttpResponse() if (platform in settings.DATAINTEGRATION_PLUGINS_INCLUDEAUTHOMATIC): di_plugin = settings.DATAINTEGRATION_PLUGINS[platform] authomatic = Authomatic(di_plugin.authomatic_config_json, di_plugin.authomatic_secretkey) result = authomatic.login(DjangoAdapter(request, html_response), di_plugin.authomatic_config_key, report_errors=True) # If there is no result, the login procedure is still pending. # Don't write anything to the response if there is no result! if result: # If there is result, the login procedure is over and we can write to response. html_response.write('<a href="/dashboard/myunits/">Go back to dashboard</a>') if result.error: # Login procedure finished with an error. html_response.write('<h2>Error: {0}</h2>'.format(result.error.message)) elif result.user: # Hooray, we have the user! # OAuth 2.0 and OAuth 1.0a provide only limited user data on login, # We need to update the user to get more info. if not (result.user.name and result.user.id): result.user.update() # Welcome the user. # html_response.write(u'<p>Hi {0}</p>'.format(result.user.name)) # response.write(u'<h2>Your id is: {0}</h2>'.format(result.user.id)) # response.write(u'<h2>Your email is: {0}</h2>'.format(result.user.email)) # If there are credentials (only by AuthorizationProvider), # we can _access user's protected resources. if result.user.credentials: group_id = request.session['group_id'] unit_id = request.session['unit'] unit = UnitOffering.objects.get(id=unit_id) if result.provider.name == 'fb': di_plugin.perform_import(group_id, unit, result) post_smimport(unit, xapi_settings.PLATFORM_FACEBOOK) #Remove all data stored in session for this view to avoid cache issues del request.session['platform'] del request.session['unit'] del request.session['group_id'] html_response.write('<h2>Facebook data import is complete.</h2>') else: html_response.write('Auth Returned no Response.') return html_response
"""Relevant result:write""" from django.http import HttpResponse from authomatic import Authomatic from authomatic.adapters import DjangoAdapter from config import CONFIG authomatic = Authomatic(CONFIG, 'a super secret random string') def login(request, provider_name): response = HttpResponse() result = authomatic.login(DjangoAdapter(request, response), provider_name) if result: Response.