Advertisement
Guest User

Untitled

a guest
Apr 29th, 2016
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.00 KB | None | 0 0
  1. import {Injectable, CORE_DIRECTIVES, Inject, NgZone, EventEmitter} from 'angular2/angular2';
  2. import {Http, Headers, Response} from 'angular2/http';
  3. import {User} from 'models/user';
  4.  
  5. @Injectable()
  6. export class AuthService {
  7. protected http: Http;
  8. public loged: boolean;
  9. public user: User;
  10. protected AuthHeader: Headers;
  11. protected grantBody: any;
  12. public CITIES: Array<any>;
  13. private jsonHeaders: Headers;
  14.  
  15. constructor( @Inject(Http) http: Http, private _zone: NgZone, @Inject('Config') private _config: any) {
  16. this.http = http;
  17. this.jsonHeaders = new Headers({ 'Content-Type': 'application/json' });
  18. this.grantBody = {
  19. 'client_id': 'cooknet',
  20. 'grant_type': 'password',
  21. 'client_secret': 'cook123net'
  22. };
  23. this.http.get(window.ApiUrl + "cities").map((res: any) => {
  24. return res.json();
  25. }).subscribe((res: any) => {
  26. this.CITIES = res;
  27. if(this._config.city) {
  28. this._config.city = this.CITIES.find((value: any, index: number, obj: any[]) => value.id === this._config.city.id);
  29. sessionStorage.setItem("city", JSON.stringify(this._config.city));
  30. }
  31. });
  32. this.loginFromStorage();
  33. }
  34.  
  35. /**
  36. * logout
  37. */
  38. public logOut() {
  39. sessionStorage.removeItem("token");
  40. this.loged = false;
  41. this.user = new User();
  42. }
  43.  
  44. /**
  45. * log in from session if user hasn't checked remember me...
  46. */
  47. private loginFromStorage(): void {
  48. if (sessionStorage.getItem("token")) {
  49.  
  50. let header = new Headers({
  51. "Authorization": "Bearer " + sessionStorage.getItem("token")
  52. });
  53.  
  54. this.http.get(window.ApiUrl + 'auth/profile', { headers: header }).subscribe((response: Response) => {
  55. if (response.status == 200) {
  56. this.user = response.json();
  57. this.AuthHeader = header;
  58. this.loged = true;
  59. } else {
  60. sessionStorage.removeItem("token");
  61. this.loged = false;
  62. this.user = new User();
  63. }
  64.  
  65. });
  66.  
  67. } else {
  68. this.loged = false;
  69. this.user = new User();
  70. }
  71. }
  72. /**
  73. * return auth headers
  74. */
  75. public getAuthHeaders(): any {
  76. if (!this.loged) return {};
  77. return this.AuthHeader;
  78. }
  79.  
  80. /**
  81. * send sms to user phone
  82. */
  83. protected sendSMS(phone) {
  84. let body = {
  85. phone: phone
  86. };
  87. let headers = new Headers({
  88. 'Content-Type': 'application/json'
  89. });
  90. if (this.AuthHeader) {
  91. console.log(this.AuthHeader.get("Authorization"));
  92. headers.set('Authorization', this.AuthHeader.get("Authorization"));
  93. }
  94. return this.http.post(window.ApiUrl + "auth/phone", JSON.stringify(body), {
  95. headers: headers
  96. }).map((res: Response) => {
  97. if (res.status != 200) {
  98. throw res.json();
  99. }
  100. });
  101. }
  102.  
  103. protected LoginWithKey(key) {
  104. let body: any = {};
  105. Object.assign(body, this.grantBody);
  106. body.key = key;
  107.  
  108. return this.http.post(window.ApiUrl + "auth/phone/login", JSON.stringify(body), { headers: this.jsonHeaders }).map((res: Response) => {
  109. if (res.status == 200) {
  110. let response: any = res.json();
  111. this.loged = true;
  112. this.user = response.user;
  113. this.AuthHeader = new Headers({
  114. "Authorization": "Bearer " + response.access_token
  115. });
  116. return this.user;
  117. }
  118. throw res.json();
  119. });
  120. }
  121.  
  122. /**
  123. * register a new user
  124. * @param {User} user user data
  125. * @description registers a new user and save its authentication data in storage.
  126. */
  127. public register(user: User): any {
  128. let body: any = {};
  129. Object.assign(user, this.grantBody);
  130. return this.http.post(window.ApiUrl + "auth/register", JSON.stringify(user), { headers: this.jsonHeaders }).map((res: Response) => {
  131. let response: any = res.json();
  132. if (response.errors) {
  133. throw response.errors;
  134. }
  135. this.user = response.user;
  136. this.loged = true;
  137. sessionStorage.setItem("token", response.access_token);
  138. this.AuthHeader = new Headers({ "Authorization": "Bearer " + response.access_token });
  139. });
  140. }
  141.  
  142. public logIn(phone: string, password: string, remember?: boolean): any {
  143. let body: any = {};
  144. Object.assign(body, this.grantBody);
  145. body.username = phone;
  146. body.password = password;
  147.  
  148. return this.http.post(window.ApiUrl + 'auth/login', JSON.stringify(body), { headers: this.jsonHeaders })
  149. .map((res: any): Object => {
  150. if (res.status == 200) {
  151. let response: any = res.json();
  152. this.user = response.user;
  153. this.AuthHeader = new Headers({
  154. "Authorization": "Bearer " + response.access_token
  155. });
  156. this.loged = true;
  157. sessionStorage.setItem("token", response.access_token);
  158. return this.user;
  159. }
  160. throw { status: 401 };
  161. });
  162. }
  163.  
  164. /**
  165. * login using facebook
  166. */
  167. public facebookLogin() {
  168.  
  169. let emitter: any = new EventEmitter().toRx();
  170.  
  171. let body: any = {};
  172. Object.assign(body, this.grantBody);
  173.  
  174. this._zone.runOutsideAngular(() => {
  175.  
  176. let __this = this;
  177.  
  178. FB.login(function(response) {
  179.  
  180. if (response.status == "connected") {
  181.  
  182. let facebook_token: any = response.authResponse.accessToken;
  183. body.facebook_token = facebook_token;
  184.  
  185. return __this.http.post(window.ApiUrl + "auth/facebook", JSON.stringify(body), { headers: __this.jsonHeaders })
  186. .map((response: Response) => {
  187.  
  188. if (response.status == 200 || response.status == 201) {
  189. let responseBody: any = response.json();
  190. __this.AuthHeader = new Headers({
  191. "Authorization": "Bearer " + responseBody.access_token
  192. });
  193. sessionStorage.setItem("token", responseBody.access_token);
  194. __this.loged = true;
  195. __this.user = responseBody.user;§
  196. __this._zone.run(() => {
  197. emitter.next({});
  198. });
  199. }
  200.  
  201. }).subscribe(() => { });
  202. }
  203. }, { scope: 'public_profile,email' });
  204. });
  205. return emitter;
  206. }
  207.  
  208. public verifyPhone(key: string) {
  209. return this.http.post(window.ApiUrl + "auth/verify", JSON.stringify({ key: key }), {
  210. headers: this.jsonHeaders
  211. }).map((response: Response) => {
  212.  
  213. if (response.status == 200) {
  214. this.user = response.json();
  215. return response.json();
  216. }
  217.  
  218. throw ["كود خاطئ , أعد المحاولة"];
  219.  
  220. });
  221. }
  222.  
  223. public toggleKeyModal() {
  224. let modal = $("#key-tab").addClass("active").parents(".modal");
  225. modal.find("[role=presentation].active").removeClass("active");
  226. modal.find("[role=tabpanel].active").removeClass("active");
  227. modal.find("#key-tab").parent().addClass("active");
  228. modal.modal("show");
  229. $("#key-tab").addClass("active");
  230. }
  231. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement