aboutsummaryrefslogtreecommitdiffstats
path: root/sdnr/wt/odlux/framework/src/handlers/authenticationHandler.ts
blob: 2abe82142b844dabee58d90e5e83e05cc834527a (plain)
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
import { IActionHandler } from '../flux/action';
import { UpdateAuthentication } from '../actions/authentication';

import { User } from '../models/authentication';

export interface IAuthenticationState {
  user?: User;
}

const initialToken = localStorage.getItem("userToken");

const authenticationStateInit: IAuthenticationState = {
  user: initialToken && User.fromString(initialToken) || undefined
};

export const authenticationStateHandler: IActionHandler<IAuthenticationState> = (state = authenticationStateInit, action) => {
  if (action instanceof UpdateAuthentication) {

    const user = action.bearerToken && new User(action.bearerToken) || undefined;
    if (user) {
      localStorage.setItem("userToken", user.toString());
    } else {
      localStorage.removeItem("userToken");
    }

    state = {
      ...state,
      user
    };
  }

  return state;
};