-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathuser-session.ts
82 lines (73 loc) · 2.04 KB
/
user-session.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Interacts with the user_session_controller endpoints
import {
defaultUserSession,
isUserSession,
parseUserSession,
UserSession,
} from "@/types/user-session";
import { AxiosError, AxiosResponse } from "axios";
export const loginUser = async (
email: string,
password: string
): Promise<UserSession> => {
const axios = require("axios");
console.log("email: ", email);
console.log("password: ", password.replace(/./g, "*"));
var userSession: UserSession = defaultUserSession();
var err: string = "";
const data = await axios
.post(
"http://localhost:4000/login",
{
email: email,
password: password,
},
{
withCredentials: true,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
setTimeout: 5000, // 5 seconds before timing out trying to log in with the backend
}
)
.then(function (response: AxiosResponse) {
// handle success
const userSessionData = response.data.data;
if (isUserSession(userSessionData)) {
userSession = parseUserSession(userSessionData);
}
})
.catch(function (error: AxiosError) {
// handle error
console.error(error.response?.status);
if (error.response?.status == 401) {
err = "Login failed: unauthorized";
} else {
err = `Login failed: ${error.message}`;
}
});
if (err) {
console.error(err);
throw err;
}
return userSession;
};
export const logoutUser = async (): Promise<string> => {
const axios = require("axios");
const data = await axios
.get("http://localhost:4000/logout", {
withCredentials: true,
setTimeout: 5000, // 5 seconds before timing out trying to log in with the backend
})
.then(function (response: AxiosResponse) {
// handle success
console.debug(response);
})
.catch(function (error: AxiosError) {
// handle error
const err = `Logout failed: ${error.message}`;
console.error(err);
return err;
});
return "";
};