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