authService.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. if (response.status === 200 || response.status === 201) {
  163. console.log('Signup successful');
  164. return true;
  165. } else {
  166. console.error('Signup failed:', response.status);
  167. return false;
  168. }
  169. } catch (error) {
  170. if (axios.isAxiosError(error)) {
  171. console.error('Error signing up:', error.response?.data?.message || error.message);
  172. } else {
  173. console.error('An unexpected error occurred while signing up:', error);
  174. }
  175. return false;
  176. }
  177. }
  178. //BELOW CODES RELATE TO "FORGET PASSWORD"
  179. //BELOW CODES RELATE TO "FORGET PASSWORD"
  180. async sendForgetPasswordOtp(email: string) {
  181. try {
  182. const response = await axios.post(
  183. `${this.apiUrl}/public/client/customer/pw/otp`,
  184. { email },
  185. {
  186. headers: {
  187. 'Content-Type': 'application/json',
  188. Accept: 'application/json'
  189. }
  190. }
  191. );
  192. if (response.status === 200 || response.status === 201) {
  193. console.log('Forget password OTP sent successfully');
  194. return true;
  195. } else {
  196. console.error('Failed to send forget password OTP:', response.status);
  197. return false;
  198. }
  199. } catch (error) {
  200. if (axios.isAxiosError(error)) {
  201. console.error('Error sending forget password OTP:', error.response?.data?.message || error.message);
  202. } else {
  203. console.error('An unexpected error occurred while sending forget password OTP:', error);
  204. }
  205. return false;
  206. }
  207. }
  208. async verifyingOtpForgetPassword(
  209. email: string,
  210. otp: string,
  211. setForgetPasswordFormData: React.Dispatch<React.SetStateAction<forgetPasswordFormData>>,
  212. setData: React.Dispatch<React.SetStateAction<string>>
  213. ) {
  214. try {
  215. const res = await axios.put(`${this.apiUrl}/public/client/customer/pw/otp`, {
  216. email: email,
  217. code: otp
  218. });
  219. const data = res.data;
  220. setData(data.msg);
  221. console.log(data.msg);
  222. setForgetPasswordFormData((prevFormData) => ({
  223. ...prevFormData,
  224. otpAuthCompleted: true
  225. }));
  226. return true;
  227. } catch (error) {
  228. console.error('Error', error);
  229. return false;
  230. }
  231. }
  232. async changePassword(confirmedNewPassword: string, data: string) {
  233. try {
  234. const res = await axios.put(
  235. `${this.apiUrl}/clients/customer/pw/forget`,
  236. { newPassword: confirmedNewPassword },
  237. {
  238. headers: {
  239. Authorization: `Bearer ${data}`
  240. }
  241. }
  242. );
  243. return true;
  244. } catch (error) {
  245. if (axios.isAxiosError(error)) {
  246. console.error('Error changing password:', error.response?.data?.message || error.message);
  247. } else {
  248. console.error('An unexpected error occurred:', error);
  249. }
  250. }
  251. }
  252. //BELOW CODES RELATE TO "changing account info (such as gender, name)"
  253. //BELOW CODES RELATE TO "changing account info (such as gender, name)"
  254. async changeName(name: string | null, token: string | null): Promise<boolean> {
  255. try {
  256. const res = await axios.put(
  257. `${this.apiUrl}/clients/customer`,
  258. { nickname: name },
  259. {
  260. headers: {
  261. Authorization: `Bearer ${token}`
  262. }
  263. }
  264. );
  265. console.log('Change Name Successfully!');
  266. return true;
  267. } catch (error) {
  268. if (axios.isAxiosError(error)) {
  269. console.error('Error changing name:', error.response?.data?.message);
  270. } else {
  271. console.error('An unexpected error occurred:', error);
  272. }
  273. return false;
  274. }
  275. }
  276. async changePhone(phone: string | null, token: string | null): Promise<boolean> {
  277. try {
  278. const convertPhoneStringToNumber = Number(phone);
  279. const res = await axios.put(
  280. `${this.apiUrl}/clients/customer`,
  281. { phone: convertPhoneStringToNumber },
  282. {
  283. headers: {
  284. Authorization: `Bearer ${token}`
  285. }
  286. }
  287. );
  288. console.log('Change Phone Successfully!');
  289. return true;
  290. } catch (error) {
  291. if (axios.isAxiosError(error)) {
  292. console.error('Error changing phone:', error.response?.data?.message);
  293. } else {
  294. console.error('An unexpected error occurred:', error);
  295. }
  296. return false;
  297. }
  298. }
  299. async changeGender(gender: string | null, token: string | null): Promise<boolean> {
  300. try {
  301. const res = await axios.put(
  302. `${this.apiUrl}/clients/customer`,
  303. { gender: gender },
  304. {
  305. headers: {
  306. Authorization: `Bearer ${token}`
  307. }
  308. }
  309. );
  310. console.log('Change gender Successfully!');
  311. return true;
  312. } catch (error) {
  313. if (axios.isAxiosError(error)) {
  314. console.error('Error changing gender:', error.response?.data?.message);
  315. } else {
  316. console.error('An unexpected error occurred:', error);
  317. }
  318. return false;
  319. }
  320. }
  321. async getUserInfo() {
  322. try {
  323. const response = await axios.get(`${this.apiUrl}/clients/customer`, {
  324. headers: {
  325. Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
  326. }
  327. });
  328. if (response.status === 200 || response.status === 201) {
  329. // console.log(response);
  330. return response;
  331. } else {
  332. console.log('invalid response');
  333. }
  334. } catch (error) {
  335. console.log(error);
  336. }
  337. }
  338. }
  339. export const authenticationService = new AuthenticationService();