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