Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import {Injectable, CORE_DIRECTIVES, Inject, NgZone, EventEmitter} from 'angular2/angular2';
- import {Http, Headers, Response} from 'angular2/http';
- import {User} from 'models/user';
- @Injectable()
- export class AuthService {
- protected http: Http;
- public loged: boolean;
- public user: User;
- protected AuthHeader: Headers;
- protected grantBody: any;
- public CITIES: Array<any>;
- private jsonHeaders: Headers;
- constructor( @Inject(Http) http: Http, private _zone: NgZone, @Inject('Config') private _config: any) {
- this.http = http;
- this.jsonHeaders = new Headers({ 'Content-Type': 'application/json' });
- this.grantBody = {
- 'client_id': 'cooknet',
- 'grant_type': 'password',
- 'client_secret': 'cook123net'
- };
- this.http.get(window.ApiUrl + "cities").map((res: any) => {
- return res.json();
- }).subscribe((res: any) => {
- this.CITIES = res;
- if(this._config.city) {
- this._config.city = this.CITIES.find((value: any, index: number, obj: any[]) => value.id === this._config.city.id);
- sessionStorage.setItem("city", JSON.stringify(this._config.city));
- }
- });
- this.loginFromStorage();
- }
- /**
- * logout
- */
- public logOut() {
- sessionStorage.removeItem("token");
- this.loged = false;
- this.user = new User();
- }
- /**
- * log in from session if user hasn't checked remember me...
- */
- private loginFromStorage(): void {
- if (sessionStorage.getItem("token")) {
- let header = new Headers({
- "Authorization": "Bearer " + sessionStorage.getItem("token")
- });
- this.http.get(window.ApiUrl + 'auth/profile', { headers: header }).subscribe((response: Response) => {
- if (response.status == 200) {
- this.user = response.json();
- this.AuthHeader = header;
- this.loged = true;
- } else {
- sessionStorage.removeItem("token");
- this.loged = false;
- this.user = new User();
- }
- });
- } else {
- this.loged = false;
- this.user = new User();
- }
- }
- /**
- * return auth headers
- */
- public getAuthHeaders(): any {
- if (!this.loged) return {};
- return this.AuthHeader;
- }
- /**
- * send sms to user phone
- */
- protected sendSMS(phone) {
- let body = {
- phone: phone
- };
- let headers = new Headers({
- 'Content-Type': 'application/json'
- });
- if (this.AuthHeader) {
- console.log(this.AuthHeader.get("Authorization"));
- headers.set('Authorization', this.AuthHeader.get("Authorization"));
- }
- return this.http.post(window.ApiUrl + "auth/phone", JSON.stringify(body), {
- headers: headers
- }).map((res: Response) => {
- if (res.status != 200) {
- throw res.json();
- }
- });
- }
- protected LoginWithKey(key) {
- let body: any = {};
- Object.assign(body, this.grantBody);
- body.key = key;
- return this.http.post(window.ApiUrl + "auth/phone/login", JSON.stringify(body), { headers: this.jsonHeaders }).map((res: Response) => {
- if (res.status == 200) {
- let response: any = res.json();
- this.loged = true;
- this.user = response.user;
- this.AuthHeader = new Headers({
- "Authorization": "Bearer " + response.access_token
- });
- return this.user;
- }
- throw res.json();
- });
- }
- /**
- * register a new user
- * @param {User} user user data
- * @description registers a new user and save its authentication data in storage.
- */
- public register(user: User): any {
- let body: any = {};
- Object.assign(user, this.grantBody);
- return this.http.post(window.ApiUrl + "auth/register", JSON.stringify(user), { headers: this.jsonHeaders }).map((res: Response) => {
- let response: any = res.json();
- if (response.errors) {
- throw response.errors;
- }
- this.user = response.user;
- this.loged = true;
- sessionStorage.setItem("token", response.access_token);
- this.AuthHeader = new Headers({ "Authorization": "Bearer " + response.access_token });
- });
- }
- public logIn(phone: string, password: string, remember?: boolean): any {
- let body: any = {};
- Object.assign(body, this.grantBody);
- body.username = phone;
- body.password = password;
- return this.http.post(window.ApiUrl + 'auth/login', JSON.stringify(body), { headers: this.jsonHeaders })
- .map((res: any): Object => {
- if (res.status == 200) {
- let response: any = res.json();
- this.user = response.user;
- this.AuthHeader = new Headers({
- "Authorization": "Bearer " + response.access_token
- });
- this.loged = true;
- sessionStorage.setItem("token", response.access_token);
- return this.user;
- }
- throw { status: 401 };
- });
- }
- /**
- * login using facebook
- */
- public facebookLogin() {
- let emitter: any = new EventEmitter().toRx();
- let body: any = {};
- Object.assign(body, this.grantBody);
- this._zone.runOutsideAngular(() => {
- let __this = this;
- FB.login(function(response) {
- if (response.status == "connected") {
- let facebook_token: any = response.authResponse.accessToken;
- body.facebook_token = facebook_token;
- return __this.http.post(window.ApiUrl + "auth/facebook", JSON.stringify(body), { headers: __this.jsonHeaders })
- .map((response: Response) => {
- if (response.status == 200 || response.status == 201) {
- let responseBody: any = response.json();
- __this.AuthHeader = new Headers({
- "Authorization": "Bearer " + responseBody.access_token
- });
- sessionStorage.setItem("token", responseBody.access_token);
- __this.loged = true;
- __this.user = responseBody.user;§
- __this._zone.run(() => {
- emitter.next({});
- });
- }
- }).subscribe(() => { });
- }
- }, { scope: 'public_profile,email' });
- });
- return emitter;
- }
- public verifyPhone(key: string) {
- return this.http.post(window.ApiUrl + "auth/verify", JSON.stringify({ key: key }), {
- headers: this.jsonHeaders
- }).map((response: Response) => {
- if (response.status == 200) {
- this.user = response.json();
- return response.json();
- }
- throw ["كود خاطئ , أعد المحاولة"];
- });
- }
- public toggleKeyModal() {
- let modal = $("#key-tab").addClass("active").parents(".modal");
- modal.find("[role=presentation].active").removeClass("active");
- modal.find("[role=tabpanel].active").removeClass("active");
- modal.find("#key-tab").parent().addClass("active");
- modal.modal("show");
- $("#key-tab").addClass("active");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement