Sign in or sign out users with Ionic 4 and Django - Part two

DAY 5 - August 2019

Create a register page with Ionic 4

As we have done for login page, we need to add the register page to our ionic project:

ionic g page RegisterPage

Then we move it into our pages directory and we change the app-routing.module.ts file to reflect this change.

 { path: 'register-page', loadChildren: './pages/register-page/register-page.module#RegisterPagePageModule' }

Next we modify the register-page.page.html to setup our interface with a form to ask the main parameters required to create an account: the email, the username, the password and a password confirmation

<ion-content>
  <div class="login-container">
    <b>Bike Application</b>
       <ion-list lines="full" mode="ios" floating-form> 
        <br>
        <form (ngSubmit)="register()" #registerForm="ngForm">  
           <ion-item>
             <ion-label  position="floating">Username</ion-label>
             <ion-input type="text"   name="username"  [(ngModel)]="registerCredentials.username" required></ion-input>
           </ion-item>
           <ion-item>
             <ion-label  position="floating">E-mail</ion-label>
             <ion-input type="email" name="email"  [(ngModel)]="registerCredentials.email" required></ion-input>
           </ion-item> 
           <ion-item>
             <ion-label  position="floating">Password</ion-label>
             <ion-input type="password" name="password" [(ngModel)]="registerCredentials.password" required></ion-input>
           </ion-item>
           <ion-item>
             <ion-label  position="floating">Confirm password</ion-label>
             <ion-input type="password" name="passwordbis" [(ngModel)]="registerCredentials.passwordbis" required></ion-input>
           </ion-item>
        <div class="button-continer">
         <ion-button mode="ios" size="small" fill="outline" color="dark" expand="block"  type="submit">Register</ion-button>
         </div>
       </form>
       <div class="button-continer">
       <ion-button mode="ios" size="small" fill="outline" color="dark" expand="block" (click)="back()">Back</ion-button>
       </div>
       </ion-list>
 </div>
 </ion-content> 

To access this page, we need to create the subscribe() method in our Login page, to redirect the user on the register page, like this:


  public subscribe() {
    this.router.navigateByUrl("/register-page")
  }

Because on our login page interface, we specified a button to click on to go to the register page

  <ion-button mode="ios" size="small" fill="outline" color="dark" expand="block" (click)="subscribe()">Subscribe</ion-button>

In our register form, we indicate the method register() which will received the parameters entered. First we need to check that values have been entered, then we need to check if the network is available. If so, we need to verify if an account already exists for the email provided. If so, we show a message to the user to indicate that he should login instead of registering since we already know this email.
If everything is ok, then we can create the account.


  register() {
    if (this.registerCredentials.password != this.registerCredentials.passwordbis) {
      this.apiService.showError("Sorry passwords doesn't match");
    }
    else if (this.registerCredentials.username.length == 0 && this.registerCredentials.email.length == 0) {
      this.apiService.showError("Please enter your email and username");
    }
    else { 
      if (this.apiService.networkConnected) {
        this.apiService.showLoading();
        // Check email
        let queryPath = '?email=' + this.registerCredentials.email;
        this.apiService.findUser(queryPath).subscribe((listUser) => {
          this.apiService.stopLoading()
          console.log(JSON.stringify(listUser))
          if (listUser) {
            let nbUserFound = listUser["count"]
            if (nbUserFound==0){
              let encryptedPassword = CryptoJS.SHA256(this.registerCredentials.password).toString(CryptoJS.enc.Hex);
              let userToCreate = {
                "email": this.registerCredentials.email,
                "username": this.registerCredentials.username,
                "password": encryptedPassword,
                "valid": true,
                "is_active": true,
                "is_staff": false
              } 
              this.apiService.createUser(userToCreate).subscribe((resultat) => {
                if (resultat) {
                  console.log(resultat)
                }
                else {
                  this.apiService.stopLoading();
                  this.apiService.showError("An error occured while registering")
                }
              });
            }
            else{
              this.apiService.showError("An account already exists for this email, please login");
            } 
          }
          else { 
            this.apiService.showError("An error occured while registering") 
          }
        });
      }
    }
  }

To create the user, we will call our API with a JSON object containing the information of the user to create (email, username and passord). I also added the valid, is_active and is_staff booleans. To create a user, using our Django API, we just need to call our user endpoint with an HTTP Post

createUser(user){ 
    const options = {
      headers: new HttpHeaders({
        'Authorization': 'Bearer ' + this.tokenSSO,
        'Content-Type': 'application/json'
      })
    }; 
    let url = this.getUserUrl;
    return Observable.create(observer => {
      // At this point make a request to your backend 
      console.log("on appelle BACKEND encoded url " + url);
      this.http.post(url, user, options)
        .pipe(retry(1))
        .subscribe(res => {
          observer.next(res);
          observer.complete();
        }, error => {
          observer.next();
          observer.complete();
          console.log(error);// Error getting the data
        });
    });
  }

If everything goes fine, you should receive as result a JSON with the object created.

These are the basic steps to login and to register a user within our application. From here, we should be able to authorize the user to access the main page of our application, and may be to remember him, to avoid identificating himself each time he will be using the app. We will study this, in next tutorial.

As usual, you can find the code in my Github repository

You can find how to manage the "forget password" link in this tutorial