Merge pull request #7 from fastenhealth/spa
This commit is contained in:
commit
77c23e62f0
|
@ -57,3 +57,4 @@ fabric.properties
|
||||||
vendor
|
vendor
|
||||||
fasten.db
|
fasten.db
|
||||||
test.go
|
test.go
|
||||||
|
/.couchdb
|
||||||
|
|
|
@ -4,4 +4,28 @@ cd frontend
|
||||||
npm run dist
|
npm run dist
|
||||||
go mod vendor
|
go mod vendor
|
||||||
go run backend/cmd/fasten/fasten.go start --config ./config.example.yaml --debug
|
go run backend/cmd/fasten/fasten.go start --config ./config.example.yaml --debug
|
||||||
|
|
||||||
|
docker build -t fasten-couchdb -f docker/couchdb/Dockerfile .
|
||||||
|
docker run --rm -it -p 5984:5984 -v `pwd`/.couchdb/data:/opt/couchdb/data -v `pwd`/.couchdb/config:/opt/couchdb/etc/local.d fasten-couchdb
|
||||||
```
|
```
|
||||||
|
|
||||||
|
# Docker
|
||||||
|
``
|
||||||
|
|
||||||
|
- http://localhost:9090/web/dashboard - WebUI
|
||||||
|
- http://localhost:9090/database - CouchDB proxy
|
||||||
|
- http://localhost:5984/_utils/ - CouchDB admin UI
|
||||||
|
|
||||||
|
# Credentials
|
||||||
|
- Couchdb:
|
||||||
|
- username: `admin`
|
||||||
|
- password: `mysecretpassword`
|
||||||
|
- WebUI:
|
||||||
|
- username: `testuser`
|
||||||
|
- password: `testuser`
|
||||||
|
|
||||||
|
|
||||||
|
# Running tests
|
||||||
|
|
||||||
|
- ng test --include='**/base_client.spec.ts'
|
||||||
|
- ng test --include='lib/**/*.spec.ts'
|
||||||
|
|
27
Dockerfile
27
Dockerfile
|
@ -1,3 +1,6 @@
|
||||||
|
#########################################################################################################
|
||||||
|
# Frontend Build
|
||||||
|
#########################################################################################################
|
||||||
FROM node:18.9.0 as frontend-build
|
FROM node:18.9.0 as frontend-build
|
||||||
WORKDIR /usr/src/fastenhealth/frontend
|
WORKDIR /usr/src/fastenhealth/frontend
|
||||||
#COPY frontend/package.json frontend/yarn.lock ./
|
#COPY frontend/package.json frontend/yarn.lock ./
|
||||||
|
@ -8,6 +11,9 @@ RUN yarn config set registry "http://registry.npmjs.org" \
|
||||||
COPY frontend/ ./
|
COPY frontend/ ./
|
||||||
RUN yarn run build -- --configuration sandbox --output-path=../dist
|
RUN yarn run build -- --configuration sandbox --output-path=../dist
|
||||||
|
|
||||||
|
#########################################################################################################
|
||||||
|
# Backend Build
|
||||||
|
#########################################################################################################
|
||||||
FROM golang:1.18 as backend-build
|
FROM golang:1.18 as backend-build
|
||||||
WORKDIR /go/src/github.com/fastenhealth/fastenhealth-onprem
|
WORKDIR /go/src/github.com/fastenhealth/fastenhealth-onprem
|
||||||
COPY . .
|
COPY . .
|
||||||
|
@ -26,12 +32,29 @@ RUN mkdir -p /opt/fasten/db \
|
||||||
&& curl -o /opt/fasten/db/fasten.db -L https://github.com/fastenhealth/testdata/raw/main/fasten.db
|
&& curl -o /opt/fasten/db/fasten.db -L https://github.com/fastenhealth/testdata/raw/main/fasten.db
|
||||||
|
|
||||||
|
|
||||||
|
#########################################################################################################
|
||||||
|
# Distribution Build
|
||||||
|
#########################################################################################################
|
||||||
|
FROM couchdb:3.2
|
||||||
|
|
||||||
|
ARG S6_ARCH=amd64
|
||||||
|
RUN curl https://github.com/just-containers/s6-overlay/releases/download/v1.21.8.0/s6-overlay-${S6_ARCH}.tar.gz -L -s --output /tmp/s6-overlay-${S6_ARCH}.tar.gz \
|
||||||
|
&& tar xzf /tmp/s6-overlay-${S6_ARCH}.tar.gz -C / \
|
||||||
|
&& rm -rf /tmp/s6-overlay-${S6_ARCH}.tar.gz
|
||||||
|
|
||||||
|
COPY /docker/couchdb/local.ini /opt/couchdb/etc/
|
||||||
|
COPY /docker/rootfs /
|
||||||
|
|
||||||
FROM gcr.io/distroless/static-debian11
|
|
||||||
WORKDIR /opt/fasten/
|
WORKDIR /opt/fasten/
|
||||||
COPY --from=backend-build /opt/fasten/ /opt/fasten/
|
COPY --from=backend-build /opt/fasten/ /opt/fasten/
|
||||||
COPY --from=frontend-build /usr/src/fastenhealth/dist /opt/fasten/web
|
COPY --from=frontend-build /usr/src/fastenhealth/dist /opt/fasten/web
|
||||||
COPY --from=backend-build /go/bin/fasten /opt/fasten/fasten
|
COPY --from=backend-build /go/bin/fasten /opt/fasten/fasten
|
||||||
COPY LICENSE.md /opt/fasten/LICENSE.md
|
COPY LICENSE.md /opt/fasten/LICENSE.md
|
||||||
COPY config.yaml /opt/fasten/config/config.yaml
|
COPY config.yaml /opt/fasten/config/config.yaml
|
||||||
CMD ["/opt/fasten/fasten", "start", "--config", "/opt/fasten/config/config.yaml"]
|
|
||||||
|
ENTRYPOINT ["/init"]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
681
LICENSE.md
681
LICENSE.md
|
@ -1,15 +1,674 @@
|
||||||
Copyright (C) Jason Kulatunga - All Rights Reserved.
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
THE CONTENTS OF THIS PROJECT ARE PROPRIETARY AND CONFIDENTIAL.
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
UNAUTHORIZED COPYING, TRANSFERRING OR REPRODUCTION OF THE CONTENTS OF THIS PROJECT, VIA ANY MEDIUM IS STRICTLY PROHIBITED.
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
The receipt or possession of the source code and/or any parts thereof does not convey or imply any right to use them
|
Preamble
|
||||||
for any purpose other than the purpose for which they were provided to you.
|
|
||||||
|
|
||||||
The software is provided "AS IS", without warranty of any kind, express or implied, including but not limited to
|
The GNU General Public License is a free, copyleft license for
|
||||||
the warranties of merchantability, fitness for a particular purpose and non infringement.
|
software and other kinds of works.
|
||||||
In no event shall the authors or copyright holders be liable for any claim, damages or other liability,
|
|
||||||
whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software
|
|
||||||
or the use or other dealings in the software.
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
|
GNU General Public License for most of our software; it applies also to
|
||||||
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you
|
||||||
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
|
that there is no warranty for this free software. For both users' and
|
||||||
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run
|
||||||
|
modified versions of the software inside them, although the manufacturer
|
||||||
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
|
protecting users' freedom to change the software. The systematic
|
||||||
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents.
|
||||||
|
States should not allow patents to restrict development and use of
|
||||||
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
|
avoid the special danger that patents applied to a free program could
|
||||||
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
|
patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
<program> Copyright (C) <year> <name of author>
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||||
|
|
|
@ -6,3 +6,4 @@ Find & replace the following
|
||||||
- `fastenhealth` - find and replace this with your binary name
|
- `fastenhealth` - find and replace this with your binary name
|
||||||
- make sure you rename the folder as well.
|
- make sure you rename the folder as well.
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -1,56 +0,0 @@
|
||||||
package auth
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"github.com/golang-jwt/jwt"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
//TODO: this should match the ID and username for the user.
|
|
||||||
type JWTClaim struct {
|
|
||||||
Username string `json:"username"`
|
|
||||||
UserId string `json:"user_id"`
|
|
||||||
Email string `json:"email"`
|
|
||||||
jwt.StandardClaims
|
|
||||||
}
|
|
||||||
|
|
||||||
func GenerateJWT(encryptionKey string, username string, userId string) (tokenString string, err error) {
|
|
||||||
expirationTime := time.Now().Add(2 * time.Hour)
|
|
||||||
claims := &JWTClaim{
|
|
||||||
Username: username,
|
|
||||||
Email: username,
|
|
||||||
UserId: userId,
|
|
||||||
StandardClaims: jwt.StandardClaims{
|
|
||||||
ExpiresAt: expirationTime.Unix(),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
||||||
tokenString, err = token.SignedString([]byte(encryptionKey))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func ValidateToken(encryptionKey string, signedToken string) (*JWTClaim, error) {
|
|
||||||
token, err := jwt.ParseWithClaims(
|
|
||||||
signedToken,
|
|
||||||
&JWTClaim{},
|
|
||||||
func(token *jwt.Token) (interface{}, error) {
|
|
||||||
if jwt.SigningMethodHS256 != token.Method {
|
|
||||||
return nil, errors.New("Invalid signing algorithm")
|
|
||||||
}
|
|
||||||
return []byte(encryptionKey), nil
|
|
||||||
},
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
claims, ok := token.Claims.(*JWTClaim)
|
|
||||||
if !ok {
|
|
||||||
err = errors.New("couldn't parse claims")
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if claims.ExpiresAt < time.Now().Local().Unix() {
|
|
||||||
err = errors.New("token expired")
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return claims, nil
|
|
||||||
}
|
|
|
@ -25,7 +25,12 @@ func (c *configuration) Init() error {
|
||||||
c.SetDefault("web.listen.host", "0.0.0.0")
|
c.SetDefault("web.listen.host", "0.0.0.0")
|
||||||
c.SetDefault("web.listen.basepath", "")
|
c.SetDefault("web.listen.basepath", "")
|
||||||
c.SetDefault("web.src.frontend.path", "/opt/fasten/web")
|
c.SetDefault("web.src.frontend.path", "/opt/fasten/web")
|
||||||
c.SetDefault("web.database.location", "/opt/fasten/db/fasten.db") //TODO: should be /opt/fasten/fasten.db
|
|
||||||
|
c.SetDefault("web.couchdb.scheme", "http")
|
||||||
|
c.SetDefault("web.couchdb.host", "localhost")
|
||||||
|
c.SetDefault("web.couchdb.port", "5984")
|
||||||
|
c.SetDefault("web.couchdb.admin_username", "admin")
|
||||||
|
c.SetDefault("web.couchdb.admin_password", "mysecretpassword")
|
||||||
|
|
||||||
c.SetDefault("log.level", "INFO")
|
c.SetDefault("log.level", "INFO")
|
||||||
c.SetDefault("log.file", "")
|
c.SetDefault("log.file", "")
|
||||||
|
@ -72,9 +77,5 @@ func (c *configuration) ReadConfig(configFilePath string) error {
|
||||||
// This function ensures that required configuration keys (that must be manually set) are present
|
// This function ensures that required configuration keys (that must be manually set) are present
|
||||||
func (c *configuration) ValidateConfig() error {
|
func (c *configuration) ValidateConfig() error {
|
||||||
|
|
||||||
if !c.IsSet("web.jwt.encryptionkey") {
|
|
||||||
return errors.ConfigValidationError("`web.jwt.encryptionkey` configuration option must be set")
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,77 @@
|
||||||
|
package database
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config"
|
||||||
|
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/models"
|
||||||
|
"github.com/go-kivik/couchdb/v3"
|
||||||
|
_ "github.com/go-kivik/couchdb/v3" // The CouchDB driver
|
||||||
|
"github.com/go-kivik/kivik/v3"
|
||||||
|
"github.com/sirupsen/logrus"
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewRepository(appConfig config.Interface, globalLogger logrus.FieldLogger) (DatabaseRepository, error) {
|
||||||
|
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||||
|
// Couchdb setup
|
||||||
|
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||||
|
couchdbUrl := fmt.Sprintf("%s://%s:%s", appConfig.GetString("web.couchdb.scheme"), appConfig.GetString("web.couchdb.host"), appConfig.GetString("web.couchdb.port"))
|
||||||
|
|
||||||
|
globalLogger.Infof("Trying to connect to couchdb: %s\n", couchdbUrl)
|
||||||
|
|
||||||
|
database, err := kivik.New("couch", couchdbUrl)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("Failed to connect to database! - %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = database.Authenticate(context.Background(),
|
||||||
|
couchdb.BasicAuth(
|
||||||
|
appConfig.GetString("web.couchdb.admin_username"),
|
||||||
|
appConfig.GetString("web.couchdb.admin_password")),
|
||||||
|
)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("Failed to authenticate to database! - %v", err)
|
||||||
|
}
|
||||||
|
globalLogger.Infof("Successfully connected to couchdb: %s\n", couchdbUrl)
|
||||||
|
|
||||||
|
deviceRepo := couchdbRepository{
|
||||||
|
appConfig: appConfig,
|
||||||
|
logger: globalLogger,
|
||||||
|
client: database,
|
||||||
|
}
|
||||||
|
return &deviceRepo, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type couchdbRepository struct {
|
||||||
|
appConfig config.Interface
|
||||||
|
logger logrus.FieldLogger
|
||||||
|
|
||||||
|
client *kivik.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
type couchDbUser struct {
|
||||||
|
ID string `json:"_id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
Roles []string `json:"roles"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cr *couchdbRepository) CreateUser(ctx context.Context, user *models.User) error {
|
||||||
|
|
||||||
|
newUser := &couchDbUser{
|
||||||
|
ID: fmt.Sprintf("%s%s", kivik.UserPrefix, user.Username),
|
||||||
|
Name: user.Username,
|
||||||
|
Type: "user",
|
||||||
|
Roles: []string{},
|
||||||
|
Password: user.Password,
|
||||||
|
}
|
||||||
|
db := cr.client.DB(ctx, "_users")
|
||||||
|
_, err := db.Put(ctx, newUser.ID, newUser)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cr *couchdbRepository) Close() error {
|
||||||
|
return nil
|
||||||
|
}
|
|
@ -10,21 +10,4 @@ type DatabaseRepository interface {
|
||||||
Close() error
|
Close() error
|
||||||
|
|
||||||
CreateUser(context.Context, *models.User) error
|
CreateUser(context.Context, *models.User) error
|
||||||
GetUserByEmail(context.Context, string) (*models.User, error)
|
|
||||||
GetCurrentUser(context.Context) *models.User
|
|
||||||
|
|
||||||
GetSummary(ctx context.Context) (*models.Summary, error)
|
|
||||||
|
|
||||||
UpsertResource(context.Context, *models.ResourceFhir) error
|
|
||||||
GetResourceBySourceType(context.Context, string, string) (*models.ResourceFhir, error)
|
|
||||||
GetResourceBySourceId(context.Context, string, string) (*models.ResourceFhir, error)
|
|
||||||
ListResources(context.Context, models.ListResourceQueryOptions) ([]models.ResourceFhir, error)
|
|
||||||
GetPatientForSources(ctx context.Context) ([]models.ResourceFhir, error)
|
|
||||||
//UpsertProfile(context.Context, *models.Profile) error
|
|
||||||
//UpsertOrganziation(context.Context, *models.Organization) error
|
|
||||||
|
|
||||||
CreateSource(context.Context, *models.Source) error
|
|
||||||
GetSource(context.Context, string) (*models.Source, error)
|
|
||||||
GetSourceSummary(context.Context, string) (*models.SourceSummary, error)
|
|
||||||
GetSources(context.Context) ([]models.Source, error)
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -49,20 +49,6 @@ func (mr *MockDatabaseRepositoryMockRecorder) Close() *gomock.Call {
|
||||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockDatabaseRepository)(nil).Close))
|
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockDatabaseRepository)(nil).Close))
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreateSource mocks base method.
|
|
||||||
func (m *MockDatabaseRepository) CreateSource(arg0 context.Context, arg1 *models.Source) error {
|
|
||||||
m.ctrl.T.Helper()
|
|
||||||
ret := m.ctrl.Call(m, "CreateSource", arg0, arg1)
|
|
||||||
ret0, _ := ret[0].(error)
|
|
||||||
return ret0
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateSource indicates an expected call of CreateSource.
|
|
||||||
func (mr *MockDatabaseRepositoryMockRecorder) CreateSource(arg0, arg1 interface{}) *gomock.Call {
|
|
||||||
mr.mock.ctrl.T.Helper()
|
|
||||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateSource", reflect.TypeOf((*MockDatabaseRepository)(nil).CreateSource), arg0, arg1)
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateUser mocks base method.
|
// CreateUser mocks base method.
|
||||||
func (m *MockDatabaseRepository) CreateUser(arg0 context.Context, arg1 *models.User) error {
|
func (m *MockDatabaseRepository) CreateUser(arg0 context.Context, arg1 *models.User) error {
|
||||||
m.ctrl.T.Helper()
|
m.ctrl.T.Helper()
|
||||||
|
@ -76,166 +62,3 @@ func (mr *MockDatabaseRepositoryMockRecorder) CreateUser(arg0, arg1 interface{})
|
||||||
mr.mock.ctrl.T.Helper()
|
mr.mock.ctrl.T.Helper()
|
||||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateUser", reflect.TypeOf((*MockDatabaseRepository)(nil).CreateUser), arg0, arg1)
|
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateUser", reflect.TypeOf((*MockDatabaseRepository)(nil).CreateUser), arg0, arg1)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetCurrentUser mocks base method.
|
|
||||||
func (m *MockDatabaseRepository) GetCurrentUser(arg0 context.Context) models.User {
|
|
||||||
m.ctrl.T.Helper()
|
|
||||||
ret := m.ctrl.Call(m, "GetCurrentUser", arg0)
|
|
||||||
ret0, _ := ret[0].(models.User)
|
|
||||||
return ret0
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetCurrentUser indicates an expected call of GetCurrentUser.
|
|
||||||
func (mr *MockDatabaseRepositoryMockRecorder) GetCurrentUser(arg0 interface{}) *gomock.Call {
|
|
||||||
mr.mock.ctrl.T.Helper()
|
|
||||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentUser", reflect.TypeOf((*MockDatabaseRepository)(nil).GetCurrentUser), arg0)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetPatientForSources mocks base method.
|
|
||||||
func (m *MockDatabaseRepository) GetPatientForSources(ctx context.Context) ([]models.ResourceFhir, error) {
|
|
||||||
m.ctrl.T.Helper()
|
|
||||||
ret := m.ctrl.Call(m, "GetPatientForSources", ctx)
|
|
||||||
ret0, _ := ret[0].([]models.ResourceFhir)
|
|
||||||
ret1, _ := ret[1].(error)
|
|
||||||
return ret0, ret1
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetPatientForSources indicates an expected call of GetPatientForSources.
|
|
||||||
func (mr *MockDatabaseRepositoryMockRecorder) GetPatientForSources(ctx interface{}) *gomock.Call {
|
|
||||||
mr.mock.ctrl.T.Helper()
|
|
||||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPatientForSources", reflect.TypeOf((*MockDatabaseRepository)(nil).GetPatientForSources), ctx)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetResource mocks base method.
|
|
||||||
func (m *MockDatabaseRepository) GetResource(arg0 context.Context, arg1 string) (*models.ResourceFhir, error) {
|
|
||||||
m.ctrl.T.Helper()
|
|
||||||
ret := m.ctrl.Call(m, "GetResource", arg0, arg1)
|
|
||||||
ret0, _ := ret[0].(*models.ResourceFhir)
|
|
||||||
ret1, _ := ret[1].(error)
|
|
||||||
return ret0, ret1
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetResource indicates an expected call of GetResource.
|
|
||||||
func (mr *MockDatabaseRepositoryMockRecorder) GetResource(arg0, arg1 interface{}) *gomock.Call {
|
|
||||||
mr.mock.ctrl.T.Helper()
|
|
||||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetResource", reflect.TypeOf((*MockDatabaseRepository)(nil).GetResource), arg0, arg1)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetResourceBySourceId mocks base method.
|
|
||||||
func (m *MockDatabaseRepository) GetResourceBySourceId(arg0 context.Context, arg1, arg2 string) (*models.ResourceFhir, error) {
|
|
||||||
m.ctrl.T.Helper()
|
|
||||||
ret := m.ctrl.Call(m, "GetResourceBySourceId", arg0, arg1, arg2)
|
|
||||||
ret0, _ := ret[0].(*models.ResourceFhir)
|
|
||||||
ret1, _ := ret[1].(error)
|
|
||||||
return ret0, ret1
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetResourceBySourceId indicates an expected call of GetResourceBySourceId.
|
|
||||||
func (mr *MockDatabaseRepositoryMockRecorder) GetResourceBySourceId(arg0, arg1, arg2 interface{}) *gomock.Call {
|
|
||||||
mr.mock.ctrl.T.Helper()
|
|
||||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetResourceBySourceId", reflect.TypeOf((*MockDatabaseRepository)(nil).GetResourceBySourceId), arg0, arg1, arg2)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetSource mocks base method.
|
|
||||||
func (m *MockDatabaseRepository) GetSource(arg0 context.Context, arg1 string) (*models.Source, error) {
|
|
||||||
m.ctrl.T.Helper()
|
|
||||||
ret := m.ctrl.Call(m, "GetSource", arg0, arg1)
|
|
||||||
ret0, _ := ret[0].(*models.Source)
|
|
||||||
ret1, _ := ret[1].(error)
|
|
||||||
return ret0, ret1
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetSource indicates an expected call of GetSource.
|
|
||||||
func (mr *MockDatabaseRepositoryMockRecorder) GetSource(arg0, arg1 interface{}) *gomock.Call {
|
|
||||||
mr.mock.ctrl.T.Helper()
|
|
||||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSource", reflect.TypeOf((*MockDatabaseRepository)(nil).GetSource), arg0, arg1)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetSourceSummary mocks base method.
|
|
||||||
func (m *MockDatabaseRepository) GetSourceSummary(arg0 context.Context, arg1 string) (*models.SourceSummary, error) {
|
|
||||||
m.ctrl.T.Helper()
|
|
||||||
ret := m.ctrl.Call(m, "GetSourceSummary", arg0, arg1)
|
|
||||||
ret0, _ := ret[0].(*models.SourceSummary)
|
|
||||||
ret1, _ := ret[1].(error)
|
|
||||||
return ret0, ret1
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetSourceSummary indicates an expected call of GetSourceSummary.
|
|
||||||
func (mr *MockDatabaseRepositoryMockRecorder) GetSourceSummary(arg0, arg1 interface{}) *gomock.Call {
|
|
||||||
mr.mock.ctrl.T.Helper()
|
|
||||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSourceSummary", reflect.TypeOf((*MockDatabaseRepository)(nil).GetSourceSummary), arg0, arg1)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetSources mocks base method.
|
|
||||||
func (m *MockDatabaseRepository) GetSources(arg0 context.Context) ([]models.Source, error) {
|
|
||||||
m.ctrl.T.Helper()
|
|
||||||
ret := m.ctrl.Call(m, "GetSources", arg0)
|
|
||||||
ret0, _ := ret[0].([]models.Source)
|
|
||||||
ret1, _ := ret[1].(error)
|
|
||||||
return ret0, ret1
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetSources indicates an expected call of GetSources.
|
|
||||||
func (mr *MockDatabaseRepositoryMockRecorder) GetSources(arg0 interface{}) *gomock.Call {
|
|
||||||
mr.mock.ctrl.T.Helper()
|
|
||||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSources", reflect.TypeOf((*MockDatabaseRepository)(nil).GetSources), arg0)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetSummary mocks base method.
|
|
||||||
func (m *MockDatabaseRepository) GetSummary(ctx context.Context) (*models.Summary, error) {
|
|
||||||
m.ctrl.T.Helper()
|
|
||||||
ret := m.ctrl.Call(m, "GetSummary", ctx)
|
|
||||||
ret0, _ := ret[0].(*models.Summary)
|
|
||||||
ret1, _ := ret[1].(error)
|
|
||||||
return ret0, ret1
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetSummary indicates an expected call of GetSummary.
|
|
||||||
func (mr *MockDatabaseRepositoryMockRecorder) GetSummary(ctx interface{}) *gomock.Call {
|
|
||||||
mr.mock.ctrl.T.Helper()
|
|
||||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSummary", reflect.TypeOf((*MockDatabaseRepository)(nil).GetSummary), ctx)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetUserByEmail mocks base method.
|
|
||||||
func (m *MockDatabaseRepository) GetUserByEmail(arg0 context.Context, arg1 string) (*models.User, error) {
|
|
||||||
m.ctrl.T.Helper()
|
|
||||||
ret := m.ctrl.Call(m, "GetUserByEmail", arg0, arg1)
|
|
||||||
ret0, _ := ret[0].(*models.User)
|
|
||||||
ret1, _ := ret[1].(error)
|
|
||||||
return ret0, ret1
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetUserByEmail indicates an expected call of GetUserByEmail.
|
|
||||||
func (mr *MockDatabaseRepositoryMockRecorder) GetUserByEmail(arg0, arg1 interface{}) *gomock.Call {
|
|
||||||
mr.mock.ctrl.T.Helper()
|
|
||||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUserByEmail", reflect.TypeOf((*MockDatabaseRepository)(nil).GetUserByEmail), arg0, arg1)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListResources mocks base method.
|
|
||||||
func (m *MockDatabaseRepository) ListResources(arg0 context.Context, arg1 models.ListResourceQueryOptions) ([]models.ResourceFhir, error) {
|
|
||||||
m.ctrl.T.Helper()
|
|
||||||
ret := m.ctrl.Call(m, "ListResources", arg0, arg1)
|
|
||||||
ret0, _ := ret[0].([]models.ResourceFhir)
|
|
||||||
ret1, _ := ret[1].(error)
|
|
||||||
return ret0, ret1
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListResources indicates an expected call of ListResources.
|
|
||||||
func (mr *MockDatabaseRepositoryMockRecorder) ListResources(arg0, arg1 interface{}) *gomock.Call {
|
|
||||||
mr.mock.ctrl.T.Helper()
|
|
||||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListResources", reflect.TypeOf((*MockDatabaseRepository)(nil).ListResources), arg0, arg1)
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpsertResource mocks base method.
|
|
||||||
func (m *MockDatabaseRepository) UpsertResource(arg0 context.Context, arg1 models.ResourceFhir) error {
|
|
||||||
m.ctrl.T.Helper()
|
|
||||||
ret := m.ctrl.Call(m, "UpsertResource", arg0, arg1)
|
|
||||||
ret0, _ := ret[0].(error)
|
|
||||||
return ret0
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpsertResource indicates an expected call of UpsertResource.
|
|
||||||
func (mr *MockDatabaseRepositoryMockRecorder) UpsertResource(arg0, arg1 interface{}) *gomock.Call {
|
|
||||||
mr.mock.ctrl.T.Helper()
|
|
||||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpsertResource", reflect.TypeOf((*MockDatabaseRepository)(nil).UpsertResource), arg0, arg1)
|
|
||||||
}
|
|
||||||
|
|
|
@ -1,378 +0,0 @@
|
||||||
package database
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/models"
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/glebarez/sqlite"
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"github.com/sirupsen/logrus"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
"net/url"
|
|
||||||
)
|
|
||||||
|
|
||||||
func NewRepository(appConfig config.Interface, globalLogger logrus.FieldLogger) (DatabaseRepository, error) {
|
|
||||||
//backgroundContext := context.Background()
|
|
||||||
|
|
||||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
||||||
// Gorm/SQLite setup
|
|
||||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
||||||
globalLogger.Infof("Trying to connect to sqlite db: %s\n", appConfig.GetString("web.database.location"))
|
|
||||||
|
|
||||||
// When a transaction cannot lock the database, because it is already locked by another one,
|
|
||||||
// SQLite by default throws an error: database is locked. This behavior is usually not appropriate when
|
|
||||||
// concurrent access is needed, typically when multiple processes write to the same database.
|
|
||||||
// PRAGMA busy_timeout lets you set a timeout or a handler for these events. When setting a timeout,
|
|
||||||
// SQLite will try the transaction multiple times within this timeout.
|
|
||||||
// fixes #341
|
|
||||||
// https://rsqlite.r-dbi.org/reference/sqlitesetbusyhandler
|
|
||||||
// retrying for 30000 milliseconds, 30seconds - this would be unreasonable for a distributed multi-tenant application,
|
|
||||||
// but should be fine for local usage.
|
|
||||||
pragmaStr := sqlitePragmaString(map[string]string{
|
|
||||||
"busy_timeout": "30000",
|
|
||||||
"foreign_keys": "ON",
|
|
||||||
})
|
|
||||||
database, err := gorm.Open(sqlite.Open(appConfig.GetString("web.database.location")+pragmaStr), &gorm.Config{
|
|
||||||
//TODO: figure out how to log database queries again.
|
|
||||||
//Logger: logger
|
|
||||||
DisableForeignKeyConstraintWhenMigrating: true,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("Failed to connect to database! - %v", err)
|
|
||||||
}
|
|
||||||
globalLogger.Infof("Successfully connected to scrutiny sqlite db: %s\n", appConfig.GetString("web.database.location"))
|
|
||||||
|
|
||||||
//TODO: automigrate for now
|
|
||||||
err = database.AutoMigrate(
|
|
||||||
&models.User{},
|
|
||||||
&models.Source{},
|
|
||||||
&models.ResourceFhir{},
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("Failed to automigrate! - %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// create/update admin user
|
|
||||||
adminUser := models.User{}
|
|
||||||
err = database.FirstOrCreate(&adminUser, models.User{Username: "admin"}).Error
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("Failed to create admin user! - %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
deviceRepo := sqliteRepository{
|
|
||||||
appConfig: appConfig,
|
|
||||||
logger: globalLogger,
|
|
||||||
gormClient: database,
|
|
||||||
}
|
|
||||||
return &deviceRepo, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type sqliteRepository struct {
|
|
||||||
appConfig config.Interface
|
|
||||||
logger logrus.FieldLogger
|
|
||||||
|
|
||||||
gormClient *gorm.DB
|
|
||||||
}
|
|
||||||
|
|
||||||
func (sr *sqliteRepository) Close() error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
||||||
// User
|
|
||||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
||||||
|
|
||||||
func (sr *sqliteRepository) CreateUser(ctx context.Context, user *models.User) error {
|
|
||||||
if err := user.HashPassword(user.Password); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
record := sr.gormClient.Create(user)
|
|
||||||
if record.Error != nil {
|
|
||||||
return record.Error
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
func (sr *sqliteRepository) GetUserByEmail(ctx context.Context, username string) (*models.User, error) {
|
|
||||||
var foundUser models.User
|
|
||||||
result := sr.gormClient.Where(models.User{Username: username}).First(&foundUser)
|
|
||||||
return &foundUser, result.Error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (sr *sqliteRepository) GetCurrentUser(ctx context.Context) *models.User {
|
|
||||||
ginCtx := ctx.(*gin.Context)
|
|
||||||
var currentUser models.User
|
|
||||||
sr.gormClient.First(¤tUser, models.User{Username: ginCtx.MustGet("AUTH_USERNAME").(string)})
|
|
||||||
|
|
||||||
return ¤tUser
|
|
||||||
}
|
|
||||||
|
|
||||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
||||||
// User
|
|
||||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
||||||
|
|
||||||
func (sr *sqliteRepository) GetSummary(ctx context.Context) (*models.Summary, error) {
|
|
||||||
|
|
||||||
// we want a count of all resources for this user by type
|
|
||||||
var resourceCountResults []map[string]interface{}
|
|
||||||
|
|
||||||
//group by resource type and return counts
|
|
||||||
// SELECT source_resource_type as resource_type, COUNT(*) as count FROM resource_fhirs WHERE source_id = "53c1e930-63af-46c9-b760-8e83cbc1abd9" GROUP BY source_resource_type;
|
|
||||||
result := sr.gormClient.WithContext(ctx).
|
|
||||||
Model(models.ResourceFhir{}).
|
|
||||||
Select("source_id, source_resource_type as resource_type, count(*) as count").
|
|
||||||
Group("source_resource_type").
|
|
||||||
Where(models.OriginBase{
|
|
||||||
UserID: sr.GetCurrentUser(ctx).ID,
|
|
||||||
}).
|
|
||||||
Scan(&resourceCountResults)
|
|
||||||
if result.Error != nil {
|
|
||||||
return nil, result.Error
|
|
||||||
}
|
|
||||||
|
|
||||||
// we want a list of all sources (when they were last updated)
|
|
||||||
sources, err := sr.GetSources(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// we want the main Patient for each source
|
|
||||||
patients, err := sr.GetPatientForSources(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
summary := &models.Summary{
|
|
||||||
Sources: sources,
|
|
||||||
ResourceTypeCounts: resourceCountResults,
|
|
||||||
Patients: patients,
|
|
||||||
}
|
|
||||||
|
|
||||||
return summary, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
||||||
// Resource
|
|
||||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
||||||
|
|
||||||
func (sr *sqliteRepository) UpsertResource(ctx context.Context, resourceModel *models.ResourceFhir) error {
|
|
||||||
sr.logger.Infof("insert/update (%T) %v", resourceModel, resourceModel)
|
|
||||||
|
|
||||||
if sr.gormClient.Debug().WithContext(ctx).
|
|
||||||
Where(models.OriginBase{
|
|
||||||
SourceID: resourceModel.GetSourceID(),
|
|
||||||
SourceResourceID: resourceModel.GetSourceResourceID(),
|
|
||||||
SourceResourceType: resourceModel.GetSourceResourceType(), //TODO: and UpdatedAt > old UpdatedAt
|
|
||||||
}).Updates(resourceModel).RowsAffected == 0 {
|
|
||||||
sr.logger.Infof("resource does not exist, creating: %s %s %s", resourceModel.GetSourceID(), resourceModel.GetSourceResourceID(), resourceModel.GetSourceResourceType())
|
|
||||||
return sr.gormClient.Debug().Create(resourceModel).Error
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (sr *sqliteRepository) ListResources(ctx context.Context, queryOptions models.ListResourceQueryOptions) ([]models.ResourceFhir, error) {
|
|
||||||
|
|
||||||
queryParam := models.ResourceFhir{
|
|
||||||
OriginBase: models.OriginBase{
|
|
||||||
UserID: sr.GetCurrentUser(ctx).ID,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(queryOptions.SourceResourceType) > 0 {
|
|
||||||
queryParam.OriginBase.SourceResourceType = queryOptions.SourceResourceType
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(queryOptions.SourceID) > 0 {
|
|
||||||
sourceUUID, err := uuid.Parse(queryOptions.SourceID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
queryParam.OriginBase.SourceID = sourceUUID
|
|
||||||
}
|
|
||||||
|
|
||||||
manifestJson, _ := json.MarshalIndent(queryParam, "", " ")
|
|
||||||
sr.logger.Infof("THE QUERY OBJECT===========> %v", string(manifestJson))
|
|
||||||
|
|
||||||
var wrappedResourceModels []models.ResourceFhir
|
|
||||||
results := sr.gormClient.WithContext(ctx).
|
|
||||||
Where(queryParam).
|
|
||||||
Find(&wrappedResourceModels)
|
|
||||||
|
|
||||||
return wrappedResourceModels, results.Error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (sr *sqliteRepository) GetResourceBySourceType(ctx context.Context, sourceResourceType string, sourceResourceId string) (*models.ResourceFhir, error) {
|
|
||||||
queryParam := models.ResourceFhir{
|
|
||||||
OriginBase: models.OriginBase{
|
|
||||||
UserID: sr.GetCurrentUser(ctx).ID,
|
|
||||||
SourceResourceType: sourceResourceType,
|
|
||||||
SourceResourceID: sourceResourceId,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
var wrappedResourceModel models.ResourceFhir
|
|
||||||
results := sr.gormClient.WithContext(ctx).
|
|
||||||
Where(queryParam).
|
|
||||||
First(&wrappedResourceModel)
|
|
||||||
|
|
||||||
return &wrappedResourceModel, results.Error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (sr *sqliteRepository) GetResourceBySourceId(ctx context.Context, sourceId string, sourceResourceId string) (*models.ResourceFhir, error) {
|
|
||||||
sourceIdUUID, err := uuid.Parse(sourceId)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
queryParam := models.ResourceFhir{
|
|
||||||
OriginBase: models.OriginBase{
|
|
||||||
UserID: sr.GetCurrentUser(ctx).ID,
|
|
||||||
SourceID: sourceIdUUID,
|
|
||||||
SourceResourceID: sourceResourceId,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
var wrappedResourceModel models.ResourceFhir
|
|
||||||
results := sr.gormClient.WithContext(ctx).
|
|
||||||
Where(queryParam).
|
|
||||||
First(&wrappedResourceModel)
|
|
||||||
|
|
||||||
return &wrappedResourceModel, results.Error
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the patient for each source (for the current user)
|
|
||||||
func (sr *sqliteRepository) GetPatientForSources(ctx context.Context) ([]models.ResourceFhir, error) {
|
|
||||||
|
|
||||||
//SELECT * FROM resource_fhirs WHERE user_id = "" and source_resource_type = "Patient" GROUP BY source_id
|
|
||||||
|
|
||||||
//var sourceCred models.Source
|
|
||||||
//results := sr.gormClient.WithContext(ctx).
|
|
||||||
// Where(models.Source{UserID: sr.GetCurrentUser(ctx).ID, ModelBase: models.ModelBase{ID: sourceUUID}}).
|
|
||||||
// First(&sourceCred)
|
|
||||||
|
|
||||||
var wrappedResourceModels []models.ResourceFhir
|
|
||||||
results := sr.gormClient.WithContext(ctx).
|
|
||||||
Model(models.ResourceFhir{}).
|
|
||||||
Group("source_id").
|
|
||||||
Where(models.OriginBase{
|
|
||||||
UserID: sr.GetCurrentUser(ctx).ID,
|
|
||||||
SourceResourceType: "Patient",
|
|
||||||
}).
|
|
||||||
Find(&wrappedResourceModels)
|
|
||||||
|
|
||||||
return wrappedResourceModels, results.Error
|
|
||||||
}
|
|
||||||
|
|
||||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
||||||
// Source
|
|
||||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
||||||
|
|
||||||
func (sr *sqliteRepository) CreateSource(ctx context.Context, sourceCreds *models.Source) error {
|
|
||||||
sourceCreds.UserID = sr.GetCurrentUser(ctx).ID
|
|
||||||
|
|
||||||
if sr.gormClient.WithContext(ctx).
|
|
||||||
Where(models.Source{
|
|
||||||
UserID: sourceCreds.UserID,
|
|
||||||
SourceType: sourceCreds.SourceType,
|
|
||||||
PatientId: sourceCreds.PatientId}).Updates(sourceCreds).RowsAffected == 0 {
|
|
||||||
return sr.gormClient.WithContext(ctx).Create(sourceCreds).Error
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (sr *sqliteRepository) GetSource(ctx context.Context, sourceId string) (*models.Source, error) {
|
|
||||||
sourceUUID, err := uuid.Parse(sourceId)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var sourceCred models.Source
|
|
||||||
results := sr.gormClient.WithContext(ctx).
|
|
||||||
Where(models.Source{UserID: sr.GetCurrentUser(ctx).ID, ModelBase: models.ModelBase{ID: sourceUUID}}).
|
|
||||||
First(&sourceCred)
|
|
||||||
|
|
||||||
return &sourceCred, results.Error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (sr *sqliteRepository) GetSourceSummary(ctx context.Context, sourceId string) (*models.SourceSummary, error) {
|
|
||||||
sourceUUID, err := uuid.Parse(sourceId)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
sourceSummary := &models.SourceSummary{}
|
|
||||||
|
|
||||||
source, err := sr.GetSource(ctx, sourceId)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
sourceSummary.Source = source
|
|
||||||
|
|
||||||
//group by resource type and return counts
|
|
||||||
// SELECT source_resource_type as resource_type, COUNT(*) as count FROM resource_fhirs WHERE source_id = "53c1e930-63af-46c9-b760-8e83cbc1abd9" GROUP BY source_resource_type;
|
|
||||||
|
|
||||||
var resourceTypeCounts []map[string]interface{}
|
|
||||||
|
|
||||||
result := sr.gormClient.WithContext(ctx).
|
|
||||||
Model(models.ResourceFhir{}).
|
|
||||||
Select("source_id, source_resource_type as resource_type, count(*) as count").
|
|
||||||
Group("source_resource_type").
|
|
||||||
Where(models.OriginBase{
|
|
||||||
UserID: sr.GetCurrentUser(ctx).ID,
|
|
||||||
SourceID: sourceUUID,
|
|
||||||
}).
|
|
||||||
Scan(&resourceTypeCounts)
|
|
||||||
|
|
||||||
if result.Error != nil {
|
|
||||||
return nil, result.Error
|
|
||||||
}
|
|
||||||
|
|
||||||
sourceSummary.ResourceTypeCounts = resourceTypeCounts
|
|
||||||
|
|
||||||
//set patient
|
|
||||||
var wrappedPatientResourceModel models.ResourceFhir
|
|
||||||
results := sr.gormClient.WithContext(ctx).
|
|
||||||
Where(models.OriginBase{
|
|
||||||
UserID: sr.GetCurrentUser(ctx).ID,
|
|
||||||
SourceResourceType: "Patient",
|
|
||||||
SourceID: sourceUUID,
|
|
||||||
}).
|
|
||||||
First(&wrappedPatientResourceModel)
|
|
||||||
|
|
||||||
if results.Error != nil {
|
|
||||||
return nil, result.Error
|
|
||||||
}
|
|
||||||
sourceSummary.Patient = &wrappedPatientResourceModel
|
|
||||||
|
|
||||||
return sourceSummary, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (sr *sqliteRepository) GetSources(ctx context.Context) ([]models.Source, error) {
|
|
||||||
|
|
||||||
var sourceCreds []models.Source
|
|
||||||
results := sr.gormClient.WithContext(ctx).
|
|
||||||
Where(models.Source{UserID: sr.GetCurrentUser(ctx).ID}).
|
|
||||||
Find(&sourceCreds)
|
|
||||||
|
|
||||||
return sourceCreds, results.Error
|
|
||||||
}
|
|
||||||
|
|
||||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
||||||
// Utilities
|
|
||||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
||||||
|
|
||||||
func sqlitePragmaString(pragmas map[string]string) string {
|
|
||||||
q := url.Values{}
|
|
||||||
for key, val := range pragmas {
|
|
||||||
q.Add("_pragma", key+"="+val)
|
|
||||||
}
|
|
||||||
|
|
||||||
queryStr := q.Encode()
|
|
||||||
if len(queryStr) > 0 {
|
|
||||||
return "?" + queryStr
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
|
@ -1,12 +0,0 @@
|
||||||
# Hub
|
|
||||||
|
|
||||||
The Fasten Hub is a semi stand-alone application that can retrieve data from various Medical Providers, transform it, and
|
|
||||||
store it in the database. This code will eventually be moved into its own repository.
|
|
||||||
|
|
||||||
# Types
|
|
||||||
|
|
||||||
There are multiple protocols used by the Medical Provider industry to transfer patient data, the following mechanisms are the
|
|
||||||
ones that Fasten supports
|
|
||||||
|
|
||||||
### FHIR
|
|
||||||
|
|
|
@ -1,58 +0,0 @@
|
||||||
package hub
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/hub/internal/fhir/aetna"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/hub/internal/fhir/athena"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/hub/internal/fhir/base"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/hub/internal/fhir/bluebutton"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/hub/internal/fhir/careevolution"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/hub/internal/fhir/cerner"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/hub/internal/fhir/cigna"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/hub/internal/fhir/epic"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/hub/internal/fhir/healthit"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/hub/internal/fhir/logica"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/hub/internal/fhir/manual"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/models"
|
|
||||||
"github.com/sirupsen/logrus"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
func NewClient(sourceType pkg.SourceType, ctx context.Context, appConfig config.Interface, globalLogger logrus.FieldLogger, credentials models.Source, testHttpClient ...*http.Client) (base.Client, *models.Source, error) {
|
|
||||||
|
|
||||||
var sourceClient base.Client
|
|
||||||
var updatedSource *models.Source
|
|
||||||
var err error
|
|
||||||
switch sourceType {
|
|
||||||
case pkg.SourceTypeAetna:
|
|
||||||
sourceClient, updatedSource, err = aetna.NewClient(ctx, appConfig, globalLogger, credentials, testHttpClient...)
|
|
||||||
case pkg.SourceTypeAthena:
|
|
||||||
sourceClient, updatedSource, err = athena.NewClient(ctx, appConfig, globalLogger, credentials, testHttpClient...)
|
|
||||||
case pkg.SourceTypeAnthem:
|
|
||||||
sourceClient, updatedSource, err = cigna.NewClient(ctx, appConfig, globalLogger, credentials, testHttpClient...)
|
|
||||||
case pkg.SourceTypeBlueButtonMedicare:
|
|
||||||
sourceClient, updatedSource, err = bluebutton.NewClient(ctx, appConfig, globalLogger, credentials, testHttpClient...)
|
|
||||||
case pkg.SourceTypeCareEvolution:
|
|
||||||
sourceClient, updatedSource, err = careevolution.NewClient(ctx, appConfig, globalLogger, credentials, testHttpClient...)
|
|
||||||
case pkg.SourceTypeCerner:
|
|
||||||
sourceClient, updatedSource, err = cerner.NewClient(ctx, appConfig, globalLogger, credentials, testHttpClient...)
|
|
||||||
case pkg.SourceTypeCigna:
|
|
||||||
sourceClient, updatedSource, err = cigna.NewClient(ctx, appConfig, globalLogger, credentials, testHttpClient...)
|
|
||||||
case pkg.SourceTypeEpic:
|
|
||||||
sourceClient, updatedSource, err = epic.NewClient(ctx, appConfig, globalLogger, credentials, testHttpClient...)
|
|
||||||
case pkg.SourceTypeHealthIT:
|
|
||||||
sourceClient, updatedSource, err = healthit.NewClient(ctx, appConfig, globalLogger, credentials, testHttpClient...)
|
|
||||||
case pkg.SourceTypeLogica:
|
|
||||||
sourceClient, updatedSource, err = logica.NewClient(ctx, appConfig, globalLogger, credentials, testHttpClient...)
|
|
||||||
case pkg.SourceTypeManual:
|
|
||||||
sourceClient, updatedSource, err = manual.NewClient(ctx, appConfig, globalLogger, credentials, testHttpClient...)
|
|
||||||
default:
|
|
||||||
return nil, updatedSource, errors.New(fmt.Sprintf("Unknown Source Type: %s", sourceType))
|
|
||||||
}
|
|
||||||
|
|
||||||
return sourceClient, updatedSource, err
|
|
||||||
}
|
|
|
@ -1,49 +0,0 @@
|
||||||
package aetna
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/database"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/hub/internal/fhir/base"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/models"
|
|
||||||
"github.com/sirupsen/logrus"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
type AetnaClient struct {
|
|
||||||
*base.FHIR401Client
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewClient(ctx context.Context, appConfig config.Interface, globalLogger logrus.FieldLogger, source models.Source, testHttpClient ...*http.Client) (base.Client, *models.Source, error) {
|
|
||||||
baseClient, updatedSource, err := base.NewFHIR401Client(ctx, appConfig, globalLogger, source, testHttpClient...)
|
|
||||||
return AetnaClient{
|
|
||||||
baseClient,
|
|
||||||
}, updatedSource, err
|
|
||||||
}
|
|
||||||
|
|
||||||
//Overrides
|
|
||||||
|
|
||||||
func (c AetnaClient) SyncAll(db database.DatabaseRepository) error {
|
|
||||||
|
|
||||||
bundle, err := c.GetResourceBundle("Patient")
|
|
||||||
if err != nil {
|
|
||||||
c.Logger.Infof("An error occurred while getting patient bundle %s", c.Source.PatientId)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
wrappedResourceModels, err := c.ProcessBundle(bundle)
|
|
||||||
if err != nil {
|
|
||||||
c.Logger.Infof("An error occurred while processing patient bundle %s", c.Source.PatientId)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
//todo, create the resources in dependency order
|
|
||||||
|
|
||||||
for _, apiModel := range wrappedResourceModels {
|
|
||||||
err = db.UpsertResource(context.Background(), &apiModel)
|
|
||||||
if err != nil {
|
|
||||||
c.Logger.Info("An error occurred while upserting resource")
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
|
@ -1,49 +0,0 @@
|
||||||
package athena
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/database"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/hub/internal/fhir/base"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/models"
|
|
||||||
"github.com/sirupsen/logrus"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
type AthenaClient struct {
|
|
||||||
*base.FHIR401Client
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewClient(ctx context.Context, appConfig config.Interface, globalLogger logrus.FieldLogger, source models.Source, testHttpClient ...*http.Client) (base.Client, *models.Source, error) {
|
|
||||||
baseClient, updatedSource, err := base.NewFHIR401Client(ctx, appConfig, globalLogger, source, testHttpClient...)
|
|
||||||
return AthenaClient{
|
|
||||||
baseClient,
|
|
||||||
}, updatedSource, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c AthenaClient) SyncAll(db database.DatabaseRepository) error {
|
|
||||||
supportedResources := []string{
|
|
||||||
"AllergyIntolerance",
|
|
||||||
//"Binary",
|
|
||||||
"CarePlan",
|
|
||||||
"CareTeam",
|
|
||||||
"Condition",
|
|
||||||
"Device",
|
|
||||||
"DiagnosticReport",
|
|
||||||
"DocumentReference",
|
|
||||||
"Encounter",
|
|
||||||
"Goal",
|
|
||||||
"Immunization",
|
|
||||||
//"Location",
|
|
||||||
//"Medication",
|
|
||||||
//"MedicationRequest",
|
|
||||||
"Observation",
|
|
||||||
//"Organization",
|
|
||||||
//"Patient",
|
|
||||||
//"Practitioner",
|
|
||||||
"Procedure",
|
|
||||||
//"Provenance",
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.SyncAllByResourceName(db, supportedResources)
|
|
||||||
}
|
|
|
@ -1,154 +0,0 @@
|
||||||
package base
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/database"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/models"
|
|
||||||
"github.com/sirupsen/logrus"
|
|
||||||
"golang.org/x/oauth2"
|
|
||||||
"io"
|
|
||||||
"log"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type BaseClient struct {
|
|
||||||
Context context.Context
|
|
||||||
AppConfig config.Interface
|
|
||||||
Logger logrus.FieldLogger
|
|
||||||
|
|
||||||
OauthClient *http.Client
|
|
||||||
Source models.Source
|
|
||||||
Headers map[string]string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *BaseClient) SyncAllBundle(db database.DatabaseRepository, bundleFile *os.File) error {
|
|
||||||
panic("SyncAllBundle functionality is not available on this client")
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewBaseClient(ctx context.Context, appConfig config.Interface, globalLogger logrus.FieldLogger, source models.Source, testHttpClient ...*http.Client) (*BaseClient, *models.Source, error) {
|
|
||||||
var httpClient *http.Client
|
|
||||||
var updatedSource *models.Source
|
|
||||||
if len(testHttpClient) == 0 {
|
|
||||||
//check if we need to refresh the access token
|
|
||||||
//https://github.com/golang/oauth2/issues/84#issuecomment-520099526
|
|
||||||
// https://chromium.googlesource.com/external/github.com/golang/oauth2/+/8f816d62a2652f705144857bbbcc26f2c166af9e/oauth2.go#239
|
|
||||||
conf := &oauth2.Config{
|
|
||||||
ClientID: source.ClientId,
|
|
||||||
ClientSecret: "",
|
|
||||||
Endpoint: oauth2.Endpoint{
|
|
||||||
AuthURL: source.OauthAuthorizationEndpoint,
|
|
||||||
TokenURL: source.OauthTokenEndpoint,
|
|
||||||
},
|
|
||||||
//RedirectURL: "",
|
|
||||||
//Scopes: nil,
|
|
||||||
}
|
|
||||||
token := &oauth2.Token{
|
|
||||||
TokenType: "Bearer",
|
|
||||||
RefreshToken: source.RefreshToken,
|
|
||||||
AccessToken: source.AccessToken,
|
|
||||||
Expiry: time.Unix(source.ExpiresAt, 0),
|
|
||||||
}
|
|
||||||
if token.Expiry.Before(time.Now()) { // expired so let's update it
|
|
||||||
log.Println("access token expired, refreshing...")
|
|
||||||
src := conf.TokenSource(ctx, token)
|
|
||||||
newToken, err := src.Token() // this actually goes and renews the tokens
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
if newToken.AccessToken != token.AccessToken {
|
|
||||||
token = newToken
|
|
||||||
|
|
||||||
// update the "source" credential with new data (which will need to be sent
|
|
||||||
updatedSource = &source
|
|
||||||
updatedSource.AccessToken = newToken.AccessToken
|
|
||||||
updatedSource.ExpiresAt = newToken.Expiry.Unix()
|
|
||||||
// Don't overwrite `RefreshToken` with an empty value
|
|
||||||
// if this was a token refreshing request.
|
|
||||||
if newToken.RefreshToken != "" {
|
|
||||||
updatedSource.RefreshToken = newToken.RefreshToken
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// OLD CODE
|
|
||||||
httpClient = oauth2.NewClient(ctx, oauth2.StaticTokenSource(token))
|
|
||||||
|
|
||||||
} else {
|
|
||||||
//Testing mode.
|
|
||||||
httpClient = testHttpClient[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
httpClient.Timeout = 10 * time.Second
|
|
||||||
|
|
||||||
return &BaseClient{
|
|
||||||
Context: ctx,
|
|
||||||
AppConfig: appConfig,
|
|
||||||
Logger: globalLogger,
|
|
||||||
OauthClient: httpClient,
|
|
||||||
Source: source,
|
|
||||||
Headers: map[string]string{},
|
|
||||||
}, updatedSource, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
||||||
// HttpClient
|
|
||||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
||||||
func (c *BaseClient) GetRequest(resourceSubpathOrNext string, decodeModelPtr interface{}) error {
|
|
||||||
resourceUrl, err := url.Parse(resourceSubpathOrNext)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if !resourceUrl.IsAbs() {
|
|
||||||
resourceUrl, err = url.Parse(fmt.Sprintf("%s/%s", strings.TrimRight(c.Source.ApiEndpointBaseUrl, "/"), strings.TrimLeft(resourceSubpathOrNext, "/")))
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
req, err := http.NewRequest(http.MethodGet, resourceUrl.String(), nil)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
for key, val := range c.Headers {
|
|
||||||
//req.Header.Add("Accept", "application/json+fhir")
|
|
||||||
req.Header.Add(key, val)
|
|
||||||
}
|
|
||||||
|
|
||||||
//resp, err := c.OauthClient.Get(url)
|
|
||||||
resp, err := c.OauthClient.Do(req)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
if resp.StatusCode >= 300 || resp.StatusCode < 200 {
|
|
||||||
b, _ := io.ReadAll(resp.Body)
|
|
||||||
return fmt.Errorf("An error occurred during request %s - %d - %s [%s]", resourceUrl, resp.StatusCode, resp.Status, string(b))
|
|
||||||
}
|
|
||||||
|
|
||||||
err = ParseBundle(resp.Body, decodeModelPtr)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
||||||
// Helper Functions
|
|
||||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
||||||
func ParseBundle(r io.Reader, decodeModelPtr interface{}) error {
|
|
||||||
decoder := json.NewDecoder(r)
|
|
||||||
//decoder.DisallowUnknownFields() //make sure we throw an error if unknown fields are present.
|
|
||||||
err := decoder.Decode(decodeModelPtr)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
|
@ -1,208 +0,0 @@
|
||||||
package base
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/database"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/models"
|
|
||||||
"github.com/fastenhealth/gofhir-models/fhir401"
|
|
||||||
fhirutils "github.com/fastenhealth/gofhir-models/fhir401/utils"
|
|
||||||
"github.com/samber/lo"
|
|
||||||
"github.com/sirupsen/logrus"
|
|
||||||
"gorm.io/datatypes"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
type FHIR401Client struct {
|
|
||||||
*BaseClient
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewFHIR401Client(ctx context.Context, appConfig config.Interface, globalLogger logrus.FieldLogger, source models.Source, testHttpClient ...*http.Client) (*FHIR401Client, *models.Source, error) {
|
|
||||||
baseClient, updatedSource, err := NewBaseClient(ctx, appConfig, globalLogger, source, testHttpClient...)
|
|
||||||
return &FHIR401Client{
|
|
||||||
baseClient,
|
|
||||||
}, updatedSource, err
|
|
||||||
}
|
|
||||||
|
|
||||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
||||||
// Sync
|
|
||||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
||||||
func (c *FHIR401Client) SyncAll(db database.DatabaseRepository) error {
|
|
||||||
|
|
||||||
bundle, err := c.GetPatientBundle(c.Source.PatientId)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
wrappedResourceModels, err := c.ProcessBundle(bundle)
|
|
||||||
if err != nil {
|
|
||||||
c.Logger.Infof("An error occurred while processing patient bundle %s", c.Source.PatientId)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
//todo, create the resources in dependency order
|
|
||||||
|
|
||||||
for _, apiModel := range wrappedResourceModels {
|
|
||||||
err = db.UpsertResource(context.Background(), &apiModel)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
//TODO, find a way to sync references that cannot be searched by patient ID.
|
|
||||||
func (c *FHIR401Client) SyncAllByResourceName(db database.DatabaseRepository, resourceNames []string) error {
|
|
||||||
|
|
||||||
//Store the Patient
|
|
||||||
patientResource, err := c.GetPatient(c.Source.PatientId)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
patientJson, err := patientResource.MarshalJSON()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
patientResourceType, patientResourceId := patientResource.ResourceRef()
|
|
||||||
patientResourceFhir := models.ResourceFhir{
|
|
||||||
OriginBase: models.OriginBase{
|
|
||||||
UserID: c.Source.UserID,
|
|
||||||
SourceID: c.Source.ID,
|
|
||||||
SourceResourceType: patientResourceType,
|
|
||||||
SourceResourceID: *patientResourceId,
|
|
||||||
},
|
|
||||||
Payload: datatypes.JSON(patientJson),
|
|
||||||
}
|
|
||||||
db.UpsertResource(context.Background(), &patientResourceFhir)
|
|
||||||
|
|
||||||
//error map storage.
|
|
||||||
syncErrors := map[string]error{}
|
|
||||||
|
|
||||||
//Store all other resources.
|
|
||||||
for _, resourceType := range resourceNames {
|
|
||||||
bundle, err := c.GetResourceBundle(fmt.Sprintf("%s?patient=%s", resourceType, c.Source.PatientId))
|
|
||||||
if err != nil {
|
|
||||||
syncErrors[resourceType] = err
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
wrappedResourceModels, err := c.ProcessBundle(bundle)
|
|
||||||
if err != nil {
|
|
||||||
c.Logger.Infof("An error occurred while processing %s bundle %s", resourceType, c.Source.PatientId)
|
|
||||||
syncErrors[resourceType] = err
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
for _, apiModel := range wrappedResourceModels {
|
|
||||||
err = db.UpsertResource(context.Background(), &apiModel)
|
|
||||||
if err != nil {
|
|
||||||
syncErrors[resourceType] = err
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(syncErrors) > 0 {
|
|
||||||
return fmt.Errorf("%d error(s) occurred during sync: %v", len(syncErrors), syncErrors)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
||||||
// FHIR
|
|
||||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
||||||
func (c *FHIR401Client) GetResourceBundle(relativeResourcePath string) (fhir401.Bundle, error) {
|
|
||||||
|
|
||||||
// https://www.hl7.org/fhir/patient-operation-everything.html
|
|
||||||
bundle := fhir401.Bundle{}
|
|
||||||
err := c.GetRequest(relativeResourcePath, &bundle)
|
|
||||||
if err != nil {
|
|
||||||
return bundle, err
|
|
||||||
}
|
|
||||||
var next string
|
|
||||||
var prev string
|
|
||||||
var self string
|
|
||||||
for _, link := range bundle.Link {
|
|
||||||
if link.Relation == "next" {
|
|
||||||
next = link.Url
|
|
||||||
} else if link.Relation == "self" {
|
|
||||||
self = link.Url
|
|
||||||
} else if link.Relation == "previous" {
|
|
||||||
prev = link.Url
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for len(next) > 0 && next != self && next != prev {
|
|
||||||
c.Logger.Debugf("Paginated request => %s", next)
|
|
||||||
nextBundle := fhir401.Bundle{}
|
|
||||||
err := c.GetRequest(next, &nextBundle)
|
|
||||||
if err != nil {
|
|
||||||
return bundle, nil //ignore failures when paginating?
|
|
||||||
}
|
|
||||||
bundle.Entry = append(bundle.Entry, nextBundle.Entry...)
|
|
||||||
|
|
||||||
next = "" //reset the pointers
|
|
||||||
self = ""
|
|
||||||
prev = ""
|
|
||||||
for _, link := range nextBundle.Link {
|
|
||||||
if link.Relation == "next" {
|
|
||||||
next = link.Url
|
|
||||||
} else if link.Relation == "self" {
|
|
||||||
self = link.Url
|
|
||||||
} else if link.Relation == "previous" {
|
|
||||||
prev = link.Url
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return bundle, err
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *FHIR401Client) GetPatientBundle(patientId string) (fhir401.Bundle, error) {
|
|
||||||
return c.GetResourceBundle(fmt.Sprintf("Patient/%s/$everything", patientId))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *FHIR401Client) GetPatient(patientId string) (fhir401.Patient, error) {
|
|
||||||
|
|
||||||
patient := fhir401.Patient{}
|
|
||||||
err := c.GetRequest(fmt.Sprintf("Patient/%s", patientId), &patient)
|
|
||||||
return patient, err
|
|
||||||
}
|
|
||||||
|
|
||||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
||||||
// Process Bundles
|
|
||||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
||||||
func (c *FHIR401Client) ProcessBundle(bundle fhir401.Bundle) ([]models.ResourceFhir, error) {
|
|
||||||
|
|
||||||
//process each entry in bundle
|
|
||||||
wrappedResourceModels := lo.FilterMap[fhir401.BundleEntry, models.ResourceFhir](bundle.Entry, func(bundleEntry fhir401.BundleEntry, _ int) (models.ResourceFhir, bool) {
|
|
||||||
originalResource, _ := fhirutils.MapToResource(bundleEntry.Resource, false)
|
|
||||||
|
|
||||||
resourceType, resourceId := originalResource.(ResourceInterface).ResourceRef()
|
|
||||||
|
|
||||||
// TODO find a way to safely/consistently get the resource updated date (and other metadata) which shoudl be added to the model.
|
|
||||||
//if originalResource.Meta != nil && originalResource.Meta.LastUpdated != nil {
|
|
||||||
// if parsed, err := time.Parse(time.RFC3339Nano, *originalResource.Meta.LastUpdated); err == nil {
|
|
||||||
// patientProfile.UpdatedAt = parsed
|
|
||||||
// }
|
|
||||||
//}
|
|
||||||
if resourceId == nil {
|
|
||||||
//no resourceId present for this resource, we'll ignore it.
|
|
||||||
return models.ResourceFhir{}, false
|
|
||||||
}
|
|
||||||
|
|
||||||
wrappedResourceModel := models.ResourceFhir{
|
|
||||||
OriginBase: models.OriginBase{
|
|
||||||
ModelBase: models.ModelBase{},
|
|
||||||
UserID: c.Source.UserID,
|
|
||||||
SourceID: c.Source.ID,
|
|
||||||
SourceResourceID: *resourceId,
|
|
||||||
SourceResourceType: resourceType,
|
|
||||||
},
|
|
||||||
Payload: datatypes.JSON(bundleEntry.Resource),
|
|
||||||
}
|
|
||||||
|
|
||||||
return wrappedResourceModel, true
|
|
||||||
})
|
|
||||||
return wrappedResourceModels, nil
|
|
||||||
}
|
|
|
@ -1,80 +0,0 @@
|
||||||
package base
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
mock_config "github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config/mock"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/models"
|
|
||||||
"github.com/fastenhealth/gofhir-models/fhir401"
|
|
||||||
"github.com/golang/mock/gomock"
|
|
||||||
"github.com/sirupsen/logrus"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
"io/ioutil"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
// helpers
|
|
||||||
func readTestFixture(path string) ([]byte, error) {
|
|
||||||
jsonFile, err := os.Open(path)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer jsonFile.Close()
|
|
||||||
return ioutil.ReadAll(jsonFile)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestNewFHIR401Client(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
//setup
|
|
||||||
mockCtrl := gomock.NewController(t)
|
|
||||||
defer mockCtrl.Finish()
|
|
||||||
fakeConfig := mock_config.NewMockInterface(mockCtrl)
|
|
||||||
|
|
||||||
testLogger := logrus.WithFields(logrus.Fields{
|
|
||||||
"type": "test",
|
|
||||||
})
|
|
||||||
|
|
||||||
//test
|
|
||||||
client, _, err := NewFHIR401Client(context.Background(), fakeConfig, testLogger, models.Source{
|
|
||||||
RefreshToken: "test-refresh-token",
|
|
||||||
AccessToken: "test-access-token",
|
|
||||||
}, &http.Client{})
|
|
||||||
|
|
||||||
//assert
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Equal(t, client.Source.AccessToken, "test-access-token")
|
|
||||||
require.Equal(t, client.Source.RefreshToken, "test-refresh-token")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestFHIR401Client_ProcessBundle(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
//setup
|
|
||||||
mockCtrl := gomock.NewController(t)
|
|
||||||
defer mockCtrl.Finish()
|
|
||||||
fakeConfig := mock_config.NewMockInterface(mockCtrl)
|
|
||||||
testLogger := logrus.WithFields(logrus.Fields{
|
|
||||||
"type": "test",
|
|
||||||
})
|
|
||||||
client, _, err := NewFHIR401Client(context.Background(), fakeConfig, testLogger, models.Source{
|
|
||||||
RefreshToken: "test-refresh-token",
|
|
||||||
AccessToken: "test-access-token",
|
|
||||||
}, &http.Client{})
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
jsonBytes, err := readTestFixture("testdata/fixtures/401-R4/bundle/cigna_syntheticuser05-everything.json")
|
|
||||||
require.NoError(t, err)
|
|
||||||
var bundle fhir401.Bundle
|
|
||||||
err = json.Unmarshal(jsonBytes, &bundle)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
// test
|
|
||||||
wrappedResourceModels, err := client.ProcessBundle(bundle)
|
|
||||||
//log.Printf("%v", wrappedResourceModels)
|
|
||||||
|
|
||||||
//assert
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Equal(t, 11, len(wrappedResourceModels))
|
|
||||||
//require.Equal(t, "A00000000000005", profile.SourceResourceID)
|
|
||||||
}
|
|
|
@ -1,81 +0,0 @@
|
||||||
package base
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/models"
|
|
||||||
"github.com/fastenhealth/gofhir-models/fhir430"
|
|
||||||
fhirutils "github.com/fastenhealth/gofhir-models/fhir430/utils"
|
|
||||||
"github.com/samber/lo"
|
|
||||||
"github.com/sirupsen/logrus"
|
|
||||||
"gorm.io/datatypes"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
type FHIR430Client struct {
|
|
||||||
*BaseClient
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewFHIR430Client(ctx context.Context, appConfig config.Interface, globalLogger logrus.FieldLogger, source models.Source, testHttpClient ...*http.Client) (*FHIR430Client, *models.Source, error) {
|
|
||||||
baseClient, updatedSource, err := NewBaseClient(ctx, appConfig, globalLogger, source, testHttpClient...)
|
|
||||||
return &FHIR430Client{
|
|
||||||
baseClient,
|
|
||||||
}, updatedSource, err
|
|
||||||
}
|
|
||||||
|
|
||||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
||||||
// FHIR
|
|
||||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
||||||
func (c *FHIR430Client) GetPatientEverything(patientId string) (*fhir430.Bundle, error) {
|
|
||||||
|
|
||||||
// https://www.hl7.org/fhir/patient-operation-everything.html
|
|
||||||
bundle := fhir430.Bundle{}
|
|
||||||
err := c.GetRequest(fmt.Sprintf("Patient/%s/$everything", patientId), &bundle)
|
|
||||||
return &bundle, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *FHIR430Client) GetPatient(patientId string) (*fhir430.Patient, error) {
|
|
||||||
|
|
||||||
patient := fhir430.Patient{}
|
|
||||||
err := c.GetRequest(fmt.Sprintf("Patient/%s", patientId), &patient)
|
|
||||||
return &patient, err
|
|
||||||
}
|
|
||||||
|
|
||||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
||||||
// Process Bundles
|
|
||||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
||||||
func (c *FHIR430Client) ProcessBundle(bundle fhir430.Bundle) ([]models.ResourceFhir, error) {
|
|
||||||
|
|
||||||
//process each entry in bundle
|
|
||||||
wrappedResourceModels := lo.FilterMap[fhir430.BundleEntry, models.ResourceFhir](bundle.Entry, func(bundleEntry fhir430.BundleEntry, _ int) (models.ResourceFhir, bool) {
|
|
||||||
originalResource, _ := fhirutils.MapToResource(bundleEntry.Resource, false)
|
|
||||||
|
|
||||||
resourceType, resourceId := originalResource.(ResourceInterface).ResourceRef()
|
|
||||||
|
|
||||||
// TODO find a way to safely/consistently get the resource updated date (and other metadata) which shoudl be added to the model.
|
|
||||||
//if originalResource.Meta != nil && originalResource.Meta.LastUpdated != nil {
|
|
||||||
// if parsed, err := time.Parse(time.RFC3339Nano, *originalResource.Meta.LastUpdated); err == nil {
|
|
||||||
// patientProfile.UpdatedAt = parsed
|
|
||||||
// }
|
|
||||||
//}
|
|
||||||
if resourceId == nil {
|
|
||||||
//no resourceId present for this resource, we'll ignore it.
|
|
||||||
return models.ResourceFhir{}, false
|
|
||||||
}
|
|
||||||
|
|
||||||
wrappedResourceModel := models.ResourceFhir{
|
|
||||||
OriginBase: models.OriginBase{
|
|
||||||
ModelBase: models.ModelBase{},
|
|
||||||
UserID: c.Source.UserID,
|
|
||||||
SourceID: c.Source.ID,
|
|
||||||
SourceResourceID: *resourceId,
|
|
||||||
SourceResourceType: resourceType,
|
|
||||||
},
|
|
||||||
Payload: datatypes.JSON(bundleEntry.Resource),
|
|
||||||
}
|
|
||||||
|
|
||||||
return wrappedResourceModel, true
|
|
||||||
})
|
|
||||||
return wrappedResourceModels, nil
|
|
||||||
}
|
|
|
@ -1,19 +0,0 @@
|
||||||
package base
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/database"
|
|
||||||
"os"
|
|
||||||
)
|
|
||||||
|
|
||||||
//go:generate mockgen -source=interface.go -destination=mock/mock_client.go
|
|
||||||
type Client interface {
|
|
||||||
GetRequest(resourceSubpath string, decodeModelPtr interface{}) error
|
|
||||||
SyncAll(db database.DatabaseRepository) error
|
|
||||||
|
|
||||||
//Manual client ONLY functions
|
|
||||||
SyncAllBundle(db database.DatabaseRepository, bundleFile *os.File) error
|
|
||||||
}
|
|
||||||
|
|
||||||
type ResourceInterface interface {
|
|
||||||
ResourceRef() (string, *string)
|
|
||||||
}
|
|
|
@ -1,116 +0,0 @@
|
||||||
// Code generated by MockGen. DO NOT EDIT.
|
|
||||||
// Source: interface.go
|
|
||||||
|
|
||||||
// Package mock_base is a generated GoMock package.
|
|
||||||
package mock_base
|
|
||||||
|
|
||||||
import (
|
|
||||||
os "os"
|
|
||||||
reflect "reflect"
|
|
||||||
|
|
||||||
database "github.com/fastenhealth/fastenhealth-onprem/backend/pkg/database"
|
|
||||||
gomock "github.com/golang/mock/gomock"
|
|
||||||
)
|
|
||||||
|
|
||||||
// MockClient is a mock of Client interface.
|
|
||||||
type MockClient struct {
|
|
||||||
ctrl *gomock.Controller
|
|
||||||
recorder *MockClientMockRecorder
|
|
||||||
}
|
|
||||||
|
|
||||||
// MockClientMockRecorder is the mock recorder for MockClient.
|
|
||||||
type MockClientMockRecorder struct {
|
|
||||||
mock *MockClient
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewMockClient creates a new mock instance.
|
|
||||||
func NewMockClient(ctrl *gomock.Controller) *MockClient {
|
|
||||||
mock := &MockClient{ctrl: ctrl}
|
|
||||||
mock.recorder = &MockClientMockRecorder{mock}
|
|
||||||
return mock
|
|
||||||
}
|
|
||||||
|
|
||||||
// EXPECT returns an object that allows the caller to indicate expected use.
|
|
||||||
func (m *MockClient) EXPECT() *MockClientMockRecorder {
|
|
||||||
return m.recorder
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetRequest mocks base method.
|
|
||||||
func (m *MockClient) GetRequest(resourceSubpath string, decodeModelPtr interface{}) error {
|
|
||||||
m.ctrl.T.Helper()
|
|
||||||
ret := m.ctrl.Call(m, "GetRequest", resourceSubpath, decodeModelPtr)
|
|
||||||
ret0, _ := ret[0].(error)
|
|
||||||
return ret0
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetRequest indicates an expected call of GetRequest.
|
|
||||||
func (mr *MockClientMockRecorder) GetRequest(resourceSubpath, decodeModelPtr interface{}) *gomock.Call {
|
|
||||||
mr.mock.ctrl.T.Helper()
|
|
||||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRequest", reflect.TypeOf((*MockClient)(nil).GetRequest), resourceSubpath, decodeModelPtr)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SyncAll mocks base method.
|
|
||||||
func (m *MockClient) SyncAll(db database.DatabaseRepository) error {
|
|
||||||
m.ctrl.T.Helper()
|
|
||||||
ret := m.ctrl.Call(m, "SyncAll", db)
|
|
||||||
ret0, _ := ret[0].(error)
|
|
||||||
return ret0
|
|
||||||
}
|
|
||||||
|
|
||||||
// SyncAll indicates an expected call of SyncAll.
|
|
||||||
func (mr *MockClientMockRecorder) SyncAll(db interface{}) *gomock.Call {
|
|
||||||
mr.mock.ctrl.T.Helper()
|
|
||||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SyncAll", reflect.TypeOf((*MockClient)(nil).SyncAll), db)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SyncAllBundle mocks base method.
|
|
||||||
func (m *MockClient) SyncAllBundle(db database.DatabaseRepository, bundleFile *os.File) error {
|
|
||||||
m.ctrl.T.Helper()
|
|
||||||
ret := m.ctrl.Call(m, "SyncAllBundle", db, bundleFile)
|
|
||||||
ret0, _ := ret[0].(error)
|
|
||||||
return ret0
|
|
||||||
}
|
|
||||||
|
|
||||||
// SyncAllBundle indicates an expected call of SyncAllBundle.
|
|
||||||
func (mr *MockClientMockRecorder) SyncAllBundle(db, bundleFile interface{}) *gomock.Call {
|
|
||||||
mr.mock.ctrl.T.Helper()
|
|
||||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SyncAllBundle", reflect.TypeOf((*MockClient)(nil).SyncAllBundle), db, bundleFile)
|
|
||||||
}
|
|
||||||
|
|
||||||
// MockResourceInterface is a mock of ResourceInterface interface.
|
|
||||||
type MockResourceInterface struct {
|
|
||||||
ctrl *gomock.Controller
|
|
||||||
recorder *MockResourceInterfaceMockRecorder
|
|
||||||
}
|
|
||||||
|
|
||||||
// MockResourceInterfaceMockRecorder is the mock recorder for MockResourceInterface.
|
|
||||||
type MockResourceInterfaceMockRecorder struct {
|
|
||||||
mock *MockResourceInterface
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewMockResourceInterface creates a new mock instance.
|
|
||||||
func NewMockResourceInterface(ctrl *gomock.Controller) *MockResourceInterface {
|
|
||||||
mock := &MockResourceInterface{ctrl: ctrl}
|
|
||||||
mock.recorder = &MockResourceInterfaceMockRecorder{mock}
|
|
||||||
return mock
|
|
||||||
}
|
|
||||||
|
|
||||||
// EXPECT returns an object that allows the caller to indicate expected use.
|
|
||||||
func (m *MockResourceInterface) EXPECT() *MockResourceInterfaceMockRecorder {
|
|
||||||
return m.recorder
|
|
||||||
}
|
|
||||||
|
|
||||||
// ResourceRef mocks base method.
|
|
||||||
func (m *MockResourceInterface) ResourceRef() (string, *string) {
|
|
||||||
m.ctrl.T.Helper()
|
|
||||||
ret := m.ctrl.Call(m, "ResourceRef")
|
|
||||||
ret0, _ := ret[0].(string)
|
|
||||||
ret1, _ := ret[1].(*string)
|
|
||||||
return ret0, ret1
|
|
||||||
}
|
|
||||||
|
|
||||||
// ResourceRef indicates an expected call of ResourceRef.
|
|
||||||
func (mr *MockResourceInterfaceMockRecorder) ResourceRef() *gomock.Call {
|
|
||||||
mr.mock.ctrl.T.Helper()
|
|
||||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ResourceRef", reflect.TypeOf((*MockResourceInterface)(nil).ResourceRef))
|
|
||||||
}
|
|
|
@ -1,51 +0,0 @@
|
||||||
package base
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/tls"
|
|
||||||
"github.com/seborama/govcr"
|
|
||||||
"golang.org/x/oauth2"
|
|
||||||
"net/http"
|
|
||||||
"path"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func OAuthVcrSetup(t *testing.T, enableRecording bool) *http.Client {
|
|
||||||
accessToken := "PLACEHOLDER"
|
|
||||||
if enableRecording {
|
|
||||||
//this has to be disabled because CI is empty inside docker containers.
|
|
||||||
accessToken = ""
|
|
||||||
}
|
|
||||||
|
|
||||||
ts := oauth2.StaticTokenSource(
|
|
||||||
//setting a real access token here will allow API calls to connect successfully
|
|
||||||
&oauth2.Token{AccessToken: accessToken},
|
|
||||||
)
|
|
||||||
|
|
||||||
tr := http.DefaultTransport.(*http.Transport)
|
|
||||||
tr.TLSClientConfig = &tls.Config{
|
|
||||||
InsecureSkipVerify: true, //disable certificate validation because we're playing back http requests.
|
|
||||||
}
|
|
||||||
insecureClient := http.Client{
|
|
||||||
Transport: tr,
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx := context.WithValue(oauth2.NoContext, oauth2.HTTPClient, insecureClient)
|
|
||||||
tc := oauth2.NewClient(ctx, ts)
|
|
||||||
|
|
||||||
vcrConfig := govcr.VCRConfig{
|
|
||||||
Logging: true,
|
|
||||||
CassettePath: path.Join("testdata", "govcr-fixtures"),
|
|
||||||
Client: tc,
|
|
||||||
|
|
||||||
//this line ensures that we do not attempt to create new recordings.
|
|
||||||
//Comment this out if you would like to make recordings.
|
|
||||||
DisableRecording: !enableRecording,
|
|
||||||
}
|
|
||||||
|
|
||||||
// HTTP headers are case-insensitive
|
|
||||||
vcrConfig.RequestFilters.Add(govcr.RequestDeleteHeaderKeys("User-Agent", "user-agent"))
|
|
||||||
|
|
||||||
vcr := govcr.NewVCR(t.Name(), &vcrConfig)
|
|
||||||
return vcr.Client
|
|
||||||
}
|
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
|
@ -1,31 +0,0 @@
|
||||||
package bluebutton
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/database"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/hub/internal/fhir/base"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/models"
|
|
||||||
"github.com/sirupsen/logrus"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
type BlueButtonClient struct {
|
|
||||||
*base.FHIR401Client
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewClient(ctx context.Context, appConfig config.Interface, globalLogger logrus.FieldLogger, source models.Source, testHttpClient ...*http.Client) (base.Client, *models.Source, error) {
|
|
||||||
baseClient, updatedSource, err := base.NewFHIR401Client(ctx, appConfig, globalLogger, source, testHttpClient...)
|
|
||||||
return BlueButtonClient{
|
|
||||||
baseClient,
|
|
||||||
}, updatedSource, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c BlueButtonClient) SyncAll(db database.DatabaseRepository) error {
|
|
||||||
|
|
||||||
supportedResources := []string{
|
|
||||||
"ExplanationOfBenefit",
|
|
||||||
"Coverage",
|
|
||||||
}
|
|
||||||
return c.SyncAllByResourceName(db, supportedResources)
|
|
||||||
}
|
|
|
@ -1,22 +0,0 @@
|
||||||
package careevolution
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/hub/internal/fhir/base"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/models"
|
|
||||||
"github.com/sirupsen/logrus"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
type CareEvolutionClient struct {
|
|
||||||
*base.FHIR401Client
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewClient(ctx context.Context, appConfig config.Interface, globalLogger logrus.FieldLogger, source models.Source, testHttpClient ...*http.Client) (base.Client, *models.Source, error) {
|
|
||||||
baseClient, updatedSource, err := base.NewFHIR401Client(ctx, appConfig, globalLogger, source, testHttpClient...)
|
|
||||||
baseClient.Headers["Accept"] = "application/json+fhir"
|
|
||||||
return CareEvolutionClient{
|
|
||||||
baseClient,
|
|
||||||
}, updatedSource, err
|
|
||||||
}
|
|
|
@ -1,53 +0,0 @@
|
||||||
package cerner
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/database"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/hub/internal/fhir/base"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/models"
|
|
||||||
"github.com/sirupsen/logrus"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
type CernerClient struct {
|
|
||||||
*base.FHIR401Client
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewClient(ctx context.Context, appConfig config.Interface, globalLogger logrus.FieldLogger, source models.Source, testHttpClient ...*http.Client) (base.Client, *models.Source, error) {
|
|
||||||
baseClient, updatedSource, err := base.NewFHIR401Client(ctx, appConfig, globalLogger, source, testHttpClient...)
|
|
||||||
baseClient.Headers["Accept"] = "application/json+fhir"
|
|
||||||
return CernerClient{
|
|
||||||
baseClient,
|
|
||||||
}, updatedSource, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c CernerClient) SyncAll(db database.DatabaseRepository) error {
|
|
||||||
|
|
||||||
supportedResources := []string{
|
|
||||||
"AllergyIntolerance",
|
|
||||||
"CarePlan",
|
|
||||||
"CareTeam",
|
|
||||||
"Condition",
|
|
||||||
"Consent",
|
|
||||||
"Device",
|
|
||||||
"Encounter",
|
|
||||||
"FamilyMemberHistory",
|
|
||||||
"Goal",
|
|
||||||
"Immunization",
|
|
||||||
"InsurancePlan",
|
|
||||||
"MedicationRequest",
|
|
||||||
"NutritionOrder",
|
|
||||||
"Observation",
|
|
||||||
"Person",
|
|
||||||
"Procedure",
|
|
||||||
"Provenance",
|
|
||||||
"Questionnaire",
|
|
||||||
"QuestionnaireResponse",
|
|
||||||
"RelatedPerson",
|
|
||||||
"Schedule",
|
|
||||||
"ServiceRequest",
|
|
||||||
"Slot",
|
|
||||||
}
|
|
||||||
return c.SyncAllByResourceName(db, supportedResources)
|
|
||||||
}
|
|
|
@ -1,21 +0,0 @@
|
||||||
package cigna
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/hub/internal/fhir/base"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/models"
|
|
||||||
"github.com/sirupsen/logrus"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
type CignaClient struct {
|
|
||||||
*base.FHIR401Client
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewClient(ctx context.Context, appConfig config.Interface, globalLogger logrus.FieldLogger, source models.Source, testHttpClient ...*http.Client) (base.Client, *models.Source, error) {
|
|
||||||
baseClient, updatedSource, err := base.NewFHIR401Client(ctx, appConfig, globalLogger, source, testHttpClient...)
|
|
||||||
return CignaClient{
|
|
||||||
baseClient,
|
|
||||||
}, updatedSource, err
|
|
||||||
}
|
|
|
@ -1,48 +0,0 @@
|
||||||
package cigna
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
mock_config "github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config/mock"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/database"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/hub/internal/fhir/base"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/models"
|
|
||||||
"github.com/golang/mock/gomock"
|
|
||||||
"github.com/sirupsen/logrus"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
"io/ioutil"
|
|
||||||
"os"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestCignaClient_SyncAll(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
//setup
|
|
||||||
mockCtrl := gomock.NewController(t)
|
|
||||||
defer mockCtrl.Finish()
|
|
||||||
fakeConfig := mock_config.NewMockInterface(mockCtrl)
|
|
||||||
|
|
||||||
testDatabase, err := ioutil.TempFile("testdata", "fasten.db")
|
|
||||||
require.NoError(t, err)
|
|
||||||
defer os.Remove(testDatabase.Name())
|
|
||||||
fakeConfig.EXPECT().GetString("web.database.location").AnyTimes().Return(testDatabase.Name())
|
|
||||||
testLogger := logrus.WithFields(logrus.Fields{
|
|
||||||
"type": "test",
|
|
||||||
})
|
|
||||||
httpClient := base.OAuthVcrSetup(t, false)
|
|
||||||
client, _, err := NewClient(context.Background(), fakeConfig, testLogger, models.Source{
|
|
||||||
SourceType: "cigna",
|
|
||||||
PatientId: "A00000000000005",
|
|
||||||
ApiEndpointBaseUrl: "https://p-hi2.digitaledge.cigna.com/PatientAccess/v1-devportal",
|
|
||||||
ClientId: "e434426c-2aaf-413a-a39a-8f5f6130f287",
|
|
||||||
}, httpClient)
|
|
||||||
|
|
||||||
db, err := database.NewRepository(fakeConfig, testLogger)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
//test
|
|
||||||
err = client.SyncAll(db)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
//assert
|
|
||||||
require.NoError(t, err)
|
|
||||||
}
|
|
File diff suppressed because one or more lines are too long
|
@ -1,54 +0,0 @@
|
||||||
package epic
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/database"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/hub/internal/fhir/base"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/models"
|
|
||||||
"github.com/sirupsen/logrus"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
type EpicClient struct {
|
|
||||||
*base.FHIR401Client
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewClient(ctx context.Context, appConfig config.Interface, globalLogger logrus.FieldLogger, source models.Source, testHttpClient ...*http.Client) (base.Client, *models.Source, error) {
|
|
||||||
baseClient, updatedSource, err := base.NewFHIR401Client(ctx, appConfig, globalLogger, source, testHttpClient...)
|
|
||||||
baseClient.Headers["Accept"] = "application/json+fhir"
|
|
||||||
|
|
||||||
return EpicClient{
|
|
||||||
baseClient,
|
|
||||||
}, updatedSource, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c EpicClient) SyncAll(db database.DatabaseRepository) error {
|
|
||||||
|
|
||||||
supportedResources := []string{
|
|
||||||
"AllergyIntolerance",
|
|
||||||
"CarePlan",
|
|
||||||
"CareTeam",
|
|
||||||
"Condition",
|
|
||||||
"Consent",
|
|
||||||
"Device",
|
|
||||||
"Encounter",
|
|
||||||
"FamilyMemberHistory",
|
|
||||||
"Goal",
|
|
||||||
"Immunization",
|
|
||||||
"InsurancePlan",
|
|
||||||
"MedicationRequest",
|
|
||||||
"NutritionOrder",
|
|
||||||
"Observation",
|
|
||||||
"Person",
|
|
||||||
"Procedure",
|
|
||||||
"Provenance",
|
|
||||||
"Questionnaire",
|
|
||||||
"QuestionnaireResponse",
|
|
||||||
"RelatedPerson",
|
|
||||||
"Schedule",
|
|
||||||
"ServiceRequest",
|
|
||||||
"Slot",
|
|
||||||
}
|
|
||||||
return c.SyncAllByResourceName(db, supportedResources)
|
|
||||||
}
|
|
|
@ -1,54 +0,0 @@
|
||||||
package healthit
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/database"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/hub/internal/fhir/base"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/models"
|
|
||||||
"github.com/sirupsen/logrus"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
type HealthItClient struct {
|
|
||||||
*base.FHIR401Client
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewClient(ctx context.Context, appConfig config.Interface, globalLogger logrus.FieldLogger, source models.Source, testHttpClient ...*http.Client) (base.Client, *models.Source, error) {
|
|
||||||
baseClient, updatedSource, err := base.NewFHIR401Client(ctx, appConfig, globalLogger, source, testHttpClient...)
|
|
||||||
baseClient.Headers["Accept"] = "application/json+fhir"
|
|
||||||
|
|
||||||
return HealthItClient{
|
|
||||||
baseClient,
|
|
||||||
}, updatedSource, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c HealthItClient) SyncAll(db database.DatabaseRepository) error {
|
|
||||||
|
|
||||||
supportedResources := []string{
|
|
||||||
"AllergyIntolerance",
|
|
||||||
"CarePlan",
|
|
||||||
"CareTeam",
|
|
||||||
"Condition",
|
|
||||||
"Consent",
|
|
||||||
"Device",
|
|
||||||
"Encounter",
|
|
||||||
"FamilyMemberHistory",
|
|
||||||
"Goal",
|
|
||||||
"Immunization",
|
|
||||||
"InsurancePlan",
|
|
||||||
"MedicationRequest",
|
|
||||||
"NutritionOrder",
|
|
||||||
"Observation",
|
|
||||||
"Person",
|
|
||||||
"Procedure",
|
|
||||||
"Provenance",
|
|
||||||
"Questionnaire",
|
|
||||||
"QuestionnaireResponse",
|
|
||||||
"RelatedPerson",
|
|
||||||
"Schedule",
|
|
||||||
"ServiceRequest",
|
|
||||||
"Slot",
|
|
||||||
}
|
|
||||||
return c.SyncAllByResourceName(db, supportedResources)
|
|
||||||
}
|
|
|
@ -1,21 +0,0 @@
|
||||||
package logica
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/hub/internal/fhir/base"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/models"
|
|
||||||
"github.com/sirupsen/logrus"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
type LogicaClient struct {
|
|
||||||
*base.FHIR401Client
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewClient(ctx context.Context, appConfig config.Interface, globalLogger logrus.FieldLogger, source models.Source, testHttpClient ...*http.Client) (base.Client, *models.Source, error) {
|
|
||||||
baseClient, updatedSource, err := base.NewFHIR401Client(ctx, appConfig, globalLogger, source, testHttpClient...)
|
|
||||||
return LogicaClient{
|
|
||||||
baseClient,
|
|
||||||
}, updatedSource, err
|
|
||||||
}
|
|
|
@ -1,49 +0,0 @@
|
||||||
package logica
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
mock_config "github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config/mock"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/database"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/hub/internal/fhir/base"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/models"
|
|
||||||
"github.com/golang/mock/gomock"
|
|
||||||
"github.com/sirupsen/logrus"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
"io/ioutil"
|
|
||||||
"os"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestLogicaClient_SyncAll(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
//setup
|
|
||||||
mockCtrl := gomock.NewController(t)
|
|
||||||
defer mockCtrl.Finish()
|
|
||||||
fakeConfig := mock_config.NewMockInterface(mockCtrl)
|
|
||||||
|
|
||||||
testDatabase, err := ioutil.TempFile("", "fasten.db")
|
|
||||||
require.NoError(t, err)
|
|
||||||
defer os.Remove(testDatabase.Name())
|
|
||||||
fakeConfig.EXPECT().GetString("web.database.location").AnyTimes().Return(testDatabase.Name())
|
|
||||||
testLogger := logrus.WithFields(logrus.Fields{
|
|
||||||
"type": "test",
|
|
||||||
})
|
|
||||||
httpClient := base.OAuthVcrSetup(t, false)
|
|
||||||
client, _, err := NewClient(context.Background(), fakeConfig, testLogger, models.Source{
|
|
||||||
SourceType: "logica",
|
|
||||||
PatientId: "smart-1288992",
|
|
||||||
ApiEndpointBaseUrl: "https://api.logicahealth.org/fastenhealth/data",
|
|
||||||
ClientId: "12b14c49-a4da-42f7-9e6f-2f19db622962",
|
|
||||||
}, httpClient)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
db, err := database.NewRepository(fakeConfig, testLogger)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
//test
|
|
||||||
err = client.SyncAll(db)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
//assert
|
|
||||||
require.NoError(t, err)
|
|
||||||
}
|
|
File diff suppressed because one or more lines are too long
|
@ -1,164 +0,0 @@
|
||||||
package manual
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/database"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/hub/internal/fhir/base"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/models"
|
|
||||||
"github.com/fastenhealth/gofhir-models/fhir401"
|
|
||||||
fhir401utils "github.com/fastenhealth/gofhir-models/fhir401/utils"
|
|
||||||
"github.com/fastenhealth/gofhir-models/fhir430"
|
|
||||||
fhir430utils "github.com/fastenhealth/gofhir-models/fhir430/utils"
|
|
||||||
"github.com/samber/lo"
|
|
||||||
"github.com/sirupsen/logrus"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ManualClient struct {
|
|
||||||
Context context.Context
|
|
||||||
AppConfig config.Interface
|
|
||||||
Logger logrus.FieldLogger
|
|
||||||
|
|
||||||
Source *models.Source
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m ManualClient) GetRequest(resourceSubpath string, decodeModelPtr interface{}) error {
|
|
||||||
panic("implement me")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m ManualClient) SyncAll(db database.DatabaseRepository) error {
|
|
||||||
panic("implement me")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m ManualClient) SyncAllBundle(db database.DatabaseRepository, bundleFile *os.File) error {
|
|
||||||
|
|
||||||
// we need to find the (most populated) patient record
|
|
||||||
patientId, bundleType, err := m.ExtractPatientId(bundleFile)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("an error occurred while extracting patient id from bundle: %w", err)
|
|
||||||
}
|
|
||||||
// we need to add the patient id to the source
|
|
||||||
m.Source.PatientId = patientId
|
|
||||||
|
|
||||||
// we need to upsert Source
|
|
||||||
err = db.CreateSource(m.Context, m.Source)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("an error occurred while creating manual source: %w", err)
|
|
||||||
}
|
|
||||||
// we need to parse the bundle into resources (might need to try a couple of different times)
|
|
||||||
var resourceFhirList []models.ResourceFhir
|
|
||||||
switch bundleType {
|
|
||||||
case "fhir430":
|
|
||||||
bundle430Data := fhir430.Bundle{}
|
|
||||||
err := base.ParseBundle(bundleFile, &bundle430Data)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("an error occurred while parsing 4.3.0 bundle: %w", err)
|
|
||||||
}
|
|
||||||
client, _, err := base.NewFHIR430Client(m.Context, m.AppConfig, m.Logger, *m.Source, http.DefaultClient)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("an error occurred while creating 4.3.0 client: %w", err)
|
|
||||||
}
|
|
||||||
resourceFhirList, err = client.ProcessBundle(bundle430Data)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("an error occurred while processing 4.3.0 resources: %w", err)
|
|
||||||
}
|
|
||||||
case "fhir401":
|
|
||||||
bundle401Data := fhir401.Bundle{}
|
|
||||||
err := base.ParseBundle(bundleFile, &bundle401Data)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("an error occurred while parsing 4.0.1 bundle: %w", err)
|
|
||||||
}
|
|
||||||
client, _, err := base.NewFHIR401Client(m.Context, m.AppConfig, m.Logger, *m.Source, http.DefaultClient)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("an error occurred while creating 4.0.1 client: %w", err)
|
|
||||||
}
|
|
||||||
resourceFhirList, err = client.ProcessBundle(bundle401Data)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("an error occurred while processing 4.0.1 resources: %w", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// we need to upsert all resources (and make sure they are associated with new Source)
|
|
||||||
for _, apiModel := range resourceFhirList {
|
|
||||||
err = db.UpsertResource(context.Background(), &apiModel)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("an error occurred while upserting resources: %w", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m ManualClient) ExtractPatientId(bundleFile *os.File) (string, string, error) {
|
|
||||||
// try from newest format to the oldest format
|
|
||||||
bundle430Data := fhir430.Bundle{}
|
|
||||||
bundle401Data := fhir401.Bundle{}
|
|
||||||
|
|
||||||
var patientIds []string
|
|
||||||
|
|
||||||
bundleType := "fhir430"
|
|
||||||
if err := base.ParseBundle(bundleFile, &bundle430Data); err == nil {
|
|
||||||
patientIds = lo.FilterMap[fhir430.BundleEntry, string](bundle430Data.Entry, func(bundleEntry fhir430.BundleEntry, _ int) (string, bool) {
|
|
||||||
parsedResource, err := fhir430utils.MapToResource(bundleEntry.Resource, false)
|
|
||||||
if err != nil {
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
typedResource := parsedResource.(base.ResourceInterface)
|
|
||||||
resourceType, resourceId := typedResource.ResourceRef()
|
|
||||||
|
|
||||||
if resourceId == nil || len(*resourceId) == 0 {
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
return *resourceId, resourceType == fhir430.ResourceTypePatient.String()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
bundleFile.Seek(0, io.SeekStart)
|
|
||||||
|
|
||||||
//fallback
|
|
||||||
if patientIds == nil || len(patientIds) == 0 {
|
|
||||||
bundleType = "fhir401"
|
|
||||||
//try parsing the bundle as a 401 bundle
|
|
||||||
//TODO: find a better, more generic way to do this.
|
|
||||||
err := base.ParseBundle(bundleFile, &bundle401Data)
|
|
||||||
if err != nil {
|
|
||||||
return "", "", err
|
|
||||||
}
|
|
||||||
patientIds = lo.FilterMap[fhir401.BundleEntry, string](bundle401Data.Entry, func(bundleEntry fhir401.BundleEntry, _ int) (string, bool) {
|
|
||||||
parsedResource, err := fhir401utils.MapToResource(bundleEntry.Resource, false)
|
|
||||||
if err != nil {
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
typedResource := parsedResource.(base.ResourceInterface)
|
|
||||||
resourceType, resourceId := typedResource.ResourceRef()
|
|
||||||
|
|
||||||
if resourceId == nil || len(*resourceId) == 0 {
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
return *resourceId, resourceType == fhir430.ResourceTypePatient.String()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
bundleFile.Seek(0, io.SeekStart)
|
|
||||||
|
|
||||||
if patientIds == nil || len(patientIds) == 0 {
|
|
||||||
return "", "", fmt.Errorf("could not determine patient id")
|
|
||||||
} else {
|
|
||||||
//reset reader
|
|
||||||
|
|
||||||
return strings.TrimLeft(patientIds[0], "Patient/"), bundleType, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewClient(ctx context.Context, appConfig config.Interface, globalLogger logrus.FieldLogger, source models.Source, testHttpClient ...*http.Client) (base.Client, *models.Source, error) {
|
|
||||||
return ManualClient{
|
|
||||||
Context: ctx,
|
|
||||||
AppConfig: appConfig,
|
|
||||||
Logger: globalLogger,
|
|
||||||
Source: &models.Source{
|
|
||||||
SourceType: pkg.SourceTypeManual,
|
|
||||||
},
|
|
||||||
}, nil, nil
|
|
||||||
}
|
|
|
@ -1,50 +0,0 @@
|
||||||
package models
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ModelBase struct {
|
|
||||||
ID uuid.UUID `json:"id" gorm:"type:uuid;primary_key;"`
|
|
||||||
CreatedAt time.Time `json:"created_at"`
|
|
||||||
UpdatedAt time.Time `json:"updated_at"`
|
|
||||||
DeletedAt *time.Time `json:"deleted_at,omitempty" gorm:"index"`
|
|
||||||
}
|
|
||||||
|
|
||||||
//https://medium.com/@the.hasham.ali/how-to-use-uuid-key-type-with-gorm-cc00d4ec7100
|
|
||||||
|
|
||||||
func (base *ModelBase) BeforeCreate(tx *gorm.DB) error {
|
|
||||||
base.ID = uuid.New()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type OriginBase struct {
|
|
||||||
ModelBase
|
|
||||||
User *User `json:"user,omitempty" gorm:"-"`
|
|
||||||
UserID uuid.UUID `json:"user_id"`
|
|
||||||
|
|
||||||
Source *Source `json:"source,omitempty" gorm:"-"`
|
|
||||||
SourceID uuid.UUID `json:"source_id" gorm:"not null;index:,unique,composite:source_resource_id"`
|
|
||||||
|
|
||||||
SourceResourceType string `json:"source_resource_type" gorm:"not null;index:,unique,composite:source_resource_id"`
|
|
||||||
SourceResourceID string `json:"source_resource_id" gorm:"not null;index:,unique,composite:source_resource_id"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (o OriginBase) GetSourceID() uuid.UUID {
|
|
||||||
return o.SourceID
|
|
||||||
}
|
|
||||||
|
|
||||||
func (o OriginBase) GetSourceResourceType() string {
|
|
||||||
return o.SourceResourceType
|
|
||||||
}
|
|
||||||
func (o OriginBase) GetSourceResourceID() string {
|
|
||||||
return o.SourceResourceID
|
|
||||||
}
|
|
||||||
|
|
||||||
type OriginBaser interface {
|
|
||||||
GetSourceID() uuid.UUID
|
|
||||||
GetSourceResourceType() string
|
|
||||||
GetSourceResourceID() string
|
|
||||||
}
|
|
|
@ -1,17 +0,0 @@
|
||||||
package models
|
|
||||||
|
|
||||||
import (
|
|
||||||
"gorm.io/datatypes"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ResourceFhir struct {
|
|
||||||
OriginBase
|
|
||||||
|
|
||||||
//embedded data
|
|
||||||
Payload datatypes.JSON `json:"payload" gorm:"payload"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type ListResourceQueryOptions struct {
|
|
||||||
SourceID string
|
|
||||||
SourceResourceType string
|
|
||||||
}
|
|
|
@ -1,49 +0,0 @@
|
||||||
package models
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg"
|
|
||||||
"github.com/google/uuid"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Source Data/Medical Provider Credentials
|
|
||||||
type Source struct {
|
|
||||||
ModelBase
|
|
||||||
User User `json:"user,omitempty"`
|
|
||||||
UserID uuid.UUID `json:"user_id" gorm:"uniqueIndex:idx_user_source_patient"`
|
|
||||||
SourceType pkg.SourceType `json:"source_type" gorm:"uniqueIndex:idx_user_source_patient"`
|
|
||||||
PatientId string `json:"patient_id" gorm:"uniqueIndex:idx_user_source_patient"`
|
|
||||||
|
|
||||||
//oauth endpoints
|
|
||||||
OauthAuthorizationEndpoint string `json:"oauth_authorization_endpoint"`
|
|
||||||
OauthTokenEndpoint string `json:"oauth_token_endpoint"`
|
|
||||||
OauthRegistrationEndpoint string `json:"oauth_registration_endpoint"`
|
|
||||||
OauthIntrospectionEndpoint string `json:"oauth_introspection_endpoint"`
|
|
||||||
OauthUserInfoEndpoint string `json:"oauth_userinfo_endpoint"`
|
|
||||||
OauthTokenEndpointAuthMethods string `json:"oauth_token_endpoint_auth_methods_supported"`
|
|
||||||
|
|
||||||
ApiEndpointBaseUrl string `json:"api_endpoint_base_url"`
|
|
||||||
ClientId string `json:"client_id"`
|
|
||||||
RedirectUri string `json:"redirect_uri"`
|
|
||||||
Scopes string `json:"scopes"`
|
|
||||||
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"`
|
|
||||||
|
|
||||||
Confidential bool `json:"confidential"`
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
serverUrl: connectData.message.api_endpoint_base_url,
|
|
||||||
clientId: connectData.message.client_id,
|
|
||||||
redirectUri: connectData.message.redirect_uri,
|
|
||||||
tokenUri: `${connectData.message.oauth_endpoint_base_url}/token`,
|
|
||||||
scope: connectData.message.scopes.join(' '),
|
|
||||||
tokenResponse: payload,
|
|
||||||
expiresAt: getAccessTokenExpiration(payload, new BrowserAdapter()),
|
|
||||||
codeChallenge: codeChallenge,
|
|
||||||
codeVerifier: codeVerifier
|
|
||||||
|
|
||||||
*/
|
|
|
@ -1,7 +0,0 @@
|
||||||
package models
|
|
||||||
|
|
||||||
type SourceSummary struct {
|
|
||||||
Source *Source `json:"source,omitempty"`
|
|
||||||
ResourceTypeCounts []map[string]interface{} `json:"resource_type_counts,omitempty"`
|
|
||||||
Patient *ResourceFhir `json:"patient"`
|
|
||||||
}
|
|
|
@ -1,7 +0,0 @@
|
||||||
package models
|
|
||||||
|
|
||||||
type Summary struct {
|
|
||||||
Sources []Source `json:"sources,omitempty"`
|
|
||||||
Patients []ResourceFhir `json:"patients,omitempty"`
|
|
||||||
ResourceTypeCounts []map[string]interface{} `json:"resource_type_counts,omitempty"`
|
|
||||||
}
|
|
|
@ -1,26 +1,6 @@
|
||||||
package models
|
package models
|
||||||
|
|
||||||
import "golang.org/x/crypto/bcrypt"
|
|
||||||
|
|
||||||
type User struct {
|
type User struct {
|
||||||
ModelBase
|
Username string `json:"username"`
|
||||||
Name string `json:"name"`
|
|
||||||
Username string `json:"username" gorm:"unique"`
|
|
||||||
Password string `json:"password"`
|
Password string `json:"password"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (user *User) HashPassword(password string) error {
|
|
||||||
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
user.Password = string(bytes)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
func (user *User) CheckPassword(providedPassword string) error {
|
|
||||||
err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(providedPassword))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
|
@ -1,9 +1,6 @@
|
||||||
package handler
|
package handler
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/auth"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/database"
|
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/database"
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/models"
|
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/models"
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
|
@ -12,57 +9,17 @@ import (
|
||||||
|
|
||||||
func AuthSignup(c *gin.Context) {
|
func AuthSignup(c *gin.Context) {
|
||||||
databaseRepo := c.MustGet("REPOSITORY").(database.DatabaseRepository)
|
databaseRepo := c.MustGet("REPOSITORY").(database.DatabaseRepository)
|
||||||
appConfig := c.MustGet("CONFIG").(config.Interface)
|
|
||||||
|
|
||||||
var user models.User
|
var user models.User
|
||||||
if err := c.ShouldBindJSON(&user); err != nil {
|
if err := c.ShouldBindJSON(&user); err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false})
|
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
err := databaseRepo.CreateUser(c, &user)
|
err := databaseRepo.CreateUser(c, &user)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false})
|
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// return JWT
|
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||||
tokenString, err := auth.GenerateJWT(appConfig.GetString("web.jwt.encryptionkey"), user.Username, user.ID.String())
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": tokenString})
|
|
||||||
}
|
|
||||||
|
|
||||||
func AuthSignin(c *gin.Context) {
|
|
||||||
databaseRepo := c.MustGet("REPOSITORY").(database.DatabaseRepository)
|
|
||||||
appConfig := c.MustGet("CONFIG").(config.Interface)
|
|
||||||
|
|
||||||
var user models.User
|
|
||||||
if err := c.ShouldBindJSON(&user); err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
foundUser, err := databaseRepo.GetUserByEmail(c, user.Username)
|
|
||||||
if err != nil || foundUser == nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": fmt.Sprintf("could not find user: %s", user.Username)})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
err = foundUser.CheckPassword(user.Password)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": fmt.Sprintf("username or password does not match: %s", user.Username)})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// return JWT
|
|
||||||
tokenString, err := auth.GenerateJWT(appConfig.GetString("web.jwt.encryptionkey"), user.Username, user.ID.String())
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "an error occurred generating JWT token"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": tokenString})
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,52 @@
|
||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httputil"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
//TODO, there are security implications to this, we need to make sure we lock this down.
|
||||||
|
func CORSProxy(c *gin.Context) {
|
||||||
|
//appConfig := c.MustGet("CONFIG").(config.Interface)
|
||||||
|
corsUrl := fmt.Sprintf("https://%s", strings.TrimPrefix(c.Param("proxyPath"), "/"))
|
||||||
|
|
||||||
|
remote, err := url.Parse(corsUrl)
|
||||||
|
remote.RawQuery = c.Request.URL.Query().Encode()
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
proxy := httputil.ReverseProxy{}
|
||||||
|
//Define the director func
|
||||||
|
//This is a good place to log, for example
|
||||||
|
proxy.Director = func(req *http.Request) {
|
||||||
|
req.Header = c.Request.Header
|
||||||
|
req.Header.Add("X-Forwarded-Host", req.Host)
|
||||||
|
req.Header.Add("X-Origin-Host", remote.Host)
|
||||||
|
req.Host = remote.Host
|
||||||
|
req.URL.Scheme = remote.Scheme
|
||||||
|
req.URL.Host = remote.Host
|
||||||
|
log.Printf(c.Param("proxyPath"))
|
||||||
|
req.URL.Path = remote.Path
|
||||||
|
|
||||||
|
//TODO: throw an error if the remote.Host is not allowed
|
||||||
|
}
|
||||||
|
|
||||||
|
proxy.ModifyResponse = func(r *http.Response) error {
|
||||||
|
//b, _ := ioutil.ReadAll(r.Body)
|
||||||
|
//buf := bytes.NewBufferString("Monkey")
|
||||||
|
//buf.Write(b)
|
||||||
|
//r.Body = ioutil.NopCloser(buf)
|
||||||
|
r.Header.Set("Access-Control-Allow-Methods", "GET,HEAD")
|
||||||
|
r.Header.Set("Access-Control-Allow-Credentials", "true")
|
||||||
|
r.Header.Set("Access-Control-Allow-Origin", "*")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
proxy.ServeHTTP(c.Writer, c.Request)
|
||||||
|
}
|
|
@ -0,0 +1,40 @@
|
||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httputil"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func CouchDBProxy(c *gin.Context) {
|
||||||
|
appConfig := c.MustGet("CONFIG").(config.Interface)
|
||||||
|
|
||||||
|
couchdbUrl := fmt.Sprintf("%s://%s:%s", appConfig.GetString("web.couchdb.scheme"), appConfig.GetString("web.couchdb.host"), appConfig.GetString("web.couchdb.port"))
|
||||||
|
remote, err := url.Parse(couchdbUrl)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
proxy := httputil.NewSingleHostReverseProxy(remote)
|
||||||
|
//Define the director func
|
||||||
|
//This is a good place to log, for example
|
||||||
|
proxy.Director = func(req *http.Request) {
|
||||||
|
req.Header = c.Request.Header
|
||||||
|
req.Header.Add("X-Forwarded-Host", req.Host)
|
||||||
|
req.Header.Add("X-Origin-Host", remote.Host)
|
||||||
|
req.Host = remote.Host
|
||||||
|
req.URL.Scheme = remote.Scheme
|
||||||
|
req.URL.Host = remote.Host
|
||||||
|
log.Printf(c.Param("proxyPath"))
|
||||||
|
req.URL.Path = strings.TrimPrefix(c.Param("proxyPath"), "/database")
|
||||||
|
|
||||||
|
//todo: throw an error if not a user DB.
|
||||||
|
}
|
||||||
|
|
||||||
|
proxy.ServeHTTP(c.Writer, c.Request)
|
||||||
|
}
|
|
@ -1,35 +0,0 @@
|
||||||
package handler
|
|
||||||
|
|
||||||
import (
|
|
||||||
//"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/database"
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
//"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config"
|
|
||||||
//"github.com/sirupsen/logrus"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
func GetHelloWorld(c *gin.Context) {
|
|
||||||
//logger := c.MustGet("LOGGER").(*logrus.Entry)
|
|
||||||
//appConfig := c.MustGet("CONFIG").(config.Interface)
|
|
||||||
|
|
||||||
//device, err := deviceRepo.GetDeviceDetails(c, c.Param("wwn"))
|
|
||||||
//if err != nil {
|
|
||||||
// logger.Errorln("An error occurred while retrieving device details", err)
|
|
||||||
// c.JSON(http.StatusInternalServerError, gin.H{"success": false})
|
|
||||||
// return
|
|
||||||
//}
|
|
||||||
//
|
|
||||||
//durationKey, exists := c.GetQuery("duration_key")
|
|
||||||
//if !exists {
|
|
||||||
// durationKey = "forever"
|
|
||||||
//}
|
|
||||||
//
|
|
||||||
//smartResults, err := deviceRepo.GetSmartAttributeHistory(c, c.Param("wwn"), durationKey, nil)
|
|
||||||
//if err != nil {
|
|
||||||
// logger.Errorln("An error occurred while retrieving device smart results", err)
|
|
||||||
// c.JSON(http.StatusInternalServerError, gin.H{"success": false})
|
|
||||||
// return
|
|
||||||
//}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": map[string]interface{}{"hello": "world"}})
|
|
||||||
}
|
|
|
@ -1,51 +0,0 @@
|
||||||
package handler
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/database"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/models"
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/sirupsen/logrus"
|
|
||||||
"net/http"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
func ListResourceFhir(c *gin.Context) {
|
|
||||||
logger := c.MustGet("LOGGER").(*logrus.Entry)
|
|
||||||
databaseRepo := c.MustGet("REPOSITORY").(database.DatabaseRepository)
|
|
||||||
|
|
||||||
listResourceQueryOptions := models.ListResourceQueryOptions{}
|
|
||||||
if len(c.Query("sourceResourceType")) > 0 {
|
|
||||||
listResourceQueryOptions.SourceResourceType = c.Query("sourceResourceType")
|
|
||||||
}
|
|
||||||
if len(c.Query("sourceID")) > 0 {
|
|
||||||
listResourceQueryOptions.SourceID = c.Query("sourceID")
|
|
||||||
}
|
|
||||||
|
|
||||||
wrappedResourceModels, err := databaseRepo.ListResources(c, listResourceQueryOptions)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
logger.Errorln("An error occurred while retrieving resources", err)
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": wrappedResourceModels})
|
|
||||||
}
|
|
||||||
|
|
||||||
//this endpoint retrieves a specific resource by its ID
|
|
||||||
func GetResourceFhir(c *gin.Context) {
|
|
||||||
logger := c.MustGet("LOGGER").(*logrus.Entry)
|
|
||||||
databaseRepo := c.MustGet("REPOSITORY").(database.DatabaseRepository)
|
|
||||||
|
|
||||||
resourceId := strings.Trim(c.Param("resourceId"), "/")
|
|
||||||
sourceId := strings.Trim(c.Param("sourceId"), "/")
|
|
||||||
wrappedResourceModel, err := databaseRepo.GetResourceBySourceId(c, sourceId, resourceId)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
logger.Errorln("An error occurred while retrieving resource", err)
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": wrappedResourceModel})
|
|
||||||
}
|
|
|
@ -1,232 +0,0 @@
|
||||||
package handler
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/database"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/hub"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/models"
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/sirupsen/logrus"
|
|
||||||
"io/ioutil"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
func CreateSource(c *gin.Context) {
|
|
||||||
logger := c.MustGet("LOGGER").(*logrus.Entry)
|
|
||||||
databaseRepo := c.MustGet("REPOSITORY").(database.DatabaseRepository)
|
|
||||||
|
|
||||||
sourceCred := models.Source{}
|
|
||||||
if err := c.ShouldBindJSON(&sourceCred); err != nil {
|
|
||||||
logger.Errorln("An error occurred while parsing posted source credential", err)
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"success": false})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.Infof("Parsed Create Source Credentials Payload: %v", sourceCred)
|
|
||||||
|
|
||||||
err := databaseRepo.CreateSource(c, &sourceCred)
|
|
||||||
if err != nil {
|
|
||||||
logger.Errorln("An error occurred while storing source credential", err)
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// after creating the source, we should do a bulk import
|
|
||||||
err = syncSourceResources(c, logger, databaseRepo, sourceCred)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": sourceCred})
|
|
||||||
}
|
|
||||||
|
|
||||||
func SourceSync(c *gin.Context) {
|
|
||||||
logger := c.MustGet("LOGGER").(*logrus.Entry)
|
|
||||||
databaseRepo := c.MustGet("REPOSITORY").(database.DatabaseRepository)
|
|
||||||
|
|
||||||
logger.Infof("Get Source Credentials: %v", c.Param("sourceId"))
|
|
||||||
|
|
||||||
sourceCred, err := databaseRepo.GetSource(c, c.Param("sourceId"))
|
|
||||||
if err != nil {
|
|
||||||
logger.Errorln("An error occurred while retrieving source credential", err)
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// after creating the source, we should do a bulk import
|
|
||||||
err = syncSourceResources(c, logger, databaseRepo, *sourceCred)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": sourceCred})
|
|
||||||
}
|
|
||||||
|
|
||||||
func CreateManualSource(c *gin.Context) {
|
|
||||||
logger := c.MustGet("LOGGER").(*logrus.Entry)
|
|
||||||
databaseRepo := c.MustGet("REPOSITORY").(database.DatabaseRepository)
|
|
||||||
|
|
||||||
// single file
|
|
||||||
file, err := c.FormFile("file")
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "could not extract file from form"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
fmt.Printf("Uploaded filename: %s", file.Filename)
|
|
||||||
|
|
||||||
// create a temporary file to store this uploaded file
|
|
||||||
bundleFile, err := ioutil.TempFile("", file.Filename)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "could not create temp file"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Upload the file to specific bundleFile.
|
|
||||||
err = c.SaveUploadedFile(file, bundleFile.Name())
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "could not save temp file"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// We cannot save the "Source" object yet, as we do not know the patientID
|
|
||||||
|
|
||||||
// create a "manual" client, which we can use to parse the
|
|
||||||
manualSourceClient, _, err := hub.NewClient(pkg.SourceTypeManual, c, nil, logger, models.Source{})
|
|
||||||
if err != nil {
|
|
||||||
logger.Errorln("An error occurred while initializing hub client using manual source without credentials", err)
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
err = manualSourceClient.SyncAllBundle(databaseRepo, bundleFile)
|
|
||||||
if err != nil {
|
|
||||||
logger.Errorln("An error occurred while processing bundle", err)
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": fmt.Sprintf("'%s' uploaded!", file.Filename)})
|
|
||||||
}
|
|
||||||
|
|
||||||
func GetSource(c *gin.Context) {
|
|
||||||
logger := c.MustGet("LOGGER").(*logrus.Entry)
|
|
||||||
databaseRepo := c.MustGet("REPOSITORY").(database.DatabaseRepository)
|
|
||||||
|
|
||||||
sourceCred, err := databaseRepo.GetSource(c, c.Param("sourceId"))
|
|
||||||
if err != nil {
|
|
||||||
logger.Errorln("An error occurred while retrieving source credential", err)
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": sourceCred})
|
|
||||||
}
|
|
||||||
|
|
||||||
func GetSourceSummary(c *gin.Context) {
|
|
||||||
logger := c.MustGet("LOGGER").(*logrus.Entry)
|
|
||||||
databaseRepo := c.MustGet("REPOSITORY").(database.DatabaseRepository)
|
|
||||||
|
|
||||||
sourceSummary, err := databaseRepo.GetSourceSummary(c, c.Param("sourceId"))
|
|
||||||
if err != nil {
|
|
||||||
logger.Errorln("An error occurred while retrieving source summary", err)
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": sourceSummary})
|
|
||||||
}
|
|
||||||
|
|
||||||
func ListSource(c *gin.Context) {
|
|
||||||
logger := c.MustGet("LOGGER").(*logrus.Entry)
|
|
||||||
databaseRepo := c.MustGet("REPOSITORY").(database.DatabaseRepository)
|
|
||||||
|
|
||||||
sourceCreds, err := databaseRepo.GetSources(c)
|
|
||||||
if err != nil {
|
|
||||||
logger.Errorln("An error occurred while listing source credentials", err)
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": sourceCreds})
|
|
||||||
}
|
|
||||||
|
|
||||||
func RawRequestSource(c *gin.Context) {
|
|
||||||
logger := c.MustGet("LOGGER").(*logrus.Entry)
|
|
||||||
databaseRepo := c.MustGet("REPOSITORY").(database.DatabaseRepository)
|
|
||||||
|
|
||||||
//!!!!!!INSECURE!!!!!!S
|
|
||||||
//We're setting the username to a user provided value, this is insecure, but required for calling databaseRepo fns
|
|
||||||
c.Set("AUTH_USERNAME", c.Param("username"))
|
|
||||||
|
|
||||||
foundSource, err := databaseRepo.GetSource(c, c.Param("sourceId"))
|
|
||||||
if err != nil {
|
|
||||||
logger.Errorf("An error occurred while finding source credential: %v", err)
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if foundSource == nil {
|
|
||||||
logger.Errorf("Did not source credentials for %s", c.Param("sourceType"))
|
|
||||||
c.JSON(http.StatusNotFound, gin.H{"success": false, "error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
client, updatedSource, err := hub.NewClient(foundSource.SourceType, c, nil, logger, *foundSource)
|
|
||||||
if err != nil {
|
|
||||||
logger.Errorf("Could not initialize source client %v", err)
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if updatedSource != nil {
|
|
||||||
err := databaseRepo.CreateSource(c, updatedSource)
|
|
||||||
if err != nil {
|
|
||||||
logger.Errorf("An error occurred while updating source credential %v", err)
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var resp map[string]interface{}
|
|
||||||
|
|
||||||
parsedUrl, err := url.Parse(strings.TrimSuffix(c.Param("path"), "/"))
|
|
||||||
if err != nil {
|
|
||||||
logger.Errorf("Error parsing request, %v", err)
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
//make sure we include all query string parameters with the raw request.
|
|
||||||
parsedUrl.RawQuery = c.Request.URL.Query().Encode()
|
|
||||||
|
|
||||||
err = client.GetRequest(parsedUrl.String(), &resp)
|
|
||||||
if err != nil {
|
|
||||||
logger.Errorf("Error making raw request, %v", err)
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": err.Error(), "data": resp})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": resp})
|
|
||||||
}
|
|
||||||
|
|
||||||
////// private functions
|
|
||||||
func syncSourceResources(c *gin.Context, logger *logrus.Entry, databaseRepo database.DatabaseRepository, sourceCred models.Source) error {
|
|
||||||
// after creating the source, we should do a bulk import
|
|
||||||
sourceClient, updatedSource, err := hub.NewClient(sourceCred.SourceType, c, nil, logger, sourceCred)
|
|
||||||
if err != nil {
|
|
||||||
logger.Errorln("An error occurred while initializing hub client using source credential", err)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if updatedSource != nil {
|
|
||||||
err := databaseRepo.CreateSource(c, updatedSource)
|
|
||||||
if err != nil {
|
|
||||||
logger.Errorln("An error occurred while updating source credential", err)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
err = sourceClient.SyncAll(databaseRepo)
|
|
||||||
if err != nil {
|
|
||||||
logger.Errorln("An error occurred while bulk import of resources from source", err)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
|
@ -1,21 +0,0 @@
|
||||||
package handler
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/database"
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/sirupsen/logrus"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
func GetSummary(c *gin.Context) {
|
|
||||||
logger := c.MustGet("LOGGER").(*logrus.Entry)
|
|
||||||
databaseRepo := c.MustGet("REPOSITORY").(database.DatabaseRepository)
|
|
||||||
|
|
||||||
summary, err := databaseRepo.GetSummary(c)
|
|
||||||
if err != nil {
|
|
||||||
logger.Errorln("An error occurred while retrieving summary", err)
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": summary})
|
|
||||||
}
|
|
|
@ -1,47 +0,0 @@
|
||||||
package middleware
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/auth"
|
|
||||||
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config"
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"log"
|
|
||||||
"net/http"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
func RequireAuth() gin.HandlerFunc {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
appConfig := c.MustGet("CONFIG").(config.Interface)
|
|
||||||
|
|
||||||
authHeader := c.GetHeader("Authorization")
|
|
||||||
authHeaderParts := strings.Split(authHeader, " ")
|
|
||||||
|
|
||||||
if len(authHeaderParts) != 2 {
|
|
||||||
log.Println("Authentication header is invalid: " + authHeader)
|
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "request does not contain a valid token"})
|
|
||||||
c.Abort()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
tokenString := authHeaderParts[1]
|
|
||||||
|
|
||||||
if tokenString == "" {
|
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "request does not contain an access token"})
|
|
||||||
c.Abort()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
claim, err := auth.ValidateToken(appConfig.GetString("web.jwt.encryptionkey"), tokenString)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": err.Error()})
|
|
||||||
c.Abort()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
//todo, is this shared between all sessions??
|
|
||||||
c.Set("AUTH_TOKEN", tokenString)
|
|
||||||
c.Set("AUTH_USERNAME", claim.Username)
|
|
||||||
c.Set("AUTH_USERID", claim.UserId)
|
|
||||||
|
|
||||||
c.Next()
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -41,31 +41,11 @@ func (ae *AppEngine) Setup(logger *logrus.Entry) *gin.Engine {
|
||||||
})
|
})
|
||||||
|
|
||||||
api.POST("/auth/signup", handler.AuthSignup)
|
api.POST("/auth/signup", handler.AuthSignup)
|
||||||
api.POST("/auth/signin", handler.AuthSignin)
|
|
||||||
|
|
||||||
secure := api.Group("/secure").Use(middleware.RequireAuth())
|
|
||||||
{
|
|
||||||
secure.GET("/summary", handler.GetSummary)
|
|
||||||
|
|
||||||
secure.POST("/source", handler.CreateSource)
|
|
||||||
secure.POST("/source/manual", handler.CreateManualSource)
|
|
||||||
secure.GET("/source", handler.ListSource)
|
|
||||||
secure.GET("/source/:sourceId", handler.GetSource)
|
|
||||||
secure.POST("/source/:sourceId/sync", handler.SourceSync)
|
|
||||||
secure.GET("/source/:sourceId/summary", handler.GetSourceSummary)
|
|
||||||
secure.GET("/resource/fhir", handler.ListResourceFhir) //
|
|
||||||
secure.GET("/resource/fhir/:sourceId/:resourceId", handler.GetResourceFhir)
|
|
||||||
}
|
|
||||||
|
|
||||||
api.GET("/metadata/source", handler.GetMetadataSource)
|
api.GET("/metadata/source", handler.GetMetadataSource)
|
||||||
|
|
||||||
if ae.Config.GetString("log.level") == "DEBUG" {
|
r.Any("/database/*proxyPath", handler.CouchDBProxy)
|
||||||
//in debug mode, this endpoint lets us request data directly from the source api
|
r.GET("/cors/*proxyPath", handler.CORSProxy)
|
||||||
ae.Logger.Warningf("***INSECURE*** ***INSECURE*** DEBUG mode enables developer functionality, including unauthenticated raw api requests")
|
r.OPTIONS("/cors/*proxyPath", handler.CORSProxy)
|
||||||
|
|
||||||
//http://localhost:9090/api/raw/test@test.com/436d7277-ad56-41ce-9823-44e353d1b3f6/Patient/smart-1288992
|
|
||||||
api.GET("/raw/:username/:sourceId/*path", handler.RawRequestSource)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -6,9 +6,6 @@
|
||||||
version: 1
|
version: 1
|
||||||
|
|
||||||
web:
|
web:
|
||||||
jwt:
|
|
||||||
# used to encrypt/validate JWT session key (used for authentication)
|
|
||||||
encryptionkey: 'changethissupersecretkey'
|
|
||||||
listen:
|
listen:
|
||||||
port: 8080
|
port: 8080
|
||||||
host: 0.0.0.0
|
host: 0.0.0.0
|
||||||
|
|
|
@ -0,0 +1,16 @@
|
||||||
|
version: "3.9"
|
||||||
|
services:
|
||||||
|
couchdb:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
# environment:
|
||||||
|
# - COUCHDB_USER=admin
|
||||||
|
# - COUCHDB_PASSWORD=password
|
||||||
|
ports:
|
||||||
|
- "9090:8080"
|
||||||
|
- "5984:5984"
|
||||||
|
volumes:
|
||||||
|
- ./.couchdb/data:/opt/couchdb/data
|
||||||
|
- ./.couchdb/config:/opt/couchdb/etc/local.d
|
||||||
|
# - ./config.example.yaml:/opt/fasten/config/config.yaml
|
|
@ -0,0 +1,9 @@
|
||||||
|
# Dockerfiles
|
||||||
|
|
||||||
|
Note, the context for Dockerfiles in this directory is **always** the repository root.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker build -f docker/couchdb/Dockerfile -t couchdb-fasten .
|
||||||
|
|
||||||
|
docker run --rm -it -p 5984:5984 -v `pwd`/.couchdb/data:/opt/couchdb/data -v `pwd`/.couchdb/config:/opt/couchdb/etc/local.d couchdb-fasten
|
||||||
|
```
|
|
@ -0,0 +1,16 @@
|
||||||
|
#########################################################################################################
|
||||||
|
# CouchDB Build
|
||||||
|
# NOTE: the context for this build should be the root of the repository.
|
||||||
|
#########################################################################################################
|
||||||
|
FROM couchdb:3.2
|
||||||
|
|
||||||
|
ARG S6_ARCH=amd64
|
||||||
|
RUN curl https://github.com/just-containers/s6-overlay/releases/download/v1.21.8.0/s6-overlay-${S6_ARCH}.tar.gz -L -s --output /tmp/s6-overlay-${S6_ARCH}.tar.gz \
|
||||||
|
&& tar xzf /tmp/s6-overlay-${S6_ARCH}.tar.gz -C / \
|
||||||
|
&& rm -rf /tmp/s6-overlay-${S6_ARCH}.tar.gz
|
||||||
|
|
||||||
|
COPY /docker/couchdb/local.ini /opt/couchdb/etc/local.ini
|
||||||
|
COPY /docker/rootfs /
|
||||||
|
RUN rm -rf /etc/services.d/fasten #delete the fasten app from the couchdbase container.
|
||||||
|
|
||||||
|
ENTRYPOINT ["/init"]
|
|
@ -0,0 +1,108 @@
|
||||||
|
; CouchDB Configuration Settings
|
||||||
|
|
||||||
|
; Custom settings should be made in this file. They will override settings
|
||||||
|
; in default.ini, but unlike changes made to default.ini, this file won't be
|
||||||
|
; overwritten on server upgrade.
|
||||||
|
|
||||||
|
[cors]
|
||||||
|
origins = *
|
||||||
|
headers = accept, authorization, content-type, origin, referer
|
||||||
|
credentials = true
|
||||||
|
methods = GET, PUT, POST, HEAD, DELETE
|
||||||
|
|
||||||
|
[couchdb]
|
||||||
|
;max_document_size = 4294967296 ; bytes
|
||||||
|
;os_process_timeout = 5000
|
||||||
|
single_node=true
|
||||||
|
|
||||||
|
[couch_peruser]
|
||||||
|
; If enabled, couch_peruser ensures that a private per-user database
|
||||||
|
; exists for each document in _users. These databases are writable only
|
||||||
|
; by the corresponding user. Databases are in the following form:
|
||||||
|
; userdb-{hex encoded username}
|
||||||
|
enable = true
|
||||||
|
; If set to true and a user is deleted, the respective database gets
|
||||||
|
; deleted as well.
|
||||||
|
;delete_dbs = true
|
||||||
|
; Set a default q value for peruser-created databases that is different from
|
||||||
|
; cluster / q
|
||||||
|
;q = 1
|
||||||
|
|
||||||
|
[chttpd]
|
||||||
|
;port = 5984
|
||||||
|
;bind_address = 127.0.0.1
|
||||||
|
; Options for the MochiWeb HTTP server.
|
||||||
|
;server_options = [{backlog, 128}, {acceptor_pool_size, 16}]
|
||||||
|
; For more socket options, consult Erlang's module 'inet' man page.
|
||||||
|
;socket_options = [{sndbuf, 262144}, {nodelay, true}]
|
||||||
|
bind_address = 0.0.0.0
|
||||||
|
enable_cors = true
|
||||||
|
x_forwarded_host = X-Forwarded-Host
|
||||||
|
|
||||||
|
[httpd]
|
||||||
|
; NOTE that this only configures the "backend" node-local port, not the
|
||||||
|
; "frontend" clustered port. You probably don't want to change anything in
|
||||||
|
; this section.
|
||||||
|
; Uncomment next line to trigger basic-auth popup on unauthorized requests.
|
||||||
|
;WWW-Authenticate = Basic realm="administrator"
|
||||||
|
|
||||||
|
; Uncomment next line to set the configuration modification whitelist. Only
|
||||||
|
; whitelisted values may be changed via the /_config URLs. To allow the admin
|
||||||
|
; to change this value over HTTP, remember to include {httpd,config_whitelist}
|
||||||
|
; itself. Excluding it from the list would require editing this file to update
|
||||||
|
; the whitelist.
|
||||||
|
;config_whitelist = [{httpd,config_whitelist}, {log,level}, {etc,etc}]
|
||||||
|
enable_cors = true
|
||||||
|
|
||||||
|
[chttpd_auth]
|
||||||
|
; If you set this to true, you should also uncomment the WWW-Authenticate line
|
||||||
|
; above. If you don't configure a WWW-Authenticate header, CouchDB will send
|
||||||
|
; Basic realm="server" in order to prevent you getting logged out.
|
||||||
|
; require_valid_user = false
|
||||||
|
allow_persistent_cookies = true
|
||||||
|
;cookie_domain = localhost:5984
|
||||||
|
|
||||||
|
[ssl]
|
||||||
|
;enable = true
|
||||||
|
;cert_file = /full/path/to/server_cert.pem
|
||||||
|
;key_file = /full/path/to/server_key.pem
|
||||||
|
;password = somepassword
|
||||||
|
; set to true to validate peer certificates
|
||||||
|
;verify_ssl_certificates = false
|
||||||
|
; Set to true to fail if the client does not send a certificate. Only used if verify_ssl_certificates is true.
|
||||||
|
;fail_if_no_peer_cert = false
|
||||||
|
; Path to file containing PEM encoded CA certificates (trusted
|
||||||
|
; certificates used for verifying a peer certificate). May be omitted if
|
||||||
|
; you do not want to verify the peer.
|
||||||
|
;cacert_file = /full/path/to/cacertf
|
||||||
|
; The verification fun (optional) if not specified, the default
|
||||||
|
; verification fun will be used.
|
||||||
|
;verify_fun = {Module, VerifyFun}
|
||||||
|
; maximum peer certificate depth
|
||||||
|
;ssl_certificate_max_depth = 1
|
||||||
|
;
|
||||||
|
; Reject renegotiations that do not live up to RFC 5746.
|
||||||
|
;secure_renegotiate = true
|
||||||
|
; The cipher suites that should be supported.
|
||||||
|
; Can be specified in erlang format "{ecdhe_ecdsa,aes_128_cbc,sha256}"
|
||||||
|
; or in OpenSSL format "ECDHE-ECDSA-AES128-SHA256".
|
||||||
|
;ciphers = ["ECDHE-ECDSA-AES128-SHA256", "ECDHE-ECDSA-AES128-SHA"]
|
||||||
|
; The SSL/TLS versions to support
|
||||||
|
;tls_versions = [tlsv1, 'tlsv1.1', 'tlsv1.2']
|
||||||
|
|
||||||
|
; To enable Virtual Hosts in CouchDB, add a vhost = path directive. All requests to
|
||||||
|
; the Virual Host will be redirected to the path. In the example below all requests
|
||||||
|
; to http://example.com/ are redirected to /database.
|
||||||
|
; If you run CouchDB on a specific port, include the port number in the vhost:
|
||||||
|
; example.com:5984 = /database
|
||||||
|
[vhosts]
|
||||||
|
;example.com = /database/
|
||||||
|
|
||||||
|
; To create an admin account uncomment the '[admins]' section below and add a
|
||||||
|
; line in the format 'username = password'. When you next start CouchDB, it
|
||||||
|
; will change the password to a hash (so that your passwords don't linger
|
||||||
|
; around in plain-text files). You can add more admin accounts with more
|
||||||
|
; 'username = password' lines. Don't forget to restart CouchDB after
|
||||||
|
; changing this.
|
||||||
|
[admins]
|
||||||
|
admin = mysecretpassword
|
|
@ -0,0 +1,7 @@
|
||||||
|
#!/usr/bin/with-contenv bash
|
||||||
|
|
||||||
|
if [ -n "${TZ}" ]
|
||||||
|
then
|
||||||
|
ln -snf "/usr/share/zoneinfo/${TZ}" /etc/localtime
|
||||||
|
echo "${TZ}" > /etc/timezone
|
||||||
|
fi
|
|
@ -0,0 +1,35 @@
|
||||||
|
#!/usr/bin/with-contenv bash
|
||||||
|
|
||||||
|
if [ -f "/opt/couchdb/data/.init_complete" ]; then
|
||||||
|
echo "Couchdb initialization has already completed, skipping"
|
||||||
|
else
|
||||||
|
# start couchdb as a background process (store PID)
|
||||||
|
echo "Couchdb initialization: start couchdb in background mode (non-standard port)"
|
||||||
|
# https://linux.die.net/man/1/couchdb
|
||||||
|
sed -i -e 's/;port = 5984/port = 5432/g' /opt/couchdb/etc/local.ini
|
||||||
|
sed -i -e 's/bind_address = 0.0.0.0/bind_address = 127.0.0.1/g' /opt/couchdb/etc/local.ini
|
||||||
|
/opt/couchdb/bin/couchdb -b &
|
||||||
|
COUCHDB_PID=$!
|
||||||
|
|
||||||
|
# wait for couchdb to be ready
|
||||||
|
until $(curl --output /dev/null --silent --head --fail http://127.0.0.1:5432/_up); do echo "couchdb not ready" && sleep 5; done
|
||||||
|
|
||||||
|
# create couch_peruser required system databases manually on startup
|
||||||
|
echo "couchdb ready, start creating system databases"
|
||||||
|
curl --fail -X PUT -u admin:mysecretpassword http://127.0.0.1:5432/_users
|
||||||
|
curl --fail -X PUT -u admin:mysecretpassword http://127.0.0.1:5432/_replicator
|
||||||
|
curl --fail -X PUT -u admin:mysecretpassword http://127.0.0.1:5432/_global_changes
|
||||||
|
echo "system databases created successfully"
|
||||||
|
|
||||||
|
# gracefully stop couchdb process
|
||||||
|
echo "killing couchdb process"
|
||||||
|
/opt/couchdb/bin/couchdb -k
|
||||||
|
|
||||||
|
sed -i -e 's/port = 5432/;port = 5984/g' /opt/couchdb/etc/local.ini
|
||||||
|
sed -i -e 's/bind_address = 127.0.0.1/bind_address = 0.0.0.0/g' /opt/couchdb/etc/local.ini
|
||||||
|
|
||||||
|
# create the init complete flag
|
||||||
|
echo "Couchdb initialization: complete"
|
||||||
|
touch /opt/couchdb/data/.init_complete
|
||||||
|
|
||||||
|
fi
|
|
@ -0,0 +1,4 @@
|
||||||
|
#!/usr/bin/with-contenv bash
|
||||||
|
|
||||||
|
echo "starting couchdb"
|
||||||
|
/docker-entrypoint.sh /opt/couchdb/bin/couchdb
|
|
@ -0,0 +1,7 @@
|
||||||
|
#!/usr/bin/with-contenv bash
|
||||||
|
|
||||||
|
# wait for couchdb to be ready
|
||||||
|
until $(curl --output /dev/null --silent --head --fail http://127.0.0.1:5984/_up); do echo "couchdb not ready" && sleep 5; done
|
||||||
|
|
||||||
|
echo "starting fasten"
|
||||||
|
/opt/fasten/fasten start --config /opt/fasten/config/config.yaml
|
|
@ -34,7 +34,8 @@
|
||||||
],
|
],
|
||||||
"scripts": [
|
"scripts": [
|
||||||
"node_modules/@panva/oauth4webapi/build/index.js"
|
"node_modules/@panva/oauth4webapi/build/index.js"
|
||||||
]
|
],
|
||||||
|
"webWorkerTsConfig": "tsconfig.worker.json"
|
||||||
},
|
},
|
||||||
"configurations": {
|
"configurations": {
|
||||||
"production": {
|
"production": {
|
||||||
|
@ -125,7 +126,8 @@
|
||||||
"styles": [
|
"styles": [
|
||||||
"src/styles.scss"
|
"src/styles.scss"
|
||||||
],
|
],
|
||||||
"scripts": []
|
"scripts": [],
|
||||||
|
"webWorkerTsConfig": "tsconfig.worker.json"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"lint": {
|
"lint": {
|
||||||
|
|
|
@ -31,14 +31,22 @@
|
||||||
"@swimlane/ngx-datatable": "^20.0.0",
|
"@swimlane/ngx-datatable": "^20.0.0",
|
||||||
"bootstrap": "^4.4.1",
|
"bootstrap": "^4.4.1",
|
||||||
"chart.js": "2.9.4",
|
"chart.js": "2.9.4",
|
||||||
|
"crypto-pouch": "^4.0.1",
|
||||||
"fhirclient": "^2.5.1",
|
"fhirclient": "^2.5.1",
|
||||||
"humanize-duration": "^3.27.3",
|
"humanize-duration": "^3.27.3",
|
||||||
"moment": "^2.29.4",
|
"moment": "^2.29.4",
|
||||||
"ng2-charts": "^2.3.0",
|
"ng2-charts": "^2.3.0",
|
||||||
"ngx-dropzone": "^3.1.0",
|
"ngx-dropzone": "^3.1.0",
|
||||||
"ngx-highlightjs": "^7.0.1",
|
"ngx-highlightjs": "^7.0.1",
|
||||||
|
"ngx-moment": "^6.0.2",
|
||||||
|
"observable-webworker": "^4.0.1",
|
||||||
|
"pouchdb": "^7.3.0",
|
||||||
|
"pouchdb-authentication": "^1.1.3",
|
||||||
|
"pouchdb-find": "^7.3.0",
|
||||||
|
"pouchdb-upsert": "^2.2.0",
|
||||||
"rxjs": "~6.5.4",
|
"rxjs": "~6.5.4",
|
||||||
"tslib": "^2.0.0",
|
"tslib": "^2.0.0",
|
||||||
|
"uuid": "^9.0.0",
|
||||||
"zone.js": "~0.11.8"
|
"zone.js": "~0.11.8"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
@ -46,9 +54,11 @@
|
||||||
"@angular/cli": "^14.1.3",
|
"@angular/cli": "^14.1.3",
|
||||||
"@angular/compiler-cli": "^14.1.3",
|
"@angular/compiler-cli": "^14.1.3",
|
||||||
"@angular/language-service": "^14.1.3",
|
"@angular/language-service": "^14.1.3",
|
||||||
|
"@types/crypto-pouch": "^4.0.1",
|
||||||
"@types/jasmine": "~3.5.0",
|
"@types/jasmine": "~3.5.0",
|
||||||
"@types/jasminewd2": "~2.0.3",
|
"@types/jasminewd2": "~2.0.3",
|
||||||
"@types/node": "^12.11.1",
|
"@types/pouchdb": "^6.4.0",
|
||||||
|
"@types/pouchdb-find": "^7.3.0",
|
||||||
"codelyzer": "^5.1.2",
|
"codelyzer": "^5.1.2",
|
||||||
"jasmine-core": "~3.5.0",
|
"jasmine-core": "~3.5.0",
|
||||||
"jasmine-spec-reporter": "~5.0.0",
|
"jasmine-spec-reporter": "~5.0.0",
|
||||||
|
|
|
@ -18,7 +18,7 @@ const routes: Routes = [
|
||||||
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
|
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
|
||||||
{ path: 'dashboard', component: DashboardComponent, canActivate: [ CanActivateAuthGuard] },
|
{ path: 'dashboard', component: DashboardComponent, canActivate: [ CanActivateAuthGuard] },
|
||||||
{ path: 'source/:source_id', component: SourceDetailComponent, canActivate: [ CanActivateAuthGuard] },
|
{ path: 'source/:source_id', component: SourceDetailComponent, canActivate: [ CanActivateAuthGuard] },
|
||||||
{ path: 'source/:source_id/resource/:resource_id', component: ResourceDetailComponent, canActivate: [ CanActivateAuthGuard] },
|
{ path: 'resource/:resource_id', component: ResourceDetailComponent, canActivate: [ CanActivateAuthGuard] },
|
||||||
{ path: 'sources', component: MedicalSourcesComponent, canActivate: [ CanActivateAuthGuard] },
|
{ path: 'sources', component: MedicalSourcesComponent, canActivate: [ CanActivateAuthGuard] },
|
||||||
{ path: 'sources/callback/:source_type', component: MedicalSourcesComponent, canActivate: [ CanActivateAuthGuard] },
|
{ path: 'sources/callback/:source_type', component: MedicalSourcesComponent, canActivate: [ CanActivateAuthGuard] },
|
||||||
|
|
||||||
|
|
|
@ -1,5 +1,6 @@
|
||||||
<div>
|
<div>
|
||||||
<app-header *ngIf="showHeader"></app-header>
|
<app-header *ngIf="showHeader"></app-header>
|
||||||
|
<app-toast aria-live="polite" aria-atomic="true"></app-toast>
|
||||||
<div class="az-content-wrapper">
|
<div class="az-content-wrapper">
|
||||||
<router-outlet></router-outlet>
|
<router-outlet></router-outlet>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
@ -1,5 +1,9 @@
|
||||||
import { Component, OnInit } from '@angular/core';
|
import { Component, OnInit } from '@angular/core';
|
||||||
import {NavigationEnd, Router} from '@angular/router';
|
import {NavigationEnd, Router} from '@angular/router';
|
||||||
|
import {fromWorker} from 'observable-webworker';
|
||||||
|
import {Observable, of} from 'rxjs';
|
||||||
|
import {QueueService} from './workers/queue.service';
|
||||||
|
import {ToastService} from './services/toast.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-root',
|
selector: 'app-root',
|
||||||
|
@ -13,7 +17,7 @@ export class AppComponent implements OnInit {
|
||||||
showHeader:boolean = false;
|
showHeader:boolean = false;
|
||||||
showFooter:boolean = true;
|
showFooter:boolean = true;
|
||||||
|
|
||||||
constructor(private router: Router) {}
|
constructor(private router: Router, private queueService: QueueService, private toastService: ToastService) {}
|
||||||
|
|
||||||
ngOnInit() {
|
ngOnInit() {
|
||||||
|
|
||||||
|
|
|
@ -18,13 +18,13 @@ import { AuthSignupComponent } from './pages/auth-signup/auth-signup.component';
|
||||||
import { AuthSigninComponent } from './pages/auth-signin/auth-signin.component';
|
import { AuthSigninComponent } from './pages/auth-signin/auth-signin.component';
|
||||||
import { FormsModule } from '@angular/forms';
|
import { FormsModule } from '@angular/forms';
|
||||||
import { NgxDropzoneModule } from 'ngx-dropzone';
|
import { NgxDropzoneModule } from 'ngx-dropzone';
|
||||||
import { AuthInterceptorService } from './services/auth-interceptor.service';
|
|
||||||
import { CanActivateAuthGuard } from './services/can-activate.auth-guard';
|
import { CanActivateAuthGuard } from './services/can-activate.auth-guard';
|
||||||
import {FastenApiService} from './services/fasten-api.service';
|
import {FastenDbService} from './services/fasten-db.service';
|
||||||
import {Router} from '@angular/router';
|
import {Router} from '@angular/router';
|
||||||
import { SourceDetailComponent } from './pages/source-detail/source-detail.component';
|
import { SourceDetailComponent } from './pages/source-detail/source-detail.component';
|
||||||
import {ResourceListComponent} from './components/resource-list/resource-list.component';
|
|
||||||
import { HighlightModule, HIGHLIGHT_OPTIONS } from 'ngx-highlightjs';
|
import { HighlightModule, HIGHLIGHT_OPTIONS } from 'ngx-highlightjs';
|
||||||
|
import {AuthInterceptorService} from './services/auth-interceptor.service';
|
||||||
|
import { MomentModule } from 'ngx-moment';
|
||||||
|
|
||||||
@NgModule({
|
@NgModule({
|
||||||
declarations: [
|
declarations: [
|
||||||
|
@ -48,14 +48,15 @@ import { HighlightModule, HIGHLIGHT_OPTIONS } from 'ngx-highlightjs';
|
||||||
NgbModule,
|
NgbModule,
|
||||||
ChartsModule,
|
ChartsModule,
|
||||||
NgxDropzoneModule,
|
NgxDropzoneModule,
|
||||||
HighlightModule
|
HighlightModule,
|
||||||
|
MomentModule
|
||||||
],
|
],
|
||||||
providers: [
|
providers: [
|
||||||
{
|
{
|
||||||
provide: HTTP_INTERCEPTORS,
|
provide: HTTP_INTERCEPTORS,
|
||||||
useClass: AuthInterceptorService,
|
useClass: AuthInterceptorService,
|
||||||
multi: true,
|
multi: true,
|
||||||
deps: [FastenApiService, Router]
|
deps: [FastenDbService, Router]
|
||||||
},
|
},
|
||||||
CanActivateAuthGuard,
|
CanActivateAuthGuard,
|
||||||
{
|
{
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
import { Component, OnInit } from '@angular/core';
|
import { Component, OnInit } from '@angular/core';
|
||||||
import {FastenApiService} from '../../services/fasten-api.service';
|
import {FastenDbService} from '../../services/fasten-db.service';
|
||||||
import { Router } from '@angular/router';
|
import { Router } from '@angular/router';
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-header',
|
selector: 'app-header',
|
||||||
|
@ -8,7 +8,7 @@ import { Router } from '@angular/router';
|
||||||
})
|
})
|
||||||
export class HeaderComponent implements OnInit {
|
export class HeaderComponent implements OnInit {
|
||||||
|
|
||||||
constructor(private fastenApi: FastenApiService, private router: Router) { }
|
constructor(private fastenDb: FastenDbService, private router: Router) { }
|
||||||
|
|
||||||
ngOnInit() {
|
ngOnInit() {
|
||||||
}
|
}
|
||||||
|
@ -24,7 +24,7 @@ export class HeaderComponent implements OnInit {
|
||||||
}
|
}
|
||||||
|
|
||||||
signOut(e) {
|
signOut(e) {
|
||||||
this.fastenApi.logout()
|
this.fastenDb.Logout()
|
||||||
this.router.navigate(['auth/signin']);
|
.then(() => this.router.navigate(['auth/signin']))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -9,6 +9,6 @@
|
||||||
|
|
||||||
<ul class="list-group">
|
<ul class="list-group">
|
||||||
<li class="list-group-item" *ngFor="let resource of resourceList">
|
<li class="list-group-item" *ngFor="let resource of resourceList">
|
||||||
<a routerLink="/source/{{resource.source_id}}/resource/{{resource.source_resource_id}}">{{resource.source_resource_id}}</a>
|
<a routerLink="/resource/{{resource.base64Id()}}">{{resource.source_resource_id}}</a>
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|
|
@ -1,7 +1,8 @@
|
||||||
import {ChangeDetectorRef, Component, Input, OnInit} from '@angular/core';
|
import {ChangeDetectorRef, Component, Input, OnInit} from '@angular/core';
|
||||||
import {ResourceFhir} from '../../models/fasten/resource_fhir';
|
import {ResourceFhir} from '../../../lib/models/database/resource_fhir';
|
||||||
import {ResourceListComponentInterface} from '../list-generic-resource/list-generic-resource.component';
|
import {ResourceListComponentInterface} from '../list-generic-resource/list-generic-resource.component';
|
||||||
import {Router} from '@angular/router';
|
import {Router} from '@angular/router';
|
||||||
|
import {Base64} from '../../../lib/utils/base64';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-list-fallback-resource',
|
selector: 'app-list-fallback-resource',
|
||||||
|
@ -21,4 +22,5 @@ export class ListFallbackResourceComponent implements OnInit, ResourceListCompo
|
||||||
markForCheck(){
|
markForCheck(){
|
||||||
this.changeRef.markForCheck()
|
this.changeRef.markForCheck()
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,9 +1,9 @@
|
||||||
import {ChangeDetectorRef, Component, Input, OnChanges, OnInit, SimpleChanges, ViewChild} from '@angular/core';
|
import {ChangeDetectorRef, Component, Input, OnInit, ViewChild} from '@angular/core';
|
||||||
import {DatatableComponent, ColumnMode, SelectionType} from '@swimlane/ngx-datatable';
|
import {DatatableComponent, ColumnMode, SelectionType} from '@swimlane/ngx-datatable';
|
||||||
import {ResourceFhir} from '../../models/fasten/resource_fhir';
|
import {ResourceFhir} from '../../../lib/models/database/resource_fhir';
|
||||||
import {FORMATTERS, getPath, obsValue, attributeXTime} from './utils';
|
import {FORMATTERS, getPath, obsValue, attributeXTime} from './utils';
|
||||||
import {observableToBeFn} from 'rxjs/internal/testing/TestScheduler';
|
|
||||||
import {Router} from '@angular/router';
|
import {Router} from '@angular/router';
|
||||||
|
import {Base64} from '../../../lib/utils/base64';
|
||||||
|
|
||||||
//all Resource list components must implement this Interface
|
//all Resource list components must implement this Interface
|
||||||
export interface ResourceListComponentInterface {
|
export interface ResourceListComponentInterface {
|
||||||
|
@ -61,6 +61,7 @@ export class ListGenericResourceComponent implements OnInit, ResourceListCompone
|
||||||
|
|
||||||
this.rows = this.resourceList.map((resource) => {
|
this.rows = this.resourceList.map((resource) => {
|
||||||
let row = {
|
let row = {
|
||||||
|
_id: resource._id,
|
||||||
source_id: resource.source_id,
|
source_id: resource.source_id,
|
||||||
source_resource_type: resource.source_resource_type,
|
source_resource_type: resource.source_resource_type,
|
||||||
source_resource_id: resource.source_resource_id
|
source_resource_id: resource.source_resource_id
|
||||||
|
@ -68,7 +69,7 @@ export class ListGenericResourceComponent implements OnInit, ResourceListCompone
|
||||||
|
|
||||||
this.columnDefinitions.forEach((defn) => {
|
this.columnDefinitions.forEach((defn) => {
|
||||||
try{
|
try{
|
||||||
let resourceProp = defn.getter(resource.payload)
|
let resourceProp = defn.getter(resource.resource_raw)
|
||||||
let resourceFormatted = defn.format ? FORMATTERS[defn.format](resourceProp) : resourceProp
|
let resourceFormatted = defn.format ? FORMATTERS[defn.format](resourceProp) : resourceProp
|
||||||
row[defn.title.replace(/[^A-Z0-9]/ig, "_")] = resourceFormatted
|
row[defn.title.replace(/[^A-Z0-9]/ig, "_")] = resourceFormatted
|
||||||
}catch (e){
|
}catch (e){
|
||||||
|
@ -79,9 +80,14 @@ export class ListGenericResourceComponent implements OnInit, ResourceListCompone
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The selected object is NOT a ResourceFHIR, its actually a dynamically created row object
|
||||||
|
* created in renderList()
|
||||||
|
* @param selected
|
||||||
|
*/
|
||||||
onSelect({ selected }) {
|
onSelect({ selected }) {
|
||||||
console.log('Select Event', selected);
|
console.log('Select Event', selected);
|
||||||
this.router.navigateByUrl(`/source/${selected[0].source_id}/resource/${selected[0].source_resource_id}`);
|
this.router.navigateByUrl(`/resource/${Base64.Encode(selected[0]._id)}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,8 +1,8 @@
|
||||||
import { ResourceListOutletDirective } from './resource-list-outlet.directive';
|
import { ResourceListOutletDirective } from './resource-list-outlet.directive';
|
||||||
|
|
||||||
describe('ResourceListOutletDirective', () => {
|
// describe('ResourceListOutletDirective', () => {
|
||||||
it('should create an instance', () => {
|
// it('should create an instance', () => {
|
||||||
const directive = new ResourceListOutletDirective();
|
// const directive = new ResourceListOutletDirective();
|
||||||
expect(directive).toBeTruthy();
|
// expect(directive).toBeTruthy();
|
||||||
});
|
// });
|
||||||
});
|
// });
|
||||||
|
|
|
@ -1,8 +1,8 @@
|
||||||
import {ChangeDetectionStrategy, Component, Input, OnChanges, OnInit, SimpleChanges, Type, ViewChild} from '@angular/core';
|
import {ChangeDetectionStrategy, Component, Input, OnChanges, OnInit, SimpleChanges, Type, ViewChild} from '@angular/core';
|
||||||
import {FastenApiService} from '../../services/fasten-api.service';
|
import {FastenDbService} from '../../services/fasten-db.service';
|
||||||
import {Source} from '../../models/fasten/source';
|
import {Source} from '../../../lib/models/database/source';
|
||||||
import {Observable, of} from 'rxjs';
|
import {Observable, of} from 'rxjs';
|
||||||
import {ResourceFhir} from '../../models/fasten/resource_fhir';
|
import {ResourceFhir} from '../../../lib/models/database/resource_fhir';
|
||||||
import {ListAdverseEventComponent} from '../list-generic-resource/list-adverse-event.component';
|
import {ListAdverseEventComponent} from '../list-generic-resource/list-adverse-event.component';
|
||||||
import {ListCommunicationComponent} from '../list-generic-resource/list-communication.component';
|
import {ListCommunicationComponent} from '../list-generic-resource/list-communication.component';
|
||||||
import {ListConditionComponent} from '../list-generic-resource/list-condition.component';
|
import {ListConditionComponent} from '../list-generic-resource/list-condition.component';
|
||||||
|
@ -49,7 +49,7 @@ export class ResourceListComponent implements OnInit, OnChanges {
|
||||||
@ViewChild(ResourceListOutletDirective, {static: true}) resourceListOutlet!: ResourceListOutletDirective;
|
@ViewChild(ResourceListOutletDirective, {static: true}) resourceListOutlet!: ResourceListOutletDirective;
|
||||||
|
|
||||||
|
|
||||||
constructor(private fastenApi: FastenApiService) { }
|
constructor(private fastenDb: FastenDbService) { }
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
this.loadComponent()
|
this.loadComponent()
|
||||||
|
@ -63,7 +63,7 @@ export class ResourceListComponent implements OnInit, OnChanges {
|
||||||
const viewContainerRef = this.resourceListOutlet.viewContainerRef;
|
const viewContainerRef = this.resourceListOutlet.viewContainerRef;
|
||||||
viewContainerRef.clear();
|
viewContainerRef.clear();
|
||||||
|
|
||||||
this.getResources().subscribe((resourceList) => {
|
this.getResources().then((resourceList) => {
|
||||||
let componentType = this.typeLookup(this.resourceListType)
|
let componentType = this.typeLookup(this.resourceListType)
|
||||||
if(componentType != null){
|
if(componentType != null){
|
||||||
console.log("Attempting to create component", this.resourceListType, componentType)
|
console.log("Attempting to create component", this.resourceListType, componentType)
|
||||||
|
@ -75,18 +75,19 @@ export class ResourceListComponent implements OnInit, OnChanges {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
getResources(): Observable<ResourceFhir[]>{
|
getResources(): Promise<ResourceFhir[]>{
|
||||||
|
|
||||||
if(this.resourceListType && !this.resourceListCache[this.resourceListType]){
|
if(this.resourceListType && !this.resourceListCache[this.resourceListType]){
|
||||||
// this resource type list has not been downloaded yet, do so now
|
// this resource type list has not been downloaded yet, do so now
|
||||||
return this.fastenApi.getResources(this.resourceListType, this.source.id)
|
return this.fastenDb.GetResourcesForSource(this.source._id, this.resourceListType)
|
||||||
.pipe(map((resourceList: ResourceFhir[]) => {
|
.then((paginatedResponse) => {
|
||||||
|
let resourceList = paginatedResponse.rows as ResourceFhir[]
|
||||||
//cache this response so we can skip the request next time
|
//cache this response so we can skip the request next time
|
||||||
this.resourceListCache[this.resourceListType] = resourceList
|
this.resourceListCache[this.resourceListType] = resourceList
|
||||||
return resourceList
|
return resourceList
|
||||||
}))
|
})
|
||||||
} else {
|
} else {
|
||||||
return of(this.resourceListCache[this.resourceListType] || [])
|
return Promise.resolve(this.resourceListCache[this.resourceListType] || [])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -32,6 +32,8 @@ import {ListDiagnosticReportComponent} from './list-generic-resource/list-diagno
|
||||||
import {ListGoalComponent} from './list-generic-resource/list-goal.component';
|
import {ListGoalComponent} from './list-generic-resource/list-goal.component';
|
||||||
import { ListFallbackResourceComponent } from './list-fallback-resource/list-fallback-resource.component';
|
import { ListFallbackResourceComponent } from './list-fallback-resource/list-fallback-resource.component';
|
||||||
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
|
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
|
||||||
|
import { ToastComponent } from './toast/toast.component';
|
||||||
|
import { MomentModule } from 'ngx-moment';
|
||||||
|
|
||||||
@NgModule({
|
@NgModule({
|
||||||
imports: [
|
imports: [
|
||||||
|
@ -39,6 +41,7 @@ import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
|
||||||
BrowserModule,
|
BrowserModule,
|
||||||
NgxDatatableModule,
|
NgxDatatableModule,
|
||||||
NgbModule,
|
NgbModule,
|
||||||
|
MomentModule,
|
||||||
],
|
],
|
||||||
declarations: [
|
declarations: [
|
||||||
ComponentsSidebarComponent,
|
ComponentsSidebarComponent,
|
||||||
|
@ -70,6 +73,7 @@ import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
|
||||||
ResourceListComponent,
|
ResourceListComponent,
|
||||||
ResourceListOutletDirective,
|
ResourceListOutletDirective,
|
||||||
ListFallbackResourceComponent,
|
ListFallbackResourceComponent,
|
||||||
|
ToastComponent,
|
||||||
],
|
],
|
||||||
exports: [
|
exports: [
|
||||||
ComponentsSidebarComponent,
|
ComponentsSidebarComponent,
|
||||||
|
@ -99,7 +103,8 @@ import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
|
||||||
ListDiagnosticReportComponent,
|
ListDiagnosticReportComponent,
|
||||||
ListGoalComponent,
|
ListGoalComponent,
|
||||||
ResourceListComponent,
|
ResourceListComponent,
|
||||||
ResourceListOutletDirective
|
ResourceListOutletDirective,
|
||||||
|
ToastComponent,
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,17 @@
|
||||||
|
<div class="toast-container">
|
||||||
|
<ngb-toast
|
||||||
|
*ngFor="let toast of toastService.toasts"
|
||||||
|
[class]="toast.displayClass"
|
||||||
|
[autohide]="toast.autohide"
|
||||||
|
[delay]="toast.delay || 5000"
|
||||||
|
(hidden)="toastService.remove(toast)"
|
||||||
|
>
|
||||||
|
<ng-template ngbToastHeader>
|
||||||
|
<h6 class="tx-inverse tx-14 mg-b-0 mg-r-auto">{{toast.title}}</h6>
|
||||||
|
<small>{{toast.event_date | amTimeAgo}}</small>
|
||||||
|
</ng-template>
|
||||||
|
|
||||||
|
{{ toast.message }}
|
||||||
|
</ngb-toast>
|
||||||
|
</div>
|
||||||
|
|
|
@ -0,0 +1,23 @@
|
||||||
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||||
|
|
||||||
|
import { ToastComponent } from './toast.component';
|
||||||
|
|
||||||
|
describe('ToastComponent', () => {
|
||||||
|
let component: ToastComponent;
|
||||||
|
let fixture: ComponentFixture<ToastComponent>;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
declarations: [ ToastComponent ]
|
||||||
|
})
|
||||||
|
.compileComponents();
|
||||||
|
|
||||||
|
fixture = TestBed.createComponent(ToastComponent);
|
||||||
|
component = fixture.componentInstance;
|
||||||
|
fixture.detectChanges();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should create', () => {
|
||||||
|
expect(component).toBeTruthy();
|
||||||
|
});
|
||||||
|
});
|
|
@ -0,0 +1,15 @@
|
||||||
|
import {Component, OnInit, TemplateRef} from '@angular/core';
|
||||||
|
import {ToastService} from '../../services/toast.service';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-toast',
|
||||||
|
templateUrl: './toast.component.html',
|
||||||
|
styleUrls: ['./toast.component.scss']
|
||||||
|
})
|
||||||
|
export class ToastComponent implements OnInit {
|
||||||
|
|
||||||
|
constructor(public toastService: ToastService) {}
|
||||||
|
|
||||||
|
ngOnInit(): void {
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,7 +0,0 @@
|
||||||
export class ResourceFhir {
|
|
||||||
user_id?: string
|
|
||||||
source_id: string
|
|
||||||
source_resource_type: string
|
|
||||||
source_resource_id: string
|
|
||||||
payload: any
|
|
||||||
}
|
|
|
@ -1,7 +0,0 @@
|
||||||
import { Source } from './source';
|
|
||||||
|
|
||||||
describe('Source', () => {
|
|
||||||
it('should create an instance', () => {
|
|
||||||
expect(new Source()).toBeTruthy();
|
|
||||||
});
|
|
||||||
});
|
|
|
@ -1,26 +0,0 @@
|
||||||
export class Source {
|
|
||||||
id?: string
|
|
||||||
user_id?: number
|
|
||||||
source_type: string
|
|
||||||
patient_id: string
|
|
||||||
|
|
||||||
oauth_authorization_endpoint: string
|
|
||||||
oauth_token_endpoint: string
|
|
||||||
oauth_registration_endpoint: string
|
|
||||||
oauth_introspection_endpoint: string
|
|
||||||
oauth_userinfo_endpoint: string
|
|
||||||
oauth_token_endpoint_auth_methods_supported: string
|
|
||||||
|
|
||||||
api_endpoint_base_url: string
|
|
||||||
client_id: string
|
|
||||||
redirect_uri: string
|
|
||||||
scopes: string //space seperated string
|
|
||||||
access_token: string
|
|
||||||
refresh_token: string
|
|
||||||
id_token: string
|
|
||||||
expires_at: number
|
|
||||||
code_challenge: string
|
|
||||||
code_verifier: string
|
|
||||||
|
|
||||||
confidential: boolean
|
|
||||||
}
|
|
|
@ -0,0 +1,14 @@
|
||||||
|
export enum ToastType {
|
||||||
|
Error = "error",
|
||||||
|
Success = "success",
|
||||||
|
Info = "info"
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ToastNotification {
|
||||||
|
event_date: Date = new Date()
|
||||||
|
title?: string
|
||||||
|
message: string
|
||||||
|
type: ToastType = ToastType.Info
|
||||||
|
displayClass: string = 'demo-static-toast'
|
||||||
|
autohide: boolean = true
|
||||||
|
}
|
|
@ -0,0 +1,9 @@
|
||||||
|
import {Source} from '../../../lib/models/database/source';
|
||||||
|
|
||||||
|
export class SourceSyncMessage {
|
||||||
|
source: Source
|
||||||
|
userIdentifier: string
|
||||||
|
encryptionKey?: string
|
||||||
|
|
||||||
|
response?: any
|
||||||
|
}
|
|
@ -7,18 +7,15 @@
|
||||||
|
|
||||||
<form (ngSubmit)="signinSubmit()" #userForm="ngForm">
|
<form (ngSubmit)="signinSubmit()" #userForm="ngForm">
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>Email</label>
|
<label>Username</label>
|
||||||
<input [(ngModel)]="existingUser.username" name="username" #username="ngModel" required minlength="2" type="text" class="form-control" placeholder="Enter your email">
|
<input [(ngModel)]="existingUser.username" name="username" #username="ngModel" required minlength="2" type="text" class="form-control" placeholder="Enter your username">
|
||||||
|
|
||||||
<div *ngIf="username.invalid && (username.dirty || username.touched)" class="alert alert-danger">
|
<div *ngIf="username.invalid && (username.dirty || username.touched)" class="alert alert-danger">
|
||||||
<div *ngIf="username.errors?.['required']">
|
<div *ngIf="username.errors?.['required']">
|
||||||
Email is required.
|
Username is required.
|
||||||
</div>
|
</div>
|
||||||
<div *ngIf="username.errors?.['minlength']">
|
<div *ngIf="username.errors?.['minlength']">
|
||||||
Email must be at least 4 characters long.
|
Username must be at least 4 characters long.
|
||||||
</div>
|
|
||||||
<div *ngIf="username.errors?.['email']">
|
|
||||||
Email is not a valid email address.
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div><!-- form-group -->
|
</div><!-- form-group -->
|
||||||
|
|
|
@ -1,7 +1,9 @@
|
||||||
import { Component, OnInit } from '@angular/core';
|
import {Component, OnInit} from '@angular/core';
|
||||||
import {User} from '../../models/fasten/user';
|
import {User} from '../../../lib/models/fasten/user';
|
||||||
import {FastenApiService} from '../../services/fasten-api.service';
|
import {FastenDbService} from '../../services/fasten-db.service';
|
||||||
import {Router} from '@angular/router';
|
import {Router} from '@angular/router';
|
||||||
|
import {ToastService} from '../../services/toast.service';
|
||||||
|
import {ToastNotification, ToastType} from '../../models/fasten/toast';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-auth-signin',
|
selector: 'app-auth-signin',
|
||||||
|
@ -13,7 +15,7 @@ export class AuthSigninComponent implements OnInit {
|
||||||
existingUser: User = new User()
|
existingUser: User = new User()
|
||||||
errorMsg: string = ""
|
errorMsg: string = ""
|
||||||
|
|
||||||
constructor(private fastenApi: FastenApiService, private router: Router) { }
|
constructor(private fastenDb: FastenDbService, private router: Router, private toastService: ToastService) { }
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
}
|
}
|
||||||
|
@ -21,11 +23,19 @@ export class AuthSigninComponent implements OnInit {
|
||||||
signinSubmit(){
|
signinSubmit(){
|
||||||
this.submitted = true;
|
this.submitted = true;
|
||||||
|
|
||||||
this.fastenApi.signin(this.existingUser.username, this.existingUser.password).subscribe((tokenResp: any) => {
|
this.fastenDb.Signin(this.existingUser.username, this.existingUser.password)
|
||||||
console.log(tokenResp);
|
.then(() => this.router.navigateByUrl('/dashboard'))
|
||||||
this.router.navigateByUrl('/dashboard');
|
.catch((err)=>{
|
||||||
}, (err)=>{
|
if(err?.name){
|
||||||
this.errorMsg = err?.error?.error || "an unknown error occurred during sign-in"
|
this.errorMsg = "username or password is incorrect"
|
||||||
})
|
} else{
|
||||||
|
this.errorMsg = "an unknown error occurred during sign-in"
|
||||||
|
}
|
||||||
|
const toastNotificaiton = new ToastNotification()
|
||||||
|
toastNotificaiton.type = ToastType.Error
|
||||||
|
toastNotificaiton.message = this.errorMsg
|
||||||
|
this.toastService.show(toastNotificaiton)
|
||||||
|
})
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -19,33 +19,17 @@
|
||||||
<h4>Create an account, and get started.</h4>
|
<h4>Create an account, and get started.</h4>
|
||||||
|
|
||||||
<form (ngSubmit)="signupSubmit()" #userForm="ngForm">
|
<form (ngSubmit)="signupSubmit()" #userForm="ngForm">
|
||||||
<div class="form-group">
|
|
||||||
<label>Firstname & Lastname</label>
|
|
||||||
<input [(ngModel)]="newUser.name" name="name" #name="ngModel" required minlength="2" type="text" class="form-control" placeholder="Enter your firstname and lastname">
|
|
||||||
|
|
||||||
<div *ngIf="name.invalid && (name.dirty || name.touched)" class="alert alert-danger">
|
|
||||||
<div *ngIf="name.errors?.['required']">
|
|
||||||
Name is required.
|
|
||||||
</div>
|
|
||||||
<div *ngIf="name.errors?.['minlength']">
|
|
||||||
Name must be at least 4 characters long.
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
</div><!-- form-group -->
|
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>Email</label>
|
<label>Username</label>
|
||||||
<input [(ngModel)]="newUser.username" name="username" #username="ngModel" required email="true" minlength="5" type="text" class="form-control" placeholder="Enter your email">
|
<input [(ngModel)]="newUser.username" name="username" #username="ngModel" required minlength="5" type="text" class="form-control" placeholder="Enter your username">
|
||||||
|
|
||||||
<div *ngIf="username.invalid && (username.dirty || username.touched)" class="alert alert-danger">
|
<div *ngIf="username.invalid && (username.dirty || username.touched)" class="alert alert-danger">
|
||||||
<div *ngIf="username.errors?.['required']">
|
<div *ngIf="username.errors?.['required']">
|
||||||
Email is required.
|
Username is required.
|
||||||
</div>
|
</div>
|
||||||
<div *ngIf="username.errors?.['minlength']">
|
<div *ngIf="username.errors?.['minlength']">
|
||||||
Email must be at least 4 characters long.
|
Username must be at least 4 characters long.
|
||||||
</div>
|
|
||||||
<div *ngIf="username.errors?.['email']">
|
|
||||||
Email is not a valid email address.
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
|
@ -1,7 +1,9 @@
|
||||||
import { Component, OnInit } from '@angular/core';
|
import { Component, OnInit } from '@angular/core';
|
||||||
import {FastenApiService} from '../../services/fasten-api.service';
|
import {FastenDbService} from '../../services/fasten-db.service';
|
||||||
import {User} from '../../models/fasten/user';
|
import {User} from '../../../lib/models/fasten/user';
|
||||||
import {Router} from '@angular/router';
|
import {Router} from '@angular/router';
|
||||||
|
import {ToastNotification, ToastType} from '../../models/fasten/toast';
|
||||||
|
import {ToastService} from '../../services/toast.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-auth-signup',
|
selector: 'app-auth-signup',
|
||||||
|
@ -13,7 +15,12 @@ export class AuthSignupComponent implements OnInit {
|
||||||
newUser: User = new User()
|
newUser: User = new User()
|
||||||
errorMsg: string = ""
|
errorMsg: string = ""
|
||||||
|
|
||||||
constructor(private fastenApi: FastenApiService, private router: Router) { }
|
constructor(
|
||||||
|
// private fastenApi: FastenApiService,
|
||||||
|
private fastenDb: FastenDbService,
|
||||||
|
private router: Router,
|
||||||
|
private toastService: ToastService
|
||||||
|
) { }
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
}
|
}
|
||||||
|
@ -21,13 +28,26 @@ export class AuthSignupComponent implements OnInit {
|
||||||
signupSubmit(){
|
signupSubmit(){
|
||||||
this.submitted = true;
|
this.submitted = true;
|
||||||
|
|
||||||
this.fastenApi.signup(this.newUser).subscribe((tokenResp: any) => {
|
this.fastenDb.Signup(this.newUser).then((tokenResp: any) => {
|
||||||
console.log(tokenResp);
|
console.log(tokenResp);
|
||||||
|
|
||||||
this.router.navigateByUrl('/dashboard');
|
this.router.navigateByUrl('/dashboard');
|
||||||
},
|
},
|
||||||
(err)=>{
|
(err)=>{
|
||||||
this.errorMsg = err?.error?.error || "an unknown error occurred during sign-up"
|
console.error("an error occured while signup",err)
|
||||||
|
if(err.name === 'conflict') {
|
||||||
|
// "batman" already exists, choose another username
|
||||||
|
this.errorMsg = "username already exists"
|
||||||
|
} else if (err.name === 'forbidden') {
|
||||||
|
// invalid username
|
||||||
|
this.errorMsg = "invalid username"
|
||||||
|
} else {
|
||||||
|
this.errorMsg = "an unknown error occurred during sign-up"
|
||||||
|
}
|
||||||
|
|
||||||
|
const toastNotificaiton = new ToastNotification()
|
||||||
|
toastNotificaiton.type = ToastType.Error
|
||||||
|
toastNotificaiton.message = this.errorMsg
|
||||||
|
this.toastService.show(toastNotificaiton)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -148,15 +148,15 @@
|
||||||
<div class="media-body">
|
<div class="media-body">
|
||||||
<h5>{{metadataSource[source.source_type]?.display}}</h5>
|
<h5>{{metadataSource[source.source_type]?.display}}</h5>
|
||||||
<p>
|
<p>
|
||||||
{{getPatientSummary(patientForSource[source.id]?.payload)}}
|
{{getPatientSummary(patientForSource[source._id]?.resource_raw)}}
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td class="align-middle"><p><small class="tx-gray-600">status:</small><br/> {{isActive(source)}}</p></td>
|
<td class="align-middle"><p><small class="tx-gray-600">status:</small><br/> {{isActive(source)}}</p></td>
|
||||||
<td class="align-middle"><p><small class="tx-gray-600">last updated:</small><br/> {{source.updated_at | date}}</p></td>
|
<td class="align-middle"><p><small class="tx-gray-600">last updated:</small><br/> <span [ngbTooltip]="source.updated_at | date">{{source.updated_at | amTimeAgo}}</span></p></td>
|
||||||
<td class="align-middle"><p><small class="tx-gray-600">expires:</small><br/> {{source.expires_at}}</p></td>
|
<td class="align-middle"><p><small class="tx-gray-600">expires:</small><br/> <span [ngbTooltip]="source.expires_at | amFromUnix | date">{{source.expires_at | amFromUnix | amTimeAgo}}</span></p></td>
|
||||||
<td class="align-middle"><p><i class="fas fa-chevron-right"></i></td>
|
<td class="align-middle"><p><i class="fas fa-chevron-right"></i></td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|
||||||
|
|
|
@ -1,12 +1,13 @@
|
||||||
import { Component, OnInit } from '@angular/core';
|
import { Component, OnInit } from '@angular/core';
|
||||||
import {FastenApiService} from '../../services/fasten-api.service';
|
import {FastenApiService} from '../../services/fasten-api.service';
|
||||||
import {Source} from '../../models/fasten/source';
|
import {Source} from '../../../lib/models/database/source';
|
||||||
import {Router} from '@angular/router';
|
import {Router} from '@angular/router';
|
||||||
import {Summary} from '../../models/fasten/summary';
|
import {ResourceFhir} from '../../../lib/models/database/resource_fhir';
|
||||||
import {ResourceTypeCounts} from '../../models/fasten/source-summary';
|
|
||||||
import {ResourceFhir} from '../../models/fasten/resource_fhir';
|
|
||||||
import {forkJoin} from 'rxjs';
|
import {forkJoin} from 'rxjs';
|
||||||
import {MetadataSource} from '../../models/fasten/metadata-source';
|
import {MetadataSource} from '../../models/fasten/metadata-source';
|
||||||
|
import {FastenDbService} from '../../services/fasten-db.service';
|
||||||
|
import {Summary} from '../../../lib/models/fasten/summary';
|
||||||
|
import {Base64} from '../../../lib/utils/base64';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-dashboard',
|
selector: 'app-dashboard',
|
||||||
|
@ -22,7 +23,11 @@ export class DashboardComponent implements OnInit {
|
||||||
|
|
||||||
metadataSource: { [name: string]: MetadataSource }
|
metadataSource: { [name: string]: MetadataSource }
|
||||||
|
|
||||||
constructor(private fastenApi: FastenApiService, private router: Router) { }
|
constructor(
|
||||||
|
private fastenApi: FastenApiService,
|
||||||
|
private fastenDb: FastenDbService,
|
||||||
|
private router: Router
|
||||||
|
) { }
|
||||||
|
|
||||||
ngOnInit() {
|
ngOnInit() {
|
||||||
|
|
||||||
|
@ -44,12 +49,12 @@ export class DashboardComponent implements OnInit {
|
||||||
// })
|
// })
|
||||||
// })
|
// })
|
||||||
|
|
||||||
forkJoin([this.fastenApi.getSummary(), this.fastenApi.getMetadataSources()]).subscribe(results => {
|
forkJoin([this.fastenDb.GetSummary(), this.fastenApi.GetMetadataSources()]).subscribe(results => {
|
||||||
let summary = results[0] as Summary
|
let summary = results[0] as Summary
|
||||||
let metadataSource = results[1] as { [name: string]: MetadataSource }
|
let metadataSource = results[1] as { [name: string]: MetadataSource }
|
||||||
|
|
||||||
//process
|
//process
|
||||||
console.log(summary);
|
console.log("SUMMARY RESPONSE",summary);
|
||||||
this.sources = summary.sources
|
this.sources = summary.sources
|
||||||
this.metadataSource = metadataSource
|
this.metadataSource = metadataSource
|
||||||
this.metadataSource["manual"] = {
|
this.metadataSource["manual"] = {
|
||||||
|
@ -59,7 +64,6 @@ export class DashboardComponent implements OnInit {
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
//calculate the number of records
|
//calculate the number of records
|
||||||
summary.resource_type_counts.forEach((resourceTypeInfo) => {
|
summary.resource_type_counts.forEach((resourceTypeInfo) => {
|
||||||
this.recordsCount += resourceTypeInfo.count
|
this.recordsCount += resourceTypeInfo.count
|
||||||
|
@ -71,16 +75,13 @@ export class DashboardComponent implements OnInit {
|
||||||
summary.patients.forEach((resourceFhir) => {
|
summary.patients.forEach((resourceFhir) => {
|
||||||
this.patientForSource[resourceFhir.source_id] = resourceFhir
|
this.patientForSource[resourceFhir.source_id] = resourceFhir
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
selectSource(selectedSource: Source){
|
selectSource(selectedSource: Source){
|
||||||
this.router.navigateByUrl(`/source/${selectedSource.id}`, {
|
this.router.navigateByUrl(`/source/${Base64.Encode(selectedSource._id)}`, {
|
||||||
state: selectedSource
|
state: selectedSource
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
|
@ -23,9 +23,9 @@
|
||||||
<div *ngFor="let sourceInfo of connectedSourceList" class="col-sm-3 mg-b-20 px-3">
|
<div *ngFor="let sourceInfo of connectedSourceList" class="col-sm-3 mg-b-20 px-3">
|
||||||
<div class="card h-100 d-flex align-items-center justify-content-center p-3 rounded-0 cursor-pointer">
|
<div class="card h-100 d-flex align-items-center justify-content-center p-3 rounded-0 cursor-pointer">
|
||||||
<div (click)="openModal(contentModalRef, sourceInfo)" class="card-body">
|
<div (click)="openModal(contentModalRef, sourceInfo)" class="card-body">
|
||||||
<img [src]="'assets/sources/'+sourceInfo.metadata['source_type']+'.png'" alt="client" class="img-fluid">
|
<img [src]="'assets/sources/'+sourceInfo?.metadata['source_type']+'.png'" alt="client" class="img-fluid">
|
||||||
<div *ngIf="status[sourceInfo.source['source_type']]" class="progress">
|
<div *ngIf="status[sourceInfo.source?.source_type]" class="progress">
|
||||||
<div [style.width]="status[sourceInfo.source['source_type']] == 'authorize' ? '33%' : '66%'" class="bg-indigo progress-bar progress-bar-striped progress-bar-animated" role="progressbar"></div>
|
<div [style.width]="status[sourceInfo?.source?.source_type] == 'authorize' ? '33%' : '66%'" class="bg-indigo progress-bar progress-bar-striped progress-bar-animated" role="progressbar"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
@ -39,7 +39,7 @@
|
||||||
|
|
||||||
<div class="row row-sm">
|
<div class="row row-sm">
|
||||||
<div class="col-lg">
|
<div class="col-lg">
|
||||||
<ngx-dropzone [multiple]="false" (change)="uploadSourceBundle($event)" accept=".json">
|
<ngx-dropzone [multiple]="false" (change)="uploadSourceBundleHandler($event)" accept=".json">
|
||||||
<ngx-dropzone-label>Select your EMR/EHR bundle. Must be in JSON format</ngx-dropzone-label>
|
<ngx-dropzone-label>Select your EMR/EHR bundle. Must be in JSON format</ngx-dropzone-label>
|
||||||
<ngx-dropzone-preview *ngFor="let f of uploadedFile" [removable]="false">
|
<ngx-dropzone-preview *ngFor="let f of uploadedFile" [removable]="false">
|
||||||
<ngx-dropzone-label>{{ f.name }} ({{ f.type }})</ngx-dropzone-label>
|
<ngx-dropzone-label>{{ f.name }} ({{ f.type }})</ngx-dropzone-label>
|
||||||
|
@ -57,13 +57,13 @@
|
||||||
<div class="row row-sm">
|
<div class="row row-sm">
|
||||||
|
|
||||||
|
|
||||||
<div *ngFor="let sourceData of availableSourceList" (click)="connect($event, sourceData['source_type'])" class="col-sm-3 mg-b-20 px-3">
|
<div *ngFor="let sourceData of availableSourceList" (click)="connectHandler($event, sourceData.metadata.source_type)" class="col-sm-3 mg-b-20 px-3">
|
||||||
<div class="card h-100 d-flex align-items-center justify-content-center p-3 rounded-0 cursor-pointer" [ngClass]="{'card-disable': !sourceData.enabled}">
|
<div class="card h-100 d-flex align-items-center justify-content-center p-3 rounded-0 cursor-pointer" [ngClass]="{'card-disable': !sourceData.metadata.enabled}">
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<img [src]="'assets/sources/'+sourceData['source_type']+'.png'" [alt]="metadataSources[sourceData['source_type']].display" class="img-fluid">
|
<img [src]="'assets/sources/'+sourceData.metadata.source_type+'.png'" [alt]="metadataSources[sourceData.metadata.source_type].display" class="img-fluid">
|
||||||
|
|
||||||
<div *ngIf="status[sourceData['source_type']]" class="progress">
|
<div *ngIf="status[sourceData.metadata.source_type]" class="progress">
|
||||||
<div [style.width]="status[sourceData['source_type']] == 'authorize' ? '33%' : '66%'" class="bg-indigo progress-bar progress-bar-striped progress-bar-animated" role="progressbar"></div>
|
<div [style.width]="status[sourceData.metadata.source_type] == 'authorize' ? '33%' : '66%'" class="bg-indigo progress-bar progress-bar-striped progress-bar-animated" role="progressbar"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
@ -79,7 +79,7 @@
|
||||||
|
|
||||||
<ng-template #contentModalRef let-modal>
|
<ng-template #contentModalRef let-modal>
|
||||||
<div class="modal-header">
|
<div class="modal-header">
|
||||||
<h4 class="modal-title" id="modal-basic-title">{{modalSourceInfo.metadata["display"]}}</h4>
|
<h4 class="modal-title" id="modal-basic-title">{{modalSelectedSourceListItem?.metadata["display"]}}</h4>
|
||||||
<button type="button" class="btn btn-close" aria-label="Close" (click)="modal.dismiss('Cross click')">
|
<button type="button" class="btn btn-close" aria-label="Close" (click)="modal.dismiss('Cross click')">
|
||||||
<span aria-hidden="true">×</span>
|
<span aria-hidden="true">×</span>
|
||||||
</button>
|
</button>
|
||||||
|
@ -96,8 +96,8 @@
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="modal-footer">
|
<div class="modal-footer">
|
||||||
<button (click)="syncSource(modalSourceInfo.source)" type="button" class="btn btn-indigo">Sync</button>
|
<button (click)="sourceSyncHandler(modalSelectedSourceListItem.source)" type="button" class="btn btn-indigo">Sync</button>
|
||||||
<button (click)="connect($event, modalSourceInfo.source['source_type'])" type="button" class="btn btn-outline-light">Reconnect</button>
|
<button (click)="connectHandler($event, modalSelectedSourceListItem.source['source_type'])" type="button" class="btn btn-outline-light">Reconnect</button>
|
||||||
<button type="button" class="btn btn-outline-danger">Delete</button>
|
<button type="button" class="btn btn-outline-danger">Delete</button>
|
||||||
<button (click)="modal.dismiss('Close click')" type="button" class="btn btn-outline-light">Close</button>
|
<button (click)="modal.dismiss('Close click')" type="button" class="btn btn-outline-light">Close</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
@ -1,23 +1,31 @@
|
||||||
import {Component, HostListener, OnInit} from '@angular/core';
|
import {Component, OnInit} from '@angular/core';
|
||||||
import {LighthouseService} from '../../services/lighthouse.service';
|
import {LighthouseService} from '../../services/lighthouse.service';
|
||||||
import {FastenApiService} from '../../services/fasten-api.service';
|
import {FastenApiService} from '../../services/fasten-api.service';
|
||||||
import {LighthouseSourceMetadata} from '../../models/lighthouse/lighthouse-source-metadata';
|
import {FastenDbService} from '../../services/fasten-db.service';
|
||||||
import * as Oauth from '@panva/oauth4webapi';
|
import {LighthouseSourceMetadata} from '../../../lib/models/lighthouse/lighthouse-source-metadata';
|
||||||
import {AuthorizeClaim} from '../../models/lighthouse/authorize-claim';
|
import {Source} from '../../../lib/models/database/source';
|
||||||
import {Source} from '../../models/fasten/source';
|
|
||||||
import {getAccessTokenExpiration, jwtDecode} from 'fhirclient/lib/lib';
|
import {getAccessTokenExpiration, jwtDecode} from 'fhirclient/lib/lib';
|
||||||
import BrowserAdapter from 'fhirclient/lib/adapters/BrowserAdapter';
|
import BrowserAdapter from 'fhirclient/lib/adapters/BrowserAdapter';
|
||||||
import {Observable, of, throwError, fromEvent } from 'rxjs';
|
|
||||||
import {concatMap, delay, retryWhen, timeout, first, map, filter, catchError} from 'rxjs/operators';
|
|
||||||
import * as FHIR from "fhirclient"
|
|
||||||
import {MetadataSource} from '../../models/fasten/metadata-source';
|
import {MetadataSource} from '../../models/fasten/metadata-source';
|
||||||
import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';
|
import {ModalDismissReasons, NgbModal} from '@ng-bootstrap/ng-bootstrap';
|
||||||
import {ActivatedRoute, Router} from '@angular/router';
|
import {ActivatedRoute, Router} from '@angular/router';
|
||||||
import {Location} from '@angular/common';
|
import {Location} from '@angular/common';
|
||||||
|
import {SourceType} from '../../../lib/models/database/source_types';
|
||||||
|
import {QueueService} from '../../workers/queue.service';
|
||||||
|
import {ToastService} from '../../services/toast.service';
|
||||||
|
import {ToastNotification, ToastType} from '../../models/fasten/toast';
|
||||||
|
import {SourceSyncMessage} from '../../models/queue/source-sync-message';
|
||||||
|
import {UpsertSummary} from '../../../lib/models/fasten/upsert-summary';
|
||||||
// If you dont import this angular will import the wrong "Location"
|
// If you dont import this angular will import the wrong "Location"
|
||||||
|
|
||||||
export const sourceConnectWindowTimeout = 24*5000 //wait 2 minutes (5 * 24 = 120)
|
export const sourceConnectWindowTimeout = 24*5000 //wait 2 minutes (5 * 24 = 120)
|
||||||
|
|
||||||
|
export class SourceListItem {
|
||||||
|
source?: Source
|
||||||
|
metadata: MetadataSource
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-medical-sources',
|
selector: 'app-medical-sources',
|
||||||
templateUrl: './medical-sources.component.html',
|
templateUrl: './medical-sources.component.html',
|
||||||
|
@ -28,25 +36,28 @@ export class MedicalSourcesComponent implements OnInit {
|
||||||
constructor(
|
constructor(
|
||||||
private lighthouseApi: LighthouseService,
|
private lighthouseApi: LighthouseService,
|
||||||
private fastenApi: FastenApiService,
|
private fastenApi: FastenApiService,
|
||||||
|
private fastenDb: FastenDbService,
|
||||||
private modalService: NgbModal,
|
private modalService: NgbModal,
|
||||||
private route: ActivatedRoute,
|
private route: ActivatedRoute,
|
||||||
private router: Router,
|
private router: Router,
|
||||||
private location: Location,
|
private location: Location,
|
||||||
|
private queueService: QueueService,
|
||||||
|
private toastService: ToastService
|
||||||
) { }
|
) { }
|
||||||
status: { [name: string]: string } = {}
|
status: { [name: string]: string } = {}
|
||||||
|
|
||||||
metadataSources: {[name:string]: MetadataSource} = {}
|
metadataSources: {[name:string]: MetadataSource} = {}
|
||||||
|
|
||||||
connectedSourceList:any[] = []
|
connectedSourceList: SourceListItem[] = [] //source's are populated for this list
|
||||||
availableSourceList:MetadataSource[] = []
|
availableSourceList: SourceListItem[] = []
|
||||||
|
|
||||||
uploadedFile: File[] = []
|
uploadedFile: File[] = []
|
||||||
|
|
||||||
closeResult = '';
|
closeResult = '';
|
||||||
modalSourceInfo:any = null;
|
modalSelectedSourceListItem:SourceListItem = null;
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
this.fastenApi.getMetadataSources().subscribe((metadataSources: {[name:string]: MetadataSource}) => {
|
this.fastenApi.GetMetadataSources().subscribe((metadataSources: {[name:string]: MetadataSource}) => {
|
||||||
this.metadataSources = metadataSources
|
this.metadataSources = metadataSources
|
||||||
|
|
||||||
const callbackSourceType = this.route.snapshot.paramMap.get('source_type')
|
const callbackSourceType = this.route.snapshot.paramMap.get('source_type')
|
||||||
|
@ -54,8 +65,9 @@ export class MedicalSourcesComponent implements OnInit {
|
||||||
this.callback(callbackSourceType).then(console.log)
|
this.callback(callbackSourceType).then(console.log)
|
||||||
}
|
}
|
||||||
|
|
||||||
this.fastenApi.getSources()
|
this.fastenDb.GetSources()
|
||||||
.subscribe((sourceList: Source[]) => {
|
.then((paginatedList) => {
|
||||||
|
const sourceList = paginatedList.rows as Source[]
|
||||||
|
|
||||||
for (const sourceType in this.metadataSources) {
|
for (const sourceType in this.metadataSources) {
|
||||||
let isConnected = false
|
let isConnected = false
|
||||||
|
@ -69,7 +81,7 @@ export class MedicalSourcesComponent implements OnInit {
|
||||||
|
|
||||||
if(!isConnected){
|
if(!isConnected){
|
||||||
//this source has not been found in the connected list, lets add it to the available list.
|
//this source has not been found in the connected list, lets add it to the available list.
|
||||||
this.availableSourceList.push(this.metadataSources[sourceType])
|
this.availableSourceList.push({metadata: this.metadataSources[sourceType]})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -79,12 +91,17 @@ export class MedicalSourcesComponent implements OnInit {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
connect($event: MouseEvent, sourceType: string) {
|
/**
|
||||||
|
* after pressing the logo (connectHandler button), this function will generate an authorize url for this source, and redirec the user.
|
||||||
|
* @param $event
|
||||||
|
* @param sourceType
|
||||||
|
*/
|
||||||
|
public connectHandler($event: MouseEvent, sourceType: string):void {
|
||||||
($event.currentTarget as HTMLButtonElement).disabled = true;
|
($event.currentTarget as HTMLButtonElement).disabled = true;
|
||||||
this.status[sourceType] = "authorize"
|
this.status[sourceType] = "authorize"
|
||||||
|
|
||||||
this.lighthouseApi.getLighthouseSource(sourceType)
|
this.lighthouseApi.getLighthouseSource(sourceType)
|
||||||
.subscribe(async (sourceMetadata: LighthouseSourceMetadata) => {
|
.then(async (sourceMetadata: LighthouseSourceMetadata) => {
|
||||||
console.log(sourceMetadata);
|
console.log(sourceMetadata);
|
||||||
let authorizationUrl = await this.lighthouseApi.generateSourceAuthorizeUrl(sourceType, sourceMetadata)
|
let authorizationUrl = await this.lighthouseApi.generateSourceAuthorizeUrl(sourceType, sourceMetadata)
|
||||||
|
|
||||||
|
@ -95,11 +112,15 @@ export class MedicalSourcesComponent implements OnInit {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async callback(sourceType: string) {
|
/**
|
||||||
|
* if the user is redirected to this page from the lighthouse, we'll need to process the "code" to retrieve the access token & refresh token.
|
||||||
|
* @param sourceType
|
||||||
|
*/
|
||||||
|
public async callback(sourceType: string) {
|
||||||
|
|
||||||
//get the source metadata again
|
//get the source metadata again
|
||||||
await this.lighthouseApi.getLighthouseSource(sourceType)
|
await this.lighthouseApi.getLighthouseSource(sourceType)
|
||||||
.subscribe(async (sourceMetadata: LighthouseSourceMetadata) => {
|
.then(async (sourceMetadata: LighthouseSourceMetadata) => {
|
||||||
|
|
||||||
//get required parameters from the URI and local storage
|
//get required parameters from the URI and local storage
|
||||||
const callbackUrlParts = new URL(window.location.href)
|
const callbackUrlParts = new URL(window.location.href)
|
||||||
|
@ -145,90 +166,123 @@ export class MedicalSourcesComponent implements OnInit {
|
||||||
|
|
||||||
//Create FHIR Client
|
//Create FHIR Client
|
||||||
|
|
||||||
const sourceCredential: Source = {
|
const dbSourceCredential = new Source({
|
||||||
source_type: sourceType,
|
source_type: sourceType as SourceType,
|
||||||
oauth_authorization_endpoint: sourceMetadata.authorization_endpoint,
|
|
||||||
oauth_token_endpoint: sourceMetadata.token_endpoint,
|
authorization_endpoint: sourceMetadata.authorization_endpoint,
|
||||||
oauth_registration_endpoint: "",
|
token_endpoint: sourceMetadata.token_endpoint,
|
||||||
oauth_introspection_endpoint: sourceMetadata.introspection_endpoint,
|
introspection_endpoint: sourceMetadata.introspection_endpoint,
|
||||||
oauth_userinfo_endpoint: sourceMetadata.userinfo_endpoint,
|
userinfo_endpoint: sourceMetadata.userinfo_endpoint,
|
||||||
oauth_token_endpoint_auth_methods_supported: "",
|
|
||||||
api_endpoint_base_url: sourceMetadata.api_endpoint_base_url,
|
api_endpoint_base_url: sourceMetadata.api_endpoint_base_url,
|
||||||
client_id: sourceMetadata.client_id,
|
client_id: sourceMetadata.client_id,
|
||||||
redirect_uri: sourceMetadata.redirect_uri,
|
redirect_uri: sourceMetadata.redirect_uri,
|
||||||
scopes: sourceMetadata.scopes_supported ? sourceMetadata.scopes_supported.join(' ') : undefined,
|
scopes_supported: sourceMetadata.scopes_supported,
|
||||||
patient_id: payload.patient,
|
issuer: sourceMetadata.issuer,
|
||||||
|
grant_types_supported: sourceMetadata.grant_types_supported,
|
||||||
|
response_types_supported: sourceMetadata.response_types_supported,
|
||||||
|
aud: sourceMetadata.aud,
|
||||||
|
code_challenge_methods_supported: sourceMetadata.code_challenge_methods_supported,
|
||||||
|
confidential: sourceMetadata.confidential,
|
||||||
|
cors_relay_required: sourceMetadata.cors_relay_required,
|
||||||
|
|
||||||
|
patient: payload.patient,
|
||||||
access_token: payload.access_token,
|
access_token: payload.access_token,
|
||||||
refresh_token: payload.refresh_token,
|
refresh_token: payload.refresh_token,
|
||||||
id_token: payload.id_token,
|
id_token: payload.id_token,
|
||||||
code_challenge: "",
|
|
||||||
code_verifier: "",
|
|
||||||
|
|
||||||
// @ts-ignore - in some cases the getAccessTokenExpiration is a string, which cases failures to store Source in db.
|
// @ts-ignore - in some cases the getAccessTokenExpiration is a string, which cases failures to store Source in db.
|
||||||
expires_at: parseInt(getAccessTokenExpiration(payload, new BrowserAdapter())),
|
expires_at: parseInt(getAccessTokenExpiration(payload, new BrowserAdapter())),
|
||||||
confidential: sourceMetadata.confidential
|
})
|
||||||
}
|
|
||||||
|
|
||||||
await this.fastenApi.createSource(sourceCredential).subscribe(
|
await this.fastenDb.UpsertSource(dbSourceCredential).then(console.log)
|
||||||
(respData) => {
|
this.queueSourceSyncWorker(sourceType as SourceType, dbSourceCredential)
|
||||||
delete this.status[sourceType]
|
|
||||||
// window.location.reload();
|
|
||||||
|
|
||||||
console.log("source credential create response:", respData)
|
|
||||||
//remove item from available sources list, add to connected sources.
|
|
||||||
this.availableSourceList.splice(this.availableSourceList.indexOf(this.metadataSources[sourceType]), 1);
|
|
||||||
this.connectedSourceList.push({source: respData, metadata: this.metadataSources[sourceType]})
|
|
||||||
|
|
||||||
},
|
|
||||||
(err) => {
|
|
||||||
delete this.status[sourceType]
|
|
||||||
// window.location.reload();
|
|
||||||
|
|
||||||
console.log(err)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
uploadSourceBundle(event) {
|
/**
|
||||||
|
* this function is used to process manually "uploaded" FHIR bundle files, adding them to the database.
|
||||||
|
* @param event
|
||||||
|
*/
|
||||||
|
public uploadSourceBundleHandler(event) {
|
||||||
this.uploadedFile = [event.addedFiles[0]]
|
this.uploadedFile = [event.addedFiles[0]]
|
||||||
this.fastenApi.createManualSource(event.addedFiles[0]).subscribe(
|
//TODO: handle manual bundles.
|
||||||
(respData) => {
|
// this.fastenDb.CreateManualSource(event.addedFiles[0]).subscribe(
|
||||||
console.log("source manual source create response:", respData)
|
// (respData) => {
|
||||||
},
|
// console.log("source manual source create response:", respData)
|
||||||
(err) => {console.log(err)},
|
// },
|
||||||
() => {
|
// (err) => {console.log(err)},
|
||||||
this.uploadedFile = []
|
// () => {
|
||||||
}
|
// this.uploadedFile = []
|
||||||
)
|
// }
|
||||||
|
// )
|
||||||
}
|
}
|
||||||
|
|
||||||
openModal(contentModalRef, sourceInfo: any) {
|
public openModal(contentModalRef, sourceListItem: SourceListItem) {
|
||||||
this.modalSourceInfo = sourceInfo
|
this.modalSelectedSourceListItem = sourceListItem
|
||||||
let modalSourceInfo = this.modalSourceInfo
|
|
||||||
this.modalService.open(contentModalRef, {ariaLabelledBy: 'modal-basic-title'}).result.then((result) => {
|
this.modalService.open(contentModalRef, {ariaLabelledBy: 'modal-basic-title'}).result.then((result) => {
|
||||||
modalSourceInfo = null
|
this.modalSelectedSourceListItem = null
|
||||||
this.closeResult = `Closed with: ${result}`;
|
this.closeResult = `Closed with: ${result}`;
|
||||||
}, (reason) => {
|
}, (reason) => {
|
||||||
modalSourceInfo = null
|
this.modalSelectedSourceListItem = null
|
||||||
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
|
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
syncSource(source: Source){
|
public sourceSyncHandler(source: Source){
|
||||||
this.status[source.source_type] = "authorize"
|
this.status[source.source_type] = "authorize"
|
||||||
this.modalService.dismissAll()
|
this.modalService.dismissAll()
|
||||||
this.fastenApi.syncSource(source.id).subscribe(
|
|
||||||
(respData) => {
|
this.queueSourceSyncWorker(source.source_type as SourceType, source)
|
||||||
delete this.status[source.source_type]
|
}
|
||||||
console.log("source sync response:", respData)
|
|
||||||
},
|
|
||||||
(err) => {
|
///////////////////////////////////////////////////////////////////////////////////////
|
||||||
delete this.status[source.source_type]
|
// Private
|
||||||
console.log(err)
|
///////////////////////////////////////////////////////////////////////////////////////
|
||||||
}
|
private queueSourceSyncWorker(sourceType: SourceType, source: Source){
|
||||||
)
|
//this work is pushed to the Sync Worker.
|
||||||
|
//TODO: if the user closes the browser the data update may not complete. we should set a status flag when "starting" sync, and then remove it when compelte
|
||||||
|
// so that we can show incompelte statuses
|
||||||
|
this.queueService.runSourceSyncWorker(source)
|
||||||
|
.subscribe((msg) => {
|
||||||
|
const sourceSyncMessage = JSON.parse(msg) as SourceSyncMessage
|
||||||
|
delete this.status[sourceType]
|
||||||
|
// window.location.reload();
|
||||||
|
|
||||||
|
console.log("source sync-all response:", sourceSyncMessage)
|
||||||
|
//remove item from available sources list, add to connected sources.
|
||||||
|
this.availableSourceList.splice(this.availableSourceList.findIndex((item) => item.metadata.source_type == sourceType), 1);
|
||||||
|
if(this.connectedSourceList.findIndex((item) => item.metadata.source_type == sourceType) == -1){
|
||||||
|
//only add this as a connected source if its "new"
|
||||||
|
this.connectedSourceList.push({source: sourceSyncMessage.source, metadata: this.metadataSources[sourceType]})
|
||||||
|
}
|
||||||
|
|
||||||
|
const toastNotification = new ToastNotification()
|
||||||
|
toastNotification.type = ToastType.Success
|
||||||
|
toastNotification.message = `Successfully connected ${sourceType}`
|
||||||
|
|
||||||
|
const upsertSummary = sourceSyncMessage.response as UpsertSummary
|
||||||
|
if(upsertSummary && upsertSummary.totalResources != upsertSummary.updatedResources.length){
|
||||||
|
toastNotification.message += `\n (total: ${upsertSummary.totalResources}, updated: ${upsertSummary.updatedResources.length})`
|
||||||
|
} else if(upsertSummary){
|
||||||
|
toastNotification.message += `\n (total: ${upsertSummary.totalResources})`
|
||||||
|
}
|
||||||
|
|
||||||
|
this.toastService.show(toastNotification)
|
||||||
|
},
|
||||||
|
(err) => {
|
||||||
|
delete this.status[sourceType]
|
||||||
|
// window.location.reload();
|
||||||
|
|
||||||
|
const toastNotification = new ToastNotification()
|
||||||
|
toastNotification.type = ToastType.Error
|
||||||
|
toastNotification.message = `An error occurred while accessing ${sourceType}: ${err}`
|
||||||
|
toastNotification.autohide = false
|
||||||
|
this.toastService.show(toastNotification)
|
||||||
|
console.error(err)
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private getDismissReason(reason: any): string {
|
private getDismissReason(reason: any): string {
|
||||||
|
|
|
@ -3,11 +3,11 @@
|
||||||
<div class="az-content-body">
|
<div class="az-content-body">
|
||||||
<div class="az-content-breadcrumb">
|
<div class="az-content-breadcrumb">
|
||||||
<span>Resource</span>
|
<span>Resource</span>
|
||||||
<span>{{resource.source_resource_type}}</span>
|
<span>{{resource?.source_resource_type}}</span>
|
||||||
<span>{{resource.source_resource_id}}</span>
|
<span>{{resource?.source_resource_id}}</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<pre *ngIf="resource"><code [highlight]="resource.payload | json"></code></pre>
|
<pre *ngIf="resource"><code [highlight]="resource.resource_raw | json"></code></pre>
|
||||||
|
|
||||||
</div><!-- az-content-body -->
|
</div><!-- az-content-body -->
|
||||||
</div>
|
</div>
|
||||||
|
|
|
@ -1,8 +1,8 @@
|
||||||
import { Component, OnInit } from '@angular/core';
|
import { Component, OnInit } from '@angular/core';
|
||||||
import {FastenApiService} from '../../services/fasten-api.service';
|
import {FastenDbService} from '../../services/fasten-db.service';
|
||||||
import {ActivatedRoute, Router} from '@angular/router';
|
import {ActivatedRoute, Router} from '@angular/router';
|
||||||
import {Source} from '../../models/fasten/source';
|
import {ResourceFhir} from '../../../lib/models/database/resource_fhir';
|
||||||
import {ResourceFhir} from '../../models/fasten/resource_fhir';
|
import {Base64} from '../../../lib/utils/base64';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-resource-detail',
|
selector: 'app-resource-detail',
|
||||||
|
@ -13,14 +13,15 @@ export class ResourceDetailComponent implements OnInit {
|
||||||
|
|
||||||
resource: ResourceFhir = null
|
resource: ResourceFhir = null
|
||||||
|
|
||||||
constructor(private fastenApi: FastenApiService, private router: Router, private route: ActivatedRoute) {
|
constructor(private fastenDb: FastenDbService, private router: Router, private route: ActivatedRoute) {
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
//always request the resource by id
|
//always request the resource by id
|
||||||
this.fastenApi.getResourceBySourceId(this.route.snapshot.paramMap.get('source_id'), this.route.snapshot.paramMap.get('resource_id')).subscribe((resourceFhir) => {
|
this.fastenDb.GetResource(Base64.Decode(this.route.snapshot.paramMap.get('resource_id')))
|
||||||
this.resource = resourceFhir;
|
.then((resourceFhir) => {
|
||||||
});
|
this.resource = resourceFhir;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue