ark.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // 取得access_token
  2. function get_access_token() {
  3. console.log(localStorage.access_token); // test
  4. return localStorage.access_token;
  5. }
  6. // 檢查是否可存取該頁面
  7. function checkRoute() {
  8. let access_token = get_access_token();
  9. if(access_token == undefined) {
  10. window.location.replace("login.html");
  11. }
  12. }
  13. // 帳號登入
  14. $("#btn_login").click(function() {
  15. var username = $('#username').val();
  16. var password = $('#password').val();
  17. var param_string = {
  18. username: username,
  19. password: password
  20. };
  21. if (username == '' || password == '') {
  22. return;
  23. }
  24. $.ajax({
  25. type: 'POST',
  26. url: 'https://api.ptt.cx:8750/api/v1/login/access-token',
  27. data: param_string,
  28. success: function(res, textStatus, jqXHR) {
  29. // {access_token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2N…kyIn0.wwRK7OKPICdbcOhLfgqA5u5uxkhRVP2gQeqEF8tCY4g', token_type: 'bearer'}
  30. console.log(res); // test
  31. // 將access_token寫入localStorage
  32. localStorage.access_token = res.access_token;
  33. // 檢查是否已登入
  34. let access_token = get_access_token();
  35. if (access_token == undefined) {
  36. window.location.replace("login.html");
  37. }
  38. if (access_token) {
  39. // 導頁進Dashboard介面
  40. Swal.fire({
  41. title: '登入成功',
  42. icon: 'success',
  43. confirmButtonColor: '#3085d6'
  44. });
  45. window.setTimeout(() => {
  46. window.location.href = 'index.html';
  47. }, 1500);
  48. } else {
  49. console.log('else'); // test
  50. }
  51. }, error: function(xhr, status, error) {
  52. console.log(xhr.responseText); // test
  53. var res = JSON.parse(xhr.responseText);
  54. if (res.detail == 'Incorrect email or password') {
  55. Swal.fire({
  56. title: '注意',
  57. icon: 'error',
  58. text: '帳號/密碼錯誤,請重新輸入',
  59. confirmButtonColor: '#3085d6'
  60. });
  61. }
  62. }
  63. });
  64. return false;
  65. });