Skip to content

Commit

Permalink
Major API changes:
Browse files Browse the repository at this point in the history
-> Individual login providers are moved into respective folders
-> Fix problem of not being able to use individual login methods
-> Now it's relatively easier to use the library
  • Loading branch information
shashi278 committed Aug 6, 2020
1 parent 17772fb commit 42499e6
Show file tree
Hide file tree
Showing 11 changed files with 259 additions and 252 deletions.
Binary file modified demo/bin/glogin__armeabi-v7a-0.1-armeabi-v7a-debug.apk
Binary file not shown.
2 changes: 1 addition & 1 deletion demo/buildozer.spec
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ version = 0.1

# (list) Application requirements
# comma separated e.g. requirements = sqlite3,kivy
requirements = python3,kivy,pyjnius,kivymd,kivyauth,certifi
requirements = python3,kivy,pyjnius,kivymd,certifi

# (str) Custom source folders for requirements
# Sets custom source for any requirements with recipes
Expand Down
65 changes: 40 additions & 25 deletions demo/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,16 @@
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang.builder import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.logger import Logger
from kivy.clock import Clock
from kivy.uix.image import AsyncImage
from kivy.metrics import dp

import os

from kivyauth.initialize import initialize_google, initialize_fb, initialize_firebase
from kivyauth.logins import login_google, login_facebook, login_github, login_twitter, logout, login_providers
from kivyauth.google_auth import initialize_google, login_google, logout_google
from kivyauth.facebook_auth import initialize_fb, login_facebook, logout_facebook
from kivyauth.firebase_auth import initialize_firebase, login_github, login_twitter, logout_github, logout_twitter
from kivyauth.providers import login_providers

from kivymd.app import MDApp
from kivymd.uix.button import RectangularElevationBehavior, MDRectangleFlatIconButton
Expand All @@ -26,12 +27,13 @@
Toast= autoclass('android.widget.Toast')
String = autoclass('java.lang.String')
CharSequence= autoclass('java.lang.CharSequence')
Intent = autoclass('android.content.Intent')
Uri = autoclass('android.net.Uri')

PythonActivity= autoclass('org.kivy.android.PythonActivity')

context= PythonActivity.mActivity
RC_SIGN_IN= 999
current_provider= ""

