angularx-social-login
Version:
Social login and authentication module for Angular 9+. Supports authentication with Google, Facebook, Amazon, and VK. Can be extended to other providers also.
16 lines (14 loc) • 15.9 kB
JavaScript
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("@angular/core"),require("rxjs"),require("@angular/common")):"function"==typeof define&&define.amd?define("angularx-social-login",["exports","@angular/core","rxjs","@angular/common"],e):e((t=t||self)["angularx-social-login"]={},t.ng.core,t.rxjs,t.ng.common)}(this,(function(t,e,n,i){"use strict";
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */var o=function(t,e){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])})(t,e)};function r(t,e){function n(){this.constructor=t}o(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}Object.create;Object.create;var s=function(){function t(){}return t.prototype.loadScript=function(t,e,n,i){if(void 0===i&&(i=null),"undefined"!=typeof document&&!document.getElementById(t)){var o=document.createElement("script");o.async=!0,o.src=e,o.onload=n,i||(i=document.head),i.appendChild(o)}},t}(),a=function(){},c=function(t){function e(e,n){void 0===n&&(n={scope:"email"});var i=t.call(this)||this;return i.clientId=e,i.initOptions=n,i}return r(e,t),e.prototype.initialize=function(){var t=this;return new Promise((function(n,i){try{t.loadScript(e.PROVIDER_ID,"https://apis.google.com/js/platform.js",(function(){gapi.load("auth2",(function(){t.auth2=gapi.auth2.init(Object.assign(Object.assign({},t.initOptions),{client_id:t.clientId})),t.auth2.then((function(){n()})).catch((function(t){i(t)}))}))}))}catch(t){i(t)}}))},e.prototype.getLoginStatus=function(t){var n=this;return new Promise((function(i,o){if(n.auth2.isSignedIn.get()){var r=new a,s=n.auth2.currentUser.get().getBasicProfile();if(r.id=s.getId(),r.name=s.getName(),r.email=s.getEmail(),r.photoUrl=s.getImageUrl(),r.firstName=s.getGivenName(),r.lastName=s.getFamilyName(),r.response=s,t&&t.refreshToken)n.auth2.currentUser.get().reloadAuthResponse().then((function(t){r.authToken=t.access_token,r.idToken=t.id_token,i(r)}));else{var c=n.auth2.currentUser.get().getAuthResponse(!0);r.authToken=c.access_token,r.idToken=c.id_token,i(r)}}else o("No user is currently logged in with "+e.PROVIDER_ID)}))},e.prototype.signIn=function(t){var e=this,n=Object.assign(Object.assign({},this.initOptions),t);return new Promise((function(i,o){(n&&n.offline_access?e.auth2.grantOfflineAccess(t):e.auth2.signIn(t)).then((function(t){var n=new a;if(t&&t.code)n.authorizationCode=t.code;else{var o=e.auth2.currentUser.get().getBasicProfile(),r=e.auth2.currentUser.get().getAuthResponse(!0).access_token,s=e.auth2.currentUser.get().getAuthResponse(!0).id_token;n.id=o.getId(),n.name=o.getName(),n.email=o.getEmail(),n.photoUrl=o.getImageUrl(),n.firstName=o.getGivenName(),n.lastName=o.getFamilyName(),n.authToken=r,n.idToken=s,n.response=o}i(n)}),(function(t){o(t)})).catch((function(t){o(t)}))}))},e.prototype.signOut=function(t){var e=this;return new Promise((function(n,i){(t?e.auth2.disconnect():e.auth2.signOut()).then((function(t){t?i(t):n()})).catch((function(t){i(t)}))}))},e}(s);c.PROVIDER_ID="GOOGLE";var u=function(){function t(t){var e=this;this.providers=new Map,this.autoLogin=!1,this._user=null,this._authState=new n.ReplaySubject(1),this.initialized=!1,this._initState=new n.AsyncSubject,t instanceof Promise?t.then((function(t){e.initialize(t)})):this.initialize(t)}return Object.defineProperty(t.prototype,"authState",{get:function(){return this._authState.asObservable()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"initState",{get:function(){return this._initState.asObservable()},enumerable:!1,configurable:!0}),t.prototype.initialize=function(t){var e=this;this.autoLogin=void 0!==t.autoLogin&&t.autoLogin;var n=t.onError,i=void 0===n?console.error:n;t.providers.forEach((function(t){e.providers.set(t.id,t.provider)})),Promise.all(Array.from(this.providers.values()).map((function(t){return t.initialize()}))).then((function(){if(e.autoLogin){var t=[],n=!1;e.providers.forEach((function(i,o){var r=i.getLoginStatus();t.push(r),r.then((function(t){t.provider=o,e._user=t,e._authState.next(t),n=!0})).catch(console.debug)})),Promise.all(t).catch((function(){n||(e._user=null,e._authState.next(null))}))}})).catch((function(t){i(t)})).finally((function(){e.initialized=!0,e._initState.next(e.initialized),e._initState.complete()}))},t.prototype.refreshAuthToken=function(e){var n=this;return new Promise((function(i,o){if(n.initialized)if(e!==c.PROVIDER_ID)o(t.ERR_NOT_SUPPORTED_FOR_REFRESH_TOKEN);else{var r=n.providers.get(e);r?r.getLoginStatus({refreshToken:!0}).then((function(t){t.provider=e,n._user=t,n._authState.next(t),i()})).catch((function(t){o(t)})):o(t.ERR_LOGIN_PROVIDER_NOT_FOUND)}else o(t.ERR_NOT_INITIALIZED)}))},t.prototype.signIn=function(e,n){var i=this;return new Promise((function(o,r){if(i.initialized){var s=i.providers.get(e);s?s.signIn(n).then((function(t){t.provider=e,o(t),i._user=t,i._authState.next(t)})).catch((function(t){r(t)})):r(t.ERR_LOGIN_PROVIDER_NOT_FOUND)}else r(t.ERR_NOT_INITIALIZED)}))},t.prototype.signOut=function(e){var n=this;return void 0===e&&(e=!1),new Promise((function(i,o){if(n.initialized)if(n._user){var r=n._user.provider,s=n.providers.get(r);s?s.signOut(e).then((function(){i(),n._user=null,n._authState.next(null)})).catch((function(t){o(t)})):o(t.ERR_LOGIN_PROVIDER_NOT_FOUND)}else o(t.ERR_NOT_LOGGED_IN);else o(t.ERR_NOT_INITIALIZED)}))},t}();u.ERR_LOGIN_PROVIDER_NOT_FOUND="Login provider not found",u.ERR_NOT_LOGGED_IN="Not logged in",u.ERR_NOT_INITIALIZED="Login providers not ready yet. Are there errors on your console?",u.ERR_NOT_SUPPORTED_FOR_REFRESH_TOKEN="Chosen login provider is not supported for refreshing a token",u.decorators=[{type:e.Injectable}],u.ctorParameters=function(){return[{type:void 0,decorators:[{type:e.Inject,args:["SocialAuthServiceConfig"]}]}]};var l=function(){function t(t){if(t)throw new Error("SocialLoginModule is already loaded. Import it in the AppModule only")}return t.initialize=function(e){return{ngModule:t,providers:[u,{provide:"SocialAuthServiceConfig",useValue:e}]}},t}();l.decorators=[{type:e.NgModule,args:[{imports:[i.CommonModule],providers:[u]}]}],l.ctorParameters=function(){return[{type:l,decorators:[{type:e.Optional},{type:e.SkipSelf}]}]};var p=function(t){function e(n){var i=t.call(this)||this;return i.dummy=n||e.DEFAULT_USER,i.loggedIn=!1,i}return r(e,t),e.prototype.getLoginStatus=function(){var t=this;return new Promise((function(e,n){t.loggedIn?e(t.dummy):n("No user is currently logged in.")}))},e.prototype.initialize=function(){return new Promise((function(t,e){t()}))},e.prototype.signIn=function(){var t=this;return new Promise((function(e,n){t.loggedIn=!0,e(t.dummy)}))},e.prototype.signOut=function(t){var e=this;return new Promise((function(t,n){e.loggedIn=!1,t()}))},e}(s);p.PROVIDER_ID="DUMMY",p.DEFAULT_USER={id:"1234567890",name:"Mickey Mouse",email:"mickey@mouse.com",firstName:"Mickey",lastName:"Mouse",authToken:"dummyAuthToken",photoUrl:"https://en.wikipedia.org/wiki/File:Mickey_Mouse.png",provider:"DUMMY",idToken:"dummyIdToken",authorizationCode:"dummyAuthCode",response:{}};var f=function(t){function e(e,n){void 0===n&&(n={scope:"email,public_profile",locale:"en_US",fields:"name,email,picture,first_name,last_name",version:"v4.0"});var i=t.call(this)||this;return i.clientId=e,i.initOptions=n,i}return r(e,t),e.prototype.initialize=function(){var t=this;return new Promise((function(n,i){try{t.loadScript(e.PROVIDER_ID,"//connect.facebook.net/"+t.initOptions.locale+"/sdk.js",(function(){FB.init({appId:t.clientId,autoLogAppEvents:!0,cookie:!0,xfbml:!0,version:t.initOptions.version}),n()}))}catch(t){i(t)}}))},e.prototype.getLoginStatus=function(){var t=this;return new Promise((function(n,i){FB.getLoginStatus((function(o){if("connected"===o.status){var r=o.authResponse;FB.api("/me?fields="+t.initOptions.fields,(function(t){var e=new a;e.id=t.id,e.name=t.name,e.email=t.email,e.photoUrl="https://graph.facebook.com/"+t.id+"/picture?type=normal",e.firstName=t.first_name,e.lastName=t.last_name,e.authToken=r.accessToken,e.response=t,n(e)}))}else i("No user is currently logged in with "+e.PROVIDER_ID)}))}))},e.prototype.signIn=function(t){var e=Object.assign(Object.assign({},this.initOptions),t);return new Promise((function(t,n){FB.login((function(i){if(i.authResponse){var o=i.authResponse;FB.api("/me?fields="+e.fields,(function(e){var n=new a;n.id=e.id,n.name=e.name,n.email=e.email,n.photoUrl="https://graph.facebook.com/"+e.id+"/picture?type=normal",n.firstName=e.first_name,n.lastName=e.last_name,n.authToken=o.accessToken,n.response=e,t(n)}))}else n("User cancelled login or did not fully authorize.")}),e)}))},e.prototype.signOut=function(){return new Promise((function(t,e){FB.logout((function(e){t()}))}))},e}(s);f.PROVIDER_ID="FACEBOOK";var d=function(t){function e(e,n){void 0===n&&(n={scope:"profile",scope_data:{profile:{essential:!1}},redirect_uri:location.origin});var i=t.call(this)||this;return i.clientId=e,i.initOptions=n,i}return r(e,t),e.prototype.initialize=function(){var t=this,e=null;return document&&((e=document.createElement("div")).id="amazon-root",document.body.appendChild(e)),window.onAmazonLoginReady=function(){amazon.Login.setClientId(t.clientId)},new Promise((function(n,i){try{t.loadScript("amazon-login-sdk","https://assets.loginwithamazon.com/sdk/na/login1.js",(function(){n()}),e)}catch(t){i(t)}}))},e.prototype.getLoginStatus=function(){var t=this;return new Promise((function(n,i){var o=t.retrieveToken();o?amazon.Login.retrieveProfile(o,(function(t){if(t.success){var e=new a;e.id=t.profile.CustomerId,e.name=t.profile.Name,e.email=t.profile.PrimaryEmail,e.response=t.profile,n(e)}else i(t.error)})):i("No user is currently logged in with "+e.PROVIDER_ID)}))},e.prototype.signIn=function(t){var e=this,n=Object.assign(Object.assign({},this.initOptions),t);return new Promise((function(t,i){amazon.Login.authorize(n,(function(n){n.error?i(n.error):amazon.Login.retrieveProfile(n.access_token,(function(i){var o=new a;o.id=i.profile.CustomerId,o.name=i.profile.Name,o.email=i.profile.PrimaryEmail,o.authToken=n.access_token,o.response=i.profile,e.persistToken(n.access_token),t(o)}))}))}))},e.prototype.signOut=function(t){var e=this;return new Promise((function(t,n){try{amazon.Login.logout(),e.clearToken(),t()}catch(t){n(t.message)}}))},e.prototype.persistToken=function(t){localStorage.setItem(e.PROVIDER_ID+"_token",t)},e.prototype.retrieveToken=function(){return localStorage.getItem(e.PROVIDER_ID+"_token")},e.prototype.clearToken=function(){localStorage.removeItem(e.PROVIDER_ID+"_token")},e}(s);d.PROVIDER_ID="AMAZON";var h,g=function(t){function e(e,n){void 0===n&&(n={fields:"photo_max,contacts",version:"5.124"});var i=t.call(this)||this;return i.clientId=e,i.initOptions=n,i.VK_API_URL="//vk.com/js/api/openapi.js",i.VK_API_GET_USER="users.get",i}return r(e,t),e.prototype.initialize=function(){var t=this;return new Promise((function(n,i){try{t.loadScript(e.PROVIDER_ID,t.VK_API_URL,(function(){VK.init({apiId:t.clientId}),n()}))}catch(t){i(t)}}))},e.prototype.getLoginStatus=function(){var t=this;return new Promise((function(e,n){return t.getLoginStatusInternal(e,n)}))},e.prototype.signIn=function(){var t=this;return new Promise((function(e,n){return t.signInInternal(e,n)}))},e.prototype.signOut=function(){return new Promise((function(t,e){VK.Auth.logout((function(e){t()}))}))},e.prototype.signInInternal=function(t,e){var n=this;VK.Auth.login((function(e){"connected"===e.status&&n.getUser(e.session.mid,e.session.sid,t)}))},e.prototype.getUser=function(t,e,n){var i=this;VK.Api.call(this.VK_API_GET_USER,{user_id:t,fields:this.initOptions.fields,v:this.initOptions.version},(function(t){n(i.createUser(Object.assign({},{token:e},t.response[0])))}))},e.prototype.getLoginStatusInternal=function(t,e){var n=this;VK.Auth.getLoginStatus((function(e){"connected"===e.status&&n.getUser(e.session.mid,e.session.sid,t)}))},e.prototype.createUser=function(t){var e=new a;return e.id=t.id,e.name=t.first_name+" "+t.last_name,e.photoUrl=t.photo_max,e.authToken=t.token,e},e}(s);g.PROVIDER_ID="VK",function(t){t.AAD="AAD",t.OIDC="OIDC"}(h||(h={}));var m=function(t){function e(e,n){var i=t.call(this)||this;return i.clientId=e,i.initOptions={redirect_uri:location.origin,authority:"https://login.microsoftonline.com/common/",scopes:["openid","profile","User.Read"],knownAuthorities:[],protocolMode:h.AAD,clientCapabilities:[],cacheLocation:"sessionStorage"},i.initOptions=Object.assign(Object.assign({},i.initOptions),n),i}return r(e,t),e.prototype.initialize=function(){var t=this;return new Promise((function(n,i){t.loadScript(e.PROVIDER_ID,"https://alcdn.msauth.net/browser/2.1.0/js/msal-browser.js",(function(){try{var e={auth:{clientId:t.clientId,redirectUri:t.initOptions.redirect_uri,authority:t.initOptions.authority,knownAuthorities:t.initOptions.knownAuthorities,protocolMode:t.initOptions.protocolMode,clientCapabilities:t.initOptions.clientCapabilities},cache:t.initOptions.cacheLocation?{cacheLocation:t.initOptions.cacheLocation}:null};t._instance=new msal.PublicClientApplication(e),n()}catch(t){i(t)}}))}))},e.prototype.getSocialUser=function(t){return new Promise((function(n,i){var o=new XMLHttpRequest;o.onreadystatechange=function(){if(4==o.readyState)try{if(200==o.status){var r=JSON.parse(o.responseText),s=new a;s.provider=e.PROVIDER_ID,s.id=t.idToken,s.name=t.idTokenClaims.name,s.email=t.account.username,s.idToken=t.idToken,s.response=t,s.firstName=r.givenName,s.lastName=r.surname,n(s)}else i("Error retrieving user info: "+o.status)}catch(t){i(t)}},o.open("GET","https://graph.microsoft.com/v1.0/me"),o.setRequestHeader("Authorization","Bearer "+t.accessToken);try{o.send()}catch(t){i(t)}}))},e.prototype.getLoginStatus=function(){var t=this;return new Promise((function(n,i){var o=t._instance.getAllAccounts();if(o.length>0)try{t._instance.ssoSilent({scopes:t.initOptions.scopes,loginHint:o[0].username}).then((function(e){t.getSocialUser(e).then((function(t){return n(t)})).catch((function(t){return i(t)}))})).catch((function(t){return i(t)}))}catch(t){i(t)}else i("No user is currently logged in with "+e.PROVIDER_ID)}))},e.prototype.signIn=function(){var t=this;return new Promise((function(e,n){try{t._instance.loginPopup({scopes:t.initOptions.scopes}).then((function(i){t.getSocialUser(i).then((function(t){return e(t)})).catch((function(t){return n(t)}))})).catch((function(t){return n(t)}))}catch(t){n(t)}}))},e.prototype.signOut=function(t){var e=this;return new Promise((function(t,n){try{var i=e._instance.getAllAccounts();e._instance.logout({account:i[0],postLogoutRedirectUri:e.initOptions.redirect_uri}).then((function(){t()})).catch((function(t){n(t)}))}catch(t){n(t)}}))},e}(s);m.PROVIDER_ID="MICROSOFT",t.AmazonLoginProvider=d,t.BaseLoginProvider=s,t.DummyLoginProvider=p,t.FacebookLoginProvider=f,t.GoogleLoginProvider=c,t.MicrosoftLoginProvider=m,t.SocialAuthService=u,t.SocialLoginModule=l,t.SocialUser=a,t.VKLoginProvider=g,Object.defineProperty(t,"__esModule",{value:!0})}));
//# sourceMappingURL=angularx-social-login.umd.min.js.map