Advertisement
Guest User

Untitled

a guest
Aug 31st, 2018
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.58 KB | None | 0 0
  1. mport { Injectable } from '@angular/core';
  2. import { Config as AppConfig } from 'ionic-angular';
  3. import { CognitoUser, CognitoUserPool, CognitoUserAttribute, AuthenticationDetails , ICognitoUserPoolData , CognitoUserSession } from 'amazon-cognito-identity-js'
  4. import { Subject } from 'rxjs/Subject';
  5. import { Observable } from 'rxjs/Observable';
  6. import 'rxjs/add/observable/from';
  7.  
  8. import { UserRole } from './user/user';
  9.  
  10. declare var AWS: any;
  11.  
  12. @Injectable()
  13. export class AuthService {
  14. private unauthCreds: any;
  15. private poolData: ICognitoUserPoolData;
  16. private userPool: CognitoUserPool;
  17. private _cognitoUser: CognitoUser;
  18. private session: CognitoUserSession;
  19. private _signoutSubject: Subject<string> = new Subject<string>();
  20. private _signinSubject: Subject<string> = new Subject<string>();
  21.  
  22. constructor(
  23. private config: AppConfig
  24. ) {
  25. AWS.config.region = this.config.get( 'region' );
  26.  
  27. this.poolData = {
  28. UserPoolId : this.config.get( 'userPoolId' ),
  29. ClientId : this.config.get( 'appId' )
  30. };
  31.  
  32. this.userPool = new CognitoUserPool( this.poolData );
  33. this.refreshOrResetCreds();
  34. }
  35.  
  36. get signoutNotification() { return Observable.create( fn => this._signoutSubject.subscribe(fn) ) }
  37. get signinNotification() { return Observable.create( fn => this._signinSubject.subscribe(fn) ) }
  38. get cognitoUser(): CognitoUser { return this._cognitoUser }
  39. get currentIdentit(): string { return AWS.config.credentials.identityId }
  40. isUserSignedIn(): boolean { return this._cognitoUser !== null }
  41.  
  42. private refreshOrResetCreds() {
  43. this._cognitoUser = this.userPool.getCurrentUser();
  44.  
  45. if( this._cognitoUser !== null )
  46. this.refreshSession();
  47. else
  48. this.resetCreds();
  49. }
  50.  
  51. private setCredentials( newCreds ) {
  52. AWS.config.credentials = newCreds;
  53. }
  54.  
  55. private buildLogins( token ) {
  56. let key = this.config.get( 'idpURL' ) + '/' + this.config.get( 'userPoolId' );
  57. let json = {
  58. IdentityPoolId : this.config.get( 'identityPool' ),
  59. Logins : {}
  60. };
  61.  
  62. json.Logins[ key ] = token;
  63.  
  64. return json;
  65. }
  66.  
  67. private buildCreds() {
  68. let json = this.buildLogins( this.session.getIdToken().getJwtToken() );
  69. return new AWS.CognitoIdentityCredentials( json );
  70. }
  71.  
  72. private saveCreds( session, cognitoUser? ): void {
  73. this.session = session;
  74.  
  75. if( cognitoUser )
  76. this._cognitoUser = cognitoUser;
  77.  
  78. this.setCredentials( this.buildCreds() );
  79. }
  80.  
  81. private getNewCognitoUser( creds ): CognitoUser {
  82. return new CognitoUser({ Username: creds.username, Pool: this.userPool });
  83. }
  84.  
  85. private authDetails( creds ): AuthenticationDetails {
  86. return new AuthenticationDetails({ Username: creds.username, Password: creds.password });
  87. }
  88.  
  89. private refreshSession(): Promise<CognitoUserSession> {
  90. let self = this;
  91.  
  92. return new Promise( (resolve, reject) => {
  93. self._cognitoUser.getSession((err, session) => {
  94. if( err ) {
  95. console.log( 'Error refreshing user session', err );
  96. return reject( err );
  97. }
  98.  
  99. console.log( `${new Date()} - Refreshed session for ${self._cognitoUser.getUsername()}. Valid?: `, session.isValid() );
  100. self.saveCreds( session );
  101. resolve( session );
  102. })
  103. });
  104. }
  105.  
  106. private resetCreds( clearCache:boolean = false ) {
  107. console.log('Resetting credentials for unauth access');
  108.  
  109. AWS.config.region = this.config.get('region');
  110. this._cognitoUser = null;
  111. this.unauthCreds = this.unauthCreds || new AWS.CognitoIdentityCredentials({ IdentityPoolId: this.config.get('identityPool') });
  112.  
  113. if( clearCache )
  114. this.unauthCreds.clearCachedId();
  115.  
  116. this.setCredentials( this.unauthCreds );
  117. }
  118.  
  119. private buildAttributes (creds): Array<CognitoUserAttribute> {
  120. let attributeList = [],
  121. attributeEmail = new CognitoUserAttribute({ Name: 'email', Value: creds.email }),
  122. attributeName = new CognitoUserAttribute({ Name: 'preferred_username', Value: creds.username });
  123.  
  124. attributeList.push( attributeEmail );
  125. attributeList.push( attributeName );
  126.  
  127. return attributeList;
  128. }
  129.  
  130. private _getCreds (): Promise<any> {
  131. return new Promise( (resolve, reject) => {
  132. try {
  133. AWS.config.credentials.get( (err) => {
  134. if( err )
  135. return reject( err );
  136.  
  137. resolve( AWS.config.credentials );
  138. })
  139. } catch (e) { reject(e) }
  140. } );
  141. }
  142.  
  143. getCredentials (): Observable<any> {
  144. let result = null
  145.  
  146. if( this._cognitoUser === null )
  147. result = this._getCreds();
  148. else if( this.session && this.session.isValid() )
  149. result = this._getCreds();
  150. else
  151. result = this.refreshSession().then( this._getCreds );
  152.  
  153. return Observable.from( result );
  154. }
  155.  
  156. getUserRole(): UserRole {
  157. const idTokenPayload = this._cognitoUser.getSignInUserSession().getIdToken().decodePayload();
  158. const cognitoGroups: String[] = idTokenPayload["cognito:groups"];
  159.  
  160. if( cognitoGroups.indexOf( UserRole.admin ) !== -1 )
  161. return UserRole.admin;
  162.  
  163. let rolesFound = cognitoGroups.filter( (role) => <string>role in UserRole );
  164.  
  165. if( rolesFound.length === 1 ) {
  166. const role = <UserRole>rolesFound.shift();
  167. console.log( 'User role determined: ', role );
  168. return role;
  169. } else if( rolesFound.length > 1 ) {
  170. throw new Error( 'Multiple roles specified.' );
  171. }
  172.  
  173. throw new Error( 'Unspecified role.' );
  174. }
  175.  
  176. signout() {
  177. if( this._cognitoUser ) {
  178. let name = this._cognitoUser.getUsername();
  179.  
  180. this._cognitoUser['signOut']();
  181. this.resetCreds( true );
  182. this._signoutSubject.next( name );
  183. }
  184. }
  185.  
  186. register( creds ): Promise<CognitoUser> {
  187. let self = this;
  188. return new Promise((resolve, reject) => {
  189. try {
  190. self.userPool.signUp( creds.username, creds.password, self.buildAttributes( creds ), null, (err, result) => {
  191. if( err )
  192. return reject( err );
  193.  
  194. console.log( 'Register', result );
  195. resolve( result.user );
  196. })
  197. } catch (e) { reject(e) }
  198. })
  199. }
  200.  
  201. confirm( creds ): Promise<CognitoUser> {
  202. let cognitoUser = this.getNewCognitoUser( creds );
  203.  
  204. return new Promise( (resolve, reject) => {
  205. try {
  206. console.log( 'Confirming...', CognitoUser );
  207. cognitoUser.confirmRegistration( creds.confcode, true, (err, result) => {
  208. if( err ) return reject( err );
  209.  
  210. resolve( result.CognitoUser );
  211. })
  212. } catch( e ) { reject( e ) }
  213. });
  214. }
  215.  
  216. signin( creds ): Promise<CognitoUser> {
  217. let cognitoUser = this.getNewCognitoUser(creds)
  218. let self = this
  219.  
  220. return new Promise((resolve, reject) => {
  221. try {
  222. cognitoUser.authenticateUser( self.authDetails(creds), {
  223. onSuccess: (session) => {
  224. console.log( `Signed in user ${cognitoUser.getUsername()}. Sessiong valid?: `, session.isValid() );
  225.  
  226. self.saveCreds( session, cognitoUser );
  227. self._signinSubject.next( cognitoUser.getUsername() );
  228.  
  229. resolve( cognitoUser );
  230. },
  231. newPasswordRequired: (userAttributes, requiredAttributes) => {},
  232. mfaRequired: (challengeName, challengeParameters) => {},
  233. customChallenge: (challengeParameters) => {},
  234. onFailure: reject
  235. })
  236. } catch( e ) { reject( e ) }
  237. })
  238. }
  239. }
  240.  
  241. export let AuthServiceProvider = {
  242. provide : AuthService,
  243. useFactory : (config: AppConfig) => { return new AuthService( config ); },
  244. deps : [ AppConfig ],
  245. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement