summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/srp/src/jqueryRest.js
blob: 0c58eb2bfbe33f6e9e2bddcd03b954856706b04b (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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
srp.remote = (function(){
  var jqueryRest = (function() {

    // TODO: Do we need to differentiate between PUT and POST?
    function register(session) {
      return $.post("/1/users.json", {user: session.signup() });
    }

    function update(session, token) {
      return $.ajax({
        url: "/1/users/" + session.id() + ".json",
        type: 'PUT',
        headers: { Authorization: 'Token token="' + token + '"' },
        data: {user: session.update() }
      });
    }

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

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

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


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

  function update(submitEvent){
    var form = submitEvent.target;
    var token = form.dataset.token;
    jqueryRest.update(srp.session, token)
    .done(srp.updated)
    .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,
    update: update,
    login: login
  }

}());