summaryrefslogtreecommitdiffstats
path: root/examples/ajax-broker/app.js
blob: 7a627c926ddd44a636e3d04150cb9e40d2553a2c (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
104
105
106
107
+function($) {
  // Init
  attach();
  
  /**
   * Attach session.
   * Will redirect to SSO server.
   */
  function attach() {
    var req = $.ajax({
      url: 'api.php?command=attach',
      crossDomain: true,
      dataType: 'jsonp'
    });
    
    req.done(function(data, code) {
      if (code && code >= 400) { // jsonp failure
        showError(data.error);
        return;
      }
      
      loadUserInfo();
    });
    
    req.fail(function(jqxhr) {
      showError(jqxhr.responseJSON || jqxhr.textResponse)
    });
  }
    
  /**
   * Do an AJAX request to the API
   * 
   * @param command   API command
   * @param params    POST data
   * @param callback  Callback function
   */
  function doApiRequest(command, params, callback) {
    var req = $.ajax({
      url: 'api.php?command=' + command,
      method: params ? 'POST' : 'GET',
      data: params,
      dataType: 'json'
    });

    req.done(callback);
    
    req.fail(function(jqxhr) {
      showError(jqxhr.responseJSON || jqxhr.textResponse);
    });
  }

  /**
   * Display the error message
   * 
   * @param data
   */
  function showError(data) {
    var message = typeof data === 'object' && data.error ? data.error : 'Unexpected error';
    $('#error').text(message).show();
  }

  /**
   * Load and display user info
   */
  function loadUserInfo() {
    doApiRequest('getUserinfo', null, showUserInfo);
  }
  
  /**
   * Display user info
   * 
   * @param info
   */
  function showUserInfo(info) {
    $('body').removeClass('anonymous authenticated');
    $('#user-info').html('');
    
    if (info) {
      for (var key in info) {
        $('#user-info').append($('<dt>').text(key));
        $('#user-info').append($('<dd>').text(info[key]));
      }
    }
    
    $('body').addClass(info ? 'authenticated' : 'anonymous');
  }

  /**
   * Submit login form through AJAX
   */
  $('#login-form').on('submit', function(e) {
    e.preventDefault();
    
    $('#error').text('').hide();
    
    var data = {
      username: this.username.value,
      password: this.password.value
    };
    
    doApiRequest('login', data, showUserInfo);
  });
  
  $('#logout').on('click', function() {
    doApiRequest('logout', {}, function() { showUserInfo(null); });
  })
}(jQuery);