authService.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. import axios from 'axios';
  2. import { Alert } from 'react-native';
  3. import * as SecureStore from 'expo-secure-store';
  4. import { EXPO_PUBLIC_API_URL } from '@env';
  5. import { forgetPasswordFormData } from '../types/signup';
  6. import { CustomerData } from '../types/signUpFormData';
  7. import * as FileSystem from 'expo-file-system';
  8. class AuthenticationService {
  9. private apiUrl: string;
  10. constructor() {
  11. this.apiUrl = EXPO_PUBLIC_API_URL;
  12. if (!this.apiUrl) {
  13. throw new Error('API URL is not defined in environment variables');
  14. }
  15. }
  16. async emailLogin(username: string, password: string, isBinding?: boolean) {
  17. try {
  18. console.log('username in emailLogin auth service', username);
  19. console.log('password in emailLogin auth service', password);
  20. console.log('isBinding in emailLogin auth service', isBinding);
  21. const response = await axios.post(
  22. `${this.apiUrl}/public/client/customer/sign-in`,
  23. {
  24. email: username,
  25. password: password,
  26. isBinding: isBinding
  27. },
  28. {
  29. headers: {
  30. 'Content-Type': 'application/json',
  31. Accept: 'application/json'
  32. }
  33. }
  34. );
  35. if (response.status === 201) {
  36. const token = response.data.accessToken;
  37. await SecureStore.setItemAsync('accessToken', token);
  38. console.log('AccessToken', token);
  39. console.log('Login successful!');
  40. return true;
  41. } else {
  42. console.error('Login failed:', response.status);
  43. return false;
  44. }
  45. } catch (error) {
  46. if (axios.isAxiosError(error)) {
  47. console.error('Login error:', error.response?.data?.message || error.message);
  48. } else {
  49. console.error('An unexpected error occurred:', error);
  50. }
  51. return false;
  52. }
  53. }
  54. async phoneLogin(username: string, password: string, isBinding?: boolean) {
  55. try {
  56. console.log('username', username);
  57. console.log('password', password);
  58. console.log('isBinding', isBinding);
  59. const response = await axios.post(
  60. // `${this.apiUrl}/public/client/customer/sign-in`,
  61. // `${this.apiUrl}/public/client/customer/sign-in`,
  62. `${this.apiUrl}/public/client/customer/phone/sign-in`,
  63. {
  64. phone: username,
  65. password: password,
  66. isBinding: isBinding
  67. },
  68. {
  69. headers: {
  70. 'Content-Type': 'application/json',
  71. Accept: '*/*'
  72. }
  73. }
  74. );
  75. if (response.status === 201) {
  76. const token = response.data.accessToken;
  77. await SecureStore.setItemAsync('accessToken', token);
  78. console.log('AccessToken', token);
  79. console.log('Login successful!');
  80. return 'login successful';
  81. } else {
  82. console.log('this, ', response.data.message);
  83. return response.data.message;
  84. }
  85. } catch (error) {
  86. if (axios.isAxiosError(error)) {
  87. console.error('Login error:', error.response?.data?.message || error.message);
  88. return error.response?.data?.message || error.message;
  89. } else {
  90. console.error('An unexpected error occurred:', error);
  91. return 'An unexpected error occurred: ' + error;
  92. }
  93. }
  94. }
  95. async logout() {
  96. await SecureStore.deleteItemAsync('accessToken');
  97. console.log('log out successfully, accessToken deleted');
  98. }
  99. //BELOW CODES RELATE TO "SIGN UP"
  100. //BELOW CODES RELATE TO "SIGN UP"
  101. async sendOtpToSignUpEmail(email: string) {
  102. try {
  103. const response = await axios.post(
  104. `${this.apiUrl}/public/client/customer/otp`,
  105. { email: email },
  106. {
  107. headers: {
  108. 'Content-Type': 'application/json',
  109. Accept: 'application/json'
  110. }
  111. }
  112. );
  113. if (response.status === 200 || response.status === 201) {
  114. console.log('OTP sent successfully');
  115. return true;
  116. } else {
  117. console.error('Failed to send OTP:', response.status);
  118. return false;
  119. }
  120. } catch (error) {
  121. if (axios.isAxiosError(error)) {
  122. console.error('Error sending OTP:', error.response?.data?.message || error.message);
  123. } else {
  124. console.error('An unexpected error occurred while sending OTP:', error);
  125. }
  126. return false;
  127. }
  128. }
  129. async uploadUberImage(imageUri: string, customFileName: string) {
  130. try {
  131. const fileInfo = await FileSystem.getInfoAsync(imageUri);
  132. if (!fileInfo.exists) {
  133. throw new Error('File does not exist');
  134. }
  135. const fileExtension = imageUri.split('.').pop().toLowerCase();
  136. const allowedExtensions = ['jpg', 'jpeg', 'png'];
  137. if (!allowedExtensions.includes(fileExtension)) {
  138. throw new Error('只接受jpg,jpeg,png格式的圖片');
  139. }
  140. const formData = new FormData();
  141. const fileName = customFileName || imageUri.split('/').pop();
  142. formData.append('file', {
  143. uri: imageUri,
  144. name: fileName,
  145. type: `image/${fileExtension}`
  146. } as any);
  147. const accessToken = await SecureStore.getItemAsync('accessToken');
  148. const response = await axios.post(`${this.apiUrl}/clients/customer/image?type=uber`, formData, {
  149. headers: {
  150. accept: '*/*',
  151. 'Content-Type': 'multipart/form-data',
  152. Authorization: `Bearer ${accessToken}`
  153. }
  154. });
  155. console.log('Upload response:', response.data);
  156. return response.data;
  157. } catch (error) {
  158. console.error('Error uploading image:', error);
  159. throw error;
  160. }
  161. }
  162. async verifySignUpOtp(
  163. email: string,
  164. code: string,
  165. setScreen: React.Dispatch<React.SetStateAction<number>>,
  166. setError: React.Dispatch<React.SetStateAction<string>>
  167. ) {
  168. try {
  169. const response = await axios.put(
  170. `${this.apiUrl}/public/client/customer/otp`,
  171. { email, code },
  172. {
  173. headers: {
  174. 'Content-Type': 'application/json',
  175. Accept: 'application/json'
  176. }
  177. }
  178. );
  179. if (response.status === 200) {
  180. console.log('OTP verified successfully');
  181. setScreen((currentScreenNumber: number) => currentScreenNumber + 1);
  182. return true;
  183. } else {
  184. console.error('OTP verification failed:', response.status);
  185. setError('OTP驗證碼錯誤');
  186. return false;
  187. }
  188. } catch (error) {
  189. if (axios.isAxiosError(error)) {
  190. console.error('Error verifying OTP:', error.response?.data?.message || error.message);
  191. setError('發生意外錯誤,請確保您輸入的電子郵件正確,並再次確認您的OTP驗證碼是否正確。');
  192. } else {
  193. console.error('An unexpected error occurred while verifying OTP:', error);
  194. setError('發生意外錯誤,請稍後再試');
  195. }
  196. return false;
  197. }
  198. }
  199. async signUp(data: CustomerData) {
  200. try {
  201. const response = await axios.post(`${this.apiUrl}/public/client/customer`, data, {
  202. headers: {
  203. 'Content-Type': 'application/json',
  204. Accept: 'application/json'
  205. }
  206. });
  207. console.log('Signup response.data:', response.data);
  208. console.log('Signup response.status:', response.status);
  209. if (response.status === 200 || response.status === 201) {
  210. console.log('Signup successful');
  211. return true;
  212. } else {
  213. console.error('Signup failed:', response.status);
  214. return false;
  215. }
  216. } catch (error) {
  217. if (axios.isAxiosError(error)) {
  218. console.error('Error signing up:', error.response?.data?.message || error.message);
  219. } else {
  220. console.error('An unexpected error occurred while signing up:', error);
  221. }
  222. return false;
  223. }
  224. }
  225. //BELOW CODES RELATE TO "FORGET PASSWORD"
  226. //BELOW CODES RELATE TO "FORGET PASSWORD"
  227. async sendForgetPasswordOtp(email: string) {
  228. try {
  229. const response = await axios.post(
  230. `${this.apiUrl}/public/client/customer/pw/otp`,
  231. { email },
  232. {
  233. headers: {
  234. 'Content-Type': 'application/json',
  235. Accept: 'application/json'
  236. }
  237. }
  238. );
  239. if (response.status === 200 || response.status === 201) {
  240. console.log('Forget password OTP sent successfully');
  241. return true;
  242. } else {
  243. console.error('Failed to send forget password OTP:', response.status);
  244. return false;
  245. }
  246. } catch (error) {
  247. if (axios.isAxiosError(error)) {
  248. console.error('Error sending forget password OTP:', error.response?.data?.message || error.message);
  249. } else {
  250. console.error('An unexpected error occurred while sending forget password OTP:', error);
  251. }
  252. return false;
  253. }
  254. }
  255. async getVersion() {
  256. try {
  257. const response = await axios.get(`${this.apiUrl}/public/client/app/version`);
  258. return response.data.data;
  259. } catch (error) {
  260. console.error('Error getting version:', error);
  261. return null;
  262. }
  263. }
  264. async verifyingOtpForgetPassword(
  265. email: string,
  266. otp: string,
  267. setForgetPasswordFormData: React.Dispatch<React.SetStateAction<forgetPasswordFormData>>,
  268. setData: React.Dispatch<React.SetStateAction<string>>
  269. ) {
  270. try {
  271. const res = await axios.put(`${this.apiUrl}/public/client/customer/pw/otp`, {
  272. email: email,
  273. code: otp
  274. });
  275. const data = res.data;
  276. setData(data.msg);
  277. console.log(data.msg);
  278. setForgetPasswordFormData((prevFormData) => ({
  279. ...prevFormData,
  280. otpAuthCompleted: true
  281. }));
  282. return true;
  283. } catch (error) {
  284. console.error('Error', error);
  285. return false;
  286. }
  287. }
  288. async changePassword(confirmedNewPassword: string, data: string) {
  289. try {
  290. const res = await axios.put(
  291. `${this.apiUrl}/clients/customer/pw/forget`,
  292. { newPassword: confirmedNewPassword },
  293. {
  294. headers: {
  295. Authorization: `Bearer ${data}`
  296. }
  297. }
  298. );
  299. return true;
  300. } catch (error) {
  301. if (axios.isAxiosError(error)) {
  302. console.error('Error changing password:', error.response?.data?.message || error.message);
  303. } else {
  304. console.error('An unexpected error occurred:', error);
  305. }
  306. }
  307. }
  308. //BELOW CODES RELATE TO "changing account info (such as gender, name)"
  309. //BELOW CODES RELATE TO "changing account info (such as gender, name)"
  310. async changeName(name: string | null, token: string | null): Promise<boolean> {
  311. try {
  312. const res = await axios.put(
  313. `${this.apiUrl}/clients/customer`,
  314. { nickname: name },
  315. {
  316. headers: {
  317. Authorization: `Bearer ${token}`
  318. }
  319. }
  320. );
  321. console.log('Change Name Successfully!');
  322. return true;
  323. } catch (error) {
  324. if (axios.isAxiosError(error)) {
  325. console.error('Error changing name:', error.response?.data?.message);
  326. } else {
  327. console.error('An unexpected error occurred:', error);
  328. }
  329. return false;
  330. }
  331. }
  332. async changeNotifySessionID(notifySessionID: string | null): Promise<boolean> {
  333. try {
  334. const res = await axios.put(
  335. `${this.apiUrl}/clients/customer`,
  336. { notify_session_id: notifySessionID },
  337. {
  338. headers: {
  339. Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
  340. }
  341. }
  342. );
  343. if (res.data.status == 200) {
  344. console.log('Change notifySessionID Successfully!');
  345. return true;
  346. } else {
  347. console.log('Change notifySessionID Failed!');
  348. return false;
  349. }
  350. } catch (error) {
  351. if (axios.isAxiosError(error)) {
  352. console.error('Error changing name:', error.response?.data?.message);
  353. } else {
  354. console.error('An unexpected error occurred:', error);
  355. }
  356. return false;
  357. }
  358. }
  359. async changePhone(phone: string | null, token: string | null): Promise<boolean> {
  360. try {
  361. const convertPhoneStringToNumber = Number(phone);
  362. const res = await axios.put(
  363. `${this.apiUrl}/clients/customer`,
  364. { phone: convertPhoneStringToNumber },
  365. {
  366. headers: {
  367. Authorization: `Bearer ${token}`
  368. }
  369. }
  370. );
  371. console.log('Change Phone Successfully!');
  372. return true;
  373. } catch (error) {
  374. if (axios.isAxiosError(error)) {
  375. console.error('Error changing phone:', error.response?.data?.message);
  376. } else {
  377. console.error('An unexpected error occurred:', error);
  378. }
  379. return false;
  380. }
  381. }
  382. async changeGender(gender: string | null, token: string | null): Promise<boolean> {
  383. try {
  384. const res = await axios.put(
  385. `${this.apiUrl}/clients/customer`,
  386. { gender: gender },
  387. {
  388. headers: {
  389. Authorization: `Bearer ${token}`
  390. }
  391. }
  392. );
  393. console.log('Change gender Successfully!');
  394. return true;
  395. } catch (error) {
  396. if (axios.isAxiosError(error)) {
  397. console.error('Error changing gender:', error.response?.data?.message);
  398. } else {
  399. console.error('An unexpected error occurred:', error);
  400. }
  401. return false;
  402. }
  403. }
  404. async getUserInfo() {
  405. try {
  406. const response = await axios.get(`${this.apiUrl}/clients/customer`, {
  407. headers: {
  408. Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
  409. }
  410. });
  411. if (response.status === 200 || response.status === 201) {
  412. // console.log(response);
  413. return response;
  414. } else {
  415. console.log('invalid response');
  416. }
  417. } catch (error) {
  418. console.log(error);
  419. }
  420. }
  421. async deleteAccount(): Promise<boolean> {
  422. try {
  423. const accessToken = await SecureStore.getItemAsync('accessToken');
  424. const response = await axios.delete(`${this.apiUrl}/clients/customer`, {
  425. headers: {
  426. Authorization: `Bearer ${accessToken}`
  427. }
  428. });
  429. if (response.status === 200 || response.status === 201) {
  430. console.log('Account deleted successfully');
  431. return true;
  432. } else {
  433. console.error('Failed to delete account:', response.status);
  434. return false;
  435. }
  436. } catch (error) {
  437. if (axios.isAxiosError(error)) {
  438. console.error('Error deleting account:', error.response?.data?.message || error.message);
  439. } else {
  440. console.error('An unexpected error occurred while deleting account:', error);
  441. }
  442. return false;
  443. }
  444. }
  445. async checkPhoneSame(phoneNumber: string) {
  446. try {
  447. console.log('being checkPhoneSame');
  448. const response = await axios.post(
  449. `${this.apiUrl}/clients/customer/binding/sms`,
  450. {
  451. phone: phoneNumber,
  452. type: 3
  453. },
  454. {
  455. headers: {
  456. Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
  457. }
  458. }
  459. );
  460. const token = await SecureStore.getItemAsync('accessToken');
  461. console.log('accessToken', token);
  462. console.log('checkPhoneSame response', response.data);
  463. return response.data;
  464. } catch (error) {
  465. console.log(error);
  466. }
  467. }
  468. async confirmBindingPhone(phoneNumber: string, otp: string, notify_session_id: string) {
  469. try {
  470. const response = await axios.put(
  471. `${this.apiUrl}/public/client/customer/phone/otp`,
  472. {
  473. phone: phoneNumber,
  474. code: otp,
  475. notify_session_id: notify_session_id,
  476. type: 3
  477. },
  478. {
  479. headers: {
  480. 'Content-Type': 'application/json',
  481. Accept: 'application/json'
  482. }
  483. }
  484. );
  485. console.log('confirmBindingPhone response', response.data);
  486. return response.data;
  487. } catch (error) {
  488. console.log(error);
  489. }
  490. }
  491. async verifyPhoneOtp(phoneNumber: string, otp: string, notify_session_id: string) {
  492. try {
  493. const response = await axios.put(
  494. `${this.apiUrl}/public/client/customer/phone/otp`,
  495. {
  496. phone: phoneNumber,
  497. code: otp,
  498. notify_session_id: notify_session_id
  499. },
  500. {
  501. headers: {
  502. 'Content-Type': 'application/json',
  503. Accept: '*/*'
  504. }
  505. }
  506. );
  507. console.log('verifyPhoneOtp response:', response.data);
  508. return response.data;
  509. } catch (error) {
  510. if (axios.isAxiosError(error)) {
  511. console.error('Error verifying phone OTP:', error.response?.data || error.message);
  512. throw error;
  513. } else {
  514. console.error('Unexpected error:', error);
  515. throw new Error('Failed to verify phone OTP');
  516. }
  517. }
  518. }
  519. async sendOtpToSignUpPhone(phone: string) {
  520. try {
  521. const response = await axios.post(`${this.apiUrl}/public/client/customer/phone/sms`, {
  522. phone: phone,
  523. type: 1
  524. });
  525. if (response.status === 200 || response.status === 201) {
  526. console.log('OTP sent successfully -- from api sendOtpToSignUpPhone, response:', response);
  527. return true;
  528. } else {
  529. console.error('Failed to send OTP -- from api sendOtpToSignUpPhone.. response:', response);
  530. return false;
  531. }
  532. } catch (error) {
  533. console.log(error);
  534. }
  535. }
  536. }
  537. export const authenticationService = new AuthenticationService();