Change password requires all fields to be input before checking equivalence.
[osm/UI.git] / skyquake / plugins / user_management / src / userProfile / userProfile.jsx
1 /*
2  * STANDARD_RIFT_IO_COPYRIGHT
3  */
4
5 import React from 'react';
6 import ReactDOM from 'react-dom';
7 import AppHeader from 'widgets/header/header.jsx';
8 import UserProfileStore from './userProfileStore.js';
9 import SkyquakeComponent from 'widgets/skyquake_container/skyquakeComponent.jsx';
10 import 'style/layout.scss';
11 import '../dashboard/userMgmt.scss';
12 import {Panel, PanelWrapper} from 'widgets/panel/panel';
13
14
15 import TextInput from 'widgets/form_controls/textInput.jsx';
16 import Input from 'widgets/form_controls/input.jsx';
17 import Button, {ButtonGroup} from 'widgets/button/sq-button.jsx';
18 import SelectOption from 'widgets/form_controls/selectOption.jsx';
19 import 'widgets/form_controls/formControls.scss';
20 import imgAdd from '../../node_modules/open-iconic/svg/plus.svg'
21 import imgRemove from '../../node_modules/open-iconic/svg/trash.svg';
22
23 class UserProfileDashboard extends React.Component {
24     constructor(props) {
25         super(props);
26         this.Store = this.props.flux.stores.hasOwnProperty('UserProfileStore') ? this.props.flux.stores.UserProfileStore : this.props.flux.createStore(UserProfileStore);
27        this.state = this.Store.getState();
28        this.actions = this.state.actions;
29
30     }
31     componentDidUpdate() {
32         let self = this;
33         ReactDOM.findDOMNode(this.UserList).addEventListener('transitionend', this.onTransitionEnd, false);
34         setTimeout(function() {
35             let element = self[`user-ref-${self.state.activeIndex}`]
36             element && !isElementInView(element) && element.scrollIntoView({block: 'end', behavior: 'smooth'});
37         })
38     }
39     componentWillMount() {
40         this.Store.listen(this.updateState);
41     }
42     componentWillUnmount() {
43         this.Store.unlisten(this.updateState);
44     }
45     updateState = (state) => {
46         this.setState(state);
47     }
48     updateInput = (key, e) => {
49         let property = key;
50         this.actions.handleUpdateInput({
51             [property]:e.target.value
52         })
53     }
54     disabledChange = (e) => {
55         this.actions.handleDisabledChange(e.target.checked);
56     }
57     platformChange = (platformRole, e) => {
58         this.actions.handlePlatformRoleUpdate(platformRole, e.currentTarget.checked);
59     }
60     addProjectRole = (e) => {
61         this.actions.handleAddProjectItem();
62     }
63     removeProjectRole = (i, e) => {
64         this.actions.handleRemoveProjectItem(i);
65     }
66     updateProjectRole = (i, e) => {
67         this.actions.handleUpdateProjectRole(i, e)
68     }
69     addUser = () => {
70         this.actions.handleAddUser();
71     }
72     viewUser = (un, index) => {
73         this.actions.viewUser(un, index);
74     }
75     editUser = () => {
76         this.actions.editUser(false);
77     }
78     cancelEditUser = () => {
79         this.actions.editUser(true)
80     }
81     osePanel = () => {
82         this.actions.handleCloseUserPanel();
83     }
84     // updateUser = (e) => {
85     //     e.preventDefault();
86     //     e.stopPropagation();
87
88     //     this.Store.updateUser();
89     // }
90     deleteUser = (e) => {
91         e.preventDefault();
92         e.stopPropagation();
93         this.Store.deleteUser({
94                 'user-name': this.state['user-name'],
95                 'user-domain': this.state['user-domain']
96             });
97     }
98     createUser = (e) => {
99         e.preventDefault();
100         e.stopPropagation();
101         if(this.state['new-password'] != this.state['confirm-password']) {
102             this.props.actions.showNotification('Passwords do not match')
103         } else {
104             this.Store.createUser({
105                 'user-name': this.state['user-name'],
106                 'user-domain': this.state['user-domain'],
107                 'password': this.state['new-password']
108                 // 'confirm-password': this.state['confirm-password']
109             });
110         }
111     }
112     updateUser = (e) => {
113         let self = this;
114         e.preventDefault();
115         e.stopPropagation();
116         let validatedPasswords = validatePasswordFields(this.state);
117         if(validatedPasswords) {
118             this.Store.updateUser(_.merge({
119                             'user-name': this.context.userProfile.userId,
120                             'user-domain': this.state['user-domain'],
121                             'password': this.state['new-password']
122                         }));
123         }
124         function validatePasswordFields(state) {
125             let oldOne = state['old-password'];
126             let newOne = state['new-password'];
127             let confirmOne = state['confirm-password'];
128             if(true) {
129                 if(!oldOne || !newOne) {
130                      self.props.actions.showNotification('Please fill in all fields.');
131                     return false;
132                 }
133                 if(oldOne == newOne) {
134                     self.props.actions.showNotification('Your new password must not match your old one');
135                     return false;
136                 }
137                 if(newOne != confirmOne) {
138                     self.props.actions.showNotification('Passwords do not match');
139                     return false;
140                 }
141                 return {
142                     // 'old-password': oldOne,
143                     'new-password': newOne,
144                     'confirm-password': confirmOne
145                 }
146             } else {
147                 return {};
148             }
149         }
150     }
151      evaluateSubmit = (e) => {
152         if (e.keyCode == 13) {
153             if (this.props.isEdit) {
154                 this.updateUser(e);
155             } else {
156                 this.createUser(e);
157             }
158             e.preventDefault();
159             e.stopPropagation();
160         }
161     }
162     onTransitionEnd = (e) => {
163         this.actions.handleHideColumns(e);
164         console.log('transition end')
165     }
166     disableChange = (e) => {
167         let value = e.target.value;
168         value = value.toUpperCase();
169         if (value=="TRUE") {
170             value = true;
171         } else {
172             value = false;
173         }
174         console.log(value)
175     }
176     render() {
177
178         let self = this;
179         const User = this.context.userProfile || {};
180         let html;
181         let props = this.props;
182         let state = this.state;
183         let passwordSectionHTML = null;
184         let formButtonsHTML = (
185             <ButtonGroup className="buttonGroup">
186                 <Button label="EDIT" type="submit" onClick={this.editUser} />
187             </ButtonGroup>
188         );
189         passwordSectionHTML = (
190             (
191                 <FormSection title="PASSWORD CHANGE">
192                     <Input label="NEW PASSWORD" type="password" value={state['new-password']}  onChange={this.updateInput.bind(null, 'new-password')}/>
193                     <Input label="REPEAT NEW PASSWORD" type="password"  value={state['confirm-password']}  onChange={this.updateInput.bind(null, 'confirm-password')}/>
194                 </FormSection>
195             )
196         );
197         formButtonsHTML = (
198                 <ButtonGroup className="buttonGroup">
199                     <Button label="Update" type="submit" onClick={this.updateUser} />
200                 </ButtonGroup>
201         )
202
203         html = (
204             <PanelWrapper column>
205                 <PanelWrapper className={`row userManagement ${!this.state.userOpen ? 'userList-open' : ''}`} style={{'flexDirection': 'row'}} >
206                     <PanelWrapper ref={(div) => { this.UserList = div}} className={`column userList expanded hideColumns`}>
207                         <Panel title={User.userId} style={{marginBottom: 0}} no-corners>
208                             <FormSection title="USER INFO">
209                                 <table className="userProfile-table">
210                                     <thead>
211                                         <tr>
212                                             <td>Project</td>
213                                             <td>Role</td>
214                                         </tr>
215                                     </thead>
216                                     <tbody>
217                                         {
218                                             User.data && User.data.projectId && User.data.projectId.map((p,i)=> {
219                                                 let project = User.data.project[p];
220                                                 let projectConfig = project && project.data['project-config'];
221                                                 let userRoles = [];
222                                                 return (
223                                                     <tr key={i}>
224                                                         <td>
225                                                             {p}
226                                                         </td>
227                                                         <td>
228                                                             {
229                                                                 project && Object.keys(project.role).map(function(k) {
230                                                                     return <div>{k}</div>
231                                                                 })
232                                                             }
233                                                         </td>
234                                                     </tr>
235                                                 )
236                                             })
237                                         }
238                                     </tbody>
239                                 </table>
240                             </FormSection>
241                             {passwordSectionHTML}
242
243                         </Panel>
244                         <div  className="buttonSection">
245                             {formButtonsHTML}
246                         </div>
247                     </PanelWrapper>
248
249                 </PanelWrapper>
250             </PanelWrapper>
251         );
252         return html;
253     }
254 }
255 // onClick={this.Store.update.bind(null, Account)}
256 UserProfileDashboard.contextTypes = {
257     router: React.PropTypes.object,
258     userProfile: React.PropTypes.object
259 };
260
261 UserProfileDashboard.defaultProps = {
262     userList: [],
263     selectedUser: {}
264 }
265
266 export default SkyquakeComponent(UserProfileDashboard);
267
268
269 function isElementInView(el) {
270     var rect = el && el.getBoundingClientRect() || {};
271
272     return (
273         rect.top >= 0 &&
274         rect.left >= 0 &&
275         rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
276         rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
277     );
278 }
279
280
281 // isReadOnly={state.isReadOnly} disabled={state.disabled} onChange={this.disableChange}
282
283 class isDisabled extends React.Component {
284     constructor(props) {
285         super(props);
286     }
287     render() {
288         let props = this.props;
289         return (<div/>)
290     }
291 }
292
293 /**
294  * AddItemFn:
295  */
296 class InputCollection extends React.Component {
297     constructor(props) {
298         super(props);
299         this.collection = props.collection;
300     }
301     buildTextInput(onChange, v, i) {
302         return (
303             <Input
304                 readonly={this.props.readonly}
305                 style={{flex: '1 1'}}
306                 key={i}
307                 value={v}
308                 onChange= {onChange.bind(null, i)}
309             />
310         )
311     }
312     buildSelectOption(initial, options, onChange, v, i) {
313         return (
314             <SelectOption
315                 readonly={this.props.readonly}
316                 key={`${i}-${v.replace(' ', '_')}`}
317                 intial={initial}
318                 defaultValue={v}
319                 options={options}
320                 onChange={onChange.bind(null, i)}
321             />
322         );
323     }
324     showInput() {
325
326     }
327     render() {
328         const props = this.props;
329         let inputType;
330         let className = "InputCollection";
331         if (props.className) {
332             className = `${className} ${props.className}`;
333         }
334         if (props.type == 'select') {
335             inputType = this.buildSelectOption.bind(this, props.initial, props.options, props.onChange);
336         } else {
337             inputType = this.buildTextInput.bind(this, props.onChange)
338         }
339         let html = (
340             <div className="InputCollection-wrapper">
341                 {props.collection.map((v,i) => {
342                     return (
343                         <div key={i} className={className} >
344                             {inputType(v, i)}
345                             {
346                                 props.readonly ? null : <span onClick={props.RemoveItemFn.bind(null, i)} className="removeInput"><img src={imgRemove} />Remove</span>}
347                         </div>
348                     )
349                 })}
350                 { props.readonly ? null : <span onClick={props.AddItemFn} className="addInput"><img src={imgAdd} />Add</span>}
351             </div>
352         );
353         return html;
354     }
355 }
356
357 InputCollection.defaultProps = {
358     input: Input,
359     collection: [],
360     onChange: function(i, e) {
361         console.log(`
362                         Updating with: ${e.target.value}
363                         At index of: ${i}
364                     `)
365     },
366     AddItemFn: function(e) {
367         console.log(`Adding a new item to collection`)
368     },
369     RemoveItemFn: function(i, e) {
370         console.log(`Removing item from collection at index of: ${i}`)
371     }
372 }
373
374 class FormSection extends React.Component {
375     render() {
376         let className = 'FormSection ' + this.props.className;
377         let html = (
378             <div
379                 style={this.props.style}
380                 className={className}
381             >
382                 <div className="FormSection-title">
383                     {this.props.title}
384                 </div>
385                 <div className="FormSection-body">
386                     {this.props.children}
387                 </div>
388             </div>
389         );
390         return html;
391     }
392 }
393
394 FormSection.defaultProps = {
395     className: ''
396 }