authService.tsx 20 KB

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