authService.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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 login(username: string, password: string) {
  17. try {
  18. const response = await axios.post(
  19. // `${this.apiUrl}/public/client/customer/sign-in`,
  20. `${this.apiUrl}/public/client/customer/sign-in`,
  21. {
  22. email: username,
  23. password: password
  24. },
  25. {
  26. headers: {
  27. 'Content-Type': 'application/json',
  28. Accept: 'application/json'
  29. }
  30. }
  31. );
  32. if (response.status === 201) {
  33. const token = response.data.accessToken;
  34. await SecureStore.setItemAsync('accessToken', token);
  35. console.log('Login successful!');
  36. return true;
  37. } else {
  38. console.error('Login failed:', response.status);
  39. return false;
  40. }
  41. } catch (error) {
  42. if (axios.isAxiosError(error)) {
  43. console.error('Login error:', error.response?.data?.message || error.message);
  44. } else {
  45. console.error('An unexpected error occurred:', error);
  46. }
  47. return false;
  48. }
  49. }
  50. async logout() {
  51. await SecureStore.deleteItemAsync('accessToken');
  52. console.log('log out successfully, accessToken deleted');
  53. }
  54. //BELOW CODES RELATE TO "SIGN UP"
  55. //BELOW CODES RELATE TO "SIGN UP"
  56. async sendOtpToSignUpEmail(email: string) {
  57. try {
  58. const response = await axios.post(
  59. `${this.apiUrl}/public/client/customer/otp`,
  60. { email: email },
  61. {
  62. headers: {
  63. 'Content-Type': 'application/json',
  64. Accept: 'application/json'
  65. }
  66. }
  67. );
  68. if (response.status === 200 || response.status === 201) {
  69. console.log('OTP sent successfully');
  70. return true;
  71. } else {
  72. console.error('Failed to send OTP:', response.status);
  73. return false;
  74. }
  75. } catch (error) {
  76. if (axios.isAxiosError(error)) {
  77. console.error('Error sending OTP:', error.response?.data?.message || error.message);
  78. } else {
  79. console.error('An unexpected error occurred while sending OTP:', error);
  80. }
  81. return false;
  82. }
  83. }
  84. async uploadUberImage(imageUri: string, customFileName: string) {
  85. try {
  86. const fileInfo = await FileSystem.getInfoAsync(imageUri);
  87. if (!fileInfo.exists) {
  88. throw new Error('File does not exist');
  89. }
  90. const fileExtension = imageUri.split('.').pop().toLowerCase();
  91. const allowedExtensions = ['jpg', 'jpeg', 'png'];
  92. if (!allowedExtensions.includes(fileExtension)) {
  93. throw new Error('只接受jpg,jpeg,png格式的圖片');
  94. }
  95. const formData = new FormData();
  96. const fileName = customFileName || imageUri.split('/').pop();
  97. formData.append('file', {
  98. uri: imageUri,
  99. name: fileName,
  100. type: `image/${fileExtension}`
  101. } as any);
  102. const accessToken = await SecureStore.getItemAsync('accessToken');
  103. const response = await axios.post(`${this.apiUrl}/clients/customer/image?type=uber`, formData, {
  104. headers: {
  105. accept: '*/*',
  106. 'Content-Type': 'multipart/form-data',
  107. Authorization: `Bearer ${accessToken}`
  108. }
  109. });
  110. console.log('Upload response:', response.data);
  111. return response.data;
  112. } catch (error) {
  113. console.error('Error uploading image:', error);
  114. throw error;
  115. }
  116. }
  117. async verifySignUpOtp(
  118. email: string,
  119. code: string,
  120. setScreen: React.Dispatch<React.SetStateAction<number>>,
  121. setError: React.Dispatch<React.SetStateAction<string>>
  122. ) {
  123. try {
  124. const response = await axios.put(
  125. `${this.apiUrl}/public/client/customer/otp`,
  126. { email, code },
  127. {
  128. headers: {
  129. 'Content-Type': 'application/json',
  130. Accept: 'application/json'
  131. }
  132. }
  133. );
  134. if (response.status === 200) {
  135. console.log('OTP verified successfully');
  136. setScreen((currentScreenNumber: number) => currentScreenNumber + 1);
  137. return true;
  138. } else {
  139. console.error('OTP verification failed:', response.status);
  140. setError('OTP驗證碼錯誤');
  141. return false;
  142. }
  143. } catch (error) {
  144. if (axios.isAxiosError(error)) {
  145. console.error('Error verifying OTP:', error.response?.data?.message || error.message);
  146. setError('發生意外錯誤,請確保您輸入的電子郵件正確,並再次確認您的OTP驗證碼是否正確。');
  147. } else {
  148. console.error('An unexpected error occurred while verifying OTP:', error);
  149. setError('發生意外錯誤,請稍後再試');
  150. }
  151. return false;
  152. }
  153. }
  154. async signUp(data: CustomerData) {
  155. try {
  156. const response = await axios.post(`${this.apiUrl}/public/client/customer`, data, {
  157. headers: {
  158. 'Content-Type': 'application/json',
  159. Accept: 'application/json'
  160. }
  161. });
  162. console.log('Signup response.data:', response.data);
  163. console.log('Signup response.status:', response.status);
  164. if (response.status === 200 || response.status === 201) {
  165. console.log('Signup successful');
  166. return true;
  167. } else {
  168. console.error('Signup failed:', response.status);
  169. return false;
  170. }
  171. } catch (error) {
  172. if (axios.isAxiosError(error)) {
  173. console.error('Error signing up:', error.response?.data?.message || error.message);
  174. } else {
  175. console.error('An unexpected error occurred while signing up:', error);
  176. }
  177. return false;
  178. }
  179. }
  180. //BELOW CODES RELATE TO "FORGET PASSWORD"
  181. //BELOW CODES RELATE TO "FORGET PASSWORD"
  182. async sendForgetPasswordOtp(email: string) {
  183. try {
  184. const response = await axios.post(
  185. `${this.apiUrl}/public/client/customer/pw/otp`,
  186. { email },
  187. {
  188. headers: {
  189. 'Content-Type': 'application/json',
  190. Accept: 'application/json'
  191. }
  192. }
  193. );
  194. if (response.status === 200 || response.status === 201) {
  195. console.log('Forget password OTP sent successfully');
  196. return true;
  197. } else {
  198. console.error('Failed to send forget password OTP:', response.status);
  199. return false;
  200. }
  201. } catch (error) {
  202. if (axios.isAxiosError(error)) {
  203. console.error('Error sending forget password OTP:', error.response?.data?.message || error.message);
  204. } else {
  205. console.error('An unexpected error occurred while sending forget password OTP:', error);
  206. }
  207. return false;
  208. }
  209. }
  210. async getVersion() {
  211. try {
  212. const response = await axios.get(`${this.apiUrl}/public/client/app/version`);
  213. return response.data.data.version;
  214. } catch (error) {
  215. console.error('Error getting version:', error);
  216. return null;
  217. }
  218. }
  219. async verifyingOtpForgetPassword(
  220. email: string,
  221. otp: string,
  222. setForgetPasswordFormData: React.Dispatch<React.SetStateAction<forgetPasswordFormData>>,
  223. setData: React.Dispatch<React.SetStateAction<string>>
  224. ) {
  225. try {
  226. const res = await axios.put(`${this.apiUrl}/public/client/customer/pw/otp`, {
  227. email: email,
  228. code: otp
  229. });
  230. const data = res.data;
  231. setData(data.msg);
  232. console.log(data.msg);
  233. setForgetPasswordFormData((prevFormData) => ({
  234. ...prevFormData,
  235. otpAuthCompleted: true
  236. }));
  237. return true;
  238. } catch (error) {
  239. console.error('Error', error);
  240. return false;
  241. }
  242. }
  243. async changePassword(confirmedNewPassword: string, data: string) {
  244. try {
  245. const res = await axios.put(
  246. `${this.apiUrl}/clients/customer/pw/forget`,
  247. { newPassword: confirmedNewPassword },
  248. {
  249. headers: {
  250. Authorization: `Bearer ${data}`
  251. }
  252. }
  253. );
  254. return true;
  255. } catch (error) {
  256. if (axios.isAxiosError(error)) {
  257. console.error('Error changing password:', error.response?.data?.message || error.message);
  258. } else {
  259. console.error('An unexpected error occurred:', error);
  260. }
  261. }
  262. }
  263. //BELOW CODES RELATE TO "changing account info (such as gender, name)"
  264. //BELOW CODES RELATE TO "changing account info (such as gender, name)"
  265. async changeName(name: string | null, token: string | null): Promise<boolean> {
  266. try {
  267. const res = await axios.put(
  268. `${this.apiUrl}/clients/customer`,
  269. { nickname: name },
  270. {
  271. headers: {
  272. Authorization: `Bearer ${token}`
  273. }
  274. }
  275. );
  276. console.log('Change Name Successfully!');
  277. return true;
  278. } catch (error) {
  279. if (axios.isAxiosError(error)) {
  280. console.error('Error changing name:', error.response?.data?.message);
  281. } else {
  282. console.error('An unexpected error occurred:', error);
  283. }
  284. return false;
  285. }
  286. }
  287. async changePhone(phone: string | null, token: string | null): Promise<boolean> {
  288. try {
  289. const convertPhoneStringToNumber = Number(phone);
  290. const res = await axios.put(
  291. `${this.apiUrl}/clients/customer`,
  292. { phone: convertPhoneStringToNumber },
  293. {
  294. headers: {
  295. Authorization: `Bearer ${token}`
  296. }
  297. }
  298. );
  299. console.log('Change Phone Successfully!');
  300. return true;
  301. } catch (error) {
  302. if (axios.isAxiosError(error)) {
  303. console.error('Error changing phone:', error.response?.data?.message);
  304. } else {
  305. console.error('An unexpected error occurred:', error);
  306. }
  307. return false;
  308. }
  309. }
  310. async changeGender(gender: string | null, token: string | null): Promise<boolean> {
  311. try {
  312. const res = await axios.put(
  313. `${this.apiUrl}/clients/customer`,
  314. { gender: gender },
  315. {
  316. headers: {
  317. Authorization: `Bearer ${token}`
  318. }
  319. }
  320. );
  321. console.log('Change gender Successfully!');
  322. return true;
  323. } catch (error) {
  324. if (axios.isAxiosError(error)) {
  325. console.error('Error changing gender:', error.response?.data?.message);
  326. } else {
  327. console.error('An unexpected error occurred:', error);
  328. }
  329. return false;
  330. }
  331. }
  332. async getUserInfo() {
  333. try {
  334. const response = await axios.get(`${this.apiUrl}/clients/customer`, {
  335. headers: {
  336. Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
  337. }
  338. });
  339. if (response.status === 200 || response.status === 201) {
  340. // console.log(response);
  341. return response;
  342. } else {
  343. console.log('invalid response');
  344. }
  345. } catch (error) {
  346. console.log(error);
  347. }
  348. }
  349. async deleteAccount(): Promise<boolean> {
  350. try {
  351. const accessToken = await SecureStore.getItemAsync('accessToken');
  352. const response = await axios.delete(`${this.apiUrl}/clients/customer`, {
  353. headers: {
  354. Authorization: `Bearer ${accessToken}`
  355. }
  356. });
  357. if (response.status === 200 || response.status === 201) {
  358. console.log('Account deleted successfully');
  359. return true;
  360. } else {
  361. console.error('Failed to delete account:', response.status);
  362. return false;
  363. }
  364. } catch (error) {
  365. if (axios.isAxiosError(error)) {
  366. console.error('Error deleting account:', error.response?.data?.message || error.message);
  367. } else {
  368. console.error('An unexpected error occurred while deleting account:', error);
  369. }
  370. return false;
  371. }
  372. }
  373. }
  374. export const authenticationService = new AuthenticationService();