An open API service indexing awesome lists of open source software.

https://github.com/Cap-go/capacitor-social-login

One plugin to make login with Google,Apple,Facebook and so on, simple and fast to implement
https://github.com/Cap-go/capacitor-social-login

capacitor capacitor-plugin plugin

Last synced: 12 months ago
JSON representation

One plugin to make login with Google,Apple,Facebook and so on, simple and fast to implement

Awesome Lists containing this project

README

          

# @capgo/capacitor-social-login
Capgo - Instant updates for capacitor


➡️ Get Instant updates for your App with Capgo 🚀


Fix your annoying bug now, Hire a Capacitor expert 💪


## Fork Information
This plugin is a fork of [@codetrix-studio/capacitor-google-auth](https://github.com/CodetrixStudio/CapacitorGoogleAuth). We created this fork because the original plugin is "virtually" archived with no way to reach the maintainer in any medium, and only one person (@reslear) has write rights but doesn't handle native code.

If you're currently using `@codetrix-studio/capacitor-google-auth`, we recommend migrating to this plugin. You can follow our [migration guide here](https://github.com/Cap-go/capacitor-social-login/blob/main/MIGRATION_CODETRIX.md).

## About
All social logins in one plugin

This plugin implement social auth for:
- Google (with credential manager)
- Apple (with 0auth on android)
- Facebook ( with latest SDK)

We plan in the future to keep adding others social login and make this plugin the all in one solution.

This plugin is the only one who implement all 3 majors social login on WEB, IOS and Android

## Documentation

Best experience to read the doc here:

https://capgo.app/docs/plugins/social-login/getting-started/

## Install

```bash
npm install @capgo/capacitor-social-login
npx cap sync
```

## Apple

[How to get the credentials](https://github.com/Cap-go/capacitor-social-login/blob/main/docs/setup_apple.md)
[How to setup redirect url](https://github.com/Cap-go/capacitor-social-login/blob/main/docs/apple_redirect_url.png)

### Android configuration

For android you need a server to get the callback from the apple login. As we use the web SDK .

Call the `initialize` method with the `apple` provider

```typescript
await SocialLogin.initialize({
apple: {
clientId: 'your-client-id',
redirectUrl: 'your-redirect-url',
},
});
const res = await SocialLogin.login({
provider: 'apple',
options: {
scopes: ['email', 'name'],
},
});
```

### iOS configuration

call the `initialize` method with the `apple` provider

```typescript
await SocialLogin.initialize({
apple: {
clientId: 'your-client-id', // it not used at os level only in plugin to know which provider initialize
},
});
const res = await SocialLogin.login({
provider: 'apple',
options: {
scopes: ['email', 'name'],
},
});
```

## Facebook

Docs: [How to setup facebook login](./docs/setup_facebook.md)

### Android configuration

More information can be found here: https://developers.facebook.com/docs/android/getting-started

Then call the `initialize` method with the `facebook` provider

```typescript
await SocialLogin.initialize({
facebook: {
appId: 'your-app-id',
clientToken: 'your-client-token',
},
});
const res = await SocialLogin.login({
provider: 'facebook',
options: {
permissions: ['email', 'public_profile'],
},
});
```

### iOS configuration

In file `ios/App/App/AppDelegate.swift` add or replace the following:

```swift
import UIKit
import Capacitor
import FBSDKCoreKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FBSDKCoreKit.ApplicationDelegate.shared.application(
application,
didFinishLaunchingWithOptions: launchOptions
)

return true
}

...

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
// Called when the app was launched with a url. Feel free to add additional processing here,
// but if you want the App API to support tracking app url opens, make sure to keep this call
if (FBSDKCoreKit.ApplicationDelegate.shared.application(
app,
open: url,
sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
annotation: options[UIApplication.OpenURLOptionsKey.annotation]
)) {
return true;
} else {
return ApplicationDelegateProxy.shared.application(app, open: url, options: options)
}
}
}

```

Add the following in the `ios/App/App/info.plist` file inside of the outermost ``:

```xml

CFBundleURLTypes


CFBundleURLSchemes

fb[APP_ID]

FacebookAppID
[APP_ID]
FacebookClientToken
[CLIENT_TOKEN]
FacebookDisplayName
[APP_NAME]
LSApplicationQueriesSchemes

fbapi
fbauth
fb-messenger-share-api
fbauth2
fbshareextension

```

More information can be found here: https://developers.facebook.com/docs/facebook-login/ios

Then call the `initialize` method with the `facebook` provider

```typescript
await SocialLogin.initialize({
facebook: {
appId: 'your-app-id',
},
});
const res = await SocialLogin.login({
provider: 'facebook',
options: {
permissions: ['email', 'public_profile'],
},
});
```

## Google

[How to get the credentials](https://github.com/Cap-go/capacitor-social-login/blob/main/docs/setup_google.md)

### Android configuration

The implemention use the new library of Google who use Google account at Os level, make sure your device does have at least one google account connected

Directly call the `initialize` method with the `google` provider

```typescript
await SocialLogin.initialize({
google: {
webClientId: 'your-client-id', // the web client id for Android and Web
},
});
const res = await SocialLogin.login({
provider: 'google',
options: {
scopes: ['email', 'profile'],
},
});
```

### iOS configuration

Call the `initialize` method with the `google` provider

```typescript
await SocialLogin.initialize({
google: {
iOSClientId: 'your-client-id', // the iOS client id
iOSServerClientId: 'your-server-client-id', // the iOS server client id (required in mode offline)
},
});
const res = await SocialLogin.login({
provider: 'google',
options: {
scopes: ['email', 'profile'],
},
});
```

### Web

Initialize method to create a script tag with Google lib. We cannot know when it's ready so be sure to do it early in web otherwise it will fail.

## API

* [`initialize(...)`](#initialize)
* [`login(...)`](#login)
* [`logout(...)`](#logout)
* [`isLoggedIn(...)`](#isloggedin)
* [`getAuthorizationCode(...)`](#getauthorizationcode)
* [`refresh(...)`](#refresh)
* [`providerSpecificCall(...)`](#providerspecificcall)
* [Interfaces](#interfaces)
* [Type Aliases](#type-aliases)

### initialize(...)

```typescript
initialize(options: InitializeOptions) => Promise
```

Initialize the plugin

| Param | Type |
| ------------- | --------------------------------------------------------------- |
| **`options`** | InitializeOptions |

--------------------

### login(...)

```typescript
login(options: Extract) => Promise<{ provider: T; result: ProviderResponseMap[T]; }>
```

Login with the selected provider

| Param | Type |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **`options`** | Extract<{ provider: 'facebook'; options: FacebookLoginOptions; }, { provider: T; }> \| Extract<{ provider: 'google'; options: GoogleLoginOptions; }, { provider: T; }> \| Extract<{ provider: 'apple'; options: AppleProviderOptions; }, { provider: T; }> |

**Returns:** Promise<{ provider: T; result: ProviderResponseMap[T]; }>

--------------------

### logout(...)

```typescript
logout(options: { provider: 'apple' | 'google' | 'facebook'; }) => Promise
```

Logout

| Param | Type |
| ------------- | ------------------------------------------------------------- |
| **`options`** | { provider: 'apple' \| 'google' \| 'facebook'; } |

--------------------

### isLoggedIn(...)

```typescript
isLoggedIn(options: isLoggedInOptions) => Promise<{ isLoggedIn: boolean; }>
```

IsLoggedIn

| Param | Type |
| ------------- | --------------------------------------------------------------- |
| **`options`** | isLoggedInOptions |

**Returns:** Promise<{ isLoggedIn: boolean; }>

--------------------

### getAuthorizationCode(...)

```typescript
getAuthorizationCode(options: AuthorizationCodeOptions) => Promise
```

Get the current access token

| Param | Type |
| ------------- | ----------------------------------------------------------------------------- |
| **`options`** | AuthorizationCodeOptions |

**Returns:** Promise<AuthorizationCode>

--------------------

### refresh(...)

```typescript
refresh(options: LoginOptions) => Promise
```

Refresh the access token

| Param | Type |
| ------------- | ----------------------------------------------------- |
| **`options`** | LoginOptions |

--------------------

### providerSpecificCall(...)

```typescript
providerSpecificCall(options: { call: T; options: ProviderSpecificCallOptionsMap[T]; }) => Promise
```

Execute provider-specific calls

| Param | Type |
| ------------- | --------------------------------------------------------------------- |
| **`options`** | { call: T; options: ProviderSpecificCallOptionsMap[T]; } |

**Returns:** Promise<ProviderSpecificCallResponseMap[T]>

--------------------

### Interfaces

#### InitializeOptions

| Prop | Type |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **`facebook`** | { appId: string; clientToken?: string; } |
| **`google`** | { iOSClientId?: string; iOSServerClientId?: string; webClientId?: string; mode?: 'online' \| 'offline'; hostedDomain?: string; redirectUrl?: string; } |
| **`apple`** | { clientId?: string; redirectUrl?: string; } |

#### FacebookLoginResponse

| Prop | Type |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **`accessToken`** | AccessToken \| null |
| **`idToken`** | string \| null |
| **`profile`** | { userID: string; email: string \| null; friendIDs: string[]; birthday: string \| null; ageRange: { min?: number; max?: number; } \| null; gender: string \| null; location: { id: string; name: string; } \| null; hometown: { id: string; name: string; } \| null; profileURL: string \| null; name: string \| null; imageURL: string \| null; } |

#### AccessToken

| Prop | Type |
| ------------------------- | --------------------- |
| **`applicationId`** | string |
| **`declinedPermissions`** | string[] |
| **`expires`** | string |
| **`isExpired`** | boolean |
| **`lastRefresh`** | string |
| **`permissions`** | string[] |
| **`token`** | string |
| **`refreshToken`** | string |
| **`userId`** | string |

#### GoogleLoginResponseOnline

| Prop | Type |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **`accessToken`** | AccessToken \| null |
| **`idToken`** | string \| null |
| **`profile`** | { email: string \| null; familyName: string \| null; givenName: string \| null; id: string \| null; name: string \| null; imageUrl: string \| null; } |
| **`responseType`** | 'online' |

#### GoogleLoginResponseOffline

| Prop | Type |
| -------------------- | ---------------------- |
| **`serverAuthCode`** | string |
| **`responseType`** | 'offline' |

#### AppleProviderResponse

| Prop | Type |
| ----------------- | ------------------------------------------------------------------------------------------------------------ |
| **`accessToken`** | AccessToken \| null |
| **`idToken`** | string \| null |
| **`profile`** | { user: string; email: string \| null; givenName: string \| null; familyName: string \| null; } |

#### FacebookLoginOptions

| Prop | Type | Description | Default |
| ------------------ | --------------------- | ---------------- | ------------------ |
| **`permissions`** | string[] | Permissions | |
| **`limitedLogin`** | boolean | Is Limited Login | false |
| **`nonce`** | string | Nonce | |

#### GoogleLoginOptions

| Prop | Type | Description | Default |
| ----------------------- | ----------------------------------- | ---------------------------------------------------------------------------------------------------- | ----------------------- |
| **`scopes`** | string[] | Specifies the scopes required for accessing Google APIs The default is defined in the configuration. | |
| **`nonce`** | string | Nonce | |
| **`forceRefreshToken`** | boolean | Force refresh token (only for Android) | false |
| **`forcePrompt`** | boolean | Force account selection prompt (iOS) | false |
| **`style`** | 'bottom' \| 'standard' | Style | 'standard' |

#### AppleProviderOptions

| Prop | Type | Description |
| ------------ | --------------------- | ----------- |
| **`scopes`** | string[] | Scopes |
| **`nonce`** | string | Nonce |
| **`state`** | string | State |

#### isLoggedInOptions

| Prop | Type | Description |
| -------------- | ---------------------------------------------- | ----------- |
| **`provider`** | 'apple' \| 'google' \| 'facebook' | Provider |

#### AuthorizationCode

| Prop | Type | Description |
| ----------------- | ------------------- | ------------ |
| **`jwt`** | string | Jwt |
| **`accessToken`** | string | Access Token |

#### AuthorizationCodeOptions

| Prop | Type | Description |
| -------------- | ---------------------------------------------- | ----------- |
| **`provider`** | 'apple' \| 'google' \| 'facebook' | Provider |

#### FacebookGetProfileResponse

| Prop | Type | Description |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- |
| **`profile`** | { [key: string]: any; id: string \| null; name: string \| null; email: string \| null; first_name: string \| null; last_name: string \| null; picture?: { data: { height: number \| null; is_silhouette: boolean \| null; url: string \| null; width: number \| null; }; } \| null; } | Facebook profile data |

#### FacebookGetProfileOptions

| Prop | Type | Description |
| ------------ | --------------------- | ---------------------------------------- |
| **`fields`** | string[] | Fields to retrieve from Facebook profile |

### Type Aliases

#### ProviderResponseMap

{ facebook: FacebookLoginResponse; google: GoogleLoginResponse; apple: AppleProviderResponse; }

#### GoogleLoginResponse

GoogleLoginResponseOnline | GoogleLoginResponseOffline

#### LoginOptions

{ provider: 'facebook'; options: FacebookLoginOptions; } | { provider: 'google'; options: GoogleLoginOptions; } | { provider: 'apple'; options: AppleProviderOptions; }

#### Extract

Extract from T those types that are assignable to U

T extends U ? T : never

#### ProviderSpecificCallResponseMap

{ 'facebook#getProfile': FacebookGetProfileResponse; }

#### ProviderSpecificCall

'facebook#getProfile'

#### ProviderSpecificCallOptionsMap

{ 'facebook#getProfile': FacebookGetProfileOptions; }

### Credits

This plugin implementation of google is based on [CapacitorGoogleAuth](https://github.com/CodetrixStudio/CapacitorGoogleAuth) with a lot of rework, the current maintainer is unreachable, we are thankful for his work and are now going forward on our own!
Thanks to [reslear](https://github.com/reslear) for helping to tranfer users to this plugin from the old one and all the work.

## Privacy Manifest for App Developers

If you use Google, Facebook, or Apple login, you must declare the data collected by their SDKs in your app's `PrivacyInfo.xcprivacy` file (not in the plugin).

Add this file in your app at: `ios/App/PrivacyInfo.xcprivacy`

### Google Sign-In Example
```json
{
"NSPrivacyCollectedDataTypes": [
{ "NSPrivacyCollectedDataType": "EmailAddress", "NSPrivacyCollectedDataTypeLinked": true, "NSPrivacyCollectedDataTypeTracking": false },
{ "NSPrivacyCollectedDataType": "Name", "NSPrivacyCollectedDataTypeLinked": true, "NSPrivacyCollectedDataTypeTracking": false },
{ "NSPrivacyCollectedDataType": "UserID", "NSPrivacyCollectedDataTypeLinked": true, "NSPrivacyCollectedDataTypeTracking": false }
]
}
```

### Facebook Login Example
```json
{
"NSPrivacyCollectedDataTypes": [
{ "NSPrivacyCollectedDataType": "EmailAddress", "NSPrivacyCollectedDataTypeLinked": true, "NSPrivacyCollectedDataTypeTracking": false },
{ "NSPrivacyCollectedDataType": "Name", "NSPrivacyCollectedDataTypeLinked": true, "NSPrivacyCollectedDataTypeTracking": false },
{ "NSPrivacyCollectedDataType": "UserID", "NSPrivacyCollectedDataTypeLinked": true, "NSPrivacyCollectedDataTypeTracking": false },
{ "NSPrivacyCollectedDataType": "FriendsList", "NSPrivacyCollectedDataTypeLinked": true, "NSPrivacyCollectedDataTypeTracking": false }
]
}
```

### Apple Sign-In Example
```json
{
"NSPrivacyCollectedDataTypes": [
{ "NSPrivacyCollectedDataType": "EmailAddress", "NSPrivacyCollectedDataTypeLinked": true, "NSPrivacyCollectedDataTypeTracking": false },
{ "NSPrivacyCollectedDataType": "Name", "NSPrivacyCollectedDataTypeLinked": true, "NSPrivacyCollectedDataTypeTracking": false }
]
}
```

- Adjust the data types to match your app's usage and the SDK documentation.
- See [Apple docs](https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/) for all allowed keys and values.

## Combine facebook and google URL handler in `AppDelegate.swift`

```swift
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
// Called when the app was launched with a url. Feel free to add additional processing here,
// but if you want the App API to support tracking app url opens, make sure to keep this call

// Return true if the URL was handled by either Facebook or Google authentication
// https://github.com/Cap-go/capacitor-social-login/blob/main/docs/setup_facebook.md#ios-setup
// https://github.com/Cap-go/capacitor-social-login/blob/main/docs/setup_google.md#using-google-login-on-ios
if FBSDKCoreKit.ApplicationDelegate.shared.application(
app,
open: url,
sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
annotation: options[UIApplication.OpenURLOptionsKey.annotation]
) || GIDSignIn.sharedInstance.handle(url) {
return true
}

// If URL wasn't handled by auth services, pass it to Capacitor for processing
return ApplicationDelegateProxy.shared.application(app, open: url, options: options)
}
```

## Troubleshooting

### Invalid Privacy Manifest (ITMS-91056)
If you get this error on App Store Connect:

> ITMS-91056: Invalid privacy manifest - The PrivacyInfo.xcprivacy file from the following path is invalid: ...

**How to fix:**
- Make sure your app's `PrivacyInfo.xcprivacy` is valid JSON, with only Apple-documented keys/values.
- Do not include a privacy manifest in the plugin, only in your app.