Advertisement
Guest User

Untitled

a guest
Nov 25th, 2016
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // WORKS ON MOZILLA ONLY!
  2. // "Error: Cannot connect due to network error." ON CHROME! ?!?!
  3.  
  4.  
  5. function startApp() {
  6.  
  7.     const kinveyBaseUrl = "https://baas.kinvey.com/";
  8.     const kinveyAppKey = "kid_SkJltdBfl";
  9.     const kinveyAppSecret =
  10.         "4292f7c2fdc94ae6a2682923f9222627";
  11.     const kinveyAppAuthHeaders = {
  12.         'Authorization': "Basic " + btoa(kinveyAppKey + ":" + kinveyAppSecret),
  13.     };
  14.  
  15.     sessionStorage.clear(); // Clear user auth data
  16.  
  17.     showHideMenuLinks();
  18.     showView('viewHome');
  19.  
  20.     // Bind the navigation menu links
  21.     $("#linkHome").click(showHomeView);
  22.     $("#linkLogin").click(showLoginView);
  23.     $("#linkRegister").click(showRegisterView);
  24.     $("#linkListAds").click(listAds);
  25.     $("#linkCreateAd").click(showCreateAdView);
  26.     $("#linkLogout").click(logoutUser);
  27.  
  28.     // Bind the form submit buttons
  29.     $("#buttonLoginUser").click(loginUser);
  30.     $("#buttonRegisterUser").click(registerUser);
  31.     $("#buttonCreateAd").click(createAd);
  32.     $("#buttonEditAd").click(editAd);
  33.  
  34.     // Bind the info / error boxes: hide on click
  35.     $("#infoBox, #errorBox").click(function () {
  36.         $(this).fadeOut();
  37.     });
  38.  
  39.     function showHideMenuLinks() {
  40.         $("#linkHome").show();
  41.         if (sessionStorage.getItem('authToken')) {
  42.             // We have logged in user
  43.             $("#linkLogin").hide();
  44.             $("#linkRegister").hide();
  45.             $("#linkListAds").show();
  46.             $("#linkCreateAd").show();
  47.             $("#linkLogout").show();
  48.         } else {
  49.             // No logged in user
  50.             $("#linkLogin").show();
  51.             $("#linkRegister").show();
  52.             $("#linkListAds").hide();
  53.             $("#linkCreateAd").hide();
  54.             $("#linkLogout").hide();
  55.         }
  56.     }
  57.  
  58.     function showView(viewName) {
  59.         // Hide all views and show the selected view only
  60.         $('main > section').hide();
  61.         $('#' + viewName).show();
  62.     }
  63.  
  64.     function showHomeView() {
  65.         showView('viewHome');
  66.     }
  67.  
  68.     function showLoginView() {
  69.         showView('viewLogin');
  70.         $('#formLogin').trigger('reset');
  71.     }
  72.  
  73.     function showRegisterView() {
  74.         $('#formRegister').trigger('reset');
  75.         showView('viewRegister');
  76.     }
  77.  
  78.     function showCreateAdView() {
  79.         $('#formCreateAd').trigger('reset');
  80.         showView('viewCreateAd');
  81.     }
  82.  
  83.     function listAds() {
  84.         $('#ads').empty();
  85.         showView('viewAds');
  86.         $.ajax({
  87.             method: "GET",
  88.             url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/adverts",
  89.             headers: getKinveyUserAuthHeaders(),
  90.             success: loadAdsSuccess,
  91.             error: handleAjaxError
  92.         });
  93.  
  94.         function loadAdsSuccess(ads) {
  95.             showInfo('Adverts loaded.');
  96.             if (ads.length == 0) {
  97.                 $('#ads').text('No ads in the library.');
  98.             } else {
  99.                 let adsTable = $('<table>')
  100.                     .append($('<tr>').append(
  101.                         '<th>Title</th><th>Description</th>',
  102.                         '<th>Publisher</th><th>Date Published</th>',
  103.                         '<th>Price</th><th>Actions</th>'));
  104.                 for (let ad of ads)
  105.                     appendAdRow(ad, adsTable);
  106.                 $('#ads').append(adsTable);
  107.             }
  108.         }
  109.  
  110.         function appendAdRow(ad, adsTable) {
  111.             let links = [];
  112.             if (ad._acl.creator == sessionStorage['userId']) {
  113.                 let deleteLink = $('<a href="#">[Delete]</a>')
  114.                     .click(function () {
  115.                         deleteAd(ad)
  116.                     });
  117.                 let editLink = $('<a href="#">[Edit]</a>')
  118.                     .click(function () {
  119.                         loadAdForEdit(ad)
  120.                     });
  121.                 links = [deleteLink, ' ', editLink];
  122.             }
  123.  
  124.             adsTable.append($('<tr>').append(
  125.                 $('<td>').text(ad.title),
  126.                 $('<td>').text(ad.description),
  127.                 $('<td>').text(ad.publisher),
  128.                 $('<td>').text(ad.date),
  129.                 $('<td>').text(ad.price),
  130.                 $('<td>').append(links)
  131.             ));
  132.         }
  133.     }
  134.  
  135.     function createAd() {
  136.         let adData = {
  137.             title: $('#formCreateAd input[name=title]').val(),
  138.             description: $('#formCreateAd textarea[name=description]').val(),
  139.             publisher: sessionStorage.getItem('username'),
  140.             date: $('#formCreateAd input[name=datePublished]').val(),
  141.             price: Math.round($('#formCreateAd input[name=price]').val() * 100) / 100
  142.         };
  143.         $.ajax({
  144.             method: "POST",
  145.             url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/adverts",
  146.             headers: getKinveyUserAuthHeaders(),
  147.             data: adData,
  148.             success: createAdSuccess,
  149.             error: handleAjaxError
  150.         });
  151.  
  152.         function createAdSuccess(response) {
  153.             listAds();
  154.             showInfo('Advert created.');
  155.         }
  156.     }
  157.  
  158.     function editAd() {
  159.         let adData = {
  160.             title: $('#formEditAd input[name=title]').val(),
  161.             description: $('#formEditAd textarea[name=description]').val(),
  162.             publisher: sessionStorage.getItem('username'),
  163.             date: $('#formEditAd input[name=datePublished]').val(),
  164.             price: Math.round($('#formEditAd input[name=price]').val() * 100) / 100
  165.         };
  166.         $.ajax({
  167.             method: "PUT",
  168.             url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/adverts/" + $('#formEditAd input[name=id]').val(),
  169.             headers: getKinveyUserAuthHeaders(),
  170.             data: adData,
  171.             success: editAdSuccess,
  172.             error: handleAjaxError
  173.         });
  174.  
  175.         function editAdSuccess(response) {
  176.             listAds();
  177.             showInfo('Advert edited.');
  178.         }
  179.     }
  180.  
  181.     function deleteAd(ad) {
  182.         $.ajax({
  183.             method: "DELETE",
  184.             url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/adverts/" + ad._id,
  185.             headers: getKinveyUserAuthHeaders(),
  186.             success: deleteAdSuccess,
  187.             error: handleAjaxError
  188.         });
  189.         function deleteAdSuccess(response) {
  190.             listAds();
  191.             showInfo('Advert deleted.');
  192.         }
  193.     }
  194.  
  195.     function loadAdForEdit(ad) {
  196.  
  197.         let req = {
  198.             method: "GET",
  199.             url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/adverts/" + ad._id,
  200.             headers: getKinveyUserAuthHeaders()
  201.         };
  202.  
  203.         $.ajax(req)
  204.             .then(loadAdForEditSuccess)
  205.             .catch(handleAjaxError);
  206.  
  207.         function loadAdForEditSuccess(ad) {
  208.             $('#formEditAd input[name=id]').val(ad._id);
  209.             $('#formEditAd input[name=title]').val(ad.title);
  210.             $('#formEditAd textarea[name=description]').val(ad.description);
  211.             $('#formEditAd input[name=datePublished]').val(ad.date);
  212.             $('#formEditAd input[name=price]').val(ad.price);
  213.             showView('viewEditAd');
  214.         }
  215.     }
  216.  
  217.     function loginUser() {
  218.         let userData = {
  219.             username: $('#formLogin input[name=username]').val(),
  220.             password: $('#formLogin input[name=passwd]').val()
  221.         };
  222.         $.ajax({
  223.             method: "POST",
  224.             url: kinveyBaseUrl + "user/" + kinveyAppKey + "/login",
  225.             headers: kinveyAppAuthHeaders,
  226.             data: userData,
  227.             success: loginSuccess,
  228.             error: handleAjaxError
  229.         });
  230.  
  231.         function loginSuccess(userInfo) {
  232.             saveAuthInSession(userInfo);
  233.             showHideMenuLinks();
  234.             listAds();
  235.             showInfo('Login successful.');
  236.         }
  237.     }
  238.  
  239.     function registerUser() {
  240.         let userData = {
  241.             username: $('#formRegister input[name=username]').val(),
  242.             password: $('#formRegister input[name=passwd]').val()
  243.         };
  244.         $.ajax({
  245.             method: "POST",
  246.             url: kinveyBaseUrl + "user/" + kinveyAppKey + "/",
  247.             headers: kinveyAppAuthHeaders,
  248.             data: userData,
  249.             success: registerSuccess,
  250.             error: handleAjaxError
  251.         });
  252.  
  253.         function registerSuccess(userInfo) {
  254.             saveAuthInSession(userInfo);
  255.             showHideMenuLinks();
  256.             listAds();
  257.             showInfo('User registration successful.');
  258.         }
  259.     }
  260.  
  261.     function logoutUser() {
  262.         sessionStorage.clear();
  263.         $('#loggedInUser').text("");
  264.         showHideMenuLinks();
  265.         showView('viewHome');
  266.         showInfo('Logout successful.');
  267.     }
  268.  
  269.     function saveAuthInSession(userInfo) {
  270.         let userAuth = userInfo._kmd.authtoken;
  271.         sessionStorage.setItem('authToken', userAuth);
  272.         let userId = userInfo._id;
  273.         sessionStorage.setItem('userId', userId);
  274.         let username = userInfo.username;
  275.         sessionStorage.setItem('username', username);
  276.         $('#loggedInUser').text(
  277.             "Welcome, " + username + "!");
  278.     }
  279.  
  280.     function getKinveyUserAuthHeaders() {
  281.         return {
  282.             'Authorization': "Kinvey " + sessionStorage.getItem('authToken'),
  283.         };
  284.     }
  285.  
  286.     function handleAjaxError(response) {
  287.         let errorMsg = JSON.stringify(response);
  288.         if (response.readyState === 0)
  289.             errorMsg = "Cannot connect due to network error.";
  290.         if (response.responseJSON &&
  291.             response.responseJSON.description)
  292.             errorMsg = response.responseJSON.description;
  293.         showError(errorMsg);
  294.     }
  295.  
  296.     function showInfo(message) {
  297.         $('#infoBox').text(message);
  298.         $('#infoBox').show();
  299.         setTimeout(function () {
  300.             $('#infoBox').fadeOut();
  301.         }, 3000);
  302.     }
  303.  
  304.     function showError(errorMsg) {
  305.         $('#errorBox').text("Error: " + errorMsg);
  306.         $('#errorBox').show();
  307.     }
  308. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement