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