From ccf656dfce2409b3c8d517f5a68969e2d285ab22 Mon Sep 17 00:00:00 2001 From: Fuzi_fauzia Date: Wed, 3 Jul 2024 17:39:46 +0700 Subject: [PATCH] integrasi update password --- package-lock.json | 14 ++ package.json | 1 + src/app/_services/auth.service.ts | 6 + .../hemat-app/service/login.service.ts | 22 +++ .../update-password.component.ts | 87 ++++++++++-- src/app/login/login.component.ts | 127 ++++++------------ 6 files changed, 161 insertions(+), 96 deletions(-) create mode 100644 src/app/content/hemat-app/service/login.service.ts diff --git a/package-lock.json b/package-lock.json index 9266f92..ff0df1c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -56,6 +56,7 @@ "js-datepicker": "^5.18.2", "jspdf": "^2.5.1", "jspdf-autotable": "^3.5.28", + "jwt-decode": "^4.0.0", "lodash-es": "^4.17.21", "ng-chartist": "^4.1.0", "ng-multiselect-dropdown": "^0.3.9", @@ -11982,6 +11983,14 @@ "promise": "^7.0.1" } }, + "node_modules/jwt-decode": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jwt-decode/-/jwt-decode-4.0.0.tgz", + "integrity": "sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==", + "engines": { + "node": ">=18" + } + }, "node_modules/karma": { "version": "6.4.1", "resolved": "https://registry.npmjs.org/karma/-/karma-6.4.1.tgz", @@ -28494,6 +28503,11 @@ "promise": "^7.0.1" } }, + "jwt-decode": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jwt-decode/-/jwt-decode-4.0.0.tgz", + "integrity": "sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==" + }, "karma": { "version": "6.4.1", "resolved": "https://registry.npmjs.org/karma/-/karma-6.4.1.tgz", diff --git a/package.json b/package.json index 68f3e72..478ed44 100644 --- a/package.json +++ b/package.json @@ -62,6 +62,7 @@ "js-datepicker": "^5.18.2", "jspdf": "^2.5.1", "jspdf-autotable": "^3.5.28", + "jwt-decode": "^4.0.0", "lodash-es": "^4.17.21", "ng-chartist": "^4.1.0", "ng-multiselect-dropdown": "^0.3.9", diff --git a/src/app/_services/auth.service.ts b/src/app/_services/auth.service.ts index 6c9d3da..beb4483 100644 --- a/src/app/_services/auth.service.ts +++ b/src/app/_services/auth.service.ts @@ -107,11 +107,17 @@ export class AuthService { doLogout() { return new Promise((resolve, reject) => { if (firebase.auth().currentUser) { + console.log('masuk atas'); localStorage.removeItem('currentUser'); + localStorage.removeItem('account_info'); + localStorage.removeItem('access_token'); localStorage.removeItem('remember'); this.afAuth.signOut(); resolve(); } else { + console.log('masuk bawah'); + localStorage.removeItem('account_info'); + localStorage.removeItem('access_token'); localStorage.removeItem('currentUser'); resolve(); } diff --git a/src/app/content/hemat-app/service/login.service.ts b/src/app/content/hemat-app/service/login.service.ts new file mode 100644 index 0000000..7805c07 --- /dev/null +++ b/src/app/content/hemat-app/service/login.service.ts @@ -0,0 +1,22 @@ +import { Injectable } from "@angular/core"; +import { HttpClient, HttpHeaders } from "@angular/common/http"; +import { Observable } from "rxjs"; + +const BASE_URL = 'https://kapi.absys.ninja/hemat'; + +@Injectable({ + providedIn: "root", +}) +export class LoginService { + constructor(private http: HttpClient) {} + + updatePassword(data: any): Observable { + const endpoint = `/users`; + const url = `${BASE_URL}${endpoint}/reset-password`; + const headers = new HttpHeaders({ + 'Content-Type': 'application/json', + 'x-api-key': 'j2yaYvPSQcsEEmHh3NEobfiXyyXmmnHT' + }); + return this.http.put(url, data, { headers }); + } +} diff --git a/src/app/content/hemat-app/user-profile/update-password/update-password.component.ts b/src/app/content/hemat-app/user-profile/update-password/update-password.component.ts index bf83ab4..b75b8ce 100644 --- a/src/app/content/hemat-app/user-profile/update-password/update-password.component.ts +++ b/src/app/content/hemat-app/user-profile/update-password/update-password.component.ts @@ -1,6 +1,16 @@ import { Component, ViewChild } from "@angular/core"; -import { FormBuilder, FormGroup, NgForm, Validators, AbstractControl, ValidatorFn } from "@angular/forms"; +import { + FormBuilder, + FormGroup, + NgForm, + Validators, + AbstractControl, + ValidatorFn, +} from "@angular/forms"; import { ActivatedRoute, Router } from "@angular/router"; +import { LoginService } from "../../service/login.service"; +import { ToastrService } from "ngx-toastr"; +import { AuthService } from "src/app/_services/auth.service"; @Component({ selector: "app-update-password", @@ -17,21 +27,35 @@ export class UpdatePasswordComponent { showNewPass: boolean = false; showConfirmPass: boolean = false; + storedData: any; + constructor( private formBuilder: FormBuilder, private router: Router, - private route: ActivatedRoute + private route: ActivatedRoute, + private authService: LoginService, + private toastr: ToastrService, + private logoutService: AuthService, ) {} ngOnInit(): void { + this.storedData = JSON.parse(localStorage.getItem("account_info")); this.profilInfo = this.formBuilder.group({ + userid: this.storedData.sub, currentPass: ["", Validators.required], - newPass: ["", [Validators.required, Validators.minLength(8), Validators.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/)]], - confirmPass: ["", [Validators.required, this.matchPassword('newPass')]], + newPass: [ + "", + [ + Validators.required, + Validators.minLength(8), + Validators.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/), + ], + ], + confirmPass: ["", [Validators.required, this.matchPassword("newPass")]], }); - this.profilInfo.get('newPass').valueChanges.subscribe(() => { - this.profilInfo.get('confirmPass').updateValueAndValidity(); + this.profilInfo.get("newPass").valueChanges.subscribe(() => { + this.profilInfo.get("confirmPass").updateValueAndValidity(); }); } @@ -73,15 +97,54 @@ export class UpdatePasswordComponent { } cancel() { - // Handle cancel action + this.profilInfo = this.formBuilder.group({ + userid: this.storedData.sub, + currentPass: ["", Validators.required], + newPass: [ + "", + [ + Validators.required, + Validators.minLength(8), + Validators.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/), + ], + ], + confirmPass: ["", [Validators.required, this.matchPassword("newPass")]], + }); } saveEdit() { - // Handle save action - console.log(this.profilInfo); - console.log(this.profilInfo.invalid); - console.log(this.profilInfo.valid); - + if (this.profilInfo.valid) { + const dataPassword = { + userid: this.profilInfo.value.userid, + password: this.profilInfo.value.newPass, + }; + this.authService.updatePassword(dataPassword).subscribe( + (res) => { + this.toastr.success("Success", "Update Password Completed.", { + timeOut: 2000, + closeButton: true, + }); + this.logout() + }, + (error) => { + console.error(error); + this.toastr.error("Error", "Something went wrong!", { + timeOut: 2000, + closeButton: true, + }); + } + ); + } + } + + logout() { + if (localStorage.getItem('currentUser')) { + this.logoutService.doLogout().then(res => { + window.location.href = '/login'; + }, err => { + console.log(err); + }); + } } toggleCurrentPassVisibility() { diff --git a/src/app/login/login.component.ts b/src/app/login/login.component.ts index 2647de1..81a409b 100644 --- a/src/app/login/login.component.ts +++ b/src/app/login/login.component.ts @@ -6,6 +6,19 @@ import { AlertService } from "../_services/alert.service"; import { HttpClient } from "@angular/common/http"; import { BuildingService } from "../content/hemat-app/service/monitoring-api.service"; import { ToastrService } from "ngx-toastr"; +import { jwtDecode } from "jwt-decode"; + +interface CustomJwtPayload { + exp: number; + scope: string; + iat: number; + preferred_username: string; + name: string; + email: string; + family_name: string; + given_name: string; + sub: string; +} @Component({ templateUrl: "login.component.html", @@ -33,79 +46,20 @@ export class LoginComponent implements OnInit { } ngOnInit() { - // this.loginForm = this.formBuilder.group({ - // email: ["john@pixinvent.com", Validators.required], - // password: ["password@123", Validators.required], - // rememberMe: false, - // }); this.loginForm = this.formBuilder.group({ - email: ["user1", Validators.required], - password: ["password", Validators.required], + email: ["", Validators.required], + password: ["", Validators.required], rememberMe: false, }); if (localStorage.getItem("currentUser")) { this.router.navigate(["/monitoring"]); } - // Remember Me - // console.log(localStorage.getItem("remember")); - - // if (localStorage.getItem("remember")) { - // this.renderer.removeClass(document.body, "bg-full-screen-image"); - // localStorage.removeItem("currentLayoutStyle"); - // this.router.navigate(["/monitoring"]); - // } else if (localStorage.getItem("currentUser")) { - // // Force logout on login if not remember me - // this.authService.doLogout(); - // this.isPageLoaded = true; - // } else { - // this.isPageLoaded = true; - // } } - // convenience getter for easy access to form fields get f() { return this.loginForm.controls; } - // tryLogin() { - // this.submitted = true; - - // // stop here if form is invalid - // if (this.loginForm.invalid) { - // return; - // } - // const value = { - // email: this.f.email.value, - // password: this.f.password.value, - // }; - - // this.authService.doLogin(value).then( - // (res) => { - // console.log(res, 'res login'); - - // if ( - // this.loginForm.controls["rememberMe"] && - // this.loginForm.controls["rememberMe"].value - // ) { - // localStorage.setItem("remember", "true"); - // } else { - // localStorage.removeItem("remember"); - // } - // this.setUserInStorage(res); - // localStorage.removeItem("currentLayoutStyle"); - // let returnUrl = "/monitoring"; - // if (this.returnUrl) { - // returnUrl = this.returnUrl; - // } - // this.router.navigate([returnUrl]); - // }, - // (err) => { - // this.submitted = false; - // this.alertService.error(err.message); - // } - // ); - // } - tryLogin() { this.submitted = true; @@ -115,33 +69,38 @@ export class LoginComponent implements OnInit { const loginData = { username: this.loginForm.value.email, - password: this.loginForm.value.password + password: this.loginForm.value.password, }; - this.monitoringApiService.postLogin(loginData) - .subscribe( - (response: any) => { - localStorage.setItem('access_token', response.access_token); - const userProfile = { - displayName: this.loginForm.value.email, - buildingId: 4 - }; - this.toastr.success("Success", "Selamat Datang " + userProfile.displayName , { + this.monitoringApiService.postLogin(loginData).subscribe( + (response: any) => { + const decodedToken = jwtDecode(response.access_token); + // localStorage.setItem("access_token", response.access_token); + localStorage.setItem("account_info", JSON.stringify(decodedToken)); + + const userProfile = { + displayName: decodedToken.name, + buildingId: 4, + }; + this.toastr.success( + "Success", + "Selamat Datang " + userProfile.displayName, + { timeOut: 5000, closeButton: true, - }); - localStorage.setItem('currentUser', JSON.stringify(userProfile)); - this.router.navigate(['/monitoring']); - - }, - error => { - this.toastr.error("Error", "Akun yang anda masukan salah!", { - timeOut: 5000, - closeButton: true, - }); - console.error('Login failed:', error); - } - ); + } + ); + localStorage.setItem("currentUser", JSON.stringify(userProfile)); + this.router.navigate(["/monitoring"]); + }, + (error) => { + this.toastr.error("Error", "Akun yang anda masukan salah!", { + timeOut: 5000, + closeButton: true, + }); + console.error("Login failed:", error); + } + ); } addCheckbox(event) {