This repository has been archived by the owner on Jan 20, 2024. It is now read-only.
/
auth.ts
90 lines (82 loc) · 2.4 KB
/
auth.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
83
84
85
86
87
88
89
90
import req from "../axios";
import { AxiosResponse } from "axios";
import { Dispatch } from "redux";
import Actions from "./list";
import { AuthAction } from "../typings/actions";
import { serializeAuthData } from "../helpers/api";
import { SuccessAction, FailAction } from "../typings/api";
const tokenHeader = "Authorization";
const tokenPrefix = "Bearer";
/**
* Redux action creator. Performs an HTTP request, if it succeeds, copies
* the token from the response.
* @param user User name
* @param pass Password in plain text
*/
export const login = (user: string, pass: string) => (dispatch: Dispatch) => {
req.post("/login", serializeAuthData(user, pass)).then(
(res: AxiosResponse) => {
setToken(res.data.token);
dispatch({
type: Actions.LoginSuccess,
username: user,
token: res.data.token,
} as AuthAction);
},
() => {
dispatch({
type: Actions.LoginFailed,
} as AuthAction);
}
);
};
/**
* Redux action creator. Performs an HTTP request, if it succeeds, clears
* the token from the cache.
*/
export const logout = () => (dispatch: Dispatch) => {
req.post("/logout", {}).then(() => {
resetToken();
dispatch({
type: Actions.LoggedOut,
} as AuthAction);
});
};
/** Redux action creator. Performs a logout locally without making an API call.
* */
export const localLogout = () => {
resetToken();
return {
type: Actions.LoggedOut,
} as AuthAction;
};
/**
* Signup function. Performs an HTTP POST request, calls the provided functions
* on success/fail.
* @param user Username
* @param pass Password in plain text
* @param sh Function to be called on success
* @param fh Function to be called on fail
*/
export const signup = (
user: string,
pass: string,
sh: SuccessAction,
fh: FailAction
) => {
req.post("/signup", serializeAuthData(user, pass)).then(sh, fh);
};
/**
* Sets an auth token in the app's Axios instance to be used in every request
* from now on.
* @param token Auth token in plain text.
*/
export const setToken = (token: string) => {
req.defaults.headers.common[tokenHeader] = `${tokenPrefix} ${token}`;
};
/**
* Resets the auth token set in app's Axios instance.
*/
export const resetToken = () => {
delete req.defaults.headers.common[tokenHeader];
};