fengxiang
2018-02-08 bde1723df23bd3c3ee4a76cdc6951b1140f6f525
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import { Authorization } from '@business/entity/token';
import { LoginService } from './../../../business/services/http/login.service';
import { SettingsService } from '@delon/theme';
import { Component, OnDestroy, Inject } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';
import { SocialService, SocialOpenType, ITokenService, DA_SERVICE_TOKEN } from '@delon/auth';
import { environment } from '@env/environment';
@Component({
    selector: 'passport-login',
    templateUrl: './login.component.html',
    styleUrls: [ './login.component.less' ],
    providers: [ SocialService]
})
export class UserLoginComponent implements OnDestroy {
 
    form: FormGroup;
    error = '';
    type = 0;
    loading = false;
 
    constructor(
        fb: FormBuilder,
        private router: Router,
        public msg: NzMessageService,
        private settingsService: SettingsService,
        private socialService: SocialService,
        private loginService:LoginService,
        @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService) {
        this.form = fb.group({
            userName: [null, [Validators.required, Validators.minLength(5)]],
            password: [null, Validators.required],
            mobile: [null, [Validators.required, Validators.pattern(/^1\d{10}$/)]],
            captcha: [null, [Validators.required]],
            remember: [true]
        });
    }
 
    // region: fields
 
    get userName() { return this.form.controls.userName; }
    get password() { return this.form.controls.password; }
    get mobile() { return this.form.controls.mobile; }
    get captcha() { return this.form.controls.captcha; }
 
    // endregion
 
    switch(ret: any) {
        this.type = ret.index;
    }
 
    // region: get captcha
 
    count = 0;
    interval$: any;
 
    getCaptcha() {
        this.count = 59;
        this.interval$ = setInterval(() => {
            this.count -= 1;
            if (this.count <= 0)
                clearInterval(this.interval$);
        }, 1000);
    }
 
    // endregion
 
    submit() {
        this.error = '';
        if (this.type === 0) {
            this.userName.markAsDirty();
            this.password.markAsDirty();
            if (this.userName.invalid || this.password.invalid) return;
        } else {
            this.mobile.markAsDirty();
            this.captcha.markAsDirty();
            if (this.mobile.invalid || this.captcha.invalid) return;
        }
        this.loading = true;
            this.loginService.validate(this.userName.value,this.password.value).subscribe(
                (res:Authorization) => {
                   if(res.token!=null){
                       this.tokenService.set({
                           token: res.token,
                           name: this.userName.value,
                           time: +new Date
                       });
                       this.validateError = {};
                       this.router.navigate(['/']);
                   }
                },
                (err) => {
                    console.log(err);
                    if(err instanceof ProgressEvent){
                        const error = <ProgressEvent>err;
                        let xmlHttp = error.target;
                        if(xmlHttp instanceof XMLHttpRequest){
                            const xmlHttpRequest = <XMLHttpRequest> xmlHttp;      
                            console.log(xmlHttpRequest.response);                           
                            const response = JSON.parse(xmlHttpRequest.response);                                                  
                            if(response.status == 401&&response.errorCode==10){                                
                                 this.validateError["password_incorrect"]=true;
                                 this.loading = false;
                            } else if(response.status == 401&&response.errorCode==12) {
                                this.validateError["account_expired"]=true;
                                this.loading = false;
                            }
                        }
                    }
                }
           );
 
    }
    public validateError:{[s:string]:boolean} = {};
    // region: social
 
    open(type: string, openType: SocialOpenType = 'href') {
        let url = ``;
        let callback = ``;
        if (environment.production)
            callback = 'https://cipchk.github.io/ng-alain/callback/' + type;
        else
            callback = 'http://localhost:4200/callback/' + type;
        switch (type) {
            case 'auth0':
                url = `//cipchk.auth0.com/login?client=8gcNydIDzGBYxzqV0Vm1CX_RXH-wsWo5&redirect_uri=${decodeURIComponent(callback)}`;
                break;
            case 'github':
                url = `//github.com/login/oauth/authorize?client_id=9d6baae4b04a23fcafa2&response_type=code&redirect_uri=${decodeURIComponent(callback)}`;
                break;
            case 'weibo':
                url = `https://api.weibo.com/oauth2/authorize?client_id=1239507802&response_type=code&redirect_uri=${decodeURIComponent(callback)}`;
                break;
        }
        if (openType === 'window') {
            this.socialService.login(url, '/', {
                type: 'window'
            }).subscribe(res => {
                if (res) {
                    this.settingsService.setUser(res);
                    this.router.navigateByUrl('/');
                }
            });
        } else {
            this.socialService.login(url, '/', {
                type: 'href'
            });
        }
    }
 
    // endregion
 
    ngOnDestroy(): void {
        if (this.interval$) clearInterval(this.interval$);
    }
}