Advertisement
Guest User

Untitled

a guest
Dec 21st, 2016
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.71 KB | None | 0 0
  1. /**
  2. * Created by Merrie on 12/20/16.
  3. */
  4. function startApp() {
  5. const kinveyBaseUrl = "https://baas.kinvey.com/";
  6. const kinveyAppKey = "kid_BkgrHyPNx";
  7. const kinveyAppSecret = "0a80d7870a094292ab4f8e89484ccf62";
  8. const kinveyAppAuthHeaders = {
  9. 'Authorization': "Basic " + btoa(kinveyAppKey + ":" + kinveyAppSecret),
  10. };
  11.  
  12. //Hide status boxes
  13. $('#infoBox').hide();
  14. $('#errorBox').hide();
  15. $('#loadingBox').hide();
  16.  
  17. sessionStorage.clear(); // Clear user auth data
  18.  
  19. showHideMenuLinks();
  20.  
  21. if(sessionStorage.getItem('authToken')) {
  22. $('#spanMenuLoggedInUser').text('Welcome, ' + sessionStorage.getItem('name') + '!');
  23. showUserHomeView()
  24. }else {
  25. $('#spanMenuLoggedInUser').empty();
  26. showAppHomeView();
  27. }
  28.  
  29. //Bind menu links with views
  30. $("#linkMenuAppHome").click(showAppHomeView);
  31. $("#linkMenuLogin").click(showLoginView);
  32. $("#linkMenuRegister").click(showRegisterView);
  33.  
  34. $("#linkMenuUserHome").click(showUserHomeView);
  35. $("#linkMenuShop").click(showShopView);
  36. $("#linkMenuCart").click(showCartView);
  37. $("#linkMenuLogout").click(logoutUser);
  38.  
  39. // Bind the form submit buttons
  40. $(`#formLogin input[type="submit"]`).click(loginUser);
  41. $(`#formRegister input[type="submit"]`).click(registerUser);
  42.  
  43.  
  44. $("#infoBox, #errorBox").click(function () {
  45. $(this).fadeOut();
  46. });
  47.  
  48. // Attach AJAX "loading" event listener
  49. $(document).on({
  50. ajaxStart: function () {
  51. $("#loadingBox").show()
  52. },
  53. ajaxStop: function () {
  54. $("#loadingBox").hide()
  55. }
  56. });
  57.  
  58. function showHideMenuLinks() {
  59. if (sessionStorage.getItem('authToken')) {
  60. // We have logged in user
  61. $("#linkMenuAppHome").hide();
  62. $("#linkMenuLogin").hide();
  63. $("#linkMenuRegister").hide();
  64. $("#linkMenuUserHome").show();
  65. $("#linkMenuShop").show();
  66. $("#linkMenuCart").show();
  67. $("#linkMenuLogout").show();
  68. } else {
  69. // No logged in user
  70. $("#linkMenuAppHome").show();
  71. $("#linkMenuLogin").show();
  72. $("#linkMenuRegister").show();
  73. $("#linkMenuUserHome").hide();
  74. $("#linkMenuShop").hide();
  75. $("#linkMenuCart").hide();
  76. $("#linkMenuLogout").hide();
  77. }
  78. }
  79.  
  80. function showView(viewName) {
  81. // Hide all views and show the selected view only
  82. $('main > section').hide();
  83. $('#' + viewName).show();
  84. }
  85.  
  86. function showAppHomeView() {
  87. //Bind the user home buttons
  88. $("#linkUserHomeShop").click(showShopView);
  89. $("#linkUserHomeCart").click(showCartView);
  90. showView('viewAppHome');
  91. }
  92.  
  93. function showUserHomeView() {
  94. $('#viewUserHomeHeading').text('Welcome, ' + sessionStorage.getItem('name') + '!');
  95. showView('viewUserHome');
  96. }
  97.  
  98. function showLoginView() {
  99. showView('viewLogin');
  100. $('#formLogin').trigger('reset');
  101. }
  102.  
  103. function showRegisterView() {
  104. $('#formRegister').trigger('reset');
  105. showView('viewRegister');
  106. }
  107.  
  108. function showShopView() {
  109. $('#viewShop').empty();
  110. const getShopUrl = kinveyBaseUrl + "appdata/" + kinveyAppKey + `/products`;
  111. let table = $('<table>').append(
  112. `<thead>
  113. <tr>
  114. <th>Product</th>
  115. <th>Description</th>
  116. <th>Price</th>
  117. <th>Actions</th>
  118. </tr>
  119. </thead>`);
  120. $.ajax({
  121. method: "GET",
  122. url: getShopUrl,
  123. headers: getKinveyUserAuthHeaders(),
  124. success: fillTable,
  125. error: handleAjaxError
  126. });
  127. function fillTable(products) {
  128. if (products.length == 0) {
  129. $('#viewShop').empty();
  130. $('#viewShop').text('No products found.')
  131. }
  132. else {
  133. let tbody = $('<tbody>');
  134. for (let prd of products) {
  135. let prcBtn = $('<button>').text("Purchase");
  136. prcBtn.click(x => purchaseProduct(prd._id));
  137. tbody.append($('<tr>')
  138. .append($(`<td>`).text(prd.name))
  139. .append($(`<td>`).text(prd.description))
  140. .append($(`<td>`).text(prd.price.toFixed(2)))
  141. .append($('<td>').append(prcBtn)));
  142. }
  143.  
  144. table.append(tbody);
  145. $('#viewShop').empty();
  146. $('#viewShop').append(table);
  147. }
  148. }
  149. showView('viewShop');
  150. }
  151.  
  152. function showCartView() {
  153. $('#viewCart').empty();
  154. const getCartUrl = kinveyBaseUrl + "appdata/" + kinveyAppKey + `/shoppingCart`;
  155. let table = $('<table>').append(
  156. `<thead>
  157. <tr>
  158. <th>Product</th>
  159. <th>Description</th>
  160. <th>Quantity</th>
  161. <th>Total Price</th>
  162. <th>Actions</th>
  163. </tr>
  164. </thead>`);
  165. $.ajax({
  166. method: "GET",
  167. url: getCartUrl,
  168. headers: getKinveyUserAuthHeaders(),
  169. success: fillTable,
  170. error: handleAjaxError
  171. });
  172. function fillTable(products) {
  173. if (products.length == 0) {
  174. $('#viewCart').empty();
  175. $('#viewCart').text('No products found.')
  176. }
  177. else {
  178. let tbody = $('<tbody>');
  179. for (let prd of products) {
  180. let prcBtn = $('<button>').text("Discard");
  181. prcBtn.click(x => discardProduct(prd._id));
  182. tbody.append($('<tr>')
  183. .append($(`<td>`).text(prd.name))
  184. .append($(`<td>`).text(prd.description))
  185. .append($('<td>').text(prd.quantity))
  186. .append($(`<td>`).text(prd.totalPrice.toFixed(2)))
  187. .append($('<td>').append(prcBtn)));
  188. }
  189.  
  190. table.append(tbody);
  191. $('#viewCart').empty();
  192. $('#viewCart').append(table);
  193. }
  194. }
  195. showView('viewCart');
  196. }
  197.  
  198. function purchaseProduct(id) {
  199. let purUrl = kinveyBaseUrl + "appdata/" + kinveyAppKey + "/products/"+ id;
  200. $.ajax({
  201. method: "GET",
  202. url: purUrl,
  203. headers: getKinveyUserAuthHeaders(),
  204. error: handleAjaxError
  205. });
  206.  
  207. function purchaseSuccess(){
  208. showInfo('Product purchased.');
  209. }
  210.  
  211. function putProductToCart() {
  212. let cartUrl = kinveyBaseUrl + "appdata/" + kinveyAppKey + `/shoppingCart`;
  213.  
  214. let productData = {
  215. UserId: SessionStorage.getItem('userId'),
  216. ProductId:id,
  217. Quantity: 1
  218. };
  219.  
  220. $.ajax({
  221. method: "POST",
  222. url: cartUrl,
  223. data: productData,
  224. headers: getKinveyUserAuthHeaders(),
  225. success: purchaseSuccess,
  226. error: handleAjaxError
  227. });
  228. }
  229.  
  230. }
  231.  
  232. function loginUser(newUser) {
  233. newUser.preventDefault();
  234. let userData = {
  235. username: $('#loginUsername').val(),
  236. password: $('#loginPasswd').val()
  237. };
  238.  
  239. $.ajax({
  240. method: "POST",
  241. url: kinveyBaseUrl + "user/" + kinveyAppKey + "/login",
  242. headers: kinveyAppAuthHeaders,
  243. data: userData,
  244. success: loginSuccess,
  245. error: handleAjaxError
  246. });
  247.  
  248. function loginSuccess(userInfo) {
  249. saveAuthInSession(userInfo);
  250. showHideMenuLinks();
  251. $('#spanMenuLoggedInUser').text("Welcome, " + sessionStorage.getItem('name') + '!');
  252. showUserHomeView();
  253. showInfo('Login successful.');
  254. }
  255. }
  256. function registerUser(newUser) {
  257. newUser.preventDefault();
  258. let userData = {
  259. username: $('#registerUsername').val(),
  260. password: $('#registerPasswd').val(),
  261. name: $('#registerName').val()
  262. };
  263. $.ajax({
  264. method: "POST",
  265. url: kinveyBaseUrl + "user/" + kinveyAppKey + "/",
  266. headers: kinveyAppAuthHeaders,
  267. data: userData,
  268. success: registerSuccess,
  269. error: handleAjaxError
  270. });
  271.  
  272. function registerSuccess(userInfo) {
  273. saveAuthInSession(userInfo);
  274. showHideMenuLinks();
  275. showUserHomeView();
  276. showInfo('User registration successful.');
  277. }
  278. }
  279.  
  280. function logoutUser() {
  281. sessionStorage.clear();
  282. $('#spanMenuLoggedInUser').empty();
  283. showHideMenuLinks();
  284. showView('viewAppHome');
  285. showInfo('Logout successful.');
  286. }
  287.  
  288.  
  289. function getKinveyUserAuthHeaders() {
  290. return {
  291. 'Authorization': "Kinvey " +
  292. sessionStorage.getItem('authToken'),
  293. };
  294. }
  295.  
  296. function saveAuthInSession(userInfo) {
  297. let userAuth = userInfo._kmd.authtoken;
  298. sessionStorage.setItem('authToken', userAuth);
  299. let userId = userInfo._id;
  300. sessionStorage.setItem('userId', userId);
  301. let username = userInfo.username;
  302. sessionStorage.setItem('username', username);
  303. let name = userInfo.name;
  304. sessionStorage.setItem('name', name);
  305. $('#loggedInUser').text(
  306. "Welcome, " + username + "!");
  307. }
  308.  
  309. function handleAjaxError(response) {
  310. let errorMsg = JSON.stringify(response);
  311. if (response.readyState === 0)
  312. errorMsg = "Cannot connect due to network error.";
  313. if (response.responseJSON &&
  314. response.responseJSON.description)
  315. errorMsg = response.responseJSON.description;
  316. showError(errorMsg);
  317. }
  318. function showInfo(message) {
  319. $('#infoBox').text(message);
  320. $('#infoBox').show();
  321. setTimeout(function () {
  322. $('#infoBox').fadeOut();
  323. }, 2000);
  324. }
  325. function showError(errorMsg) {
  326. $('#errorBox').text("Error: " + errorMsg);
  327. $('#errorBox').show();
  328. setTimeout(function () {
  329. $('#errorBox').fadeOut();
  330. }, 2000);
  331. }
  332.  
  333. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement