]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/+login/login.component.ts
Implement two factor in client
[github/Chocobozzz/PeerTube.git] / client / src / app / +login / login.component.ts
1
2 import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core'
3 import { ActivatedRoute, Router } from '@angular/router'
4 import { AuthService, Notifier, RedirectService, SessionStorageService, UserService } from '@app/core'
5 import { HooksService } from '@app/core/plugins/hooks.service'
6 import { LOGIN_PASSWORD_VALIDATOR, LOGIN_USERNAME_VALIDATOR } from '@app/shared/form-validators/login-validators'
7 import { USER_OTP_TOKEN_VALIDATOR } from '@app/shared/form-validators/user-validators'
8 import { FormReactive, FormValidatorService, InputTextComponent } from '@app/shared/shared-forms'
9 import { InstanceAboutAccordionComponent } from '@app/shared/shared-instance'
10 import { NgbAccordion, NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'
11 import { PluginsManager } from '@root-helpers/plugins-manager'
12 import { RegisteredExternalAuthConfig, ServerConfig } from '@shared/models'
13
14 @Component({
15 selector: 'my-login',
16 templateUrl: './login.component.html',
17 styleUrls: [ './login.component.scss' ]
18 })
19
20 export class LoginComponent extends FormReactive implements OnInit, AfterViewInit {
21 private static SESSION_STORAGE_REDIRECT_URL_KEY = 'login-previous-url'
22
23 @ViewChild('forgotPasswordModal', { static: true }) forgotPasswordModal: ElementRef
24 @ViewChild('otpTokenInput') otpTokenInput: InputTextComponent
25
26 accordion: NgbAccordion
27 error: string = null
28 forgotPasswordEmail = ''
29
30 isAuthenticatedWithExternalAuth = false
31 externalAuthError = false
32 externalLogins: string[] = []
33
34 instanceInformationPanels = {
35 terms: true,
36 administrators: false,
37 features: false,
38 moderation: false,
39 codeOfConduct: false
40 }
41
42 otpStep = false
43
44 private openedForgotPasswordModal: NgbModalRef
45 private serverConfig: ServerConfig
46
47 constructor (
48 protected formValidatorService: FormValidatorService,
49 private route: ActivatedRoute,
50 private modalService: NgbModal,
51 private authService: AuthService,
52 private userService: UserService,
53 private redirectService: RedirectService,
54 private notifier: Notifier,
55 private hooks: HooksService,
56 private storage: SessionStorageService,
57 private router: Router
58 ) {
59 super()
60 }
61
62 get signupAllowed () {
63 return this.serverConfig.signup.allowed === true
64 }
65
66 get instanceName () {
67 return this.serverConfig.instance.name
68 }
69
70 onTermsClick (event: Event, instanceInformation: HTMLElement) {
71 event.preventDefault()
72
73 if (this.accordion) {
74 this.accordion.expand('terms')
75 instanceInformation.scrollIntoView({ behavior: 'smooth' })
76 }
77 }
78
79 isEmailDisabled () {
80 return this.serverConfig.email.enabled === false
81 }
82
83 ngOnInit () {
84 const snapshot = this.route.snapshot
85
86 // Avoid undefined errors when accessing form error properties
87 this.buildForm({
88 username: LOGIN_USERNAME_VALIDATOR,
89 password: LOGIN_PASSWORD_VALIDATOR,
90 'otp-token': {
91 VALIDATORS: [], // Will be set dynamically
92 MESSAGES: USER_OTP_TOKEN_VALIDATOR.MESSAGES
93 }
94 })
95
96 this.serverConfig = snapshot.data.serverConfig
97
98 if (snapshot.queryParams.externalAuthToken) {
99 this.loadExternalAuthToken(snapshot.queryParams.username, snapshot.queryParams.externalAuthToken)
100 return
101 }
102
103 if (snapshot.queryParams.externalAuthError) {
104 this.externalAuthError = true
105 return
106 }
107
108 const previousUrl = this.redirectService.getPreviousUrl()
109 if (previousUrl && previousUrl !== '/') {
110 this.storage.setItem(LoginComponent.SESSION_STORAGE_REDIRECT_URL_KEY, previousUrl)
111 }
112 }
113
114 ngAfterViewInit () {
115 this.hooks.runAction('action:login.init', 'login')
116 }
117
118 getExternalLogins () {
119 return this.serverConfig.plugin.registeredExternalAuths
120 }
121
122 getAuthHref (auth: RegisteredExternalAuthConfig) {
123 return PluginsManager.getExternalAuthHref(auth)
124 }
125
126 login () {
127 this.error = null
128
129 const options = {
130 username: this.form.value['username'],
131 password: this.form.value['password'],
132 otpToken: this.form.value['otp-token']
133 }
134
135 this.authService.login(options)
136 .pipe()
137 .subscribe({
138 next: () => this.redirectService.redirectToPreviousRoute(),
139
140 error: err => {
141 this.handleError(err)
142 }
143 })
144 }
145
146 askResetPassword () {
147 this.userService.askResetPassword(this.forgotPasswordEmail)
148 .subscribe({
149 next: () => {
150 const message = $localize`An email with the reset password instructions will be sent to ${this.forgotPasswordEmail}.
151 The link will expire within 1 hour.`
152
153 this.notifier.success(message)
154 this.hideForgotPasswordModal()
155 },
156
157 error: err => this.notifier.error(err.message)
158 })
159 }
160
161 openForgotPasswordModal () {
162 this.openedForgotPasswordModal = this.modalService.open(this.forgotPasswordModal)
163 }
164
165 hideForgotPasswordModal () {
166 this.openedForgotPasswordModal.close()
167 }
168
169 onInstanceAboutAccordionInit (instanceAboutAccordion: InstanceAboutAccordionComponent) {
170 this.accordion = instanceAboutAccordion.accordion
171 }
172
173 hasUsernameUppercase () {
174 return this.form.value['username'].match(/[A-Z]/)
175 }
176
177 private loadExternalAuthToken (username: string, token: string) {
178 this.isAuthenticatedWithExternalAuth = true
179
180 this.authService.login({ username, password: null, token })
181 .subscribe({
182 next: () => {
183 const redirectUrl = this.storage.getItem(LoginComponent.SESSION_STORAGE_REDIRECT_URL_KEY)
184 if (redirectUrl) {
185 this.storage.removeItem(LoginComponent.SESSION_STORAGE_REDIRECT_URL_KEY)
186 return this.router.navigateByUrl(redirectUrl)
187 }
188
189 this.redirectService.redirectToLatestSessionRoute()
190 },
191
192 error: err => {
193 this.handleError(err)
194 this.isAuthenticatedWithExternalAuth = false
195 }
196 })
197 }
198
199 private handleError (err: any) {
200 if (this.authService.isOTPMissingError(err)) {
201 this.otpStep = true
202
203 setTimeout(() => {
204 this.form.get('otp-token').setValidators(USER_OTP_TOKEN_VALIDATOR.VALIDATORS)
205 this.otpTokenInput.focus()
206 })
207
208 return
209 }
210
211 if (err.message.indexOf('credentials are invalid') !== -1) this.error = $localize`Incorrect username or password.`
212 else if (err.message.indexOf('blocked') !== -1) this.error = $localize`Your account is blocked.`
213 else this.error = err.message
214 }
215 }