Selaa lähdekoodia

Login context

wilitp 4 vuotta sitten
vanhempi
commit
6031cd30bc

+ 22 - 0
app/src/api/auth.ts

@@ -0,0 +1,22 @@
+export function login(username: string, password: string) {
+  const headers = new Headers();
+  headers.append("Content-Type", "application/x-www-form-urlencoded");
+  headers.append("Access-Control-Allow-Origin", "*");
+  headers.append(
+    "Cookie",
+    "csrftoken=H9Vl6eq4nSBWr9UjJ5KfoH1L0HSYV745xy65G9e5FumSt9eZo2ODpmRua9v4N8Si"
+  );
+
+  const urlencoded = new URLSearchParams();
+  urlencoded.append("username", username);
+  urlencoded.append("password", password);
+
+  const requestOptions: RequestInit = {
+    method: "POST",
+    headers: headers,
+    body: urlencoded,
+    mode: "cors",
+    redirect: "follow",
+  };
+  return fetch(`http://localhost:8000/v1/login`, requestOptions);
+}

+ 1 - 0
app/src/api/index.ts

@@ -0,0 +1 @@
+export * from "./auth";

+ 2 - 1
app/src/context/auth/actionTypes.ts

@@ -8,6 +8,7 @@ export const LOGOUT = "LOGOUT";
 export type ActionType =
   | "LOGIN_REQUEST"
   | "LOGIN_SUCCESS"
+  | "LOGIN_FAILURE_DISMISS"
   | "LOGIN_FAILURE"
   | "LOGOUT";
 
@@ -15,5 +16,5 @@ export type Action = {
   type: ActionType;
   username?: string;
   userToken?: string;
-  error?: number;
+  error?: string;
 };

+ 33 - 12
app/src/context/auth/actions.ts

@@ -1,31 +1,52 @@
 import { Dispatch } from "react";
 import { Action } from "./actionTypes";
+import { login as apiLoginRequest } from "../../api";
 
-export const loginRequest = (username: string, password: string) => async (
+export const login = (username: string, password: string) => async (
   dispatch: Dispatch<Action>
 ) => {
-  // Request
-  const res = await fetch(`${process.env.BACKEND_BASE_URL}/login`, {});
+  // Loading login state
+  dispatch(loginRequest());
 
-  // TODO: get user token
-  const userToken = "";
+  const errors = {
+    400: "Credenciales inválidas",
+  };
+
+  try {
+    const res = await apiLoginRequest(username, password);
+    if (!res.ok) {
+      const msg = (errors as any)[res.status];
+      dispatch(loginFailure(msg ?? "Request inválida"));
+      const text = await res.text();
+      console.log("Error en el login", text);
+      return;
+    }
+
+    const body = await res.json();
+
+    const userToken = body.token;
 
-  // Handle request
-  if (res.ok) {
     dispatch(loginSuccess(username, userToken));
-    return;
+  } catch (e) {
+    console.error(e);
+    dispatch(loginFailure("Error de conexión"));
   }
-
-  const code = res.status;
-  dispatch(loginFailure(code));
 };
 
+export const loginRequest = (): Action => ({
+  type: "LOGIN_REQUEST",
+});
+
 export const loginSuccess = (username: string, userToken: string): Action => ({
   type: "LOGIN_SUCCESS",
   username,
   userToken,
 });
-export const loginFailure = (code: number): Action => ({
+export const loginFailure = (code: string): Action => ({
   type: "LOGIN_FAILURE",
   error: code,
 });
+
+export const failureDismiss = (): Action => ({
+  type: "LOGIN_FAILURE_DISMISS",
+});

+ 7 - 2
app/src/context/auth/reducer.ts

@@ -1,5 +1,5 @@
 import { Reducer } from "react";
-import { Action } from "./actionTypes";
+import { Action, ActionType } from "./actionTypes";
 
 export const defaultState = {
   loggingIn: false,
@@ -13,7 +13,7 @@ export type State = {
   loggedIn?: Boolean;
   userToken?: string;
   username?: string;
-  error?: number;
+  error?: string;
 };
 
 const reducer: Reducer<State, Action> = (state, action) => {
@@ -32,6 +32,11 @@ const reducer: Reducer<State, Action> = (state, action) => {
         username: action.username,
         userToken: action.userToken,
       };
+    case "LOGIN_FAILURE_DISMISS":
+      return {
+        ...state,
+        error: undefined,
+      };
     case "LOGIN_FAILURE":
       return {
         error: action.error,