integrasi update password

This commit is contained in:
Fuzi_fauzia 2024-07-03 17:39:46 +07:00
parent 4b023b2527
commit ccf656dfce
6 changed files with 161 additions and 96 deletions

14
package-lock.json generated
View File

@ -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",

View File

@ -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",

View File

@ -107,11 +107,17 @@ export class AuthService {
doLogout() {
return new Promise<void>((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();
}

View File

@ -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<any> {
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<any>(url, data, { headers });
}
}

View File

@ -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() {

View File

@ -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<CustomJwtPayload>(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) {