working frontend, after token swap store credential in SQLite db.

This commit is contained in:
Jason Kulatunga 2022-08-25 21:57:29 -07:00
parent 745768e2e6
commit 41e60cd7d6
10 changed files with 112 additions and 31 deletions

View File

@ -25,6 +25,7 @@ func (c *configuration) Init() error {
c.SetDefault("web.listen.host", "0.0.0.0")
c.SetDefault("web.listen.basepath", "")
c.SetDefault("web.src.frontend.path", "/opt/fasten/web")
c.SetDefault("web.database.location", "fasten.db") //TODO: should be /opt/fasten/fasten.db
c.SetDefault("log.level", "INFO")
c.SetDefault("log.file", "")

View File

@ -41,6 +41,16 @@ func NewRepository(appConfig config.Interface, globalLogger logrus.FieldLogger)
}
globalLogger.Infof("Successfully connected to scrutiny sqlite db: %s\n", appConfig.GetString("web.database.location"))
//TODO: automigrate for now
err = database.AutoMigrate(&models.User{})
if err != nil {
return nil, fmt.Errorf("Failed to automigrate! - %v", err)
}
err = database.AutoMigrate(&models.ProviderCredential{})
if err != nil {
return nil, fmt.Errorf("Failed to automigrate! - %v", err)
}
deviceRepo := sqliteRepository{
appConfig: appConfig,
logger: globalLogger,
@ -65,7 +75,7 @@ func (sr *sqliteRepository) Close() error {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
func (sr *sqliteRepository) CreateProviderCredentials(ctx context.Context, providerCreds models.ProviderCredential) error {
return sr.gormClient.WithContext(ctx).Create(providerCreds).Error
return sr.gormClient.WithContext(ctx).Create(&providerCreds).Error
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

View File

@ -5,18 +5,18 @@ import "gorm.io/gorm"
type ProviderCredential struct {
gorm.Model
OauthEndpointBaseUrl string `json:"oauth_endpoint_base_url"`
ApiEndpointBaseUrl string `json:"api_endpoint_base_url"`
ClientId string `json:"client_id"`
RedirectUri string `json:"redirect_uri"`
Scopes []string `json:"scopes"`
PatientId string `json:"patient"`
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
IdToken string `json:"id_token"`
ExpiresAt string `json:"expires_at"`
CodeChallenge string `json:"code_challenge"`
CodeVerifier string `json:"code_verifier"`
OauthEndpointBaseUrl string `json:"oauth_endpoint_base_url"`
ApiEndpointBaseUrl string `json:"api_endpoint_base_url"`
ClientId string `json:"client_id"`
RedirectUri string `json:"redirect_uri"`
Scopes string `json:"scopes"`
PatientId string `json:"patient"`
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
IdToken string `json:"id_token"`
ExpiresAt int64 `json:"expires_at"`
CodeChallenge string `json:"code_challenge"`
CodeVerifier string `json:"code_verifier"`
}
/*

View File

@ -0,0 +1,7 @@
package models
type ResponseWrapper struct {
Success bool `json:"success"`
Error string `json:"error"`
Data interface{} `json:"data"`
}

View File

@ -19,6 +19,8 @@ func CreateProviderCredentials(c *gin.Context) {
return
}
logger.Infof("Parsed Create Provider Credentials Payload: %v", providerCred)
err := databaseRepo.CreateProviderCredentials(c, providerCred)
if err != nil {
logger.Errorln("An error occurred while storing provider credential", err)

View File

@ -39,7 +39,7 @@ func (ae *AppEngine) Setup(logger *logrus.Entry) *gin.Engine {
"success": true,
})
})
api.POST("/provider_credentials", handler.CreateProviderCredentials) //used to save settings
api.POST("/provider_credential", handler.CreateProviderCredentials) //used to save settings
}
}

View File

@ -8,6 +8,8 @@ import BrowserAdapter from 'fhirclient/lib/adapters/BrowserAdapter';
import {PassportService} from './services/passport.service';
import {ProviderConfig} from './models/passport/provider-config';
import {AuthorizeClaim} from './models/passport/authorize-claim';
import {FastenApiService} from './services/fasten-api.service';
import {ProviderCredential} from './models/fasten/provider-credential';
export const retryCount = 24; //wait 2 minutes (5 * 24 = 120)
export const retryWaitMilliSeconds = 5000; //wait 5 seconds
@ -20,7 +22,10 @@ export class AppComponent {
title = 'fastenhealth';
constructor(private passportApi: PassportService) { }
constructor(
private passportApi: PassportService,
private fastenApi: FastenApiService,
) { }
connect(provider: string) {
this.passportApi.getProviderConfig(provider)
@ -81,23 +86,34 @@ export class AppComponent {
//Create FHIR Client
const clientState = {
serverUrl: connectData.api_endpoint_base_url,
clientId: connectData.client_id,
redirectUri: connectData.redirect_uri,
tokenUri: `${connectData.oauth_endpoint_base_url}/token`,
scope: connectData.scopes.join(' '),
tokenResponse: payload,
expiresAt: getAccessTokenExpiration(payload, new BrowserAdapter()),
codeChallenge: codeChallenge,
codeVerifier: codeVerifier
const providerCredential: ProviderCredential = {
oauth_endpoint_base_url: connectData.oauth_endpoint_base_url,
api_endpoint_base_url: connectData.api_endpoint_base_url,
client_id: connectData.client_id,
redirect_uri: connectData.redirect_uri,
scopes: connectData.scopes.join(' '),
patient: payload.patient,
access_token: payload.access_token,
refresh_token: payload.refresh_token,
id_token: payload.id_token,
expires_at: getAccessTokenExpiration(payload, new BrowserAdapter()),
code_challenge: codeChallenge,
code_verifier: codeVerifier,
}
console.log("STARTING--- FHIR.client(clientState)", clientState)
const fhirClient = FHIR.client(clientState);
console.log("STARTING--- client.request(Patient)")
const patientResponse = await fhirClient.request("PatientAccess/v1/$userinfo")
console.log(patientResponse)
this.fastenApi.createProviderCredential(providerCredential).subscribe( (respData) => {
console.log("provider credential create response:", respData)
})
// console.log("STARTING--- FHIR.client(clientState)", clientState)
// const fhirClient = FHIR.client(clientState);
//
// console.log("STARTING--- client.request(Patient)")
// const patientResponse = await fhirClient.request("PatientAccess/v1/$userinfo")
// console.log(patientResponse)

View File

@ -0,0 +1,7 @@
import { ProviderCredential } from './provider-credential';
describe('ProviderCredential', () => {
it('should create an instance', () => {
expect(new ProviderCredential()).toBeTruthy();
});
});

View File

@ -0,0 +1,16 @@
export class ProviderCredential {
id?: number
oauth_endpoint_base_url: string
api_endpoint_base_url: string
client_id: string
redirect_uri: string
scopes: string //space seperated string
patient: string
access_token: string
refresh_token: string
id_token: string
expires_at: number
code_challenge: string
code_verifier: string
}

View File

@ -1,9 +1,31 @@
import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {ProviderConfig} from '../models/passport/provider-config';
import {environment} from '../../environments/environment';
import {map} from 'rxjs/operators';
import {ResponseWrapper} from '../models/response-wrapper';
import {ProviderCredential} from '../models/fasten/provider-credential';
@Injectable({
providedIn: 'root'
})
export class FastenApiService {
constructor() { }
constructor(private _httpClient: HttpClient) {
}
getBasePath(): string {
return window.location.pathname.split('/web').slice(0, 1)[0];
}
createProviderCredential(providerCredential: ProviderCredential): Observable<ProviderCredential> {
return this._httpClient.post<any>(`${this.getBasePath()}/api/provider_credential`, providerCredential)
.pipe(
map((response: ResponseWrapper) => {
console.log("PROVIDER CREDENTIAL RESPONSE", response)
return response.data as ProviderCredential
})
);
}
}