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