UNPKG

2.32 kBTypeScriptView Raw
1
2declare var require: any;
3import * as React from 'react';
4import {IC_USER_ID, IC_WEB_TOKEN} from "../authentication/auth-middleware";
5
6import ExecutionEnvironment from 'exenv';
7import Cookies from 'universal-cookie';
8
9import {getBasename} from "../libs/iso-libs";
10
11
12// create empty context as default
13const UserContext = React.createContext({});
14
15
16
17export function getUserId(request) {
18 if (request) {
19 return new Cookies(request.headers.cookie).get(IC_USER_ID)
20 } else if (ExecutionEnvironment.canUseDOM) {
21 return new Cookies().get(IC_USER_ID)
22 }
23
24 return undefined;
25
26}
27
28
29export function getWebToken(request) {
30 if (request) {
31 return new Cookies(request.headers.cookie).get(IC_WEB_TOKEN)
32 } else if (ExecutionEnvironment.canUseDOM) {
33 return new Cookies().get(IC_WEB_TOKEN)
34 }
35
36 return undefined;
37
38}
39
40interface IAttachUserProps {
41 request: any // passed by `withRequest`
42}
43/**
44 * This HOC attaches the User-Id to a webapp, may be undefined!
45 */
46const AttachUser: React.SFC<IAttachUserProps> = (props) => {
47
48 //console.log("attaching user: ", getUserId(undefined));
49
50 return <UserContext.Provider
51 value={{
52 userId: ExecutionEnvironment.canUseDOM ?
53 new Cookies().get(IC_USER_ID) :
54 new Cookies(props.request.headers.cookie).get(IC_USER_ID)
55 }}>{props.children}</UserContext.Provider>
56
57};
58
59/**
60 * @param Component
61 * @returns {function(any): any}
62 */
63export function withUser(Component) {
64 return function WrapperComponent(props) {
65 return (
66 <UserContext.Consumer>
67 {(context: any) => {
68
69 return <Component
70 {...props}
71 userId={context.userId}
72 />
73 }}
74 </UserContext.Consumer>
75 );
76 };
77}
78
79export function userLogout(pathUrl: string | undefined ) {
80 const path = require('path');
81
82 const cookies = new Cookies();
83 cookies.remove(IC_USER_ID, { path: '/' });
84 cookies.remove(IC_WEB_TOKEN, { path: '/' });
85
86 if (pathUrl !== undefined) {
87 window.location.href = path.join(getBasename(), pathUrl);
88 } else {
89 window.location.reload()
90 }
91
92}
93
94export default require("infrastructure-components").withRequest(AttachUser);
\No newline at end of file