title: User Authentication with Go and AngularJS
body: <p>I want to set up an authentication system with tokens on my Go application, which use an AngularJS front-end.</p>
  
  <p>What I'm looking for is advices about all steps to create a safe system. Here's my steps :</p>
  
  <p><em>We will considerate a user entry is already written in our database.</em></p>
  
  <h2>1 - The user wants to sign in</h2>
  
  <p>The user goes to the index of the web app which prompts him to sign in.</p>
  
  <p>With my <strong>app.yaml</strong> file, I declare my <strong>HTML</strong> file with <strong>dependencies</strong> for the  AngularJS front-end:</p>
  
  <pre><code>application: authtest
  version: 1
  runtime: go
  api_version: go1
  
  handlers:
  - url: /
    static_files: frontend/index.html
    upload: frontend/(.*\.html)
  
  - url: /js
    static_dir: frontend/js
  
  - url: /.*
    script: _go_app
  </code></pre>
  
  <p><strong>Visual :</strong></p>
  
  <p><img src="https://i.imgur.com/he49Ey7.png" alt="Alt text"></p>
  
  <p><strong>Code:</strong></p>
  
  <pre><code>&lt;form ng-submit="signIn()" ng-controller="signInCtrl"&gt;
      &lt;input type="email" ng-model="credentials.email" placeholder="Email" name="email"&gt;
      &lt;input type="password" ng-model="credentials.password" placeholder="Password" name="password"&gt;
      &lt;input type="submit" value="Sign in"&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>The user enters his <strong>credentials</strong>, and click on <strong>Sign in</strong> button.</p>
  
  <h2>2 - Request the server</h2>
  
  <p>The AngularJS module code:</p>
  
  <pre><code>&lt;script&gt;
      angular.module('authtest', ['ngCookies'])
      .controller('signInCtrl', ['$scope', '$http', '$window', '$cookieStore', '$route', function($scope, $http, $window, $cookieStore, $route){
          var credentials = {}
          $scope.signIn = function() {
              $http.post('/signin', credentials)
              .success(function (data, status) {
                  if(status == 200) {
                      if(data.Access_token){
                          //set cookies with tokens
                          $cookieStore.put('access_token', data.Access_token);
                          $cookieStore.put('refresh_token', data.Refresh_token);
                          $route.reload();
                      }
                      else {
                          $window.alert('Wrong credentials, try again.');
                      }
                  }
              })
              .error(function (data, status) {
                  $window.alert('error: ' + data + '(errorStatus: ' + status + ')');
              });
          };
      }]);
  &lt;/script&gt;
  </code></pre>
  
  <p>The Angular module posts the form to <strong>/signin</strong> path, so the Go application needs to handle it:</p>
  
  <pre><code>package main
  import (
      "net/http"
      "encoding/json"
      "fmt"
  )
  type SignInCredentials struct {
      Email string
      Password string
  }
  type Token struct {
      Access_token string
      Refresh_token string
      Id_token string
  }
  func init() {        //I use init() instead of main() because I'm using App Engine.
      http.HandleFunc("/signin", SignInHandler)
  }
  func SignInHandler (w http.ResponseWriter, r *http.Request) {
      decoder := json.NewDecoder(r.Body)
      var c SignInCredentials
      err := decoder.Decode(&amp;c)
      if err != nil {
          panic()
      }
      var hashPassword = hash(c.Password) //Is it at a good level to hash it ?
      if isInDatabase(c.Email, hashPassword) == false {
          fmt.Fprintf(w, "") // Really useful ?
          return
      }
  
      var tokens Token
      /**
      * The user seems to be well stored in the database, but how
      * to manage my tokens ?
      */
      response, _ := json.Marshal(tokens)
      fmt.Fprintf(w, string(response))
  }
  </code></pre>
  
  <p><em>Obviously, <code>hashPassword(p string)</code> hashes the user password and <code>isInDatabase(e string, p string)</code> is a boolean which checks if the provided credentials are stored in our database.</em>  </p>
  
  <ul>
  <li>As I said inside the code, I'm wondering if it's the <strong>good moment</strong> to hash the password of the user, or maybe hash it in <strong>client-side</strong> ?  </li>
  <li>Print a zero-car string if the user is not in database is really useful or could I just <strong>return</strong> the function ?  </li>
  <li>The main question here is how to manage my tokens ? I often see tokens are mainly composed of <code>access_token</code>, <code>refresh_token</code> and <code>id_token</code>. I also know <code>access_token</code> is limited in time to use (the current session, ot 3600seconds for example) and we use <code>refresh_token</code> to have a fresh new <code>access_token</code>. But how to generate it and store it ?</li>
  </ul>
  
  <h2>3 - Handle response with AngularJS</h2>
  
  <p>As already written in AngularJS module code, when the user is well authenticated, we <strong>set cookies</strong> with provided <strong>tokens</strong>. Is it a good way ? I'm also wondering how to prevent <a href="http://fr.wikipedia.org/wiki/Cross-Site_Request_Forgery" rel="noreferrer">XSRF</a> (CSRF) attacks in my system ?</p>
  
  <p>Thank you for your future answers and advices.</p>