-
-
Save anonymous/9247a87dad642be2614ce9c593c0be9d to your computer and use it in GitHub Desktop.
This file contains 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 { SignInPage } from '../pages/signin/signin'; | |
import { Component } from '@angular/core'; | |
import { Platform } from 'ionic-angular'; | |
import { StatusBar } from '@ionic-native/status-bar'; | |
import { SplashScreen } from '@ionic-native/splash-screen'; | |
import { HomePage } from '../pages/home/home'; | |
import { AuthService } from '../providers/auth-service'; | |
@Component({ | |
templateUrl: 'app.html' | |
}) | |
export class MyApp { | |
rootPage:any = SignInPage; | |
constructor(platform: Platform, statusBar: StatusBar | |
, splashScreen: SplashScreen, | |
authService :AuthService) { | |
//Entrar directamente si el usuario ya está autenticado | |
//si su valor es true entonces el usuario ya está autenticado por lo que establecemos a HomePage | |
if(authService.authenticated) { | |
this.rootPage=SignInPage; | |
} else { | |
this.rootPage = HomePage; | |
} | |
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(); | |
splashScreen.hide(); | |
}); | |
} | |
} | |
This file contains 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 '@angular/core'; | |
//importamos la clase de AngularFire que nos permite acceder al API de autenticación. | |
import { AngularFireAuth } from 'angularfire2/auth'; | |
//importamos las clases User y Promise de FireBase | |
import {User , Promise} from 'firebase/app'; | |
import { UserModel } from '../models/user-model'; | |
import firebase from 'firebase'; | |
@Injectable() | |
export class AuthService { | |
user : User ; | |
//inyectamos una instancia de AngularFireAuth y nos suscribimos | |
// al cambio de estado de la autenticación , asi podemos saber cuando un usuario inicia o cierra sesión | |
//asi como obtener datos basicos asi como guardar la propiedad user | |
constructor (public angularFireAuth: AngularFireAuth){ | |
angularFireAuth.authState.subscribe((user:User) =>{ | |
this.user = user; | |
}); | |
} | |
//autenticated compara la propiedad user con null, | |
//de este modo sabemos si el usuario está o no autenticado. | |
get authenticated(): boolean{ | |
return this.user !=null; | |
} | |
//recibe una instancia del modelo UserModel del cual utiliza | |
// el correo y la contraseña para autenticar al usuario llamando al método de igual | |
//nombre de la propiedad auth (instancia de la clase Auth de Firebase)perteneciente a angularFireAut | |
signInWithEmailAndPassword(userModel:UserModel): Promise <any> { | |
return this.angularFireAuth.auth.signInWithEmailAndPassword(userModel.email, userModel.password); | |
} | |
// similar al anterior sólo que este es para crear un usuario, utilizando el método | |
//de igual nombre de la propiedad auth en angularFireAuth. | |
createUserWithEmailAndPassword(userModel:UserModel):Promise <any> { | |
return this.angularFireAuth.auth.createUserWithEmailAndPassword(userModel.email,userModel.password); | |
} | |
//utiliza el método de igual nombre de la propiedad auth en angularFireAuth para cerrar la sesión. | |
signOut() :Promise <any> { | |
return this.angularFireAuth.auth.signOut(); | |
} | |
/*/ | |
register(email : string,password:string, firstName :string ,apellido :string,age :number){ | |
return firebase.database().ref('reg') | |
.push({email,password,firstName,apellido,age}); | |
}/*/ | |
} |
This file contains 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 { BrowserModule } from '@angular/platform-browser'; | |
import { ErrorHandler, NgModule } from '@angular/core'; | |
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular'; | |
import { SplashScreen } from '@ionic-native/splash-screen'; | |
import { StatusBar } from '@ionic-native/status-bar'; | |
import {AngularFireModule} from 'angularfire2'; | |
import {AngularFireAuthModule} from 'angularfire2/auth'; | |
import {AngularFireDatabaseModule} from 'angularfire2/database'; | |
import { AuthService } from '../providers/auth-service'; | |
import { MyApp } from './app.component'; | |
import { HomePage } from '../pages/home/home'; | |
import { SignInPage } from '../pages/signin/signin'; | |
import { SignupPage } from '../pages/signup/signup'; | |
import {HttpModule} from '@angular/http'; | |
export const firebaseConfig ={//definimos la constante firebaseConfig con las | |
//configuraciones de nuestro proyecto de Firebase | |
//configuraciones que necesitamos para inicializar AngularFire(encontradas en la pagina de nuestro proyecto firebase) | |
apiKey: "AIzaSyCZNakBMoRFYEc0Ce6QAcjKMzA27xoWuqE", | |
authDomain: "ionfire-571ad.firebaseapp.com", | |
databaseURL: "https://ionfire-571ad.firebaseio.com", | |
projectId: "ionfire-571ad", | |
storageBucket: "ionfire-571ad.appspot.com", | |
messagingSenderId: "663242344540" | |
} | |
@NgModule({ | |
declarations: [ | |
MyApp, | |
HomePage, | |
SignInPage, | |
SignupPage | |
], | |
imports: [ | |
BrowserModule, | |
IonicModule.forRoot(MyApp), | |
// inicializamos el módulo AngularFireModule utilizando | |
// las configuraciones establecidas en la constante firebaseConfig | |
AngularFireModule.initializeApp(firebaseConfig), | |
AngularFireAuthModule | |
], | |
bootstrap: [IonicApp], | |
entryComponents: [ | |
MyApp, | |
HomePage, | |
SignInPage, | |
SignupPage | |
], | |
providers: [ | |
StatusBar, | |
SplashScreen, | |
{provide: ErrorHandler, useClass: IonicErrorHandler}, | |
AuthService | |
] | |
}) | |
export class AppModule {} |
This file contains 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
<ion-header> | |
<ion-navbar> | |
<ion-title>Signup</ion-title> | |
</ion-navbar> | |
</ion-header> | |
<ion-content padding> | |
<!--<form #signUpForm="ngForm" (submit)="signUp()" novalidate>--> | |
<form [FormGroup]="myForm" novalidate> | |
<ion-list> | |
<ion-item> | |
<ion-icon name="person" item-left></ion-icon> | |
<ion-label stacked>User</ion-label> | |
<ion-input formNameControl="firstName" type="text" placeholder="example:edward" required minlength="4" | |
[class.invalid]="!myForm.controls.firstName.valid && myForm.controls.firstName.dirty" ></ion-input> | |
</ion-item> | |
<ion-item class="error-message" | |
*ngIf="!myForm.controls.user.valid && myForm.controls.user.dirty"> | |
<p> | |
Campo vacio o mal escrito | |
</p> | |
</ion-item> | |
<ion-item> | |
<ion-icon name="person" item-left></ion-icon> | |
<ion-label stacked>Apellido</ion-label> | |
<ion-input formNameControl="apellido" type="text" placeholder =" example:Wilson" required | |
[class.invalid]="!myForm.controls.apellido.valid && myForm.controls.apellido.dirty"></ion-input> | |
</ion-item> | |
<ion-item class="error-message" | |
*ngIf="!myForm.controls.apellido.valid && myForm.controls.apellido.dirty"> | |
<p> | |
Campo vacio o mal escrito | |
</p> | |
</ion-item> | |
<ion-item> | |
<ion-icon name="person" item-left></ion-icon> | |
<ion-label stacked>Age person</ion-label> | |
<ion-input formNameControl="age" type="number" placeholder="your age" required | |
[class.invalid]="!myForm.controls.age.valid && myForm.controls.age.dirty" | |
></ion-input> | |
</ion-item> | |
<ion-item class="error-message" | |
*ngIf="!myForm.controls.age.valid && myForm.controls.age.dirty"> | |
<p> | |
You must be 18 or older to use this app. | |
</p> | |
</ion-item> | |
<ion-item> | |
<ion-icon name="mail" item-left></ion-icon> | |
<ion-label stacked>email</ion-label> | |
<ion-input formControlName="email" type="email" autocorrect="off" autocapitalize="none" | |
[class.invalid]="!myForm.controls.email.valid && myForm.controls.email.dirty" | |
required></ion-input> | |
</ion-item> | |
<ion-item class="error-message" | |
*ngIf="!myForm.controls.email.valid && myForm.controls.email.dirty"> | |
<p> | |
Correo No valido | |
</p> | |
</ion-item> | |
<ion-item> | |
<ion-icon name="key" item-left></ion-icon> | |
<ion-label stacked>Password</ion-label> | |
<ion-input formControlName="password" type="password" required minlength="6" | |
[class.invalid]="!myForm.controls.password.valid && myForm.controls.password.dirty"></ion-input> | |
<!--[(ngModel)]="userModel.password" --> | |
</ion-item> | |
<ion-item class="error-message" | |
*ngIf="!myForm.controls.password.valid && myForm.controls.password.dirty"> | |
<p> | |
Contraseña No valida | |
</p> | |
</ion-item> | |
<div padding-left padding-right padding-top> | |
<button ion-button block primary [disabled]="!myForm.valid" type="submit" >Registrate</button> | |
<!-- <button ion-button block primary [disabled]="!signUpForm.form.valid">Registrate</button>--> | |
</div> | |
</ion-list> | |
</form> | |
</ion-content> |
This file contains 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 { Component } from '@angular/core'; | |
import { NavController, NavParams , LoadingController, AlertController} from 'ionic-angular'; | |
/** | |
* Generated class for the SignupPage page. | |
* | |
* See http://ionicframework.com/docs/components/#navigation for more info | |
* on Ionic pages and navigation. | |
*/ | |
import { AuthService } from '../../providers/auth-service'; | |
import { UserModel } from '../../models/user-model'; | |
import { SignInPage } from '../signin/signin'; | |
import { FormBuilder, FormGroup, Validators } from '@angular/forms'; | |
import { ageValidator } from '../../Validators/age'; | |
@Component({ | |
selector: 'page-signup', | |
templateUrl: 'signup.html', | |
}) | |
export class SignupPage { | |
//public userModel :UserModel; | |
private myForm : FormGroup; | |
//inyectamos los servicios al contructor | |
constructor(public navCtrl: NavController, | |
public navParams: NavParams, | |
public loadingCtrl: LoadingController, | |
public alertCtrl : AlertController, | |
public authService :AuthService, | |
private formBuilder : FormBuilder) { | |
//this.userModel =new UserModel(); | |
//this.myForm = this.Register(); | |
this.myForm=this.formBuilder.group({ | |
user : ['',Validators.required,Validators.pattern(/^[a-z0-9_-]{3,16}$/)], | |
apellido :['',Validators.required], | |
//validacion asincronica puesto que tenemos que pedirla se una funcion externa | |
age: ['', Validators.compose([Validators.required, ageValidator.isValid])], | |
email :['', Validators.compose([Validators.required, Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$')])], | |
password : ['', Validators.compose([Validators.required, Validators.minLength(6)])] | |
}); | |
} | |
ionViewDidLoad() { | |
console.log('ionViewDidLoad SignupPage'); | |
} | |
/*/ | |
saveData (){// | |
console.log(JSON.stringify(this.myForm.valid)); | |
}/*/ | |
signUp() { | |
//mostramos una ventana mientra se registra al usuario | |
let loading = this.loadingCtrl.create({ | |
content: 'Creando cuenta. Por favor, espere...' | |
}); | |
loading.present(); | |
let userModel=new UserModel(); | |
userModel.email=this.myForm.value.email; | |
userModel.password=this.myForm.value.password; | |
userModel.firstName=this.myForm.value.user; | |
userModel.apellido=this.myForm.value.apellido; | |
userModel.age=this.myForm.value.age; | |
//Utilizamos el servicio AuthService que injectamos en el contructor para ejecutar su método createUserWithEmailAndPassword() | |
//el cual recibe el modelo UserModel el cual ya va a tener los datos del usuario capturados en la vista | |
this.authService.createUserWithEmailAndPassword(userModel).then(result => { | |
loading.dismiss(); | |
// el metodo devuelve la promesa ,vamos a suponer que el usuario fue registrado por lo que enviamos al usuario | |
// a la pantalla de inicio de sesión para que pueda utilizar sus nuevas credenciales y entrar | |
this.navCtrl.push(SignInPage); | |
}).catch(error => {//si existe un error | |
loading.dismiss(); | |
console.log(error); | |
this.alert('Error', 'Ha ocurrido un error inesperado. Por favor intente nuevamente.'); | |
}); | |
}//cierre del metodo signUp | |
/*/ | |
addUser(){ | |
if (!this.myForm.valid){ | |
console.log("Nice try!"); | |
} else { | |
this.authService.register(this.myForm.value.email,this.myForm.value.password,this.myForm.value.firstName, this.myForm.value.apellido, | |
parseFloat(this.myForm.value.age)).then( () => { | |
this.myForm.reset(); | |
}); | |
} /*/ | |
} | |
alert(title :string , message :string ){ | |
let alert =this.alertCtrl.create({ | |
title : title, | |
subTitle: message, | |
buttons :['OK'] | |
}); | |
alert.present(); | |
} | |
} |
This file contains 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
export class UserModel { | |
email : string; | |
password :string ; | |
firstName :string; | |
apellido : string; | |
age :number; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment