authService.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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. //BELOW CODES RELATE TO "changing account info (such as gender, name)"
  298. //BELOW CODES RELATE TO "changing account info (such as gender, name)"
  299. async changeName(name: string | null, token: string | null): Promise<boolean> {
  300. try {
  301. const res = await axios.put(
  302. `${this.apiUrl}/clients/customer`,
  303. { nickname: name },
  304. {
  305. headers: {
  306. Authorization: `Bearer ${token}`
  307. }
  308. }
  309. );
  310. console.log('Change Name Successfully!');
  311. return true;
  312. } catch (error) {
  313. if (axios.isAxiosError(error)) {
  314. console.error('Error changing name:', error.response?.data?.message);
  315. } else {
  316. console.error('An unexpected error occurred:', error);
  317. }
  318. return false;
  319. }
  320. }
  321. async changeNotifySessionID(notifySessionID: string | null): Promise<boolean> {
  322. try {
  323. const res = await axios.put(
  324. `${this.apiUrl}/clients/customer`,
  325. { notify_session_id: notifySessionID },
  326. {
  327. headers: {
  328. Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
  329. }
  330. }
  331. );
  332. if (res.data.status == 200) {
  333. console.log('Change notifySessionID Successfully!');
  334. return true;
  335. } else {
  336. console.log('Change notifySessionID Failed!');
  337. return false;
  338. }
  339. } catch (error) {
  340. if (axios.isAxiosError(error)) {
  341. console.error('Error changing name:', error.response?.data?.message);
  342. } else {
  343. console.error('An unexpected error occurred:', error);
  344. }
  345. return false;
  346. }
  347. }
  348. async changePhone(phone: string | null, token: string | null): Promise<boolean> {
  349. try {
  350. const convertPhoneStringToNumber = Number(phone);
  351. const res = await axios.put(
  352. `${this.apiUrl}/clients/customer`,
  353. { phone: convertPhoneStringToNumber },
  354. {
  355. headers: {
  356. Authorization: `Bearer ${token}`
  357. }
  358. }
  359. );
  360. return true;
  361. } catch (error) {
  362. if (axios.isAxiosError(error)) {
  363. console.error('Error changing phone:', error.response?.data?.message);
  364. } else {
  365. console.error('An unexpected error occurred:', error);
  366. }
  367. return false;
  368. }
  369. }
  370. async changeGender(gender: string | null, token: string | null): Promise<boolean> {
  371. try {
  372. const res = await axios.put(
  373. `${this.apiUrl}/clients/customer`,
  374. { gender: gender },
  375. {
  376. headers: {
  377. Authorization: `Bearer ${token}`
  378. }
  379. }
  380. );
  381. console.log('Change gender Successfully!');
  382. return true;
  383. } catch (error) {
  384. if (axios.isAxiosError(error)) {
  385. console.error('Error changing gender:', error.response?.data?.message);
  386. } else {
  387. console.error('An unexpected error occurred:', error);
  388. }
  389. return false;
  390. }
  391. }
  392. async getUserInfo() {
  393. try {
  394. const response = await axios.get(`${this.apiUrl}/clients/customer`, {
  395. headers: {
  396. Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
  397. }
  398. });
  399. if (response.status === 200 || response.status === 201) {
  400. return response;
  401. } else {
  402. console.log('invalid response');
  403. }
  404. } catch (error) {
  405. console.log(error);
  406. }
  407. }
  408. async deleteAccount(): Promise<boolean> {
  409. try {
  410. const accessToken = await SecureStore.getItemAsync('accessToken');
  411. const response = await axios.delete(`${this.apiUrl}/clients/customer`, {
  412. headers: {
  413. Authorization: `Bearer ${accessToken}`
  414. }
  415. });
  416. if (response.status === 200 || response.status === 201) {
  417. console.log('Account deleted successfully');
  418. return true;
  419. } else {
  420. console.error('Failed to delete account:', response.status);
  421. return false;
  422. }
  423. } catch (error) {
  424. if (axios.isAxiosError(error)) {
  425. console.error('Error deleting account:', error.response?.data?.message || error.message);
  426. } else {
  427. console.error('An unexpected error occurred while deleting account:', error);
  428. }
  429. return false;
  430. }
  431. }
  432. async checkPhoneSame(phoneNumber: string) {
  433. try {
  434. console.log('being checkPhoneSame');
  435. const response = await axios.post(
  436. `${this.apiUrl}/clients/customer/binding/sms`,
  437. {
  438. phone: phoneNumber,
  439. type: 3
  440. },
  441. {
  442. headers: {
  443. Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
  444. }
  445. }
  446. );
  447. const token = await SecureStore.getItemAsync('accessToken');
  448. console.log('accessToken', token);
  449. console.log('checkPhoneSame response', response.data);
  450. return response.data;
  451. } catch (error) {
  452. console.log(error);
  453. }
  454. }
  455. async confirmBindingPhone(phoneNumber: string, otp: string, notify_session_id: string) {
  456. try {
  457. const response = await axios.put(
  458. `${this.apiUrl}/public/client/customer/phone/otp`,
  459. {
  460. phone: phoneNumber,
  461. code: otp,
  462. notify_session_id: notify_session_id,
  463. type: 3
  464. },
  465. {
  466. headers: {
  467. 'Content-Type': 'application/json',
  468. Accept: 'application/json'
  469. }
  470. }
  471. );
  472. console.log('confirmBindingPhone response', response.data);
  473. return response.data;
  474. } catch (error) {
  475. console.log(error);
  476. }
  477. }
  478. async verifyPhoneOtp(phoneNumber: string, otp: string, notify_session_id: string) {
  479. try {
  480. const response = await axios.put(
  481. `${this.apiUrl}/public/client/customer/phone/otp`,
  482. {
  483. phone: phoneNumber,
  484. code: otp,
  485. notify_session_id: notify_session_id
  486. },
  487. {
  488. headers: {
  489. 'Content-Type': 'application/json',
  490. Accept: '*/*'
  491. }
  492. }
  493. );
  494. console.log('verifyPhoneOtp response:', response.data);
  495. return response.data;
  496. } catch (error) {
  497. if (axios.isAxiosError(error)) {
  498. console.error('Error verifying phone OTP:', error.response?.data || error.message);
  499. throw error;
  500. } else {
  501. console.error('Unexpected error:', error);
  502. throw new Error('Failed to verify phone OTP');
  503. }
  504. }
  505. }
  506. async sendOtpToSignUpPhone(phone: string) {
  507. try {
  508. const response = await axios.post(`${this.apiUrl}/public/client/customer/phone/sms`, {
  509. phone: phone,
  510. type: 1
  511. });
  512. if (response.status === 200 || response.status === 201) {
  513. console.log('OTP sent successfully -- from api sendOtpToSignUpPhone, response:', response);
  514. return true;
  515. } else {
  516. console.error('Failed to send OTP -- from api sendOtpToSignUpPhone.. response:', response);
  517. return false;
  518. }
  519. } catch (error) {
  520. console.log(error);
  521. }
  522. }
  523. }
  524. export const authenticationService = new AuthenticationService();