├── .gitignore ├── .npmignore ├── LICENSE ├── README.md ├── __tests__ └── components │ └── test.js ├── package-lock.json ├── package.json ├── src ├── components │ ├── customLogin │ │ └── index.jsx │ ├── customLogout │ │ └── index.jsx │ ├── index.jsx │ ├── login │ │ └── index.jsx │ └── logout │ │ └── index.jsx ├── index.js ├── services │ └── index.jsx └── styles.css └── webpack.config.dev.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | npm-debug.log 3 | coverage/ 4 | dist/ 5 | 6 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | src/ 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![npm version](https://badge.fury.io/js/react-google-oauth.svg)](https://badge.fury.io/js/react-google-oauth) 2 | 3 | # react-google-oauth 4 | 5 | *Directly inspired from [react-google-login](https://github.com/anthonyjgrove/react-google-login) project.* 6 | 7 | With react-google-oauth you can quickly and easly add Login and Logout Google button. 8 | 9 | ![Google button with hover state](https://i.imgur.com/PDgUgJW.gif) 10 | 11 | 12 | 13 | - [How it works](#how-it-works) 14 | - [Install](#install) 15 | - [How use it](#how-use-it) 16 | - [1- Inject and init Google API script](#1--inject-and-init-google-api-script) 17 | - [GooleApi props](#gooleapi-props) 18 | - [onUpdateSigninStatus - Callback](#onupdatesigninstatus-callback) 19 | - [onInitFailure - Callback](#oninitfailure-callback) 20 | - [2- Add a button](#2--add-a-button) 21 | - [GoogleLogin params](#googlelogin-params) 22 | - [GoogleLogout params](#googlelogout-params) 23 | - [3- Get informations](#3--get-informations) 24 | - [googleGetBasicProfil](#googlegetbasicprofil) 25 | - [googleGetAuthResponse](#googlegetauthresponse) 26 | - [Rendering](#rendering) 27 | - [\ & \](#googlelogin-googlelogout) 28 | - [Text, Color, Width](#text-color-width) 29 | - [\ & \](#customgooglelogin-customgooglelogout) 30 | 31 | # How it works 32 | 33 | This module is composed by two kind of components : 34 | 35 | - \ used to inject and initialize the Google Api with your Google client ID, follow this [Google's documentation](https://developers.google.com/identity/sign-in/web/devconsole-project) to get yours 36 | - \ \ \ \ components used to display buttons and connect each *clickEvents* to Google Oauth Api. 37 | 38 | # Install 39 | 40 | ```bash 41 | npm install react-google-oauth 42 | ``` 43 | 44 | # How use it 45 | 46 | ## 1- Inject and init Google API script 47 | 48 | Add \ component in your tree 49 | 50 | ```jsx 51 | import React from 'react'; 52 | import ReactDOM from 'react-dom'; 53 | import {GoogleAPI} from 'react-google-oauth' 54 | 55 | ReactDOM.render( 56 | 59 | 60 | , document.getElementById('root')); 61 | ``` 62 | 63 | By default the Google API is initialize to make a simple Oauth with profile... 64 | 65 | **Caution** : As other React component \ can have only one child 66 | 67 | ### GooleAPI props 68 | 69 | See [Google documentation](https://developers.google.com/api-client-library/javascript/reference/referencedocs#gapiauth2clientconfig) for complete values 70 | 71 | | Parameters | Default value | Comment | Type | 72 | | -------------------- | ------------------------- | ---------------------------------------- | ------ | 73 | | clientId | **REQUIRED** | | String | 74 | | responseType | 'permission' | | String | 75 | | prompt | '' | [Doc](https://developers.google.com/identity/protocols/OpenIDConnect#prompt) | String | 76 | | cookiePolicy | 'single_host_origin' | | String | 77 | | fetchBasicProfile | true | Automatically add profile and email in Scope see [Doc](https://developers.google.com/api-client-library/javascript/reference/referencedocs#gapiauth2clientconfig) | Bool | 78 | | uxMode | 'popup' | | String | 79 | | hostedDomain | None | | String | 80 | | redirectUri | None | | String | 81 | | scope | '' | More scope on this [page](https://developers.google.com/identity/protocols/googlescopes) | String | 82 | | onUpdateSigninStatus | f => f | See below | Func | 83 | | onInitFailure | err => console.error(err) | See below | Func | 84 | 85 | 86 | 87 | #### onUpdateSigninStatus - Callback 88 | 89 | [Doc](https://developers.google.com/api-client-library/javascript/reference/referencedocs#googleauthissignedinlistenlistener) : listen for changes in the current user's sign-in state 90 | 91 | A function that takes a boolean value. Passes `true` to this function when the user signs in, and `false` when the user signs out. 92 | 93 | 94 | 95 | #### onInitFailure - Callback 96 | 97 | The function called with an object containing an `error` property, if `GoogleAuth` failed to initialize 98 | 99 | 100 | 101 | ## 2- Add a button 102 | 103 | Add a button component under GoogleAPI *(each button component check if it is a child of GoogleAPI, if not an error message is displayed)* 104 | 105 | ```jsx 106 | import React from 'react'; 107 | import ReactDOM from 'react-dom'; 108 | import {GoogleAPI,GoogleLogin,GoogleLogout} from 'react-google-oauth' 109 | 110 | ReactDOM.render( 111 | 114 |
115 |
116 |
117 |
118 |
, document.getElementById('root')); 119 | ``` 120 | 121 | 122 | 123 | ### GoogleLogin params 124 | 125 | | Callback | Default value | Comment | 126 | | ------------------------ | ---------------------- | ---------------------------------------- | 127 | | onLoginSuccess(response) | f => f | Function called when the authentification is done. Maybe it's more preferable to use onUpdateSigninStatus from \. Fulfilled with the `GoogleUser` instance when the user successfully authenticates and grants the requested scopes. | 128 | | onLoginFailure(error) | f => f | function called when a error occured. By example when a user closed the Google's popup before he choiced an account. This function take an object containing an error property. See Error Code on Google's documentation for more details. | 129 | | onRequest() | f => f | Called just before the call to Google Api Script, you can used this callback to display a loader by example. None parameter. | 130 | | Text | ' Sign in with Google' | Text displayed in button | 131 | | backgroundColor | \#4285f4 | See Rendering paragraph | 132 | | disabled | False | See Rendering paragraph | 133 | | width | 240px | See Rendering paragraph | 134 | 135 | 136 | 137 | ### GoogleLogout params 138 | 139 | | Callback | Default value | Comment | 140 | | ---------------------- | ---------------------- | ---------------------------------------- | 141 | | onLogoutSuccess() | f => f | Function called when the user has been signed out | 142 | | onLogoutFailure(error) | f => f | function called when a error occured. This function take an object containing an error property. See Error Code on Google's documentation for more details. | 143 | | onRequest() | f => f | Called just before the call to Google Api Script, you can used this callback to display a loader by example. None parameter. | 144 | | Text | ' Sign in with Google' | Text displayed in button | 145 | | backgroundColor | \#4285f4 | See Rendering paragraph | 146 | | disabled | False | See Rendering paragraph | 147 | | width | 240px | See Rendering paragraph | 148 | 149 | 150 | 151 | ## 3- Get informations 152 | 153 | Tow methods can help you to get informations 154 | 155 | ### googleGetBasicProfil 156 | 157 | ```javascript 158 | return {id : basicProfile.getId(), 159 | name : basicProfile.getName(), 160 | givenName :basicProfile.getGivenName(), 161 | familyName : basicProfile.getFamilyName(), 162 | imageUrl : basicProfile.getImageUrl(), 163 | email : basicProfile.getEmail(), 164 | hostedDomain : authInstance.currentUser.get().getHostedDomain(), 165 | scopes:authInstance.currentUser.get().getGrantedScopes()} 166 | ``` 167 | 168 | ### googleGetAuthResponse 169 | 170 | ```javascript 171 | return {accessToken : authResponse.access_token, 172 | id_token : authResponse.id_token, 173 | scope : authResponse.scope, 174 | expiresIn : authResponse.expires_in, 175 | firstIssuedAt : authResponse.first_issued_at, 176 | expiresAt : authResponse.expires_at} 177 | ``` 178 | 179 | 180 | 181 | # Rendering 182 | 183 | ## \ & \ 184 | 185 | Without parameters, buttons look like this : 186 | 187 | ```jsx 188 | 189 | 190 | ``` 191 | 192 | ![GoogleLogin button](https://i.imgur.com/LvEQ6yz.png) ![GoogleLogout button](https://i.imgur.com/SiR83vT.png) 193 | 194 | ## Text, Color, Width 195 | 196 | With pre-define rendering you can only change the text, the width and the background color. 197 | 198 | *Sample* 199 | 200 | ```jsx 201 | 206 | ``` 207 | 208 | ![Red GoogleLogin button](https://i.imgur.com/3LD3FTF.png) 209 | 210 | *Hover and active state are automaticaly generate (opacity 50% for Hover state and filter:brightness(80%) for active state.)* 211 | 212 | **Login button** 213 | 214 | | Parameter | Default value | 215 | | --------------- | ------------------- | 216 | | text | Sign in with Google | 217 | | width | 240px | 218 | | backgroundColor | \#4285f4 | 219 | 220 | **Logout button** 221 | 222 | | Parameter | Default value | 223 | | --------------- | ------------- | 224 | | text | Sign out | 225 | | width | 180px | 226 | | backgroundColor | \#A31515 | 227 | 228 | 229 | 230 | ## \ & \ 231 | 232 | With CustomGoogleLogin and CustomeGoogleLogout you can custom button as you want. 233 | 234 | 235 | 236 | | Parameters | Type | Comment | 237 | | ---------- | ------ | ---------------------------------------- | 238 | | tag | String | You can choose kind of tag use for rendering. An onClick event is attached on this tag during rendering | 239 | | className | String | CSS class | 240 | 241 | Sample with this rendering ![](https://i.imgur.com/PQbVOHu.png) 242 | 243 | ```html 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | ``` 257 | 258 | -------------------------------------------------------------------------------- /__tests__/components/test.js: -------------------------------------------------------------------------------- 1 | import deepFreeze from 'deep-freeze' 2 | import renderer from 'react-test-renderer' 3 | import {shallow} from 'enzyme' 4 | import {renderDefaultButton} from '../../src/components/' 5 | 6 | describe("Test shared component functions",() => { 7 | 8 | it("Test renderDefaultButton", () => { 9 | const params = { 10 | width: "100px", 11 | disabled: true, 12 | text: "bonjour", 13 | backgroundColor: "red", 14 | className: "test1", 15 | onClickFunc: "" 16 | } 17 | deepFreeze(params) 18 | const wrapper = shallow(renderDefaultButton(params)) 19 | const div = wrapper.find('.test1 > .react-google-oauth-button-border > .react-google-oauth-button-iconWrapper > .react-google-oauth-button-icon') 20 | expect(div.length).toEqual(1) 21 | const div2 = wrapper.find('.test1') 22 | expect(div2.prop('onClick')).toBeNull() 23 | const span = wrapper.find(".test1 > .react-google-oauth-button-border > .react-google-oauth-button-span") 24 | expect(span.text()).toEqual("bonjour") 25 | 26 | 27 | 28 | //console.log(div) 29 | //expect(div.hasClass('test1')).toEqual(true) 30 | }) 31 | }) -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-google-oauth", 3 | "version": "1.0.1", 4 | "description": "A Google OAuth component for React", 5 | "main": "dist/react-google-oauth.js", 6 | "scripts": { 7 | "start": "webpack --config ./config/webpack.config.dev.js", 8 | "build": "BABEL_ENV=development webpack --config ./webpack.config.dev.js --watch", 9 | "test": "jest --coverage" 10 | }, 11 | "repository": { 12 | "type": "git", 13 | "url": "git+https://github.com/CyrilSiman/react-google-oauth.git" 14 | }, 15 | "keywords": [ 16 | "React", 17 | "Google", 18 | "Oauth", 19 | "Login", 20 | "Logout" 21 | ], 22 | "author": "Cyril Siman", 23 | "license": "MIT", 24 | "bugs": { 25 | "url": "https://github.com/CyrilSiman/react-google-oauth/issues" 26 | }, 27 | "homepage": "https://github.com/CyrilSiman/react-google-oauth#readme", 28 | "dependencies": { 29 | "prop-types": "^15.5.10", 30 | "react": "^15.6.1" 31 | }, 32 | "devDependencies": { 33 | "autoprefixer": "^7.1.2", 34 | "babel-cli": "^6.24.1", 35 | "babel-eslint": "^7.2.3", 36 | "babel-jest": "^20.0.3", 37 | "babel-loader": "^7.1.1", 38 | "babel-plugin-transform-object-rest-spread": "^6.23.0", 39 | "babel-preset-es2015": "^6.24.1", 40 | "babel-preset-react-app": "^3.0.2", 41 | "case-sensitive-paths-webpack-plugin": "^2.1.1", 42 | "clean-webpack-plugin": "^0.1.16", 43 | "css-loader": "^0.28.4", 44 | "deep-freeze": "0.0.1", 45 | "enzyme": "^2.9.1", 46 | "eslint": "^4.4.1", 47 | "eslint-config-react-app": "^2.0.0", 48 | "eslint-loader": "^1.9.0", 49 | "eslint-plugin-flowtype": "^2.35.0", 50 | "eslint-plugin-import": "^2.7.0", 51 | "eslint-plugin-jsx-a11y": "^5.1.1", 52 | "eslint-plugin-react": "^7.1.0", 53 | "file-loader": "^0.11.2", 54 | "invariant": "^2.2.2", 55 | "jest": "^20.0.4", 56 | "jest-css-modules": "^1.1.0", 57 | "postcss-flexbugs-fixes": "^3.2.0", 58 | "postcss-loader": "^2.0.6", 59 | "react-addons-test-utils": "^15.6.0", 60 | "react-test-renderer": "^15.6.1", 61 | "style-loader": "^0.18.2", 62 | "webpack": "^3.5.1", 63 | "webpack-dev-server": "^2.7.1" 64 | }, 65 | "babel": { 66 | "presets": [ 67 | "react-app" 68 | ] 69 | }, 70 | "eslintConfig": { 71 | "extends": "react-app" 72 | }, 73 | "jest": { 74 | "verbose": true, 75 | "moduleNameMapper": { 76 | "\\.( css) $": "< rootDir >/ node_modules/ jest-css-modules" 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/components/customLogin/index.jsx: -------------------------------------------------------------------------------- 1 | import { Component } from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import invariant from 'invariant' 4 | import { renderCustomDefaultButton } from '../' 5 | 6 | class CustomGoogleLogin extends Component { 7 | constructor(props, context) { 8 | super(props, context); 9 | this.signIn = this.signIn.bind(this); 10 | } 11 | 12 | componentWillMount() { 13 | invariant( 14 | this.context.reactGoogleApi, 15 | 'A can be used only as child or descendant of ' 16 | ) 17 | } 18 | 19 | signIn(e) { 20 | if (e) { 21 | e.preventDefault(); // to prevent submit if used within form 22 | } 23 | 24 | const auth2 = window.gapi.auth2.getAuthInstance(); 25 | const { onLoginSuccess, onLoginFailure, onRequest } = this.props 26 | 27 | onRequest(); 28 | 29 | auth2.signIn() 30 | .then( 31 | res => onLoginSuccess(res), 32 | err => onLoginFailure(err) 33 | ); 34 | 35 | } 36 | 37 | render() { 38 | return renderCustomDefaultButton({ 39 | tag: this.props.tag, 40 | className: this.props.className, 41 | text: this.props.text, 42 | disabled: this.props.disabled, 43 | children: this.props.children, 44 | onClickFunc: this.signIn 45 | }) 46 | } 47 | } 48 | 49 | CustomGoogleLogin.contextTypes = { 50 | reactGoogleApi: PropTypes.bool 51 | } 52 | 53 | CustomGoogleLogin.propTypes = { 54 | onLoginSuccess: PropTypes.func, 55 | onLoginFailure: PropTypes.func, 56 | onRequest: PropTypes.func, 57 | text: PropTypes.string, 58 | children: PropTypes.node, 59 | disabled: PropTypes.bool, 60 | className: PropTypes.string, 61 | tag: PropTypes.string, 62 | }; 63 | 64 | CustomGoogleLogin.defaultProps = { 65 | onLoginFailure: f => f, 66 | onLoginSuccess: f => f, 67 | onRequest: f => f, 68 | tag: "a", 69 | text: 'Sign in with Google', 70 | }; 71 | 72 | export default CustomGoogleLogin; -------------------------------------------------------------------------------- /src/components/customLogout/index.jsx: -------------------------------------------------------------------------------- 1 | import {Component} from 'react' 2 | import PropTypes from 'prop-types'; 3 | import invariant from 'invariant' 4 | import { renderCustomDefaultButton } from '../' 5 | 6 | class CustomGoogleLogout extends Component { 7 | constructor(props, context) { 8 | super(props, context); 9 | this.signOut = this.signOut.bind(this); 10 | } 11 | 12 | componentWillMount() { 13 | invariant( 14 | this.context.reactGoogleApi, 15 | 'A must be used only as child or descendant of ' 16 | ) 17 | } 18 | 19 | signOut(e) { 20 | if (e) { 21 | e.preventDefault(); // to prevent submit if used within form 22 | } 23 | 24 | const authInstance = window.gapi.auth2.getAuthInstance(); 25 | 26 | if (authInstance.isSignedIn.get()) { 27 | const { onLogoutSuccess, onLogoutFailure, onRequest } = this.props 28 | 29 | //Call onRequest function 30 | onRequest(); 31 | 32 | authInstance.signOut() 33 | .then( 34 | () => { 35 | onLogoutSuccess() 36 | }, 37 | () => { 38 | onLogoutFailure() 39 | } 40 | ); 41 | } 42 | } 43 | 44 | render() { 45 | return renderCustomDefaultButton({ 46 | tag: this.props.tag, 47 | className: this.props.className, 48 | text: this.props.text, 49 | disabled: this.props.disabled, 50 | children: this.props.children, 51 | onClickFunc: this.signOut 52 | }) 53 | } 54 | } 55 | 56 | CustomGoogleLogout.contextTypes = { 57 | reactGoogleApi: PropTypes.bool 58 | } 59 | 60 | CustomGoogleLogout.propTypes = { 61 | onLogoutSuccess: PropTypes.func, 62 | onLogoutFailure: PropTypes.func, 63 | onRequest: PropTypes.func, 64 | text: PropTypes.string, 65 | children: PropTypes.node, 66 | disabled: PropTypes.bool, 67 | width: PropTypes.string 68 | }; 69 | 70 | CustomGoogleLogout.defaultProps = { 71 | onLogoutSuccess: f => f, 72 | onLogoutFailure: f => f, 73 | onRequest: f => f, 74 | text: 'Sign out', 75 | tag: "a", 76 | }; 77 | 78 | export default CustomGoogleLogout; -------------------------------------------------------------------------------- /src/components/index.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | 3 | export const renderDefaultButton = ({ width, disabled, text, backgroundColor, className, onClickFunc }) => { 4 | 5 | const func = disabled ? null : onClickFunc 6 | let style = backgroundColor ? { backgroundColor: backgroundColor } : {} 7 | style = width ? {...style,width} : style 8 | 9 | const classNameTmp = `react-google-oauth-button-main ${className}` 10 | 11 | return
12 |
13 |
14 |
15 | 17 | 18 | 19 | 20 | 21 | 22 |
23 |
24 | {text} 25 |
26 |
27 | } 28 | 29 | export const renderCustomDefaultButton = ({ tag, className, text, disabled, children, onClickFunc }) => { 30 | 31 | const Tag = tag 32 | 33 | return tag === "a" ? 34 | 35 | {children ? children : text} 36 | 37 | : 38 | {children ? children : text} 39 | 40 | } -------------------------------------------------------------------------------- /src/components/login/index.jsx: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import invariant from 'invariant' 4 | import { renderDefaultButton } from '../' 5 | import '../../styles.css' 6 | 7 | class GoogleLogin extends Component { 8 | constructor(props, context) { 9 | super(props, context); 10 | this.signIn = this.signIn.bind(this); 11 | } 12 | 13 | componentWillMount() { 14 | invariant( 15 | this.context.reactGoogleApi, 16 | 'A can be used only as child or descendant of ' 17 | ) 18 | invariant( 19 | React.Children.count(this.props.children) === 0, 20 | 'A can\'t have child, use instead' 21 | ) 22 | } 23 | 24 | signIn(e) { 25 | if (e) { 26 | e.preventDefault() // to prevent submit if used within form 27 | } 28 | 29 | const auth2 = window.gapi.auth2.getAuthInstance() 30 | const { onLoginSuccess, onLoginFailure, onRequest } = this.props 31 | 32 | onRequest(); 33 | 34 | auth2.signIn() 35 | .then( 36 | res => onLoginSuccess(res), 37 | err => onLoginFailure(err) 38 | ); 39 | 40 | } 41 | 42 | render() { 43 | 44 | return renderDefaultButton({ 45 | text: this.props.text, 46 | backgroundColor: this.props.backgroundColor, 47 | disabled: this.props.disabled, 48 | className: "react-google-oauth-button-login", 49 | onClickFunc: this.signIn, 50 | width: this.props.width 51 | }) 52 | } 53 | } 54 | 55 | GoogleLogin.contextTypes = { 56 | reactGoogleApi: PropTypes.bool 57 | } 58 | 59 | GoogleLogin.propTypes = { 60 | onLoginSuccess: PropTypes.func, 61 | onLoginFailure: PropTypes.func, 62 | onRequest: PropTypes.func, 63 | text: PropTypes.string, 64 | children: PropTypes.node, 65 | disabled: PropTypes.bool, 66 | width: PropTypes.string 67 | }; 68 | 69 | GoogleLogin.defaultProps = { 70 | onLoginFailure: f => f, 71 | onLoginSuccess: f => f, 72 | onRequest: f => f, 73 | text: 'Sign in with Google' 74 | }; 75 | 76 | export default GoogleLogin; -------------------------------------------------------------------------------- /src/components/logout/index.jsx: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import invariant from 'invariant' 4 | import {renderDefaultButton} from '../' 5 | import '../../styles.css' 6 | 7 | class GoogleLogout extends Component { 8 | constructor(props, context) { 9 | super(props, context); 10 | this.signOut = this.signOut.bind(this); 11 | } 12 | 13 | componentWillMount() { 14 | invariant( 15 | this.context.reactGoogleApi, 16 | 'A can be used only as child or descendant of ' 17 | ) 18 | invariant( 19 | React.Children.count(this.props.children) === 0, 20 | 'A can\'t have child, use instead' 21 | ) 22 | } 23 | 24 | signOut(e) { 25 | if (e) { 26 | e.preventDefault(); // to prevent submit if used within form 27 | } 28 | 29 | const authInstance = window.gapi.auth2.getAuthInstance(); 30 | 31 | if (authInstance.isSignedIn.get()) { 32 | const { onLogoutSuccess, onLogoutFailure, onRequest } = this.props 33 | 34 | //Call onRequest function 35 | onRequest(); 36 | 37 | authInstance.signOut() 38 | .then( 39 | () => { 40 | onLogoutSuccess() 41 | }, 42 | () => { 43 | onLogoutFailure() 44 | } 45 | ); 46 | } 47 | } 48 | 49 | render() { 50 | 51 | return renderDefaultButton({ 52 | text:this.props.text, 53 | backgroundColor:this.props.backgroundColor, 54 | disabled:this.props.disabled, 55 | className:"react-google-oauth-button-logout", 56 | onClickFunc:this.signOut, 57 | with:this.props.width 58 | }) 59 | } 60 | } 61 | GoogleLogout.contextTypes = { 62 | reactGoogleApi: PropTypes.bool 63 | } 64 | 65 | GoogleLogout.propTypes = { 66 | onLogoutSuccess: PropTypes.func, 67 | onLogoutFailure: PropTypes.func, 68 | onRequest: PropTypes.func, 69 | text: PropTypes.string, 70 | children: PropTypes.node, 71 | disabled: PropTypes.bool, 72 | width: PropTypes.string 73 | }; 74 | 75 | GoogleLogout.defaultProps = { 76 | onLogoutSuccess: f => f, 77 | onLogoutFailure: f => f, 78 | onRequest: f => f, 79 | text: 'Sign out', 80 | }; 81 | 82 | export default GoogleLogout; -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import _GoogleAPI from './services/index.jsx' 2 | import _GoogleLogin from './components/login/' 3 | import _GoogleLogout from './components/logout/' 4 | import _CustomGoogleLogin from './components/customLogin/' 5 | import _CustomGoogleLogout from './components/customLogout/' 6 | 7 | export const GoogleAPI = _GoogleAPI 8 | export const GoogleLogin = _GoogleLogin 9 | export const GoogleLogout = _GoogleLogout 10 | export const CustomGoogleLogin = _CustomGoogleLogin 11 | export const CustomGoogleLogout = _CustomGoogleLogout 12 | 13 | export const googleGetAuthResponse = () => { 14 | let returnObj = {} 15 | 16 | //Lib loaded 17 | if (window.gapi && window.gapi.auth2) { 18 | //Lib correctly init 19 | let authInstance = window.gapi.auth2.getAuthInstance() 20 | //User authenticated 21 | if (authInstance && authInstance.currentUser.get().getBasicProfile()) { 22 | let authResponse = authInstance.currentUser.get().getAuthResponse(true) 23 | 24 | if(authResponse) { 25 | 26 | returnObj = { 27 | accessToken : authResponse.access_token, 28 | id_token : authResponse.id_token, 29 | scope : authResponse.scope, 30 | expiresIn : authResponse.expires_in, 31 | firstIssuedAt : authResponse.first_issued_at, 32 | expiresAt : authResponse.expires_at 33 | } 34 | } 35 | } 36 | } 37 | return returnObj 38 | } 39 | 40 | export const googleGetBasicProfil = () => { 41 | let returnObj = {} 42 | //Lib loaded 43 | if (window.gapi && window.gapi.auth2) { 44 | //Lib correctly init 45 | let authInstance = window.gapi.auth2.getAuthInstance() 46 | //User authenticated 47 | if (authInstance && authInstance.currentUser.get().getBasicProfile()) { 48 | let basicProfile = authInstance.currentUser.get().getBasicProfile() 49 | 50 | returnObj = { 51 | id : basicProfile.getId(), 52 | name : basicProfile.getName(), 53 | givenName :basicProfile.getGivenName(), 54 | familyName : basicProfile.getFamilyName(), 55 | imageUrl : basicProfile.getImageUrl(), 56 | email : basicProfile.getEmail(), 57 | hostedDomain : authInstance.currentUser.get().getHostedDomain(), 58 | scopes : authInstance.currentUser.get().getGrantedScopes() 59 | } 60 | } 61 | } 62 | return returnObj 63 | } 64 | -------------------------------------------------------------------------------- /src/services/index.jsx: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import invariant from 'invariant' 4 | 5 | const insertGoogleScript = (documentRoot, id, handleClientLoad) => { 6 | //Check if script already present 7 | if (!documentRoot.getElementById(id)) { 8 | const firstScriptTag = documentRoot.getElementsByTagName('script')[0]; 9 | const scriptTag = documentRoot.createElement('script'); 10 | scriptTag.async = 'async' 11 | scriptTag.defer = 'defer' 12 | scriptTag.id = id; 13 | scriptTag.src = '//apis.google.com/js/client:platform.js'; 14 | scriptTag.onload = handleClientLoad; 15 | firstScriptTag.parentNode.insertBefore(scriptTag, firstScriptTag); 16 | } 17 | } 18 | 19 | // Loads auth2 library 20 | const handleClientLoad = (initGoogleClient) => () => 21 | window.gapi.load('auth2', initGoogleClient); 22 | 23 | const initGoogleClientAPI = (params, onUpdateSigninStatus, onInitFailure) => () => { 24 | 25 | const auth2 = window.gapi.auth2 26 | auth2.init(params).then( 27 | () => { 28 | // Listen for sign-in state changes. 29 | auth2.getAuthInstance().isSignedIn.listen(onUpdateSigninStatus); 30 | // Handle the initial sign-in state. 31 | onUpdateSigninStatus(auth2.getAuthInstance().isSignedIn.get()); 32 | }, onInitFailure 33 | ) 34 | } 35 | 36 | const makeGoogleParams = (props) => { 37 | const { clientId, cookiePolicy, hostedDomain, fetchBasicProfile, redirectUri, uxMode, scope } = props 38 | 39 | return ({ 40 | client_id: clientId, 41 | cookiepolicy: cookiePolicy, 42 | hosted_domain: hostedDomain, 43 | fetch_basic_profile: fetchBasicProfile, 44 | ux_mode: uxMode, 45 | redirect_uri: redirectUri, 46 | scope 47 | }) 48 | } 49 | 50 | //The function called if the Google libraries failed to load. 51 | const initGoogleClientAPIFailure = err => 52 | console.error(err) 53 | 54 | class GoogleAPI extends Component { 55 | 56 | getChildContext() { 57 | return { 58 | reactGoogleApi: true 59 | } 60 | } 61 | 62 | componentWillMount() { 63 | 64 | const { children } = this.props 65 | 66 | invariant( 67 | children == null || React.Children.count(children) === 1, 68 | 'A may have only one child element' 69 | ) 70 | } 71 | 72 | componentDidMount() { 73 | 74 | const onUpdateSigninStatus = this.props.onUpdateSigninStatus ? this.props.onUpdateSigninStatus : f => f 75 | const onInitFailure = this.props.onFailure ? this.props.onInitFailure : initGoogleClientAPIFailure 76 | 77 | const params = makeGoogleParams(this.props) 78 | 79 | const initClient = initGoogleClientAPI(params, onUpdateSigninStatus, onInitFailure) 80 | const initGoogleApi = handleClientLoad(initClient) 81 | 82 | insertGoogleScript(document, 'react-google-oauth-id', initGoogleApi); 83 | } 84 | 85 | render() { 86 | const { children } = this.props 87 | return children ? React.Children.only(children) : null 88 | } 89 | } 90 | 91 | GoogleAPI.childContextTypes = { 92 | reactGoogleApi: PropTypes.bool 93 | } 94 | 95 | GoogleAPI.propTypes = { 96 | onUpdateSigninStatus: PropTypes.func, 97 | onInitFailure: PropTypes.func, 98 | clientId: PropTypes.string.isRequired, 99 | scope: PropTypes.string, 100 | cookiePolicy: PropTypes.string, 101 | fetchBasicProfile: PropTypes.bool, 102 | prompt: PropTypes.string, 103 | uxMode: PropTypes.string, 104 | hostedDomain: PropTypes.string, 105 | redirectUri: PropTypes.string, 106 | children: PropTypes.node, 107 | }; 108 | 109 | GoogleAPI.defaultProps = { 110 | scope: '', 111 | cookiePolicy: 'single_host_origin', 112 | fetchBasicProfile: true, 113 | prompt: '', 114 | uxMode: 'popup', 115 | }; 116 | 117 | export default GoogleAPI; -------------------------------------------------------------------------------- /src/styles.css: -------------------------------------------------------------------------------- 1 | .react-google-oauth-button-span { 2 | margin-left: 6px; 3 | margin-right: 6px; 4 | vertical-align: top; 5 | font-size: 16px; 6 | font-weight: 500; 7 | font-family: Roboto, arial, sans-serif; 8 | letter-spacing: .21px; 9 | line-height: 48px; 10 | } 11 | 12 | .react-google-oauth-button-icon { 13 | width: 18px; 14 | height: 18px; 15 | } 16 | 17 | .react-google-oauth-button-iconWrapper { 18 | padding: 15px; 19 | background-color: white; 20 | float: left; 21 | } 22 | 23 | .react-google-oauth-button-border { 24 | border: 1px solid transparent; 25 | height: 100%; 26 | width: 100%; 27 | } 28 | 29 | .react-google-oauth-button-main { 30 | display: inline-block; 31 | color: #fff; 32 | height: 50px; 33 | padding: 0px; 34 | border-radius: 1px; 35 | border: none; 36 | cursor: pointer; 37 | text-align: center; 38 | transition: all 0.4s 39 | } 40 | 41 | .react-google-oauth-button-main:hover { 42 | opacity: 0.5; 43 | } 44 | 45 | .react-google-oauth-button-main:active { 46 | filter: brightness(80%); 47 | opacity: 1; 48 | } 49 | 50 | .react-google-oauth-button-login { 51 | background-color: #4285f4; 52 | width: 240px; 53 | } 54 | 55 | .react-google-oauth-button-logout { 56 | background-color: green; 57 | width: 180px; 58 | } 59 | 60 | 61 | -------------------------------------------------------------------------------- /webpack.config.dev.js: -------------------------------------------------------------------------------- 1 | const autoprefixer = require('autoprefixer'); 2 | const path = require('path'); 3 | const webpack = require('webpack'); 4 | const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin'); 5 | const CleanWebpackPlugin = require('clean-webpack-plugin'); 6 | 7 | module.exports = { 8 | devtool: 'cheap-module-source-map', 9 | entry: './src/index.js', 10 | output: { 11 | filename: 'react-google-oauth.js', 12 | path: path.resolve(__dirname, 'dist'), 13 | // include comments in bundles with information about the contained modules 14 | pathinfo: true, 15 | publicPath: '/', 16 | library: "react-google-oauth", 17 | libraryTarget: "umd" 18 | }, 19 | module: { 20 | //makes missing exports an error instead of warning 21 | strictExportPresence: true, 22 | 23 | rules: [ 24 | // First, run the linter. 25 | // It's important to do this before Babel processes the JS. 26 | { 27 | test: /\.(js|jsx)$/, 28 | enforce: 'pre', 29 | use: [ 30 | { 31 | loader: require.resolve('eslint-loader'), 32 | }, 33 | ], 34 | exclude: /node_modules/, 35 | }, 36 | // ** ADDING/UPDATING LOADERS ** 37 | // The "file" loader handles all assets unless explicitly excluded. 38 | // The `exclude` list *must* be updated with every change to loader extensions. 39 | // When adding a new loader, you must add its `test` 40 | // as a new entry in the `exclude` list for "file" loader. 41 | 42 | // "file" loader makes sure those assets get served by WebpackDevServer. 43 | // When you `import` an asset, you get its (virtual) filename. 44 | // In production, they would get copied to the `build` folder. 45 | { 46 | exclude: [ 47 | /\.html$/, 48 | /\.(js|jsx)$/, 49 | /\.css$/, 50 | /\.json$/, 51 | /\.bmp$/, 52 | /\.gif$/, 53 | /\.jpe?g$/, 54 | /\.png$/, 55 | ], 56 | loader: require.resolve('file-loader'), 57 | options: { 58 | name: 'static/media/[name].[hash:8].[ext]', 59 | }, 60 | }, 61 | // Process JS with Babel. 62 | { 63 | test: /\.(js|jsx)$/, 64 | exclude: /node_modules/, 65 | loader: require.resolve('babel-loader'), 66 | options: { 67 | presets: ['env'], 68 | plugins: [require('babel-plugin-transform-object-rest-spread')], 69 | // This is a feature of `babel-loader` for webpack (not Babel itself). 70 | // It enables caching results in ./node_modules/.cache/babel-loader/ 71 | // directory for faster rebuilds. 72 | cacheDirectory: true, 73 | }, 74 | }, 75 | { 76 | test: /\.css$/, 77 | use: [ 78 | require.resolve('style-loader'), 79 | { 80 | loader: require.resolve('css-loader'), 81 | options: { 82 | importLoaders: 1, 83 | modules: false, 84 | localIdentName: "[name]__[local]___[hash:base64:5]" 85 | }, 86 | }, 87 | // "postcss" loader applies autoprefixer to our CSS. 88 | // "css" loader resolves paths in CSS and adds assets as dependencies. 89 | // "style" loader turns CSS into JS modules that inject