summaryrefslogtreecommitdiff
path: root/src/jqueryRest.js
blob: bc3bb5100e27ab5f81ad3f328abc4c6237310d3d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
srp.remote = (function(){
  var jqueryRest = (function() {

    // we do not fetch the salt from the server
    function register(session) {
      return $.post("/users.json", { user: session.signup() });
    }

    function handshake(session) {
      return $.post("/sessions.json", session.handshake());
    }

    function authenticate(session) {
      return $.ajax({
        url: "/sessions/" + session.getI() + ".json",
        type: 'PUT',
        data: {client_auth: session.getM()}
      });
    }

    return {
      register: register,
      handshake: handshake,
      authenticate: authenticate
    };
  }());


  function signup(){
    jqueryRest.register(srp.session)
    .done(srp.signedUp)
    .fail(error)
  };

  function login(){
    jqueryRest.handshake(srp.session)
    .done(receiveSalts)
    .fail(error)
  };

  function receiveSalts(response){
    // B = 0 will make the algorithm always succeed
    // -> refuse such a server answer
    if(response.B === 0) {
      srp.error("Server send random number 0 - could not login.");
    }
    else if(! response.salt || response.salt === 0) {
      srp.error("Server failed to send salt - could not login.");
    } 
    else 
    {
      srp.session.calculations(response.salt, response.B);
      jqueryRest.authenticate(srp.session)
      .done(confirmAuthentication)
      .fail(error);
    }
  };

  // Receive M2 from the server and verify it
  // If an error occurs, raise it as an alert.
  function confirmAuthentication(response)
  {
    if (srp.session.validate(response.M2))
      srp.loggedIn();
    else
      srp.error("Server key does not match");
  };

  // The server will send error messages as json alongside
  // the http error response.
  function error(xhr, text, thrown)
  { 
    if (xhr.responseText && xhr.responseText != "")
      srp.error($.parseJSON(xhr.responseText));
    else
      srp.error("Server did not respond.");
  };

  return {
    signup: signup,
    login: login
  }

}());