import PouchDB from "pouchdb-browser" ; import { AppConfig } from "../../app-config/app-config" ; import { Injectable } from "@angular/core" ; import { HttpClient , HttpErrorResponse } from "@angular/common/http" ; import { DatabaseUser } from "./local-user" ; import { SessionService } from "./session.service" ; import { LoginState } from "../session-states/login-state.enum" ; import { Database } from "../../database/database" ; import { PouchDatabase } from "../../database/pouch-database" ; import { LoggingService } from "../../logging/logging.service" ; /**
 * Responsibilities:
 * - Hold the remote DB
 * - Handle auth against CouchDB
 * - provide "am i online"-info
 */ @ Injectable ( ) export class RemoteSession extends SessionService { readonly UNAUTHORIZED_STATUS_CODE = 401 ; /** remote (!) database PouchDB */ public pouchDB : PouchDB . Database ; private readonly database : Database ; private currentDBUser : DatabaseUser ; /**
     * Create a RemoteSession and set up connection to the remote CouchDB server configured in AppConfig.
     */ constructor ( private httpClient , private loggingService ) { super ( ) ; this . pouchDB = new PouchDB ( AppConfig . settings . database . remote_url + AppConfig . settings . database . name , { skip_setup : true , } ) ; this . database = new PouchDatabase ( this . pouchDB , this . loggingService ) ; } param username param password public async login ( username , password ) { try { const response = await this . httpClient . post ( `${ AppConfig . settings . database . remote_url }_session` , { name : username , password : password } , { withCredentials : true } ) . toPromise ( ) ; this . assignDatabaseUser ( response ) ; this . loginState . next ( LoginState . LOGGED_IN ) ; } catch ( error ) { const httpError = error as HttpErrorResponse ; if ( httpError ?. status === this . UNAUTHORIZED_STATUS_CODE ) { this . loginState . next ( LoginState . LOGIN_FAILED ) ; } else { this . loginState . next ( LoginState . UNAVAILABLE ) ; } } return this . loginState . value ; } private assignDatabaseUser ( couchDBResponse ) { this . currentDBUser = { name : couchDBResponse . name , roles : couchDBResponse . roles , } ; } /**
     * Logout at the remote database.
     */ public async logout ( ) { await this . httpClient . delete ( `${ AppConfig . settings . database . remote_url }_session` , { withCredentials : true , } ) . toPromise ( ) ; this . currentDBUser = undefined ; this . loginState . next ( LoginState . LOGGED_OUT ) ; } getCurrentUser ( ) { return this . currentDBUser ; } checkPassword ( username , password ) { throw Error ( "Can't check password in remote session" ) ; } getDatabase ( ) { return this . database ; } sync ( ) { return Promise . reject ( new Error ( "Cannot sync remote session" ) ) ; } }