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