Guest User

Untitled

a guest
Jul 26th, 2018
361
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.51 KB | None | 0 0
  1. /**
  2. * @module Services
  3. */
  4. // import { Facebook, FacebookLoginResponse } from '@ionic-native/facebook';
  5. // import { TwitterConnect } from '@ionic-native/twitter-connect';
  6.  
  7. import firebase from 'firebase/app';
  8. import 'firebase/auth';
  9.  
  10. export class AuthService {
  11. public service: firebase.auth.Auth;
  12. public session: any;
  13.  
  14. constructor(
  15. // private facebook: Facebook,
  16. // private twitter: TwitterConnect
  17. config?: any
  18. ) {
  19. // this.user = afAuth.authState;
  20. let firstRun = false;
  21. if (firebase.apps.length === 0) {
  22. firebase.initializeApp(config);
  23. firstRun = true;
  24. }
  25. this.service = firebase.auth();
  26.  
  27. if (firstRun) {
  28. this.service.getRedirectResult().then(data => {
  29. if (data && data.user) {
  30. this.emitLoggedInEvent(data);
  31. }
  32. });
  33. }
  34. }
  35.  
  36. async onEmailLink() {
  37. if (firebase.auth().isSignInWithEmailLink(window.location.href)) {
  38. let email = window.localStorage.getItem('emailForSignIn');
  39. if (!email) {
  40. email = window.prompt('Please provide your email for confirmation');
  41. }
  42.  
  43. const authUser = await firebase
  44. .auth()
  45. .signInWithEmailLink(email, window.location.href);
  46. window.localStorage.removeItem('emailForSignIn');
  47.  
  48. this.emitLoggedInEvent(authUser);
  49.  
  50. return authUser;
  51. }
  52. }
  53.  
  54. async createCaptcha(buttonId: string) {
  55. (<any>window).RecaptchaVerifier = new firebase.auth.RecaptchaVerifier(
  56. buttonId,
  57. {
  58. size: 'invisible',
  59. callback: function() {
  60. return true;
  61. }
  62. }
  63. );
  64. }
  65.  
  66. withPhoneNumber(phoneNumber: string, capId: any) {
  67. phoneNumber = '+' + phoneNumber;
  68. window.localStorage.setItem('phoneForSignIn', phoneNumber);
  69.  
  70. return this.service.signInWithPhoneNumber(phoneNumber, capId);
  71. }
  72.  
  73. withEmailLink(email: string, actionCodeSettings: any) {
  74. window.localStorage.setItem('emailForSignIn', email);
  75.  
  76. return this.service.sendSignInLinkToEmail(email, actionCodeSettings);
  77. }
  78.  
  79. anonymously() {
  80. return this.service.signInAnonymously();
  81. }
  82.  
  83. onAuthChanged(callback) {
  84. this.service.onAuthStateChanged(session => {
  85. if (
  86. !session ||
  87. (!session.emailVerified &&
  88. session.providerData &&
  89. session.providerData[0].providerId === 'password')
  90. ) {
  91. return false;
  92. }
  93.  
  94. if (session) {
  95. localStorage.setItem('tmg:session', JSON.stringify(session));
  96. }
  97. if (callback && typeof callback === 'function') {
  98. callback(session);
  99. }
  100. });
  101. }
  102.  
  103. getFromStorage() {
  104. return localStorage.getItem('referaflood:session')
  105. ? JSON.parse(localStorage.getItem('referaflood:session'))
  106. : null;
  107. }
  108.  
  109. isLoggedIn() {
  110. return this.service.currentUser
  111. ? this.service.currentUser
  112. : this.getFromStorage();
  113. }
  114.  
  115. emitLoggedInEvent(data) {
  116. document.body.dispatchEvent(
  117. new CustomEvent('authLoggedIn', { detail: { data } })
  118. );
  119. }
  120.  
  121. emitLoggedOutEvent() {
  122. document.body.dispatchEvent(
  123. new CustomEvent('authLoggedOut', { detail: {} })
  124. );
  125. }
  126.  
  127. createUser(email: string, password: string) {
  128. return new Promise((resolve, reject) => {
  129. try {
  130. this.service
  131. .createUserWithEmailAndPassword(email, password)
  132. .then(data => {
  133. resolve(data);
  134. })
  135. .catch(error => {
  136. reject(error);
  137. });
  138. } catch (e) {
  139. reject(e);
  140. }
  141. });
  142. }
  143.  
  144. sendEmailVerification(options?) {
  145. return this.service.currentUser.sendEmailVerification(
  146. options ? options : null
  147. );
  148. }
  149.  
  150. sendPasswordReset(emailAddress: string, options?) {
  151. return this.service.sendPasswordResetEmail(
  152. emailAddress,
  153. options ? options : null
  154. );
  155. }
  156.  
  157. withEmail(email: string, password: string) {
  158. return new Promise((resolve, reject) => {
  159. try {
  160. this.service
  161. .signInWithEmailAndPassword(email, password)
  162. .then(user => {
  163. this.emitLoggedInEvent({ user });
  164. resolve({ data: { user } });
  165. })
  166. .catch(error => {
  167. reject(error);
  168. });
  169. } catch (e) {
  170. reject(e);
  171. }
  172. });
  173. }
  174.  
  175. // facebookNative(): Promise<any> {
  176. // return new Promise((resolve, reject) => {
  177. // if (this.platform.is('cordova')) {
  178. // this.facebook.login(['email', 'public_profile', 'user_friends'])
  179. // .then((facebookData: FacebookLoginResponse) => {
  180. // const credential = firebase.auth.FacebookAuthProvider.credential(facebookData.authResponse.accessToken);
  181. // firebase.auth().signInWithCredential(credential).then((firebaseData) => {
  182. // resolve(firebaseData);
  183. // });
  184. // }, (error) => {
  185. // reject(error);
  186. // });
  187. // } else {
  188. // reject({ message: 'This platform does not support native login.' });
  189. // }
  190. // });
  191. // }
  192.  
  193. googleNative(): Promise<any> {
  194. return new Promise((resolve, reject) => {
  195. (<any>window).plugins.googleplus.login(
  196. {
  197. webClientId:
  198. 'YOUR_WEB_CLIENT_ID_HERE',
  199. offline: true
  200. },
  201. googleData => {
  202. const credential = firebase.auth.GoogleAuthProvider.credential(
  203. googleData.idToken
  204. );
  205. firebase
  206. .auth()
  207. .signInWithCredential(credential)
  208. .then(firebaseData => {
  209. resolve(firebaseData);
  210. });
  211. },
  212. error => {
  213. reject(error);
  214. }
  215. );
  216. });
  217. }
  218.  
  219. // twitterNative(): Promise<any> {
  220. // return new Promise((resolve, reject) => {
  221. // this.twitter.login().then((twitterData) => {
  222. // const credential = firebase.auth.TwitterAuthProvider.credential(twitterData.token, twitterData.secret);
  223. // firebase.auth().signInWithCredential(credential).then((firebaseData) => {
  224. // resolve(firebaseData);
  225. // });
  226. // }, (error) => {
  227. // reject(error);
  228. // });
  229. // });
  230. // }
  231.  
  232. withSocial(network: string, redirect = false): Promise<any> {
  233. // let provider;
  234. // return new Promise((resolve, reject) => {
  235. // if (this.platform.is('cordova')) {
  236. // if (network === 'facebook') {
  237. // this.facebookNative().then((result) => {
  238. // resolve(result);
  239. // });
  240. // } else if (network === 'google') {
  241. // this.googleNative().then((result) => {
  242. // resolve(result);
  243. // });
  244. // } else if (network === 'twitter') {
  245. // this.twitterNative().then((result) => {
  246. // resolve(result);
  247. // });
  248. // } else {
  249. // reject({ message: 'A social network is required or the one provided is not yet supported.' });
  250. // }
  251. // } else {
  252.  
  253. // }
  254. // });
  255. let provider;
  256. let shouldRedirect = redirect;
  257. if (window.matchMedia('(display-mode: standalone)').matches) {
  258. console.log('Running in PWA mode...');
  259. shouldRedirect = shouldRedirect ? shouldRedirect : true;
  260. }
  261.  
  262. return new Promise((resolve, reject) => {
  263. // console.log('here or not?');
  264.  
  265. // if ((<any>window).Capacitor.isNative) {
  266. // console.log('what')
  267. // if (network === 'google') {
  268. // this.googleNative().then((result) => {
  269. // resolve(result);
  270. // });
  271. // }
  272. // }
  273. if (network === 'facebook') {
  274. provider = new firebase.auth.FacebookAuthProvider();
  275. } else if (network === 'google') {
  276. provider = new firebase.auth.GoogleAuthProvider();
  277. } else if (network === 'twitter') {
  278. provider = new firebase.auth.TwitterAuthProvider();
  279. } else {
  280. reject({
  281. message:
  282. 'A social network is required or the one provided is not yet supported.'
  283. });
  284. }
  285. const authService: any = this.service;
  286. authService[shouldRedirect ? 'signInWithRedirect' : 'signInWithPopup'](
  287. provider
  288. )
  289. .then(data => {
  290. this.emitLoggedInEvent(data);
  291. resolve(data);
  292. })
  293. .catch(error => {
  294. reject(error);
  295. });
  296. });
  297. }
  298.  
  299. logout() {
  300. this.emitLoggedOutEvent();
  301.  
  302. return this.service.signOut();
  303. }
  304.  
  305. async updatePassword(newPassword: string) {
  306. // await user.reauthenticateWithCredential(credential);
  307.  
  308. return firebase.auth().currentUser.updatePassword(newPassword);
  309. }
  310. }
Add Comment
Please, Sign In to add comment