ark.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. Swal.fire({
  37. title: '權限不足',
  38. icon: 'info',
  39. confirmButtonColor: '#3085d6'
  40. });
  41. window.location.replace("login.html");
  42. }
  43. if (access_token) {
  44. // 導頁進Dashboard介面
  45. Swal.fire({
  46. title: '登入成功',
  47. icon: 'success',
  48. confirmButtonColor: '#3085d6'
  49. });
  50. window.setTimeout(() => {
  51. window.location.href = 'index.html';
  52. }, 1500);
  53. } else {
  54. console.log('else'); // test
  55. }
  56. }, error: function(xhr, status, error) {
  57. console.log(xhr.responseText); // test
  58. var res = JSON.parse(xhr.responseText);
  59. console.log(res.detail);
  60. if (res.detail == 'Incorrect email or password') {
  61. Swal.fire({
  62. title: '注意',
  63. icon: 'error',
  64. text: '帳號/密碼錯誤,請重新輸入',
  65. confirmButtonColor: '#3085d6'
  66. });
  67. } else {
  68. Swal.fire({
  69. title: '注意',
  70. icon: 'error',
  71. text: '權限不足',
  72. confirmButtonColor: '#3085d6'
  73. });
  74. }
  75. }
  76. });
  77. return false;
  78. });