authService.tsx 21 KB

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