authService.tsx 12 KB

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