2abe82142b844dabee58d90e5e83e05cc834527a
[ccsdk/features.git] / sdnr / wt / odlux / framework / src / handlers / authenticationHandler.ts
1 import { IActionHandler } from '../flux/action';
2 import { UpdateAuthentication } from '../actions/authentication';
3
4 import { User } from '../models/authentication';
5
6 export interface IAuthenticationState {
7   user?: User;
8 }
9
10 const initialToken = localStorage.getItem("userToken");
11
12 const authenticationStateInit: IAuthenticationState = {
13   user: initialToken && User.fromString(initialToken) || undefined
14 };
15
16 export const authenticationStateHandler: IActionHandler<IAuthenticationState> = (state = authenticationStateInit, action) => {
17   if (action instanceof UpdateAuthentication) {
18
19     const user = action.bearerToken && new User(action.bearerToken) || undefined;
20     if (user) {
21       localStorage.setItem("userToken", user.toString());
22     } else {
23       localStorage.removeItem("userToken");
24     }
25
26     state = {
27       ...state,
28       user
29     };
30   }
31
32   return state;
33 };