1 |
|
2 | declare var require: any;
|
3 | import * as React from 'react';
|
4 | import {IC_USER_ID, IC_WEB_TOKEN} from "../authentication/auth-middleware";
|
5 |
|
6 | import ExecutionEnvironment from 'exenv';
|
7 | import Cookies from 'universal-cookie';
|
8 |
|
9 | import {getBasename} from "../libs/iso-libs";
|
10 |
|
11 |
|
12 |
|
13 | const UserContext = React.createContext({});
|
14 |
|
15 |
|
16 |
|
17 | export 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 |
|
29 | export 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 |
|
40 | interface IAttachUserProps {
|
41 | request: any
|
42 | }
|
43 |
|
44 |
|
45 |
|
46 | const AttachUser: React.SFC<IAttachUserProps> = (props) => {
|
47 |
|
48 |
|
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 |
|
61 |
|
62 |
|
63 | export 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 |
|
79 | export 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 |
|
94 | export default require("infrastructure-components").withRequest(AttachUser); |
\ | No newline at end of file |