import { Injectable } from "@angular/core" ; import { HttpClient , HttpHeaders } from "@angular/common/http" ; @ Injectable ( { providedIn : "root" , } ) export class UserAccountService { private static readonly COUCHDB_USER_ENDPOINT = "/db/_users/org.couchdb.user" ; constructor ( private http ) { } param username param oldPassword param newPassword return public async changePassword ( username , oldPassword , newPassword ) { let userResponse ; try { userResponse = await this . getCouchDBUser ( username , oldPassword ) ; } catch ( e ) { throw new Error ( "Current password incorrect or server not available" ) ; } userResponse [ "password" ] = newPassword ; try { await this . saveNewPasswordToCouchDB ( username , oldPassword , userResponse ) ; } catch ( e ) { throw new Error ( "Could not save new password, please contact your system administrator" ) ; } } private getCouchDBUser ( username , password ) { const userUrl = UserAccountService . COUCHDB_USER_ENDPOINT + ":" + username ; const headers = new HttpHeaders ( { Authorization : "Basic " + btoa ( username + ":" + password ) , } ) ; return this . http . get ( userUrl , { headers : headers } ) . toPromise ( ) ; } private saveNewPasswordToCouchDB ( username , oldPassword , userObj ) { const userUrl = UserAccountService . COUCHDB_USER_ENDPOINT + ":" + username ; const headers = new HttpHeaders ( { Authorization : "Basic " + btoa ( username + ":" + oldPassword ) , } ) ; return this . http . put ( userUrl , userObj , { headers : headers } ) . toPromise ( ) ; } }