Last active
January 11, 2017 14:10
-
-
Save lricoy/efb099885566fa07624011a7e321e53b to your computer and use it in GitHub Desktop.
Simple Angular2/Ionic2 auth
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//TODO: Validar os operadores necessários para diminuir o tamanho | |
import 'rxjs/Rx'; | |
import {App, Platform} from 'ionic-angular'; | |
import {StatusBar} from 'ionic-native'; | |
import {LoginPage} from './pages/login/login'; | |
import {HttpClient} from "./common/providers/http"; | |
import {AuthService} from './services/auth/auth'; | |
import {JobService} from "./services/job/job"; | |
@App({ | |
template: ` | |
<ion-menu [content]="mainNavigation"> | |
<ion-content> | |
Menu | |
</ion-content> | |
</ion-menu> | |
<ion-nav [root]="rootPage" #mainNavigation></ion-nav>`, | |
config: { | |
mode: 'md', | |
tabbarPlacement: 'bottom' | |
}, // http://ionicframework.com/docs/v2/api/config/Config/ | |
providers: [HttpClient, AuthService, JobService] | |
}) | |
export class MyApp { | |
rootPage: any = LoginPage; | |
constructor(platform: Platform, private auth: AuthService) { | |
platform.ready().then(() => { | |
// Okay, so the platform is ready and our plugins are available. | |
// Here you can do any higher level native things you might need. | |
StatusBar.styleDefault(); | |
}); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Injectable} from 'angular2/core'; | |
import {HttpClient as Http} from '../../common/providers/http'; | |
import {SERVER_URI} from '../../config'; | |
import {Observable} from "rxjs/Observable"; | |
export interface IAuthToken { | |
token: string; | |
} | |
@Injectable() | |
export class AuthService implements IAuthToken{ | |
/** | |
* Internal prop to keep track of the token | |
*/ | |
public token:string; | |
/** | |
* The local storage proxy | |
* TODO: Import from lib instead of using the one from window | |
* @type {Storage} | |
* @private | |
*/ | |
private _localStorage = window.localStorage; | |
/** | |
* The local Auth URL. | |
* @type {string|string} | |
*/ | |
private authUrl = `${SERVER_URI}/auth/local`; | |
constructor (private _http: Http) { | |
} | |
/** | |
* Set local storage token value | |
* @param {string} token | |
*/ | |
private addToken(token) { | |
this.token = token; | |
this._localStorage.setItem('token', token); | |
this._http.setToken(token); | |
} | |
/** | |
* Get 'token' | |
* @returns {any} | |
*/ | |
private getToken() { | |
return this.token; | |
} | |
/** | |
* Get 'token' | |
* @returns {any} | |
*/ | |
private getTokenFromLocalStorage() { | |
return this._localStorage.getItem('token'); | |
} | |
/** | |
* Check for 'token' key | |
* @returns {boolean} | |
*/ | |
public isAutheticated() { | |
return this.getToken() !== null; | |
} | |
/** | |
* Authenticates a given user by email and password | |
* @param {string} email | |
* @param {string} password | |
* @returns {Subscriber} | |
*/ | |
public login(email: string, password: string) { | |
let reqBody = JSON.stringify({email, password}); | |
return Observable.create(observer => { | |
this._http.post(this.authUrl, reqBody) | |
.map(res => res.json()) | |
.subscribe( | |
res => { | |
this.addToken((<IAuthToken> (res.token))); | |
observer.next({ authenticated: true, token: this.token }); | |
observer.complete(); | |
}, | |
error => { | |
let errorBody = JSON.parse(error._body); | |
console.error('AuthService:login', errorBody); | |
observer.error(errorBody); | |
} | |
) | |
}); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Http, Headers} from 'angular2/http'; | |
import {Injectable} from 'angular2/core'; | |
import {contentHeaders} from './headers'; | |
@Injectable() | |
export class HttpClient { | |
headers:Headers; | |
token: string; | |
constructor(public _http: Http) { | |
this.headers = contentHeaders; | |
} | |
setToken(token){ | |
this.token = token; | |
this.headers.append('Authorization', `Bearer ${this.token}`); | |
} | |
get(url) { | |
return this._http.get(url, { | |
headers: this.headers | |
}); | |
} | |
post(url, data) { | |
return this._http.post(url, data, { | |
headers: this.headers | |
}); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Page, NavController, Form} from 'ionic-angular'; | |
import {FormBuilder, Validators} from 'angular2/common'; | |
import {AuthService} from "../../services/auth/auth"; | |
import {MainPage} from '../main/main'; | |
@Page({ | |
templateUrl: 'build/pages/login/login.html' | |
}) | |
export class LoginPage{ | |
submitted:boolean = false; | |
loginData:any = {}; | |
constructor (public auth:AuthService, public nav: NavController) { | |
} | |
onLogin(form: any) { | |
if (form.valid) { | |
this.auth.login(this.loginData.email, this.loginData.password).subscribe( | |
authenticated => { | |
console.log(authenticated); | |
this.nav.setRoot(MainPage); | |
}, | |
onError => { | |
} | |
); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment