Advertisement
Guest User

Untitled

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