Pman.Login.js
[Pman.Core] / Pman.Login.js
1 //<script type="text/javascript">
2
3
4 /***
5 re-arrange language code...
6
7 * flipping language should be like this:
8
9 * Ext.apply(_T, _T[lang]);
10
11 **/
12  
13   
14
15 Pman.Login =  new Roo.util.Observable({
16     
17     events : {
18         
19         'render' : true
20     },
21     disabled : false,
22     
23     dialog : false,
24     form: false,
25     haslogo : false,
26     
27     authUserId: 0,
28     authUser: { id : false },
29        
30     checkFails : 0,
31     versionWarn: false,
32     sending : false,
33     
34     onLoad : function() // called on page load...
35     {
36         // load 
37        
38          
39         if (Roo.get('loading')) {
40             Roo.get('loading').remove();
41         }
42         this.switchLang('en');
43        
44         // check if we are logged in..
45         Roo.Ajax.request({  
46             url: baseURL + '/Login.js',  
47             params: {
48                 getAuthUser: true
49             },  
50             method: 'GET',  
51             success:  function(response, opts)  {  // check successfull...
52             
53                 var res = Pman.processResponse(response);
54                 this.checkFails =0;
55                 if (!res.success) { // error!
56                     this.checkFails = 5;
57                     //console.log('call failure');
58                     return Pman.Login.failure(response,opts);
59                 }
60                 
61                 
62                 if (!res.data.id) { // id=0 == login failure.
63                     return this.show(true);
64                 }
65                 
66                               
67                         //console.log(success);
68                 this.fillAuth(res.data);   
69                 this.checkFails =0;
70                 Pman.onload();
71             },
72             failure : Pman.Login.show,
73             scope : Pman.Login
74               
75         });  
76     }, 
77     
78     
79     check: function(again) // called every so often to refresh cookie etc..
80     {
81         if (again) { // could be undefined..
82             Pman.Login.checkFails++;
83         } else {
84             Pman.Login.checkFails = 0;
85         }
86         var _this = this;
87         if (this.sending) {
88             
89             if ( Pman.Login.checkFails > 4) {
90                 Pman.Preview.disable();
91                 Roo.MessageBox.alert("Error",  
92                     "Error getting authentication status. - try reloading, or wait a while", function() {
93                         _this.sending = false;
94                     }); 
95                 return;
96             }
97             
98             _this.check.defer(10000, _this, [ true ]); // check in 10 secs.
99             return;
100         }
101         this.sending = true;
102         
103         Roo.Ajax.request({  
104             url: baseURL + '/Login.js',  
105             params: {
106                 getAuthUser: true
107             },  
108             method: 'GET',  
109             success:  Pman.Login.success,
110             failure : Pman.Login.failure,
111             scope : Pman.Login
112               
113         });  
114     }, 
115     
116     
117     
118     failure : function (response, opts) // called if login 'check' fails.. (causes re-check)
119     {
120         this.authUser = -1;
121         this.sending = false;
122         var res = Pman.processResponse(response);
123         //console.log(res);
124         if ( Pman.Login.checkFails > 2) {
125             Pman.Preview.disable();
126             Roo.MessageBox.alert("Error", res.errorMsg ? res.errorMsg : 
127                 "Error getting authentication status. - try reloading"); 
128             return;
129         }
130             
131         Pman.Login.check.defer(1000, Pman.Login, [ true ]);
132         return;  
133     },
134     
135     
136     success : function(response, opts)  // check successfull...
137     {  
138         this.sending = false;
139         var res = Pman.processResponse(response);
140         if (!res.success) {
141             return this.failure(response, opts);
142         }
143         if (!res.data || !res.data.id) {
144             return this.failure(response,opts);
145         }
146         //console.log(res);
147         this.fillAuth(res.data);
148         
149         this.checkFails =0;
150         Pman.onload();
151     },
152     
153     fillAuth: function(au) {
154         this.startAuthCheck();
155         this.authUserId = au.id;
156         this.authUser = au;
157         this.lastChecked = new Date();
158         Pman.fireEvent('authrefreshed', au);
159         //Pman.Tab.FaxQueue.newMaxId(au.faxMax);
160         //Pman.Tab.FaxTab.setTitle(au.faxNumPending);
161         
162         //this.switchLang(Roo.state.Manager.get('Pman.Login.lang', 'en'));
163         Roo.state.Manager.set('Pman.Login.lang.'+appNameShort, au.lang);
164         this.switchLang(au.lang);
165         
166      
167         // open system... - -on setyp..
168         if (this.authUserId  < 0) {
169             Roo.MessageBox.alert("Warning", 
170                 "This is an open system - please set up a admin user with a password.");  
171         }
172          
173         //Pman.onload(); // which should do nothing if it's a re-auth result...
174         
175              
176     },
177     
178     
179     intervalID : false,   /// the login refresher...
180     
181     lastChecked : false,
182     
183     startAuthCheck : function() // starter for timeout checking..
184     {
185         if (Pman.Login.intervalID) { // timer already in place...
186             return false;
187         }
188         
189         Pman.Login.intervalID =  window.setInterval(function() {
190                   Pman.Login.check(false);
191                 }, 120000); // every 120 secs = 2mins..
192         
193         
194     },
195     
196     
197     create : function()
198     {
199         if (this.dialog) {
200             return;
201         }
202         var _this = this;
203         
204         this.dialog = new Roo.LayoutDialog(Roo.get(document.body).createChild({tag:'div'}),
205         { // the real end set is here...
206             autoCreated: true,
207             title: "Login",
208             modal: true,
209             width:  350,
210             height: 230,
211             shadow:true,
212             minWidth:200,
213             minHeight:180,
214             //proxyDrag: true,
215             closable: false,
216             draggable: false,
217             collapsible: false,
218             resizable: false,
219             center: {
220                 autoScroll:false,
221                 titlebar: false,
222                // tabPosition: 'top',
223                 hideTabs: true,
224                 closeOnTab: true,
225                 alwaysShowTabs: false
226             }  
227             
228         });
229         
230         
231         
232         this.dialog.addButton("Forgot Password", function()
233         {
234             
235             var n = _this.form.findField('username').getValue();
236             if (!n.length) {
237                 Roo.MessageBox.alert("Error", "Fill in your email address");
238                 return;
239             }
240             Roo.Ajax.request({
241                 url: baseURL + '/Login.js',  
242                 params: {
243                     passwordRequest: n
244                 },
245                 method: 'POST',  
246                 success:  function(response, opts)  {  // check successfull...
247                 
248                     var res = Pman.processResponse(response);
249                     if (!res.success) { // error!
250                        Roo.MessageBox.alert("Error" , res.errorMsg ? res.errorMsg  : "Problem Requesting Password Reset");
251                        return;
252                     }
253                     Roo.MessageBox.alert("Notice" , "Please check you email for the Password Reset message");
254                 },
255                 failure : function() {
256                     Roo.MessageBox.alert("Error" , "Problem Requesting Password Reset");
257                 }
258                 
259             });
260         });
261         
262         this.dialog.addButton("Login", function()
263         {
264             Pman.Login.dialog.el.mask("Logging in");
265             Pman.Login.form.doAction('submit', {
266                     url: baseURL + '/Login',
267                     method: 'POST'
268             });
269         });
270         this.layout = this.dialog.getLayout();
271         this.layout.beginUpdate();
272         
273         //layout.add('center', new Roo.ContentPanel('center', {title: 'The First Tab'}));
274         // generate some other tabs
275         this.form = new Roo.form.Form({
276             labelWidth: 100 ,
277             
278             listeners : {
279                 actionfailed : function(f, act) {
280                     // form can return { errors: .... }
281                         
282                     //act.result.errors // invalid form element list...
283                     //act.result.errorMsg// invalid form element list...
284                     
285                     Pman.Login.dialog.el.unmask();
286                     Roo.MessageBox.alert("Error", act.result.errorMsg ? act.result.errorMsg : 
287                                 "Login failed - communication error - try again.");
288                               
289                 },
290                 actioncomplete: function(re, act) {
291                      
292                     Roo.state.Manager.set('Pman.Login.username.'+appNameShort,  Pman.Login.form.findField('username').getValue() );
293                     Roo.state.Manager.set('Pman.Login.lang.'+appNameShort,  Pman.Login.form.findField('lang').getValue() );
294                     Pman.Login.fillAuth(act.result.data);
295                       
296                     Pman.Login.dialog.hide();
297                     if (Roo.get('loading-mask')) {
298                         //Roo.get('loading').show();
299                         Roo.get('loading-mask').show();
300                     }
301                    
302                     Pman.onload();
303                     
304                      
305                     
306                 }
307             }
308         
309             
310             
311              
312         });
313           
314         
315         
316         this.form.add( 
317        
318             new Roo.form.TextField({
319                 fieldLabel: "Email Address",
320                 name: 'username',
321                 width:200,
322                 autoCreate : {tag: "input", type: "text", size: "20"}
323             }),
324
325             new Roo.form.TextField({
326                 fieldLabel: "Password",
327                 inputType: 'password',
328                 name: 'password',
329                 width:200,
330                 autoCreate : {tag: "input", type: "text", size: "20"},
331                 listeners : {
332                     specialkey : function(e,ev) {
333                         if (ev.keyCode == 13) {
334                             Pman.Login.dialog.el.mask("Logging in");
335                             Pman.Login.form.doAction('submit', {
336                                     url: baseURL + '/Login.json',
337                                     method: 'POST'
338                             });
339                         }
340                     }
341                 }  
342             }) ,
343             new Roo.form.ComboBox({
344                 fieldLabel: "Language",
345                 name : 'langdisp',
346                 store: {
347                     xtype : 'SimpleStore',
348                     fields: ['lang', 'ldisp'],
349                     data : [
350                         [ 'en', 'English' ],
351                         [ 'zh_HK' , '\u7E41\u4E2D' ],
352                         [ 'zh_CN', '\u7C21\u4E2D' ]
353                     ]
354                 },
355                 
356                 valueField : 'lang',
357                 hiddenName:  'lang',
358                 width: 200,
359                 displayField:'ldisp',
360                 typeAhead: false,
361                 editable: false,
362                 mode: 'local',
363                 triggerAction: 'all',
364                 emptyText:'Select a Language...',
365                 selectOnFocus:true,
366                 listeners : {
367                     select :  function(cb, rec, ix) {
368                         
369                         
370                         Pman.Login.switchLang(rec.data.lang);
371                         
372                     }
373                 }
374             
375             })
376
377         );
378          
379         
380         var ef = this.dialog.getLayout().getEl().createChild({tag: 'div'});
381         ef.dom.style.margin = 10;
382           
383         this.form.render(ef.dom);
384          // logoprefix comes from base config.
385         Pman.Login.form.el.createChild({
386                 tag: 'img', 
387                 src: rootURL + '/Pman/'+appNameShort + '/templates/images/logo.gif',
388                 style: 'margin-bottom: 10px;'
389             },
390             Pman.Login.form.el.dom.firstChild 
391         );
392        
393         var vp = this.dialog.getLayout().add('center', new Roo.ContentPanel(ef, {
394             autoCreate : true,
395             //title: 'Org Details',
396             //toolbar: this.tb,
397             width: 250,
398             maxWidth: 250,
399             fitToFrame:true
400         }));
401         
402         this.layout.endUpdate();
403         
404         this.fireEvent('render', this);
405         
406         
407         
408         
409         
410     },
411     resizeToLogo : function()
412     {
413         var sz = Roo.get(Pman.Login.form.el.query('img')[0]).getSize();
414         if (!sz) {
415             this.resizeToLogo.defer(1000,this);
416             return;
417         }
418         var w = Ext.lib.Dom.getViewWidth() - 100;
419         var h = Ext.lib.Dom.getViewHeight() - 100;
420         Pman.Login.dialog.resizeTo(Math.max(350, Math.min(sz.width + 30, w)),Math.min(sz.height+200, h));
421         Pman.Login.dialog.center();
422     },
423     
424      
425     
426     show: function (modal) 
427     {
428         if (this.disabled) {
429             return;
430         }
431         modal = modal || false;
432         if (Pman.Login.authUserId < 0) { // logout!?
433             return;
434         }
435         
436         if (Pman.Login.intervalID) {
437             // remove the timer
438             window.clearInterval(Pman.Login.intervalID);
439             Pman.Login.intervalID = false;
440         }
441         
442         this.create();
443         
444         
445         
446         if (Roo.get('loading')) {
447             Roo.get('loading').remove();
448         }
449         if (Roo.get('loading-mask')) {
450             Roo.get('loading-mask').hide();
451         }
452         
453         //incomming._node = tnode;
454         this.form.reset();
455         this.dialog.modal = !modal;
456         this.dialog.show();
457         this.dialog.el.unmask(); 
458         this.resizeToLogo.defer(1000,this);
459         
460          
461         this.form.setValues({
462             'username' : Roo.state.Manager.get('Pman.Login.username.'+appNameShort, ''),
463             'lang' : Roo.state.Manager.get('Pman.Login.lang.'+appNameShort, 'en')
464         });
465         Pman.Login.switchLang(Roo.state.Manager.get('Pman.Login.lang.'+appNameShort, ''));
466         if (this.form.findField('username').getValue().length > 0 ){
467             this.form.findField('password').focus();
468         } else {
469            this.form.findField('username').focus();
470         }
471         
472         
473     },
474  
475     
476      
477     logout: function()
478     {
479         window.onbeforeunload = function() { }; // false does not work for IE..
480         Pman.Login.authUserId = -1;
481         Roo.Ajax.request({  
482             url: baseURL + '/Login.html',  
483             params: {
484                 logout: 1
485             },  
486             method: 'GET',
487             failure : function() {
488                 Roo.MessageBox.alert("Error", "Error logging out. - continuing anyway.", function() {
489                     document.location = baseURL + '?ts=' + Math.random();
490                 });
491                 
492             },
493             success : function() {
494                 Pman.Login.authUserId = -1;
495                 Pman.Login.checkFails =0;
496                 // remove the 
497                 document.location = baseURL + '?ts=' + Math.random();
498             }
499               
500               
501         }); 
502     },
503     switchLang : function (lang) {
504         if (!lang || !lang.length) {
505             return;
506         }
507         if (typeof(_T.en) == 'undefined') {
508             _T.en = {};
509             Roo.apply(_T.en, _T);
510         }
511         
512         if (typeof(_T[lang]) == 'undefined') {
513             Roo.MessageBox.alert("Sorry", "Language not available yet (" + lang +')');
514             return;
515         }
516         
517         
518         Roo.apply(_T, _T[lang]);
519         // just need to set the text values for everything...
520         if (this.form) {
521             
522                
523             function formLabel(name, val) {
524                 
525                 var lbl = Pman.Login.form.findField( name ).el.dom.parentNode.parentNode;
526                 if (lbl.getElementsByTagName('label').length) {
527                     lbl = lbl.getElementsByTagName('label')[0];
528                 } else  {
529                     lbl = lbl.parentNode.getElementsByTagName('label')[0];
530                 }
531                    
532                 lbl.innerHTML = val;
533             }
534             
535             formLabel('password', "Password"+':');
536             formLabel('username', "Email Address"+':');
537             formLabel('lang', "Language"+':');
538             this.dialog.setTitle("Login");
539             this.dialog.buttons[0].setText("Forgot Password");
540             this.dialog.buttons[1].setText("Login");
541         }
542         
543         
544     },
545     
546     inGroup : function(g)
547     {
548         return this.authUser && this.authUser.groups && 
549             this.authUser.groups.indexOf(g) > -1;
550     },
551     isOwner : function()
552     {
553         return this.authUser && this.authUser.company_id_comptype && 
554             this.authUser.company_id_comptype == 'OWNER';
555     },
556     
557     /**
558      * Depreciated = use Pman.I18n
559      */
560     
561     i18nList: function (type, codes)
562     {
563         
564         return Pman.I18n.listToNames(type, codes);
565     },
566     i18n: function(type, code) 
567     {
568         return Pman.I18n.toName(type, code);
569         
570     }
571     
572     
573 });
574
575
576
577
578