@run_on_ui_thread
def show_toast(text):
Expand All @@ -54,11 +56,11 @@ def show_toast(text):
orientation:"vertical"
MDToolbar:
title: "Social Auth Kivy Demo"
title: "KivyAuth Demo"
elevation:9
opposite_colos: True
left_action_items: [['menu', lambda x: None]]
right_action_items: [['information-outline', lambda x: None]]
right_action_items: [['source-fork', lambda x: app.send_to_github()]]
BoxLayout:
orientation:"vertical"
Expand Down Expand Up @@ -173,11 +175,11 @@ class RectangleRaisedIconButton(MDRectangleFlatIconButton, RectangularElevationB
elevation_normal=16

class LoginDemo(MDApp):
current_provider= ""
def build(self):

self.mGSignInClient= initialize_google(self.after_login, self.error_listener, RC_SIGN_IN)
self.mList= initialize_fb(self.after_login, self.cancel_listener, self.error_listener)
initialize_firebase()
initialize_google(self.after_login, self.error_listener)
initialize_fb(self.after_login, self.cancel_listener, self.error_listener)
initialize_firebase(self.after_login, self.error_listener)

return Builder.load_string(kv)

Expand All @@ -197,37 +199,41 @@ def on_start(self):
pass

def fb_login(self, *args):
login_facebook(self.mList)
global current_provider
current_provider= login_providers.facebook
login_facebook()
self.current_provider= login_providers.facebook

def gl_login(self, *args):
login_google(self.mGSignInClient, RC_SIGN_IN)
global current_provider
current_provider= login_providers.google
login_google()
self.current_provider= login_providers.google

def git_login(self, *args):
login_github(self.after_login, self.error_listener)
global current_provider
current_provider= login_providers.github
login_github()
self.current_provider= login_providers.github

def twitter_login(self, *args):
login_twitter(self.after_login, self.error_listener)
global current_provider
current_provider= login_providers.twitter
login_twitter()
self.current_provider= login_providers.twitter

def logout_(self):
logout(current_provider, self.after_logout)
#logout(current_provider, self.after_logout)
if self.current_provider==login_providers.google:
logout_google(self.after_logout)
if self.current_provider==login_providers.facebook:
logout_facebook(self.after_logout)
if self.current_provider==login_providers.github:
logout_github(self.after_logout)
if self.current_provider==login_providers.twitter:
logout_twitter(self.after_logout)

def after_login(self, name, email, photo_uri):
show_toast('Logged in using {}'.format(current_provider))
show_toast('Logged in using {}'.format(self.current_provider))
self.root.current= 'homescreen'
self.update_ui(name, email, photo_uri)

def after_logout(self):
self.update_ui('','','')
self.root.current= 'loginscreen'
show_toast('Logged out from {} login'.format(current_provider))
show_toast('Logged out from {} login'.format(self.current_provider))

def update_ui(self, name, email, photo_uri):
self.root.ids.home_screen.ids.user_photo.add_widget(AsyncImage(source=photo_uri, size_hint=(None, None), height=dp(60), width=dp(60)))
Expand All @@ -239,6 +245,15 @@ def cancel_listener(self):

def error_listener(self):
show_toast("Error logging in.")

def send_to_github(self):
intent = Intent()
intent.setAction(Intent.ACTION_VIEW)
intent.setData(Uri.parse('https://github.com/shashi278/social-auth-kivy'))

context.startActivity(intent)



if __name__ == "__main__":
LoginDemo().run()
45 changes: 43 additions & 2 deletions kivyauth/callbacks.py → kivyauth/facebook_auth.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
from kivy.logger import Logger
from jnius import autoclass, PythonJavaClass, java_method
from jnius import autoclass, cast, PythonJavaClass, java_method
from android.activity import bind as result_bind

CallbackManagerFactory = autoclass("com.facebook.CallbackManager$Factory")
FacebookSdk = autoclass("com.facebook.FacebookSdk")
LoginManager = autoclass("com.facebook.login.LoginManager")
AccessToken = autoclass("com.facebook.AccessToken")
GraphRequest = autoclass("com.facebook.GraphRequest")
ImageRequest = autoclass("com.facebook.internal.ImageRequest")

Bundle = autoclass("android.os.Bundle")
Arrays = autoclass("java.util.Arrays")

PythonActivity = autoclass("org.kivy.android.PythonActivity")

context = PythonActivity.mActivity
mLoginMgr = None
mList = None


class PythonGraphJSONObjectCallback(PythonJavaClass):
Expand All @@ -30,7 +41,7 @@ def onCompleted(self, me, response):
access_token = ""

uri = ImageRequest.getProfilePictureUri(
me.optString("id"), 100, 100, access_token
me.optString("id"), 200, 200, access_token
)

Logger.info(
Expand Down Expand Up @@ -77,3 +88,33 @@ def onCancel(self):
def onError(self, error):
Logger.error("KivyAuth: Error logging in.")
self.error_listener()


def initialize_fb(success_listener, cancel_listener, error_listener):
FacebookSdk.sdkInitialize(context.getApplicationContext())
mCallbackManager = CallbackManagerFactory.create()
mFacebookCallback = PythonFacebookCallback(
success_listener, cancel_listener, error_listener
)
result_bind(on_activity_result=mCallbackManager.onActivityResult)

Logger.info("KivyAuth: Initialized facebook signin")
global mList
mList = [mCallbackManager, mFacebookCallback]


def login_facebook():
Logger.info("KivyAuth: Initiated facebook login")
global mLoginMgr
mLoginMgr = LoginManager.getInstance()
mLoginMgr.registerCallback(*mList)
mLoginMgr.logInWithReadPermissions(
cast(autoclass("android.app.Activity"), context),
Arrays.asList("email", "public_profile"),
)


def logout_facebook(after_logout):
mLoginMgr.logOut()
after_logout()
Logger.info("KivyAuth: Logged out from facebook login")
100 changes: 100 additions & 0 deletions kivyauth/firebase_auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
from kivy.logger import Logger
from jnius import autoclass, PythonJavaClass, java_method
from android.activity import bind as result_bind

FirebaseAuth = autoclass("com.google.firebase.auth.FirebaseAuth")
OAuthProvider = autoclass("com.google.firebase.auth.OAuthProvider")

PythonActivity = autoclass("org.kivy.android.PythonActivity")

context = PythonActivity.mActivity

event_success_listener = None
event_error_listener = None


class OnSuccessListener(PythonJavaClass):
__javainterfaces__ = ["com/google/android/gms/tasks/OnSuccessListener"]
__javacontext__ = "app"

def __init__(self, success_listener):
self.success_listener = success_listener

@java_method("(Ljava/lang/Object;)V")
def onSuccess(self, result):
# user is signed in
Logger.info("KivyAuth: Sign in successful using firebase.")
user = FirebaseAuth.getInstance().getCurrentUser()

self.success_listener(
user.getDisplayName(), user.getEmail(), user.getPhotoUrl().toString()
)


class OnFailureListener(PythonJavaClass):
__javainterfaces__ = ["com/google/android/gms/tasks/OnFailureListener"]
__javacontext__ = "app"

def __init__(self, error_listener):
self.error_listener = error_listener

@java_method("(Ljava/lang/Exception;)V")
def onFailure(self, e):
# handle exception
Logger.info("KivyAuth: Sign in using firebase failed")
self.error_listener()


def initialize_firebase(success_listener, error_listener):
FirebaseAuth.getInstance()
Logger.info("KivyAuth: Initialized firebase auth")
global event_success_listener
event_success_listener = success_listener
global event_error_listener
event_error_listener = error_listener


def firebase_login(provider):
pendingResultTask = FirebaseAuth.getPendingAuthResult()
if pendingResultTask:
# There's something already here! Finish the sign-in for your user.

task = pendingResultTask.addOnSuccessListener(
OnSuccessListener(event_success_listener)
)
task = task.addOnFailureListener(OnFailureListener(event_error_listener))
else:
# There's no pending result so you need to start the sign-in flow.

task = FirebaseAuth.startActivityForSignInWithProvider(
context, provider.build()
)
task = task.addOnSuccessListener(OnSuccessListener(event_success_listener))
task = task.addOnFailureListener(OnFailureListener(event_error_listener))


def firebase_logout(after_logout):
Logger.info("KivyAuth: Initiated logout using firebase")
FirebaseAuth.getInstance().signOut()
after_logout()
Logger.info("KivyAuth: Logged out from firebase auth")


def login_github():
Logger.info("KivyAuth: Initiated github login")
provider = OAuthProvider.newBuilder("github.com")
firebase_login(provider)


def login_twitter():
Logger.info("KivyAuth: Initiated twitter login")
provider = OAuthProvider.newBuilder("twitter.com")
firebase_login(provider)


def logout_twitter(after_logout):
firebase_logout(after_logout)


def logout_github(after_logout):
firebase_logout(after_logout)
66 changes: 66 additions & 0 deletions kivyauth/google_auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
from kivy.logger import Logger
from kivy.clock import mainthread
from jnius import autoclass
from android.activity import bind as result_bind

Gso = autoclass("com.google.android.gms.auth.api.signin.GoogleSignInOptions")
GsoBuilder = autoclass(
"com.google.android.gms.auth.api.signin.GoogleSignInOptions$Builder"
)
GSignIn = autoclass("com.google.android.gms.auth.api.signin.GoogleSignIn")
ApiException = autoclass("com.google.android.gms.common.api.ApiException")
PythonActivity = autoclass("org.kivy.android.PythonActivity")
context = PythonActivity.mActivity

RC_SIGN_IN = 10122
mGSignInClient = None


class GoogleActivityListener:
def __init__(self, success_listener, error_listener):
self.success_listener = success_listener
self.error_listener = error_listener

def google_activity_listener(self, request_code, result_code, data):
if request_code == RC_SIGN_IN:
Logger.info("KivyAuth: google_activity_listener called.")
task = GSignIn.getSignedInAccountFromIntent(data)
try:
account = task.getResult(ApiException)
if account:
Logger.info(
"KivyAuth: Google Login success.\
Calling success listener."
)
self.success_listener(
account.getDisplayName(),
account.getEmail(),
account.getPhotoUrl().toString(),
)

except Exception as e:
Logger.info("KivyAuth: Error signing in using Google. {}".format(e))
self.error_listener()


def initialize_google(success_listener, error_listener):
gso = GsoBuilder(Gso.DEFAULT_SIGN_IN).requestEmail().build()
global mGSignInClient
mGSignInClient = GSignIn.getClient(context, gso)
gal = GoogleActivityListener(success_listener, error_listener)
result_bind(on_activity_result=gal.google_activity_listener)

Logger.info("KivyAuth: Initialized google signin")


# @mainthread
def login_google():
Logger.info("KivyAuth: Initiated google login")
signInIntent = mGSignInClient.getSignInIntent()
context.startActivityForResult(signInIntent, RC_SIGN_IN)


def logout_google(after_logout):
mGSignInClient.signOut()
after_logout()
Logger.info("KivyAuth: Logged out from google login")
Loading

0 comments on commit 42499e6

Please sign in to comment.