first commit
This commit is contained in:
15
.env.template
Normal file
15
.env.template
Normal file
@@ -0,0 +1,15 @@
|
||||
# Server
|
||||
PUBLIC_HOST=
|
||||
PORT=
|
||||
|
||||
# Database
|
||||
DB_USER=
|
||||
DB_PASSWORD=
|
||||
DB_HOST=
|
||||
DB_PORT=
|
||||
DB_NAME=
|
||||
|
||||
JWT_SECRET=
|
||||
|
||||
#token rest
|
||||
token=
|
||||
7
.gitignore
vendored
Normal file
7
.gitignore
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
.envrc
|
||||
*.env
|
||||
.vscode
|
||||
bin
|
||||
tmp
|
||||
ecom
|
||||
*.service
|
||||
26
Dockerfile
Normal file
26
Dockerfile
Normal file
@@ -0,0 +1,26 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
# Build the application from source
|
||||
FROM golang:1.22.0 AS build-stage
|
||||
WORKDIR /app
|
||||
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
COPY . .
|
||||
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -o /api ./cmd/main.go
|
||||
|
||||
# Run the tests in the container
|
||||
FROM build-stage AS run-test-stage
|
||||
RUN go test -v ./...
|
||||
|
||||
# Deploy the application binary into a lean image
|
||||
FROM scratch AS build-release-stage
|
||||
WORKDIR /
|
||||
|
||||
COPY --from=build-stage /api /api
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
ENTRYPOINT ["/api"]
|
||||
9
IMPROVEMENTS.md
Normal file
9
IMPROVEMENTS.md
Normal file
@@ -0,0 +1,9 @@
|
||||
## Here is a list of improvements that could be made to the project:
|
||||
|
||||
- Refactor the product quantity/stock to be an [atomic and concurrent safe](https://www.freecodecamp.org/news/acid-databases-explained/#what-does-atomicity-mean). The current implementation might lead to invalid stock values if multiple requests are made at the same time. Not only that, every time a product quantity is updated we need to query the products table *(violates database normalization principle)*.
|
||||
|
||||
- Implement the user addresses feature. This way we can store the user's address and use it in the checkout instead of an hardcoded value.
|
||||
|
||||
- Implement the user's order history. This way we can store the user's orders and show them in the user's profile.
|
||||
|
||||
- Implement the cancel order endpoint. This way we can allow the user to cancel an order if it's not yet shipped.
|
||||
674
LICENSE.md
Normal file
674
LICENSE.md
Normal file
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
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>.
|
||||
17
Makefile
Normal file
17
Makefile
Normal file
@@ -0,0 +1,17 @@
|
||||
build:
|
||||
@go build -o bin/westone cmd/main.go
|
||||
|
||||
test:
|
||||
@go test -v ./...
|
||||
|
||||
run: build
|
||||
@./bin/westone
|
||||
|
||||
migration:
|
||||
@migrate create -ext sql -dir cmd/migrate/migrations $(filter-out $@,$(MAKECMDGOALS))
|
||||
|
||||
migrate-up:
|
||||
@go run cmd/migrate/main.go up
|
||||
|
||||
migrate-down:
|
||||
@go run cmd/migrate/main.go down
|
||||
76
README.md
Normal file
76
README.md
Normal file
@@ -0,0 +1,76 @@
|
||||
## Setup the project
|
||||
|
||||
1. Mulai edit ```.env``` (silakan copy dari ```.env.template```), kemudian edit paramter sesuai environment masing - masing.
|
||||
```bash
|
||||
cp env.template .env
|
||||
```
|
||||
example:
|
||||
```
|
||||
PUBLIC_HOST=http://localhost
|
||||
PORT=8080
|
||||
|
||||
# Database
|
||||
DB_USER=admin
|
||||
DB_PASSWORD=Sasone!102938
|
||||
DB_HOST=127.0.0.1
|
||||
DB_PORT=4407
|
||||
DB_NAME=westone
|
||||
|
||||
JWT_SECRET=--one_api-secret-2019-04-01
|
||||
SESSION_KEY=Azw1Ds31sW1KP94ffaX2ykHg16SzxL0f2jh21Gh
|
||||
GOOGLE_CLIENT_ID=
|
||||
GOOGLE_CLIENT_SECRET=
|
||||
```
|
||||
|
||||
2. update mod dependency:
|
||||
```bash
|
||||
go mod tidy
|
||||
```
|
||||
3. shh ke server dengan PuTTy
|
||||
|
||||
4. Run:
|
||||
```bash
|
||||
go run ./cmd/main.go
|
||||
```
|
||||
|
||||
5. install ekstensi REST Client untuk menjalankan http api, coba run api login westone dari file ```auth.http```
|
||||
6. buat folder ```.vscode``` dan file ```settings.json``` dan buat parameter token dari hasil login.
|
||||
```
|
||||
{
|
||||
"rest-client.environmentVariables": {
|
||||
"$shared": {
|
||||
"token": "Bearer "
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Running the project
|
||||
|
||||
To run the project, you can use the following command:
|
||||
|
||||
```bash
|
||||
go run ./cmd/main.go
|
||||
```
|
||||
|
||||
## WRK test performance
|
||||
|
||||
1. ssh ke devone & masuk ke directory
|
||||
```
|
||||
~/perf-test/devcpone
|
||||
```
|
||||
2. upload script lua
|
||||
3. run wrk
|
||||
|
||||
Format command:
|
||||
wrk -t<number thread> -c<number connection> -d<number time in second>s -s <script name> <host name>
|
||||
example:
|
||||
|
||||
```bash
|
||||
wrk -t5 -c100 -d30s -s westone-search-patient.lua http://devcpone.aplikasi.web.id:9090
|
||||
```
|
||||
|
||||
## Response API & Error Log Name
|
||||
|
||||
- [Link DOC Response Api](https://docs.google.com/document/d/1PCEkEMC7ucuKHFPE1xVyPKhVWaQTgX2iC2z8vw-gJe0/edit#heading=h.hhevn0icya3z)
|
||||
88
cmd/api/api.go
Normal file
88
cmd/api/api.go
Normal file
@@ -0,0 +1,88 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/jmoiron/sqlx"
|
||||
"github.com/rs/cors"
|
||||
httpSwagger "github.com/swaggo/http-swagger/v2"
|
||||
"sismedika.com/sas/westone/services/auth"
|
||||
"sismedika.com/sas/westone/services/doctor"
|
||||
"sismedika.com/sas/westone/services/error_log"
|
||||
"sismedika.com/sas/westone/services/patient"
|
||||
"sismedika.com/sas/westone/services/person"
|
||||
"sismedika.com/sas/westone/services/terminology"
|
||||
"sismedika.com/sas/westone/services/user"
|
||||
)
|
||||
|
||||
type APIServer struct {
|
||||
addr string
|
||||
db *sqlx.DB
|
||||
}
|
||||
|
||||
func NewAPIServer(addr string, db *sqlx.DB) *APIServer {
|
||||
return &APIServer{
|
||||
addr: addr,
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *APIServer) Run() error {
|
||||
router := mux.NewRouter()
|
||||
subrouter := router.PathPrefix("/westone/api/v1").Subrouter()
|
||||
|
||||
subrouter.PathPrefix("/swagger/").Handler(httpSwagger.Handler())
|
||||
|
||||
// Error Log
|
||||
errorLogStore := error_log.NewStore(s.db)
|
||||
|
||||
// terminology
|
||||
terminologyStore := terminology.NewStore(s.db)
|
||||
terminologyHandler := terminology.NewHandler(terminologyStore)
|
||||
terminologyHandler.RegisterRoutes(subrouter)
|
||||
|
||||
// user
|
||||
userStore := user.NewStore(s.db)
|
||||
|
||||
// auth
|
||||
oauthStore := auth.NewStore(s.db)
|
||||
oauthHandler := auth.NewHandler(oauthStore, errorLogStore, userStore)
|
||||
oauthHandler.RegisterRoutes(subrouter)
|
||||
|
||||
// md person
|
||||
personStore := person.NewStore(s.db)
|
||||
personHandler := person.NewHandler(personStore, terminologyStore)
|
||||
personHandler.RegisterRoutes(subrouter)
|
||||
|
||||
// md patient
|
||||
patientStore := patient.NewStore(s.db)
|
||||
patientHandler := patient.NewHandler(patientStore)
|
||||
patientHandler.RegisterRoutes(subrouter)
|
||||
|
||||
// md doctor
|
||||
doctorStore := doctor.NewStore(s.db)
|
||||
doctorHandler := doctor.NewHandler(doctorStore)
|
||||
doctorHandler.RegisterRoutes(subrouter)
|
||||
|
||||
// userHandler := user.NewHandler(userStore, errorLogStore)
|
||||
// userHandler.RegisterRoutes(subrouter)
|
||||
|
||||
// productStore := product.NewStore(s.db)
|
||||
// productHandler := product.NewHandler(productStore, userStore)
|
||||
// productHandler.RegisterRoutes(subrouter)
|
||||
|
||||
// orderStore := order.NewStore(s.db)
|
||||
|
||||
// cartHandler := cart.NewHandler(productStore, orderStore, userStore)
|
||||
// cartHandler.RegisterRoutes(subrouter)
|
||||
|
||||
// Serve static files
|
||||
router.PathPrefix("/").Handler(http.FileServer(http.Dir("static")))
|
||||
|
||||
log.Println("Listening on", s.addr)
|
||||
|
||||
corsHandler := cors.Default().Handler(router)
|
||||
return http.ListenAndServe(s.addr, corsHandler)
|
||||
}
|
||||
54
cmd/main.go
Normal file
54
cmd/main.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/go-sql-driver/mysql"
|
||||
"github.com/jmoiron/sqlx"
|
||||
"sismedika.com/sas/westone/cmd/api"
|
||||
"sismedika.com/sas/westone/configs"
|
||||
"sismedika.com/sas/westone/db"
|
||||
_ "sismedika.com/sas/westone/docs"
|
||||
"sismedika.com/sas/westone/services/auth"
|
||||
)
|
||||
|
||||
// @title WESTONE API
|
||||
// @version 1.0
|
||||
// @description westone api documentation test
|
||||
// @termsOfService http://swagger.io/terms/
|
||||
// @license.name Apache 2.0
|
||||
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
|
||||
func main() {
|
||||
cfg := mysql.Config{
|
||||
User: configs.Envs.DBUser,
|
||||
Passwd: configs.Envs.DBPassword,
|
||||
Addr: configs.Envs.DBAddress,
|
||||
DBName: configs.Envs.DBName,
|
||||
Net: "tcp",
|
||||
AllowNativePasswords: true,
|
||||
ParseTime: true,
|
||||
}
|
||||
|
||||
db, err := db.NewMySQLStorage(cfg)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
auth.NewOAuth()
|
||||
initStorage(db)
|
||||
|
||||
server := api.NewAPIServer(fmt.Sprintf(":%s", configs.Envs.Port), db)
|
||||
if err := server.Run(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func initStorage(db *sqlx.DB) {
|
||||
err := db.Ping()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
log.Println("DB: Successfully connected!")
|
||||
}
|
||||
61
cmd/migrate/main.go
Normal file
61
cmd/migrate/main.go
Normal file
@@ -0,0 +1,61 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
|
||||
_ "github.com/go-sql-driver/mysql" // mysql driver
|
||||
mysqlDriver "github.com/go-sql-driver/mysql"
|
||||
"github.com/golang-migrate/migrate/v4"
|
||||
mysqlMigrate "github.com/golang-migrate/migrate/v4/database/mysql"
|
||||
_ "github.com/golang-migrate/migrate/v4/source/file"
|
||||
"sismedika.com/sas/westone/configs"
|
||||
"sismedika.com/sas/westone/db"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cfg := mysqlDriver.Config{
|
||||
User: configs.Envs.DBUser,
|
||||
Passwd: configs.Envs.DBPassword,
|
||||
Addr: configs.Envs.DBAddress,
|
||||
DBName: configs.Envs.DBName,
|
||||
Net: "tcp",
|
||||
AllowNativePasswords: true,
|
||||
ParseTime: true,
|
||||
}
|
||||
|
||||
db, err := db.NewMySQLStorage(cfg)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
driver, err := mysqlMigrate.WithInstance(db.DB, &mysqlMigrate.Config{})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
m, err := migrate.NewWithDatabaseInstance(
|
||||
"file://cmd/migrate/migrations",
|
||||
"mysql",
|
||||
driver,
|
||||
)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
v, d, _ := m.Version()
|
||||
log.Printf("Version: %d, dirty: %v", v, d)
|
||||
|
||||
cmd := os.Args[len(os.Args)-1]
|
||||
if cmd == "up" {
|
||||
if err := m.Up(); err != nil && err != migrate.ErrNoChange {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
if cmd == "down" {
|
||||
if err := m.Down(); err != nil && err != migrate.ErrNoChange {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE IF EXISTS users;
|
||||
11
cmd/migrate/migrations/20240318192427_add-user-table.up.sql
Normal file
11
cmd/migrate/migrations/20240318192427_add-user-table.up.sql
Normal file
@@ -0,0 +1,11 @@
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`firstName` VARCHAR(255) NOT NULL,
|
||||
`lastName` VARCHAR(255) NOT NULL,
|
||||
`email` VARCHAR(255) NOT NULL,
|
||||
`password` VARCHAR(255) NOT NULL,
|
||||
`createdAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY (email)
|
||||
);
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE IF EXISTS products;
|
||||
@@ -0,0 +1,10 @@
|
||||
CREATE TABLE IF NOT EXISTS products (
|
||||
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`name` VARCHAR(255) NOT NULL,
|
||||
`description` TEXT NOT NULL,
|
||||
`image` VARCHAR(255) NOT NULL,
|
||||
`price` DECIMAL(10, 2) NOT NULL,
|
||||
`quantity` INT UNSIGNED NOT NULL,
|
||||
`createdAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (id)
|
||||
);
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE IF EXISTS orders;
|
||||
@@ -0,0 +1,12 @@
|
||||
CREATE TABLE IF NOT EXISTS orders (
|
||||
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`userId` INT UNSIGNED NOT NULL,
|
||||
`total` DECIMAL(10, 2) NOT NULL,
|
||||
`status` ENUM('pending', 'completed', 'cancelled') NOT NULL DEFAULT 'pending',
|
||||
`address` TEXT NOT NULL,
|
||||
`createdAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
PRIMARY KEY (`id`),
|
||||
FOREIGN KEY (`userId`) REFERENCES users(`id`)
|
||||
);
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE IF EXISTS order_items;
|
||||
@@ -0,0 +1,11 @@
|
||||
CREATE TABLE IF NOT EXISTS `order_items` (
|
||||
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`orderId` INT UNSIGNED NOT NULL,
|
||||
`productId` INT UNSIGNED NOT NULL,
|
||||
`quantity` INT NOT NULL,
|
||||
`price` DECIMAL(10, 2) NOT NULL,
|
||||
|
||||
PRIMARY KEY (`id`),
|
||||
FOREIGN KEY (`orderId`) REFERENCES orders(`id`),
|
||||
FOREIGN KEY (`productId`) REFERENCES products(`id`)
|
||||
);
|
||||
65
configs/envs.go
Normal file
65
configs/envs.go
Normal file
@@ -0,0 +1,65 @@
|
||||
package configs
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
PublicHost string
|
||||
Port string
|
||||
DBUser string
|
||||
DBPassword string
|
||||
DBAddress string
|
||||
DBName string
|
||||
JWTSecret string
|
||||
JWTExpirationInSeconds int64
|
||||
GoogleClientID string
|
||||
GoogleClientSecret string
|
||||
SessionKey string
|
||||
}
|
||||
|
||||
var Envs = initConfig()
|
||||
|
||||
func initConfig() Config {
|
||||
godotenv.Load()
|
||||
|
||||
return Config{
|
||||
PublicHost: getEnv("PUBLIC_HOST", "http://localhost"),
|
||||
Port: getEnv("PORT", "8080"),
|
||||
DBUser: getEnv("DB_USER", "root"),
|
||||
DBPassword: getEnv("DB_PASSWORD", "mypassword"),
|
||||
DBAddress: fmt.Sprintf("%s:%s", getEnv("DB_HOST", "127.0.0.1"), getEnv("DB_PORT", "3306")),
|
||||
DBName: getEnv("DB_NAME", "ecom"),
|
||||
JWTSecret: getEnv("JWT_SECRET", "not-so-secret-now-is-it?"),
|
||||
JWTExpirationInSeconds: getEnvAsInt("JWT_EXPIRATION_IN_SECONDS", 3600*24*7),
|
||||
GoogleClientID: getEnv("GOOGLE_CLIENT_ID", "notfound"),
|
||||
GoogleClientSecret: getEnv("GOOGLE_CLIENT_SECRET", "nosecret"),
|
||||
SessionKey: getEnv("SESSION_KEY", "sessionkey"),
|
||||
}
|
||||
}
|
||||
|
||||
// Gets the env by key or fallbacks
|
||||
func getEnv(key, fallback string) string {
|
||||
if value, ok := os.LookupEnv(key); ok {
|
||||
return value
|
||||
}
|
||||
|
||||
return fallback
|
||||
}
|
||||
|
||||
func getEnvAsInt(key string, fallback int64) int64 {
|
||||
if value, ok := os.LookupEnv(key); ok {
|
||||
i, err := strconv.ParseInt(value, 10, 64)
|
||||
if err != nil {
|
||||
return fallback
|
||||
}
|
||||
|
||||
return i
|
||||
}
|
||||
|
||||
return fallback
|
||||
}
|
||||
18
db/db.go
Normal file
18
db/db.go
Normal file
@@ -0,0 +1,18 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/go-sql-driver/mysql"
|
||||
"github.com/jmoiron/sqlx"
|
||||
)
|
||||
|
||||
func NewMySQLStorage(cfg mysql.Config) (*sqlx.DB, error) {
|
||||
// sqlx.Open is used instead of sql.Open
|
||||
db, err := sqlx.Open("mysql", cfg.FormatDSN())
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
return db, nil
|
||||
}
|
||||
36
docker-compose.yml
Normal file
36
docker-compose.yml
Normal file
@@ -0,0 +1,36 @@
|
||||
version: '3'
|
||||
services:
|
||||
|
||||
db:
|
||||
image: mysql:8.0
|
||||
healthcheck:
|
||||
test: "exit 0"
|
||||
volumes:
|
||||
- db_data:/var/lib/mysql
|
||||
ports:
|
||||
- "3306:3306"
|
||||
environment:
|
||||
MYSQL_ROOT_PASSWORD: mypassword
|
||||
MYSQL_DATABASE: ecom
|
||||
|
||||
api:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
restart: on-failure
|
||||
volumes:
|
||||
- .:/go/src/api
|
||||
ports:
|
||||
- "8080:8080"
|
||||
environment:
|
||||
DB_HOST: db
|
||||
DB_USER: root
|
||||
DB_PASSWORD: mypassword
|
||||
DB_NAME: ecom
|
||||
links:
|
||||
- db
|
||||
depends_on:
|
||||
- db
|
||||
|
||||
volumes:
|
||||
db_data:
|
||||
314
docs/docs.go
Normal file
314
docs/docs.go
Normal file
@@ -0,0 +1,314 @@
|
||||
// Package docs Code generated by swaggo/swag. DO NOT EDIT
|
||||
package docs
|
||||
|
||||
import "github.com/swaggo/swag"
|
||||
|
||||
const docTemplate = `{
|
||||
"schemes": {{ marshal .Schemes }},
|
||||
"swagger": "2.0",
|
||||
"info": {
|
||||
"description": "{{escape .Description}}",
|
||||
"title": "{{.Title}}",
|
||||
"termsOfService": "http://swagger.io/terms/",
|
||||
"contact": {},
|
||||
"license": {
|
||||
"name": "Apache 2.0",
|
||||
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
|
||||
},
|
||||
"version": "{{.Version}}"
|
||||
},
|
||||
"host": "{{.Host}}",
|
||||
"basePath": "{{.BasePath}}",
|
||||
"paths": {
|
||||
"/westone/api/v1/auth/login": {
|
||||
"post": {
|
||||
"description": "login using westone account",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"Auth"
|
||||
],
|
||||
"summary": "login using westone account",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "parameter",
|
||||
"name": "parameter",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/types.SignInPayload"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/westone/api/v1/mddoctor/searchdoctor": {
|
||||
"post": {
|
||||
"description": "Search Doctors by name, NIK, Doctor Code, DOB, or phone number",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"Doctor"
|
||||
],
|
||||
"summary": "Search Doctors listing",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Authorization token",
|
||||
"name": "authorization",
|
||||
"in": "header",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "parameter",
|
||||
"name": "parameter",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/types.SearchDoctorPayload"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/westone/api/v1/mdpatient/searchpatient": {
|
||||
"post": {
|
||||
"description": "Search patients by name, NIK, registration number, DOB, or phone number",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"Patient"
|
||||
],
|
||||
"summary": "Search patient listing",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Authorization token",
|
||||
"name": "authorization",
|
||||
"in": "header",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "parameter",
|
||||
"name": "parameter",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/types.SearchPatientPayload"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/westone/api/v1/mdpatient/searchpatientold": {
|
||||
"post": {
|
||||
"description": "Search patients by name, NIK, registration number, DOB, or phone number",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"Patient"
|
||||
],
|
||||
"summary": "Search patient listing old methods",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Authorization token",
|
||||
"name": "authorization",
|
||||
"in": "header",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "parameter",
|
||||
"name": "parameter",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/types.SearchPatientPayload"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"types.SearchDoctorPayload": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"page",
|
||||
"perpage"
|
||||
],
|
||||
"properties": {
|
||||
"keyword": {
|
||||
"type": "string"
|
||||
},
|
||||
"page": {
|
||||
"type": "integer"
|
||||
},
|
||||
"perpage": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"types.SearchPatientPayload": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"page",
|
||||
"perpage"
|
||||
],
|
||||
"properties": {
|
||||
"keyword": {
|
||||
"type": "string"
|
||||
},
|
||||
"page": {
|
||||
"type": "integer"
|
||||
},
|
||||
"perpage": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"types.SignInPayload": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"email",
|
||||
"password"
|
||||
],
|
||||
"properties": {
|
||||
"email": {
|
||||
"type": "string"
|
||||
},
|
||||
"password": {
|
||||
"type": "string",
|
||||
"maxLength": 130,
|
||||
"minLength": 6
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}`
|
||||
|
||||
// SwaggerInfo holds exported Swagger Info so clients can modify it
|
||||
var SwaggerInfo = &swag.Spec{
|
||||
Version: "1.0",
|
||||
Host: "",
|
||||
BasePath: "",
|
||||
Schemes: []string{},
|
||||
Title: "WESTONE API",
|
||||
Description: "westone api documentation test",
|
||||
InfoInstanceName: "swagger",
|
||||
SwaggerTemplate: docTemplate,
|
||||
LeftDelim: "{{",
|
||||
RightDelim: "}}",
|
||||
}
|
||||
|
||||
func init() {
|
||||
swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo)
|
||||
}
|
||||
288
docs/swagger.json
Normal file
288
docs/swagger.json
Normal file
@@ -0,0 +1,288 @@
|
||||
{
|
||||
"swagger": "2.0",
|
||||
"info": {
|
||||
"description": "westone api documentation test",
|
||||
"title": "WESTONE API",
|
||||
"termsOfService": "http://swagger.io/terms/",
|
||||
"contact": {},
|
||||
"license": {
|
||||
"name": "Apache 2.0",
|
||||
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
|
||||
},
|
||||
"version": "1.0"
|
||||
},
|
||||
"paths": {
|
||||
"/westone/api/v1/auth/login": {
|
||||
"post": {
|
||||
"description": "login using westone account",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"Auth"
|
||||
],
|
||||
"summary": "login using westone account",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "parameter",
|
||||
"name": "parameter",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/types.SignInPayload"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/westone/api/v1/mddoctor/searchdoctor": {
|
||||
"post": {
|
||||
"description": "Search Doctors by name, NIK, Doctor Code, DOB, or phone number",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"Doctor"
|
||||
],
|
||||
"summary": "Search Doctors listing",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Authorization token",
|
||||
"name": "authorization",
|
||||
"in": "header",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "parameter",
|
||||
"name": "parameter",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/types.SearchDoctorPayload"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/westone/api/v1/mdpatient/searchpatient": {
|
||||
"post": {
|
||||
"description": "Search patients by name, NIK, registration number, DOB, or phone number",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"Patient"
|
||||
],
|
||||
"summary": "Search patient listing",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Authorization token",
|
||||
"name": "authorization",
|
||||
"in": "header",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "parameter",
|
||||
"name": "parameter",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/types.SearchPatientPayload"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/westone/api/v1/mdpatient/searchpatientold": {
|
||||
"post": {
|
||||
"description": "Search patients by name, NIK, registration number, DOB, or phone number",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"Patient"
|
||||
],
|
||||
"summary": "Search patient listing old methods",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Authorization token",
|
||||
"name": "authorization",
|
||||
"in": "header",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "parameter",
|
||||
"name": "parameter",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/types.SearchPatientPayload"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"types.SearchDoctorPayload": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"page",
|
||||
"perpage"
|
||||
],
|
||||
"properties": {
|
||||
"keyword": {
|
||||
"type": "string"
|
||||
},
|
||||
"page": {
|
||||
"type": "integer"
|
||||
},
|
||||
"perpage": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"types.SearchPatientPayload": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"page",
|
||||
"perpage"
|
||||
],
|
||||
"properties": {
|
||||
"keyword": {
|
||||
"type": "string"
|
||||
},
|
||||
"page": {
|
||||
"type": "integer"
|
||||
},
|
||||
"perpage": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"types.SignInPayload": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"email",
|
||||
"password"
|
||||
],
|
||||
"properties": {
|
||||
"email": {
|
||||
"type": "string"
|
||||
},
|
||||
"password": {
|
||||
"type": "string",
|
||||
"maxLength": 130,
|
||||
"minLength": 6
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
197
docs/swagger.yaml
Normal file
197
docs/swagger.yaml
Normal file
@@ -0,0 +1,197 @@
|
||||
definitions:
|
||||
types.SearchDoctorPayload:
|
||||
properties:
|
||||
keyword:
|
||||
type: string
|
||||
page:
|
||||
type: integer
|
||||
perpage:
|
||||
type: integer
|
||||
required:
|
||||
- page
|
||||
- perpage
|
||||
type: object
|
||||
types.SearchPatientPayload:
|
||||
properties:
|
||||
keyword:
|
||||
type: string
|
||||
page:
|
||||
type: integer
|
||||
perpage:
|
||||
type: integer
|
||||
required:
|
||||
- page
|
||||
- perpage
|
||||
type: object
|
||||
types.SignInPayload:
|
||||
properties:
|
||||
email:
|
||||
type: string
|
||||
password:
|
||||
maxLength: 130
|
||||
minLength: 6
|
||||
type: string
|
||||
required:
|
||||
- email
|
||||
- password
|
||||
type: object
|
||||
info:
|
||||
contact: {}
|
||||
description: westone api documentation test
|
||||
license:
|
||||
name: Apache 2.0
|
||||
url: http://www.apache.org/licenses/LICENSE-2.0.html
|
||||
termsOfService: http://swagger.io/terms/
|
||||
title: WESTONE API
|
||||
version: "1.0"
|
||||
paths:
|
||||
/westone/api/v1/auth/login:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: login using westone account
|
||||
parameters:
|
||||
- description: parameter
|
||||
in: body
|
||||
name: parameter
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/types.SignInPayload'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
summary: login using westone account
|
||||
tags:
|
||||
- Auth
|
||||
/westone/api/v1/mddoctor/searchdoctor:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Search Doctors by name, NIK, Doctor Code, DOB, or phone number
|
||||
parameters:
|
||||
- description: Authorization token
|
||||
in: header
|
||||
name: authorization
|
||||
required: true
|
||||
type: string
|
||||
- description: parameter
|
||||
in: body
|
||||
name: parameter
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/types.SearchDoctorPayload'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
summary: Search Doctors listing
|
||||
tags:
|
||||
- Doctor
|
||||
/westone/api/v1/mdpatient/searchpatient:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Search patients by name, NIK, registration number, DOB, or phone
|
||||
number
|
||||
parameters:
|
||||
- description: Authorization token
|
||||
in: header
|
||||
name: authorization
|
||||
required: true
|
||||
type: string
|
||||
- description: parameter
|
||||
in: body
|
||||
name: parameter
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/types.SearchPatientPayload'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
summary: Search patient listing
|
||||
tags:
|
||||
- Patient
|
||||
/westone/api/v1/mdpatient/searchpatientold:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Search patients by name, NIK, registration number, DOB, or phone
|
||||
number
|
||||
parameters:
|
||||
- description: Authorization token
|
||||
in: header
|
||||
name: authorization
|
||||
required: true
|
||||
type: string
|
||||
- description: parameter
|
||||
in: body
|
||||
name: parameter
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/types.SearchPatientPayload'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
summary: Search patient listing old methods
|
||||
tags:
|
||||
- Patient
|
||||
swagger: "2.0"
|
||||
53
go.mod
Normal file
53
go.mod
Normal file
@@ -0,0 +1,53 @@
|
||||
module sismedika.com/sas/westone
|
||||
|
||||
go 1.22.0
|
||||
|
||||
require (
|
||||
github.com/go-sql-driver/mysql v1.8.1
|
||||
golang.org/x/crypto v0.29.0
|
||||
)
|
||||
|
||||
require (
|
||||
cloud.google.com/go/compute v1.23.3 // indirect
|
||||
cloud.google.com/go/compute/metadata v0.2.3 // indirect
|
||||
filippo.io/edwards25519 v1.1.0 // indirect
|
||||
github.com/KyleBanks/depth v1.2.1 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
|
||||
github.com/go-openapi/jsonpointer v0.21.0 // indirect
|
||||
github.com/go-openapi/jsonreference v0.21.0 // indirect
|
||||
github.com/go-openapi/spec v0.21.0 // indirect
|
||||
github.com/go-openapi/swag v0.23.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/golang/protobuf v1.5.3 // indirect
|
||||
github.com/gorilla/securecookie v1.1.2 // indirect
|
||||
github.com/hashicorp/errwrap v1.1.0 // indirect
|
||||
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||
github.com/josharian/intern v1.0.0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/mailru/easyjson v0.7.7 // indirect
|
||||
github.com/swaggo/files/v2 v2.0.0 // indirect
|
||||
go.uber.org/atomic v1.7.0 // indirect
|
||||
golang.org/x/net v0.31.0 // indirect
|
||||
golang.org/x/oauth2 v0.17.0 // indirect
|
||||
golang.org/x/sys v0.27.0 // indirect
|
||||
golang.org/x/text v0.20.0 // indirect
|
||||
golang.org/x/tools v0.27.0 // indirect
|
||||
google.golang.org/appengine v1.6.8 // indirect
|
||||
google.golang.org/protobuf v1.32.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/go-playground/validator/v10 v10.19.0
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1
|
||||
github.com/golang-migrate/migrate/v4 v4.17.0
|
||||
github.com/gorilla/mux v1.8.1
|
||||
github.com/gorilla/sessions v1.3.0
|
||||
github.com/jmoiron/sqlx v1.4.0
|
||||
github.com/joho/godotenv v1.5.1
|
||||
github.com/markbates/goth v1.80.0
|
||||
github.com/rs/cors v1.11.1
|
||||
github.com/swaggo/http-swagger/v2 v2.0.2
|
||||
github.com/swaggo/swag v1.16.4
|
||||
)
|
||||
171
go.sum
Normal file
171
go.sum
Normal file
@@ -0,0 +1,171 @@
|
||||
cloud.google.com/go/compute v1.23.3 h1:6sVlXXBmbd7jNX0Ipq0trII3e4n1/MsADLK6a+aiVlk=
|
||||
cloud.google.com/go/compute v1.23.3/go.mod h1:VCgBUoMnIVIR0CscqQiPJLAG25E3ZRZMzcFZeQ+h8CI=
|
||||
cloud.google.com/go/compute/metadata v0.2.3 h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY=
|
||||
cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA=
|
||||
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
||||
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0=
|
||||
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
|
||||
github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=
|
||||
github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=
|
||||
github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow=
|
||||
github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dhui/dktest v0.4.0 h1:z05UmuXZHO/bgj/ds2bGMBu8FI4WA+Ag/m3ghL+om7M=
|
||||
github.com/dhui/dktest v0.4.0/go.mod h1:v/Dbz1LgCBOi2Uki2nUqLBGa83hWBGFMu5MrgMDCc78=
|
||||
github.com/docker/distribution v2.8.2+incompatible h1:T3de5rq0dB1j30rp0sA2rER+m322EBzniBPB6ZIzuh8=
|
||||
github.com/docker/distribution v2.8.2+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=
|
||||
github.com/docker/docker v24.0.7+incompatible h1:Wo6l37AuwP3JaMnZa226lzVXGA3F9Ig1seQen0cKYlM=
|
||||
github.com/docker/docker v24.0.7+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
|
||||
github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ=
|
||||
github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec=
|
||||
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
|
||||
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
|
||||
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
|
||||
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
|
||||
github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ=
|
||||
github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY=
|
||||
github.com/go-openapi/jsonreference v0.21.0 h1:Rs+Y7hSXT83Jacb7kFyjn4ijOuVGSvOdF2+tg1TRrwQ=
|
||||
github.com/go-openapi/jsonreference v0.21.0/go.mod h1:LmZmgsrTkVg9LG4EaHeY8cBDslNPMo06cago5JNLkm4=
|
||||
github.com/go-openapi/spec v0.21.0 h1:LTVzPc3p/RzRnkQqLRndbAzjY0d0BCL72A6j3CdL9ZY=
|
||||
github.com/go-openapi/spec v0.21.0/go.mod h1:78u6VdPw81XU44qEWGhtr982gJ5BWg2c0I5XwVMotYk=
|
||||
github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE=
|
||||
github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.19.0 h1:ol+5Fu+cSq9JD7SoSqe04GMI92cbn0+wvQ3bZ8b/AU4=
|
||||
github.com/go-playground/validator/v10 v10.19.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
|
||||
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
|
||||
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
||||
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
|
||||
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
|
||||
github.com/golang-migrate/migrate/v4 v4.17.0 h1:rd40H3QXU0AA4IoLllFcEAEo9dYKRHYND2gB4p7xcaU=
|
||||
github.com/golang-migrate/migrate/v4 v4.17.0/go.mod h1:+Cp2mtLP4/aXDTKb9wmXYitdrNx2HGs45rbWAo6OsKM=
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
|
||||
github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
|
||||
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
|
||||
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
|
||||
github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA=
|
||||
github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=
|
||||
github.com/gorilla/sessions v1.3.0 h1:XYlkq7KcpOB2ZhHBPv5WpjMIxrQosiZanfoy1HLZFzg=
|
||||
github.com/gorilla/sessions v1.3.0/go.mod h1:ePLdVu+jbEgHH+KWw8I1z2wqd0BAdAQh/8LRvBeoNcQ=
|
||||
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
|
||||
github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=
|
||||
github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
|
||||
github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=
|
||||
github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
|
||||
github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o=
|
||||
github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY=
|
||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
|
||||
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
|
||||
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
|
||||
github.com/markbates/goth v1.80.0 h1:NnvatczZDzOs1hn9Ug+dVYf2Viwwkp/ZDX5K+GLjan8=
|
||||
github.com/markbates/goth v1.80.0/go.mod h1:4/GYHo+W6NWisrMPZnq0Yr2Q70UntNLn7KXEFhrIdAY=
|
||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0=
|
||||
github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y=
|
||||
github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=
|
||||
github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=
|
||||
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
|
||||
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
|
||||
github.com/opencontainers/image-spec v1.0.2 h1:9yCKha/T5XdGtO0q9Q9a6T5NUCsTn/DrBg0D7ufOcFM=
|
||||
github.com/opencontainers/image-spec v1.0.2/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
|
||||
github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
|
||||
github.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA=
|
||||
github.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/swaggo/files/v2 v2.0.0 h1:hmAt8Dkynw7Ssz46F6pn8ok6YmGZqHSVLZ+HQM7i0kw=
|
||||
github.com/swaggo/files/v2 v2.0.0/go.mod h1:24kk2Y9NYEJ5lHuCra6iVwkMjIekMCaFq/0JQj66kyM=
|
||||
github.com/swaggo/http-swagger/v2 v2.0.2 h1:FKCdLsl+sFCx60KFsyM0rDarwiUSZ8DqbfSyIKC9OBg=
|
||||
github.com/swaggo/http-swagger/v2 v2.0.2/go.mod h1:r7/GBkAWIfK6E/OLnE8fXnviHiDeAHmgIyooa4xm3AQ=
|
||||
github.com/swaggo/swag v1.16.4 h1:clWJtd9LStiG3VeijiCfOVODP6VpHtKdQy9ELFG3s1A=
|
||||
github.com/swaggo/swag v1.16.4/go.mod h1:VBsHJRsDvfYvqoiMKnsdwhNV9LEMHgEDZcyVYX0sxPg=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw=
|
||||
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.29.0 h1:L5SG1JTTXupVV3n6sUqMTeWbjAyfPwoda2DLX8J8FrQ=
|
||||
golang.org/x/crypto v0.29.0/go.mod h1:+F4F4N5hv6v38hfeYwTdx20oUvLLc+QfrE9Ax9HtgRg=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.22.0 h1:D4nJWe9zXqHOmWqj4VMOJhvzj7bEZg4wEYa759z1pH4=
|
||||
golang.org/x/mod v0.22.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.31.0 h1:68CPQngjLL0r2AlUKiSxtQFKvzRVbnzLwMUn5SzcLHo=
|
||||
golang.org/x/net v0.31.0/go.mod h1:P4fl1q7dY2hnZFxEk4pPSkDHF+QqjitcnDjUQyMM+pM=
|
||||
golang.org/x/oauth2 v0.17.0 h1:6m3ZPmLEFdVxKKWnKq4VqZ60gutO35zm+zrAHVmHyDQ=
|
||||
golang.org/x/oauth2 v0.17.0/go.mod h1:OzPDGQiuQMguemayvdylqddI7qcD9lnSDb+1FiwQ5HA=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.9.0 h1:fEo0HyrW1GIgZdpbhCRO0PkJajUS5H9IFUztCgEo2jQ=
|
||||
golang.org/x/sync v0.9.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.27.0 h1:wBqf8DvsY9Y/2P8gAfPDEYNuS30J4lPHJxXSb/nJZ+s=
|
||||
golang.org/x/sys v0.27.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
|
||||
golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug=
|
||||
golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.27.0 h1:qEKojBykQkQ4EynWy4S8Weg69NumxKdn40Fce3uc/8o=
|
||||
golang.org/x/tools v0.27.0/go.mod h1:sUi0ZgbwW9ZPAq26Ekut+weQPR5eIM6GQLQ1Yjm1H0Q=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/appengine v1.6.8 h1:IhEN5q69dyKagZPYMSdIjS2HqprW324FRQZJcGqPAsM=
|
||||
google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds=
|
||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
||||
google.golang.org/protobuf v1.32.0 h1:pPC6BG5ex8PDFnkbrGU3EixyhKcQ2aDuBS36lqK/C7I=
|
||||
google.golang.org/protobuf v1.32.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
15
rest-files/auth.http
Normal file
15
rest-files/auth.http
Normal file
@@ -0,0 +1,15 @@
|
||||
POST http://localhost:8080/westone/api/v1/auth/login
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"email":"joko@gmail.com",
|
||||
"password":"sas321"
|
||||
}
|
||||
|
||||
####
|
||||
# POST http://localhost:8080/api/v1/auth/google/linking
|
||||
# Content-Type: application/json
|
||||
|
||||
# {
|
||||
# "code":"xPkMIa"
|
||||
# }
|
||||
20
rest-files/patient.http
Normal file
20
rest-files/patient.http
Normal file
@@ -0,0 +1,20 @@
|
||||
POST http://localhost:8080/westone/api/v1/mdpatient/searchpatient
|
||||
Content-Type: application/json
|
||||
Authorization: {{token}}
|
||||
|
||||
{
|
||||
"keyword":"wahyu+",
|
||||
"page":1,
|
||||
"perpage":10
|
||||
}
|
||||
|
||||
####
|
||||
GET http://localhost:8080/westone/api/v1/mddoctor/searchdoctor
|
||||
Content-Type: application/json
|
||||
Authorization: {{token}}
|
||||
|
||||
{
|
||||
"keyword":"",
|
||||
"page":1,
|
||||
"perpage":10
|
||||
}
|
||||
3
rest-files/person.http
Normal file
3
rest-files/person.http
Normal file
@@ -0,0 +1,3 @@
|
||||
GET http://localhost:8080/api/v1/mdperson/get/1
|
||||
Content-Type: application/json
|
||||
Authorization: {{token}}
|
||||
12
rest-files/terminology.http
Normal file
12
rest-files/terminology.http
Normal file
@@ -0,0 +1,12 @@
|
||||
GET http://devcpone.aplikasi.web.id:9090/westone/api/v1/termicheck
|
||||
Content-Type: application/json
|
||||
|
||||
#####
|
||||
GET http://localhost:8080/westone/api/v1/terminology/getdisplay
|
||||
Content-Type: application/json
|
||||
Authorization: {{token}}
|
||||
|
||||
{
|
||||
"code": "Bunak",
|
||||
"codesystem": "xhis.code.etnicity"
|
||||
}
|
||||
42
rest-files/user.http
Normal file
42
rest-files/user.http
Normal file
@@ -0,0 +1,42 @@
|
||||
POST http://localhost:8080/api/v1/register
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"firstName":"joko",
|
||||
"lastName":"susilo",
|
||||
"email":"joko@gmail.com",
|
||||
"password":"x123"
|
||||
}
|
||||
|
||||
####
|
||||
POST http://localhost:8080/api/v1/login
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"email":"joko@gmail.com",
|
||||
"password":"sas31"
|
||||
}
|
||||
|
||||
|
||||
###
|
||||
# GET http://localhost:8080/api/v1/users/1
|
||||
# Authorization: {{token}}
|
||||
|
||||
|
||||
###
|
||||
# POST http://localhost:8080/api/v1/auth/generateauthcode
|
||||
# Content-Type: application/json
|
||||
|
||||
# {
|
||||
# "email":"adib@sismedika.com",
|
||||
# "type":"google"
|
||||
# }
|
||||
|
||||
###
|
||||
# POST http://localhost:8080/api/v1/auth/login
|
||||
# Content-Type: application/json
|
||||
|
||||
# {
|
||||
# "email":"joko@gmail.com",
|
||||
# "password":"sas321"
|
||||
# }
|
||||
71
services/auth/auth.routes.go
Normal file
71
services/auth/auth.routes.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"sismedika.com/sas/westone/types"
|
||||
"sismedika.com/sas/westone/utils"
|
||||
)
|
||||
|
||||
// Login login using westone account
|
||||
//
|
||||
// @Summary login using westone account
|
||||
// @Description login using westone account
|
||||
// @Tags Auth
|
||||
// @Accept json
|
||||
// @Param parameter body types.SignInPayload true "parameter"
|
||||
// @Produce json
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Failure 400 {object} map[string]any
|
||||
// @Failure 500 {object} map[string]any
|
||||
// @Router /westone/api/v1/auth/login [post]
|
||||
func (h *Handler) handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
var payload types.SignInPayload
|
||||
fmt.Println("User Agent")
|
||||
fmt.Println(r.UserAgent())
|
||||
if err := utils.ParseJSON(r, &payload); err != nil {
|
||||
utils.WriteError(w, http.StatusBadRequest, err)
|
||||
h.store.LogSignIn(payload.Email, r.RemoteAddr, "FAILED", "LOGIN", "westone")
|
||||
return
|
||||
}
|
||||
|
||||
if err := utils.Validate.Struct(payload); err != nil {
|
||||
errorz := err.(validator.ValidationErrors)
|
||||
utils.WriteError(w, http.StatusBadRequest, fmt.Errorf("invalid payload: %v", errorz))
|
||||
h.store.LogSignIn(payload.Email, r.RemoteAddr, "FAILED", "LOGIN", "westone")
|
||||
return
|
||||
}
|
||||
|
||||
hashedPassword := HashWithMD5(payload.Password)
|
||||
response, err := h.store.SignInWestone(payload.Email, hashedPassword)
|
||||
if err != nil {
|
||||
var logError *utils.LogError
|
||||
if errors.As(err, &logError) {
|
||||
h.errorz.CreateErrorLog(*logError)
|
||||
utils.WriteErrorLog(w, http.StatusBadRequest, *logError)
|
||||
}
|
||||
h.store.LogSignIn(payload.Email, r.RemoteAddr, "FAILED", "LOGIN", "westone")
|
||||
return
|
||||
}
|
||||
|
||||
timenow := time.Now()
|
||||
token, err := CreateJWT(types.DataJWT{
|
||||
User: *response,
|
||||
Ip: r.RemoteAddr,
|
||||
Agent: r.UserAgent(),
|
||||
Version: "v1",
|
||||
LastLogin: timenow.Format("2006-01-02 15:04:05"),
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, err)
|
||||
h.store.LogSignIn(payload.Email, r.RemoteAddr, "FAILED", "LOGIN", "westone")
|
||||
return
|
||||
}
|
||||
|
||||
utils.WriteJSONLogin(w, http.StatusOK, response, token, "westone")
|
||||
}
|
||||
77
services/auth/auth.store.go
Normal file
77
services/auth/auth.store.go
Normal file
@@ -0,0 +1,77 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"sismedika.com/sas/westone/types"
|
||||
"sismedika.com/sas/westone/utils"
|
||||
)
|
||||
|
||||
func (s *Store) SignInWestone(email string, password string) (*types.User, error) {
|
||||
user := new(types.User)
|
||||
|
||||
qry := `
|
||||
SELECT
|
||||
M_UserID,
|
||||
M_UserName,
|
||||
M_UserGroupDashboard,
|
||||
IFNULL(M_UserFullName, "") as M_StaffName,
|
||||
10000000 as time_autologout
|
||||
FROM m_user
|
||||
JOIN m_usergroup ON M_UserM_UserGroupID = M_UserGroupID
|
||||
LEFT JOIN m_staff on M_UserM_StaffID = M_StaffID
|
||||
WHERE M_UserName = ? AND M_UserPassword = ? AND M_UserIsActive = 'Y'
|
||||
`
|
||||
if err := s.db.Get(user, qry, email, password); err != nil {
|
||||
return nil, &utils.LogError{
|
||||
Code: "151",
|
||||
TraceID: utils.RandomTraceID(15),
|
||||
Type: "AUTH",
|
||||
Params: "email: " + email,
|
||||
Query: "-",
|
||||
Message: err.Error(),
|
||||
TimeStamp: time.Now().Format("2006-01-02 15:04:05"),
|
||||
}
|
||||
}
|
||||
user.Type_Akun = "westone"
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *Store) LogSignIn(email string, ip string, status string, tipe string, provider string) error {
|
||||
tx, err := s.db.BeginTxx(context.Background(), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if err != nil {
|
||||
tx.Rollback()
|
||||
}
|
||||
}()
|
||||
|
||||
logval := types.LogLogin{
|
||||
LogLoginMUserEmail: email,
|
||||
LogLoginDateTime: time.Now().Format("2006-01-02 15:04:05"),
|
||||
LogLoginIP: ip,
|
||||
LogLoginType: tipe,
|
||||
LogLoginStatus: status,
|
||||
LogLoginLogin: provider,
|
||||
}
|
||||
|
||||
qry := `INSERT INTO log_login
|
||||
(Log_LoginM_UserEmail, Log_LoginDateTime, Log_LoginIP, Log_LoginType, Log_LoginStatus, Log_LoginLogin)
|
||||
VALUES (:Log_LoginM_UserEmail, :Log_LoginDateTime, :Log_LoginIP, :Log_LoginType, :Log_LoginStatus, :Log_LoginLogin)`
|
||||
|
||||
_, err = tx.NamedExec(qry, logval)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = tx.Commit(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
134
services/auth/jwt.go
Normal file
134
services/auth/jwt.go
Normal file
@@ -0,0 +1,134 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"sismedika.com/sas/westone/configs"
|
||||
"sismedika.com/sas/westone/types"
|
||||
"sismedika.com/sas/westone/utils"
|
||||
)
|
||||
|
||||
type ContextKey string
|
||||
|
||||
const UserContextKey ContextKey = "mk1S2sKM12KASd02dp1"
|
||||
|
||||
// func WithJWTAuth(handlerFunc http.HandlerFunc, store types.UserStore) http.HandlerFunc {
|
||||
// return func(w http.ResponseWriter, r *http.Request) {
|
||||
// tokenString := utils.GetTokenFromRequest(r)
|
||||
// token, err := validateJWT(tokenString)
|
||||
// if err != nil {
|
||||
// log.Printf("failed to validate token: %v", err)
|
||||
// permissionDenied(w)
|
||||
// return
|
||||
// }
|
||||
|
||||
// if !token.Valid {
|
||||
// log.Println("invalid token")
|
||||
// permissionDenied(w)
|
||||
// return
|
||||
// }
|
||||
|
||||
// claims := token.Claims.(jwt.MapClaims)
|
||||
// str := claims["userID"].(string)
|
||||
|
||||
// userID, err := strconv.Atoi(str)
|
||||
// if err != nil {
|
||||
// log.Printf("failed to convert userID to int: %v", err)
|
||||
// permissionDenied(w)
|
||||
// return
|
||||
// }
|
||||
|
||||
// u, err := store.GetUserByID(userID)
|
||||
// if err != nil {
|
||||
// log.Printf("failed to get user by id: %v", err)
|
||||
// permissionDenied(w)
|
||||
// return
|
||||
// }
|
||||
|
||||
// // Add the user to the context
|
||||
// ctx := r.Context()
|
||||
// ctx = context.WithValue(ctx, UserKey, u.MUserID)
|
||||
// r = r.WithContext(ctx)
|
||||
|
||||
// // Call the function if the token is valid
|
||||
// handlerFunc(w, r)
|
||||
// }
|
||||
// }
|
||||
|
||||
func CreateJWT(data types.DataJWT) (string, error) {
|
||||
secret := []byte(configs.Envs.JWTSecret)
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"M_UserID": data.M_UserID,
|
||||
"M_UserEmail": data.M_UserEmail,
|
||||
"M_UserUsername": data.M_UserUsername,
|
||||
"M_UserGroupDashboard": data.M_UserGroupDashboard,
|
||||
"M_UserDefaultTSampleStationID": data.M_UserDefaultTSampleStationID,
|
||||
"M_StaffName": data.M_StaffName,
|
||||
"Is_Courier": data.Is_Courier,
|
||||
"Time_Autologout": data.Time_Autologout,
|
||||
"Type_Akun": data.Type_Akun,
|
||||
"IP": data.Ip,
|
||||
"Agent": data.Agent,
|
||||
"Version": data.Version,
|
||||
"LastLogin": data.LastLogin,
|
||||
})
|
||||
|
||||
tokenString, err := token.SignedString(secret)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return tokenString, err
|
||||
}
|
||||
|
||||
func validateJWT(tokenString string) (*jwt.Token, error) {
|
||||
return jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
|
||||
return []byte(configs.Envs.JWTSecret), nil
|
||||
})
|
||||
}
|
||||
|
||||
func permissionDenied(w http.ResponseWriter) {
|
||||
utils.WriteError(w, http.StatusForbidden, fmt.Errorf("PERMISSION DENIED"))
|
||||
}
|
||||
|
||||
func GetUserIDFromContext(ctx context.Context) int {
|
||||
userID, ok := ctx.Value(UserContextKey).(int)
|
||||
if !ok {
|
||||
return -1
|
||||
}
|
||||
|
||||
return userID
|
||||
}
|
||||
|
||||
func AuthMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
tokenstr := utils.GetTokenFromRequest(r)
|
||||
token, err := validateJWT(tokenstr)
|
||||
if err != nil {
|
||||
log.Printf("[ERROR] Failed to validate jwt token: %v", err)
|
||||
permissionDenied(w)
|
||||
return
|
||||
}
|
||||
|
||||
if !token.Valid {
|
||||
log.Println("[ERROR] Invalid token")
|
||||
permissionDenied(w)
|
||||
return
|
||||
}
|
||||
|
||||
claims := token.Claims.(jwt.MapClaims)
|
||||
ctx := r.Context()
|
||||
ctx = context.WithValue(ctx, UserContextKey, claims)
|
||||
r = r.WithContext(ctx)
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
18
services/auth/jwt_test.go
Normal file
18
services/auth/jwt_test.go
Normal file
@@ -0,0 +1,18 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"sismedika.com/sas/westone/types"
|
||||
)
|
||||
|
||||
func TestCreateJWT(t *testing.T) {
|
||||
token, err := CreateJWT(types.DataJWT{})
|
||||
if err != nil {
|
||||
t.Errorf("error creating JWT: %v", err)
|
||||
}
|
||||
|
||||
if token == "" {
|
||||
t.Error("expected token to be not empty")
|
||||
}
|
||||
}
|
||||
73
services/auth/oauth.go
Normal file
73
services/auth/oauth.go
Normal file
@@ -0,0 +1,73 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/gorilla/sessions"
|
||||
"github.com/markbates/goth"
|
||||
"github.com/markbates/goth/gothic"
|
||||
"github.com/markbates/goth/providers/google"
|
||||
"sismedika.com/sas/westone/configs"
|
||||
)
|
||||
|
||||
var maxAge = 86400 * 1 // 30 days
|
||||
var isProd = false // set to true if in production
|
||||
var key = configs.Envs.SessionKey
|
||||
var store = sessions.NewCookieStore([]byte(key))
|
||||
var usersession = "user"
|
||||
|
||||
func NewOAuth() {
|
||||
googleClientID := configs.Envs.GoogleClientID
|
||||
googleClientSecret := configs.Envs.GoogleClientSecret
|
||||
callback := configs.Envs.PublicHost + ":" + configs.Envs.Port + "/api/v1/auth/google/callback"
|
||||
|
||||
store.MaxAge(maxAge)
|
||||
store.Options.Path = "/"
|
||||
store.Options.HttpOnly = true
|
||||
store.Options.Secure = isProd
|
||||
store.Options.SameSite = http.SameSiteLaxMode
|
||||
|
||||
gothic.Store = store
|
||||
|
||||
goth.UseProviders(
|
||||
google.New(googleClientID, googleClientSecret, callback),
|
||||
)
|
||||
}
|
||||
|
||||
func addUsertoSession(w http.ResponseWriter, r *http.Request, user goth.User) error {
|
||||
user_session, err := store.Get(r, usersession)
|
||||
if err != nil {
|
||||
user_session, err = store.New(r, usersession)
|
||||
if err != nil {
|
||||
log.Println("[ERROR] get user to session, error: ", err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
user.RawData = map[string]interface{}{}
|
||||
user_session.Values["user"] = user
|
||||
err = user_session.Save(r, w)
|
||||
if err != nil {
|
||||
log.Println("[ERROR] saving user to session, error: ", err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func removeUsertoSession(w http.ResponseWriter, r *http.Request) error {
|
||||
user_session, err := store.Get(r, usersession)
|
||||
if err != nil {
|
||||
log.Println("[ERROR] get user to session, error: ", err)
|
||||
return err
|
||||
}
|
||||
user_session.Values["user"] = goth.User{}
|
||||
err = user_session.Save(r, w)
|
||||
if err != nil {
|
||||
log.Println("[ERROR] remove user to session, error: ", err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
249
services/auth/oauth.routes.go
Normal file
249
services/auth/oauth.routes.go
Normal file
@@ -0,0 +1,249 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/markbates/goth"
|
||||
"github.com/markbates/goth/gothic"
|
||||
"sismedika.com/sas/westone/configs"
|
||||
"sismedika.com/sas/westone/types"
|
||||
"sismedika.com/sas/westone/utils"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
store types.OauthStore
|
||||
errorz types.ErrorLogStore
|
||||
usrStore types.UserStore
|
||||
}
|
||||
|
||||
func NewHandler(store types.OauthStore, errorz types.ErrorLogStore, usrStore types.UserStore) *Handler {
|
||||
return &Handler{
|
||||
store: store,
|
||||
errorz: errorz,
|
||||
usrStore: usrStore,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) RegisterRoutes(router *mux.Router) {
|
||||
authroute := router.PathPrefix("/auth").Subrouter()
|
||||
|
||||
authroute.HandleFunc("/generateauthcode", h.handlerGenerateAuthCode).Methods(http.MethodPost)
|
||||
|
||||
// auth
|
||||
authroute.HandleFunc("/login", h.handleLogin).Methods(http.MethodPost)
|
||||
// oauth
|
||||
authroute.HandleFunc("/{provider}/login", h.handleAuthLogin).Methods(http.MethodGet)
|
||||
authroute.HandleFunc("/{provider}/logout", h.handleAuthLogout).Methods(http.MethodGet)
|
||||
authroute.HandleFunc("/{provider}/callback", h.handleAuthCallback).Methods(http.MethodGet)
|
||||
authroute.HandleFunc("/{provider}/linking", h.handleAuthLinkAccount).Methods(http.MethodPost)
|
||||
authroute.HandleFunc("/{provider}/authcode", h.handlerRedirectCode).Methods(http.MethodGet)
|
||||
|
||||
protec := authroute.PathPrefix("/redirect").Subrouter()
|
||||
protec.Use(AuthMiddleware)
|
||||
protec.HandleFunc("/dashboard", h.handleRedirectDash).Methods(http.MethodGet)
|
||||
}
|
||||
|
||||
func (h *Handler) handleAuthLogin(w http.ResponseWriter, r *http.Request) {
|
||||
if gothUser, err := gothic.CompleteUserAuth(w, r); err == nil {
|
||||
// log.Println(gothUser)
|
||||
log.Printf("[INFO] account found: %v", gothUser.Email)
|
||||
} else {
|
||||
gothic.BeginAuthHandler(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) handleAuthCallback(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
provider := vars["provider"]
|
||||
|
||||
akungoogle, err := gothic.CompleteUserAuth(w, r)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
// add user to cookie session
|
||||
err = addUsertoSession(w, r, akungoogle)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
// check google is linked to server
|
||||
userID, err := h.store.CheckGoogleAccountLinked(types.UserGoogle{M_UserGoogleEmail: akungoogle.Email, M_UserGoogleIdentifier: akungoogle.UserID})
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
if userID > 0 {
|
||||
// generate jwt token
|
||||
user, err := h.usrStore.GetUserByID(userID)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
user.Type_Akun = provider
|
||||
timenow := time.Now()
|
||||
token, err := CreateJWT(types.DataJWT{
|
||||
User: *user,
|
||||
Ip: r.RemoteAddr,
|
||||
Agent: r.UserAgent(),
|
||||
Version: "v1",
|
||||
LastLogin: timenow.Format("2006-01-02 15:04:05"),
|
||||
})
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
// data := "Bearer " + token
|
||||
// w.Header().Set("Authorization", data)
|
||||
// http.Redirect(w, r, "/api/v1/auth/redirect/dashboard", http.StatusFound)
|
||||
utils.WriteJSONLogin(w, http.StatusOK, user, token, provider)
|
||||
} else {
|
||||
log.Println("[INFO] redirect to auth-code")
|
||||
// http.Redirect(w, r, "/api/v1/auth/"+provider+"/authcode", http.StatusFound)
|
||||
http.Redirect(w, r, configs.Envs.PublicHost+"/auth-code", http.StatusFound)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) handleRedirectDash(w http.ResponseWriter, r *http.Request) {
|
||||
claims, ok := r.Context().Value(UserContextKey).(jwt.MapClaims)
|
||||
if !ok {
|
||||
utils.WriteError(w, http.StatusInternalServerError, fmt.Errorf("token not found in context"))
|
||||
return
|
||||
}
|
||||
|
||||
username := claims["Username"].(string)
|
||||
temp := "WELCOME TO DASHBOARD, " + username
|
||||
utils.WriteJSON(w, http.StatusOK, temp)
|
||||
}
|
||||
|
||||
func (h *Handler) handlerRedirectCode(w http.ResponseWriter, r *http.Request) {
|
||||
user_session, _ := store.Get(r, usersession)
|
||||
user := user_session.Values["user"].(goth.User)
|
||||
if user.IDToken == "" {
|
||||
log.Println("[ERROR] token not found in context")
|
||||
utils.WriteJSON(w, http.StatusInternalServerError, "not found")
|
||||
return
|
||||
}
|
||||
|
||||
temp := "INSERT AUTH CODE, " + user.Email
|
||||
utils.WriteJSON(w, http.StatusOK, temp)
|
||||
}
|
||||
|
||||
func (h *Handler) handleAuthLogout(w http.ResponseWriter, r *http.Request) {
|
||||
err := gothic.Logout(w, r)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
err = removeUsertoSession(w, r)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
utils.WriteJSON(w, http.StatusOK, "success logout")
|
||||
}
|
||||
|
||||
func (h *Handler) handlerGenerateAuthCode(w http.ResponseWriter, r *http.Request) {
|
||||
var payload types.GenerateAuthCode
|
||||
if err := utils.ParseJSON(r, &payload); err != nil {
|
||||
utils.WriteError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := utils.Validate.Struct(payload); err != nil {
|
||||
errorss := err.(validator.ValidationErrors)
|
||||
utils.WriteError(w, http.StatusBadRequest, fmt.Errorf("invalid payload: %v", errorss))
|
||||
return
|
||||
}
|
||||
|
||||
err := h.store.GenerateAuthCode(payload.Email, payload.Types, payload.UserID)
|
||||
if err != nil {
|
||||
log.Println("[ERROR] failed generate auth code")
|
||||
utils.WriteJSON(w, http.StatusInternalServerError, "failed generate auth code")
|
||||
return
|
||||
}
|
||||
|
||||
msg := "Auth Code Generated for " + payload.Email
|
||||
utils.WriteJSON(w, http.StatusOK, msg)
|
||||
}
|
||||
|
||||
func (h *Handler) handleAuthLinkAccount(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
provider := vars["provider"]
|
||||
|
||||
// var payload types.AuthCode
|
||||
var payload types.AuthCodePayload
|
||||
if err := utils.ParseJSON(r, &payload); err != nil {
|
||||
utils.WriteError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := utils.Validate.Struct(payload); err != nil {
|
||||
errors := err.(validator.ValidationErrors)
|
||||
utils.WriteError(w, http.StatusBadRequest, fmt.Errorf("invalid payload: %v", errors))
|
||||
return
|
||||
}
|
||||
|
||||
user_session, _ := store.Get(r, usersession)
|
||||
akunGoogle := user_session.Values["user"].(goth.User)
|
||||
if akunGoogle.IDToken == "" {
|
||||
log.Println("[ERROR] google token not found in context")
|
||||
utils.WriteError(w, http.StatusInternalServerError, fmt.Errorf("token not found"))
|
||||
return
|
||||
}
|
||||
|
||||
userID, err := h.store.CompareAuthCode(payload.Code, akunGoogle, provider)
|
||||
if err != nil {
|
||||
log.Println("[ERROR] compare auth code")
|
||||
utils.WriteError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.usrStore.GetUserByID(userID)
|
||||
if err != nil {
|
||||
log.Println("[ERROR] cant get m_user data")
|
||||
utils.WriteError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
user.Type_Akun = provider
|
||||
timenow := time.Now()
|
||||
token, err := CreateJWT(types.DataJWT{
|
||||
User: *user,
|
||||
Ip: r.RemoteAddr,
|
||||
Agent: r.UserAgent(),
|
||||
Version: "v1",
|
||||
LastLogin: timenow.Format("2006-01-02 15:04:05"),
|
||||
})
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
err = h.store.AddGoolgeAccount(types.UserGoogle{
|
||||
M_UserGoogleM_UserID: user.M_UserID,
|
||||
M_UserGoogleEmail: akunGoogle.Email,
|
||||
M_UserGoogleIdentifier: akunGoogle.UserID,
|
||||
M_UserGoogleCode: payload.Code,
|
||||
M_UserGoogleToken: token,
|
||||
})
|
||||
if err != nil {
|
||||
log.Printf("[ERROR] failed insert google account to db, %v", err)
|
||||
utils.WriteError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
utils.WriteJSONLogin(w, http.StatusOK, user, token, provider)
|
||||
}
|
||||
143
services/auth/oauth.store.go
Normal file
143
services/auth/oauth.store.go
Normal file
@@ -0,0 +1,143 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
"github.com/markbates/goth"
|
||||
"sismedika.com/sas/westone/types"
|
||||
"sismedika.com/sas/westone/utils"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
db *sqlx.DB
|
||||
}
|
||||
|
||||
func NewStore(db *sqlx.DB) *Store {
|
||||
return &Store{db: db}
|
||||
}
|
||||
|
||||
func (s *Store) AddGoolgeAccount(user types.UserGoogle) error {
|
||||
tx, err := s.db.BeginTxx(context.Background(), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if err != nil {
|
||||
tx.Rollback()
|
||||
}
|
||||
}()
|
||||
|
||||
query := `INSERT INTO m_usergoogle (
|
||||
M_UserGoogleM_UserID,
|
||||
M_UserGoogleEmail,
|
||||
M_UserGoogleIdentifier,
|
||||
M_UserGoogleCode,
|
||||
M_UserGoogleToken
|
||||
) VALUES (:M_UserGoogleM_UserID, :M_UserGoogleEmail, :M_UserGoogleIdentifier, :M_UserGoogleCode, :M_UserGoogleToken)`
|
||||
_, err = tx.NamedExec(query, user)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = tx.Commit(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) CheckGoogleAccountLinked(user types.UserGoogle) (int, error) {
|
||||
var userID int
|
||||
|
||||
qry := `SELECT
|
||||
M_UserGoogleM_UserID
|
||||
FROM m_usergoogle
|
||||
WHERE M_UserGoogleEmail = ? AND M_UserGoogleIdentifier = ?`
|
||||
if err := s.db.Get(&userID, qry, user.M_UserGoogleEmail, user.M_UserGoogleIdentifier); err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if userID < 1 {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
return userID, nil
|
||||
}
|
||||
|
||||
func (s *Store) GenerateAuthCode(email string, jenis string, userid int) error {
|
||||
payload := types.AuthCode{
|
||||
AuthCodeMUserID: userid,
|
||||
AuthCodeUser: email,
|
||||
AuthCodeType: jenis,
|
||||
AuthCodeCode: utils.RandomTraceID(6),
|
||||
}
|
||||
|
||||
tx, err := s.db.BeginTxx(context.Background(), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if err != nil {
|
||||
tx.Rollback()
|
||||
}
|
||||
}()
|
||||
|
||||
sql := `INSERT INTO x_auth_code (
|
||||
AuthCodeMUserID,
|
||||
AuthCodeUser,
|
||||
AuthCodeType,
|
||||
AuthCodeCode
|
||||
) VALUES (:AuthCodeMUserID, :AuthCodeUser, :AuthCodeType, :AuthCodeCode)`
|
||||
_, err = tx.NamedExec(sql, payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = tx.Commit(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) CompareAuthCode(authcode string, user goth.User, typez string) (int, error) {
|
||||
var code types.AuthCode
|
||||
|
||||
qry := `SELECT
|
||||
AuthCodeID,
|
||||
AuthCodeMUserID,
|
||||
AuthCodeUser,
|
||||
AuthCodeType,
|
||||
AuthCodeCode,
|
||||
AuthCodeIsUsed
|
||||
FROM x_auth_code
|
||||
WHERE AuthCodeUser = ? AND AuthCodeType = ?
|
||||
AND AuthCodeIsUsed = 'N' AND AuthCodeIsActive = 'Y'`
|
||||
if err := s.db.Get(&code, qry, user.Email, typez); err != nil {
|
||||
return 0, fmt.Errorf("auth code not found, %v", err)
|
||||
}
|
||||
|
||||
if authcode != code.AuthCodeCode {
|
||||
return 0, fmt.Errorf("auth code do not match")
|
||||
} else {
|
||||
inst := `
|
||||
UPDATE x_auth_code
|
||||
SET AuthCodeIsUsed = 'Y'
|
||||
WHERE AuthCodeUser = ? AND AuthCodeType = ? AND AuthCodeCode = ?
|
||||
`
|
||||
if _, err := s.db.Exec(inst, user.Email, typez, authcode); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return code.AuthCodeMUserID, nil
|
||||
}
|
||||
}
|
||||
29
services/auth/password.go
Normal file
29
services/auth/password.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func HashPassword(password string) (string, error) {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return string(hash), nil
|
||||
}
|
||||
|
||||
func ComparePasswords(hashed string, plain []byte) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(hashed), plain)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func HashWithMD5(password string) string {
|
||||
salt := "545"
|
||||
data := []byte(salt + password + salt)
|
||||
hash := md5.Sum(data)
|
||||
return hex.EncodeToString(hash[:])
|
||||
}
|
||||
34
services/auth/password_test.go
Normal file
34
services/auth/password_test.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHashPassword(t *testing.T) {
|
||||
hash, err := HashPassword("password")
|
||||
if err != nil {
|
||||
t.Errorf("error hashing password: %v", err)
|
||||
}
|
||||
|
||||
if hash == "" {
|
||||
t.Error("expected hash to be not empty")
|
||||
}
|
||||
|
||||
if hash == "password" {
|
||||
t.Error("expected hash to be different from password")
|
||||
}
|
||||
}
|
||||
|
||||
func TestComparePasswords(t *testing.T) {
|
||||
hash, err := HashPassword("password")
|
||||
if err != nil {
|
||||
t.Errorf("error hashing password: %v", err)
|
||||
}
|
||||
|
||||
if !ComparePasswords(hash, []byte("password")) {
|
||||
t.Errorf("expected password to match hash")
|
||||
}
|
||||
if ComparePasswords(hash, []byte("notpassword")) {
|
||||
t.Errorf("expected password to not match hash")
|
||||
}
|
||||
}
|
||||
77
services/cart/routes.go
Normal file
77
services/cart/routes.go
Normal file
@@ -0,0 +1,77 @@
|
||||
package cart
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gorilla/mux"
|
||||
"sismedika.com/sas/westone/services/auth"
|
||||
"sismedika.com/sas/westone/types"
|
||||
"sismedika.com/sas/westone/utils"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
store types.ProductStore
|
||||
orderStore types.OrderStore
|
||||
userStore types.UserStore
|
||||
}
|
||||
|
||||
func NewHandler(
|
||||
store types.ProductStore,
|
||||
orderStore types.OrderStore,
|
||||
userStore types.UserStore,
|
||||
) *Handler {
|
||||
return &Handler{
|
||||
store: store,
|
||||
orderStore: orderStore,
|
||||
userStore: userStore,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) RegisterRoutes(router *mux.Router) {
|
||||
cart := router.PathPrefix("/cart").Subrouter()
|
||||
cart.Use(auth.AuthMiddleware)
|
||||
cart.HandleFunc("/checkout", h.handleCheckout).Methods(http.MethodPost)
|
||||
// router.HandleFunc("/cart/checkout", auth.WithJWTAuth(h.handleCheckout)).Methods(http.MethodPost)
|
||||
}
|
||||
|
||||
func (h *Handler) handleCheckout(w http.ResponseWriter, r *http.Request) {
|
||||
userID := auth.GetUserIDFromContext(r.Context())
|
||||
|
||||
var cart types.CartCheckoutPayload
|
||||
if err := utils.ParseJSON(r, &cart); err != nil {
|
||||
utils.WriteError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := utils.Validate.Struct(cart); err != nil {
|
||||
errors := err.(validator.ValidationErrors)
|
||||
utils.WriteError(w, http.StatusBadRequest, fmt.Errorf("invalid payload: %v", errors))
|
||||
return
|
||||
}
|
||||
|
||||
productIds, err := getCartItemsIDs(cart.Items)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
|
||||
// get products
|
||||
products, err := h.store.GetProductsByID(productIds)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
orderID, totalPrice, err := h.createOrder(products, cart.Items, userID)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
|
||||
utils.WriteJSON(w, http.StatusOK, map[string]interface{}{
|
||||
"total_price": totalPrice,
|
||||
"order_id": orderID,
|
||||
})
|
||||
}
|
||||
214
services/cart/routes_test.go
Normal file
214
services/cart/routes_test.go
Normal file
@@ -0,0 +1,214 @@
|
||||
package cart
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"sismedika.com/sas/westone/types"
|
||||
)
|
||||
|
||||
var mockProducts = []types.Product{
|
||||
{ID: 1, Name: "product 1", Price: 10, Quantity: 100},
|
||||
{ID: 2, Name: "product 2", Price: 20, Quantity: 200},
|
||||
{ID: 3, Name: "product 3", Price: 30, Quantity: 300},
|
||||
{ID: 4, Name: "empty stock", Price: 30, Quantity: 0},
|
||||
{ID: 5, Name: "almost stock", Price: 30, Quantity: 1},
|
||||
}
|
||||
|
||||
func TestCartServiceHandler(t *testing.T) {
|
||||
productStore := &mockProductStore{}
|
||||
orderStore := &mockOrderStore{}
|
||||
handler := NewHandler(productStore, orderStore, nil)
|
||||
|
||||
t.Run("should fail to checkout if the cart items do not exist", func(t *testing.T) {
|
||||
payload := types.CartCheckoutPayload{
|
||||
Items: []types.CartCheckoutItem{
|
||||
{ProductID: 99, Quantity: 100},
|
||||
},
|
||||
}
|
||||
|
||||
marshalled, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, "/cart/checkout", bytes.NewBuffer(marshalled))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
router := mux.NewRouter()
|
||||
|
||||
router.HandleFunc("/cart/checkout", handler.handleCheckout).Methods(http.MethodPost)
|
||||
|
||||
router.ServeHTTP(rr, req)
|
||||
|
||||
if rr.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected status code %d, got %d", http.StatusBadRequest, rr.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("should fail to checkout if the cart has negative quantities", func(t *testing.T) {
|
||||
payload := types.CartCheckoutPayload{
|
||||
Items: []types.CartCheckoutItem{
|
||||
{ProductID: 1, Quantity: 0}, // invalid quantity
|
||||
},
|
||||
}
|
||||
|
||||
marshalled, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, "/cart/checkout", bytes.NewBuffer(marshalled))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
router := mux.NewRouter()
|
||||
|
||||
router.HandleFunc("/cart/checkout", handler.handleCheckout).Methods(http.MethodPost)
|
||||
|
||||
router.ServeHTTP(rr, req)
|
||||
|
||||
if rr.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected status code %d, got %d", http.StatusBadRequest, rr.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("should fail to checkout if there is no stock for an item", func(t *testing.T) {
|
||||
payload := types.CartCheckoutPayload{
|
||||
Items: []types.CartCheckoutItem{
|
||||
{ProductID: 4, Quantity: 2},
|
||||
},
|
||||
}
|
||||
|
||||
marshalled, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, "/cart/checkout", bytes.NewBuffer(marshalled))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
router := mux.NewRouter()
|
||||
|
||||
router.HandleFunc("/cart/checkout", handler.handleCheckout).Methods(http.MethodPost)
|
||||
|
||||
router.ServeHTTP(rr, req)
|
||||
|
||||
if rr.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected status code %d, got %d", http.StatusBadRequest, rr.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("should fail to checkout if there is not enough stock", func(t *testing.T) {
|
||||
payload := types.CartCheckoutPayload{
|
||||
Items: []types.CartCheckoutItem{
|
||||
{ProductID: 5, Quantity: 2},
|
||||
},
|
||||
}
|
||||
|
||||
marshalled, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, "/cart/checkout", bytes.NewBuffer(marshalled))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
router := mux.NewRouter()
|
||||
|
||||
router.HandleFunc("/cart/checkout", handler.handleCheckout).Methods(http.MethodPost)
|
||||
|
||||
router.ServeHTTP(rr, req)
|
||||
|
||||
if rr.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected status code %d, got %d", http.StatusBadRequest, rr.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("should checkout and calculate the price correctly", func(t *testing.T) {
|
||||
payload := types.CartCheckoutPayload{
|
||||
Items: []types.CartCheckoutItem{
|
||||
{ProductID: 1, Quantity: 10},
|
||||
{ProductID: 2, Quantity: 20},
|
||||
{ProductID: 5, Quantity: 1},
|
||||
},
|
||||
}
|
||||
|
||||
marshalled, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, "/cart/checkout", bytes.NewBuffer(marshalled))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
router := mux.NewRouter()
|
||||
|
||||
router.HandleFunc("/cart/checkout", handler.handleCheckout).Methods(http.MethodPost)
|
||||
|
||||
router.ServeHTTP(rr, req)
|
||||
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Errorf("expected status code %d, got %d", http.StatusOK, rr.Code)
|
||||
}
|
||||
|
||||
var response map[string]interface{}
|
||||
if err := json.NewDecoder(rr.Body).Decode(&response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if response["total_price"] != 530.0 {
|
||||
t.Errorf("expected total price to be 530, got %f", response["total_price"])
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
type mockProductStore struct{}
|
||||
|
||||
func (m *mockProductStore) GetProductByID(productID int) (*types.Product, error) {
|
||||
return &types.Product{}, nil
|
||||
}
|
||||
|
||||
func (m *mockProductStore) GetProducts() ([]*types.Product, error) {
|
||||
return []*types.Product{}, nil
|
||||
}
|
||||
|
||||
func (m *mockProductStore) CreateProduct(product types.CreateProductPayload) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockProductStore) GetProductsByID(ids []int) ([]types.Product, error) {
|
||||
return mockProducts, nil
|
||||
}
|
||||
|
||||
func (m *mockProductStore) UpdateProduct(product types.Product) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type mockOrderStore struct{}
|
||||
|
||||
func (m *mockOrderStore) CreateOrder(order types.Order) (int, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (m *mockOrderStore) CreateOrderItem(orderItem types.OrderItem) error {
|
||||
return nil
|
||||
}
|
||||
96
services/cart/service.go
Normal file
96
services/cart/service.go
Normal file
@@ -0,0 +1,96 @@
|
||||
package cart
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"sismedika.com/sas/westone/types"
|
||||
)
|
||||
|
||||
func getCartItemsIDs(items []types.CartCheckoutItem) ([]int, error) {
|
||||
productIds := make([]int, len(items))
|
||||
for i, item := range items {
|
||||
if item.Quantity <= 0 {
|
||||
return nil, fmt.Errorf("invalid quantity for product %d", item.ProductID)
|
||||
}
|
||||
|
||||
productIds[i] = item.ProductID
|
||||
}
|
||||
|
||||
return productIds, nil
|
||||
}
|
||||
|
||||
func checkIfCartIsInStock(cartItems []types.CartCheckoutItem, products map[int]types.Product) error {
|
||||
if len(cartItems) == 0 {
|
||||
return fmt.Errorf("cart is empty")
|
||||
}
|
||||
|
||||
for _, item := range cartItems {
|
||||
product, ok := products[item.ProductID]
|
||||
if !ok {
|
||||
return fmt.Errorf("product %d is not available in the store, please refresh your cart", item.ProductID)
|
||||
}
|
||||
|
||||
if product.Quantity < item.Quantity {
|
||||
return fmt.Errorf("product %s is not available in the quantity requested", product.Name)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func calculateTotalPrice(cartItems []types.CartCheckoutItem, products map[int]types.Product) float64 {
|
||||
var total float64
|
||||
|
||||
for _, item := range cartItems {
|
||||
product := products[item.ProductID]
|
||||
total += product.Price * float64(item.Quantity)
|
||||
}
|
||||
|
||||
return total
|
||||
}
|
||||
|
||||
func (h *Handler) createOrder(products []types.Product, cartItems []types.CartCheckoutItem, userID int) (int, float64, error) {
|
||||
// create a map of products for easier access
|
||||
productsMap := make(map[int]types.Product)
|
||||
for _, product := range products {
|
||||
productsMap[product.ID] = product
|
||||
}
|
||||
|
||||
// check if all products are available
|
||||
if err := checkIfCartIsInStock(cartItems, productsMap); err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
|
||||
// calculate total price
|
||||
totalPrice := calculateTotalPrice(cartItems, productsMap)
|
||||
|
||||
// reduce the quantity of products in the store
|
||||
for _, item := range cartItems {
|
||||
product := productsMap[item.ProductID]
|
||||
product.Quantity -= item.Quantity
|
||||
h.store.UpdateProduct(product)
|
||||
}
|
||||
|
||||
// create order record
|
||||
orderID, err := h.orderStore.CreateOrder(types.Order{
|
||||
UserID: userID,
|
||||
Total: totalPrice,
|
||||
Status: "pending",
|
||||
Address: "some address", // could fetch address from a user addresses table
|
||||
})
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
|
||||
// create order the items records
|
||||
for _, item := range cartItems {
|
||||
h.orderStore.CreateOrderItem(types.OrderItem{
|
||||
OrderID: orderID,
|
||||
ProductID: item.ProductID,
|
||||
Quantity: item.Quantity,
|
||||
Price: productsMap[item.ProductID].Price,
|
||||
})
|
||||
}
|
||||
|
||||
return orderID, totalPrice, nil
|
||||
}
|
||||
62
services/doctor/doctor.routes.go
Normal file
62
services/doctor/doctor.routes.go
Normal file
@@ -0,0 +1,62 @@
|
||||
package doctor
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gorilla/mux"
|
||||
"sismedika.com/sas/westone/services/auth"
|
||||
"sismedika.com/sas/westone/types"
|
||||
"sismedika.com/sas/westone/utils"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
store types.DoctorStore
|
||||
}
|
||||
|
||||
func NewHandler(store types.DoctorStore) *Handler {
|
||||
return &Handler{store: store}
|
||||
}
|
||||
|
||||
func (h *Handler) RegisterRoutes(router *mux.Router) {
|
||||
doctorroutes := router.PathPrefix("/mddoctor").Subrouter()
|
||||
doctorroutes.Use(auth.AuthMiddleware)
|
||||
|
||||
doctorroutes.HandleFunc("/searchdoctor", h.handlerSearchDoctor).Methods(http.MethodPost)
|
||||
}
|
||||
|
||||
// SearchDoctor searches doctor by name, NIK, Doctor Code, DOB, or phone number
|
||||
//
|
||||
// @Summary Search Doctors listing
|
||||
// @Description Search Doctors by name, NIK, Doctor Code, DOB, or phone number
|
||||
// @Tags Doctor
|
||||
// @Accept json
|
||||
// @Param authorization header string true "Authorization token"
|
||||
// @Param parameter body types.SearchDoctorPayload true "parameter"
|
||||
// @Produce json
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Failure 400 {object} map[string]any
|
||||
// @Failure 500 {object} map[string]any
|
||||
// @Router /westone/api/v1/mddoctor/searchdoctor [post]
|
||||
func (h *Handler) handlerSearchDoctor(w http.ResponseWriter, r *http.Request) {
|
||||
var payload types.SearchDoctorPayload
|
||||
if err := utils.ParseJSON(r, &payload); err != nil {
|
||||
utils.WriteError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := utils.Validate.Struct(payload); err != nil {
|
||||
erros := err.(validator.ValidationErrors)
|
||||
utils.WriteError(w, http.StatusBadRequest, fmt.Errorf("invalid payload: %v", erros))
|
||||
return
|
||||
}
|
||||
|
||||
response, err := h.store.SearchDoctor(payload.Keyword, payload.Page, payload.Perpage)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
utils.WriteJSON(w, http.StatusOK, response)
|
||||
}
|
||||
76
services/doctor/doctor.store.go
Normal file
76
services/doctor/doctor.store.go
Normal file
@@ -0,0 +1,76 @@
|
||||
package doctor
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
"sismedika.com/sas/westone/types"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
db *sqlx.DB
|
||||
}
|
||||
|
||||
func NewStore(db *sqlx.DB) *Store {
|
||||
return &Store{db: db}
|
||||
}
|
||||
|
||||
func (s *Store) SearchDoctor(keyword string, page int, perpage int) ([]types.DoctorResult, error) {
|
||||
var list_doctor []types.DoctorResult
|
||||
var sqlFilter []string
|
||||
|
||||
if keyword != "" {
|
||||
params := strings.Split(keyword, "+")
|
||||
if len(params) > 0 && params[0] != "" {
|
||||
sqlFilter = append(sqlFilter, "PersonName LIKE '%"+params[0]+"%'")
|
||||
}
|
||||
if len(params) > 1 && params[1] != "" {
|
||||
sqlFilter = append(sqlFilter, "PersonIdentifierValue = '"+params[1]+"'")
|
||||
}
|
||||
if len(params) > 2 && params[2] != "" {
|
||||
sqlFilter = append(sqlFilter, "DoctorCode = '"+params[2]+"'")
|
||||
}
|
||||
if len(params) > 3 && params[3] != "" {
|
||||
sqlFilter = append(sqlFilter, "PersonBirthDate = '"+params[3]+"'")
|
||||
}
|
||||
if len(params) > 4 && params[4] != "" {
|
||||
sqlFilter = append(sqlFilter, "PersonTelecomValue = '"+params[4]+"'")
|
||||
}
|
||||
}
|
||||
|
||||
doctor_tb := `DoctorID, DoctorCode, DoctorIHSNumber, DoctorPersonID`
|
||||
|
||||
person_tb := `PersonID, PersonName, PersonSalutation, PersonPrefix, PersonSuffix, PersonGender, PersonBirthPlace, PersonBirthDate,
|
||||
PersonReligionCode, PersonReligionSystem, PersonBloodTypeCode, PersonBloodTypeSystem, PersonRhesusCode, PersonRhesusSystem,
|
||||
PersonEducationCode, PersonEducationSystem, PersonJobClassCode, PersonJobClassSystem, PersonEtnicityCode, PersonEtnicitySystem,
|
||||
PersonMaritalBirth, PersonMaritalStatus`
|
||||
|
||||
person_address_tb := `PersonAddressID, PersonAddressPersonID, PersonAddressIsDefault, PersonAddressUse, PersonAddressType, PersonAddressText,
|
||||
PersonAddressLine1, PersonAddressLine2, PersonAddressRegionalCd, PersonAddressRT, PersonAddressRW, PersonAddressCity,
|
||||
PersonAddressDistrict, PersonAddressState, PersonAddressCountry`
|
||||
|
||||
person_identifier_tb := `PersonIdentifierID, PersonIdentifierPersonID, PersonIdentifierUse, PersonIdentifierTypeCode,
|
||||
PersonIdentifierTypeSystem, PersonIdentifierCode, PersonIdentifierSystem, PersonIdentifierValue`
|
||||
|
||||
person_telecom_tb := `PersonTelecomID, PersonTelecomPersonID, PersonTelecomSystem, PersonTelecomValue, PersonTelecomUse`
|
||||
|
||||
offset := (page - 1) * perpage
|
||||
sql := `SELECT ` + doctor_tb + `,` + person_tb + `,` + person_identifier_tb + `,` + person_address_tb + `,` + person_telecom_tb +
|
||||
` FROM doctor
|
||||
JOIN person ON PersonID = DoctorPersonID
|
||||
JOIN person_identifier ON PersonIdentifierPersonID = PersonID
|
||||
JOIN person_telecom ON PersonTelecomPersonID = PersonID
|
||||
JOIN person_address ON PersonAddressPersonID = PersonID
|
||||
WHERE DoctorIsActive = 'Y'`
|
||||
|
||||
if len(sqlFilter) > 0 {
|
||||
sql += " AND " + strings.Join(sqlFilter, " AND ")
|
||||
}
|
||||
sql += " LIMIT ? OFFSET ?"
|
||||
|
||||
if err := s.db.Select(&list_doctor, sql, perpage, offset); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return list_doctor, nil
|
||||
}
|
||||
50
services/error_log/error.store.go
Normal file
50
services/error_log/error.store.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package error_log
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
"sismedika.com/sas/westone/utils"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
db *sqlx.DB
|
||||
}
|
||||
|
||||
func NewStore(db *sqlx.DB) *Store {
|
||||
return &Store{db: db}
|
||||
}
|
||||
|
||||
func (s *Store) CreateErrorLog(errval utils.LogError) error {
|
||||
tx, err := s.db.BeginTxx(context.Background(), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if err != nil {
|
||||
tx.Rollback()
|
||||
}
|
||||
}()
|
||||
|
||||
qry := `INSERT INTO westone_log.error_log
|
||||
(ErrorLogCode, ErrorTraceID, ErrorLogType, ErrorLogParams, ErrorLogQuery, ErrorMessage, ErrorLogTimestamp)
|
||||
VALUES (:ErrorLogCode, :ErrorTraceID, :ErrorLogType, :ErrorLogParams, :ErrorLogQuery, :ErrorMessage, :ErrorLogTimestamp)`
|
||||
|
||||
_, err = tx.NamedExec(qry, errval)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
delqry := `DELETE FROM error_log WHERE ErrorLogTimestamp < DATE_SUB(NOW(), INTERVAL 1 MONTH)`
|
||||
_, err = tx.Exec(delqry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = tx.Commit(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
82
services/order/store.go
Normal file
82
services/order/store.go
Normal file
@@ -0,0 +1,82 @@
|
||||
package order
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
"sismedika.com/sas/westone/types"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
db *sqlx.DB
|
||||
}
|
||||
|
||||
func NewStore(db *sqlx.DB) *Store {
|
||||
return &Store{db: db}
|
||||
}
|
||||
|
||||
func (s *Store) CreateOrder(order types.Order) (int, error) {
|
||||
// Start a new transaction
|
||||
tx, err := s.db.BeginTxx(context.Background(), nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
// Defer rollback to ensure transaction is rolled back in case of an error
|
||||
defer func() {
|
||||
if err != nil {
|
||||
tx.Rollback()
|
||||
}
|
||||
}()
|
||||
|
||||
query := `INSERT INTO orders (userId, total, status, address)
|
||||
VALUES (:userId, :total, :status, :address)`
|
||||
|
||||
// Using tx.NamedExec to insert the order within the transaction
|
||||
res, err := tx.NamedExec(query, order)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
// Retrieving the last inserted ID
|
||||
id, err := res.LastInsertId()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
// Commit the transaction if everything succeeded
|
||||
if err = tx.Commit(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return int(id), nil
|
||||
}
|
||||
|
||||
func (s *Store) CreateOrderItem(orderItem types.OrderItem) error {
|
||||
// Start a new transaction
|
||||
tx, err := s.db.BeginTxx(context.Background(), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Defer rollback to ensure transaction is rolled back in case of an error
|
||||
defer func() {
|
||||
if err != nil {
|
||||
tx.Rollback()
|
||||
}
|
||||
}()
|
||||
|
||||
query := `INSERT INTO order_items (orderId, productId, quantity, price)
|
||||
VALUES (:orderId, :productId, :quantity, :price)`
|
||||
|
||||
// Using tx.NamedExec to insert the order item within the transaction
|
||||
_, err = tx.NamedExec(query, orderItem)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Commit the transaction if everything succeeded
|
||||
if err = tx.Commit(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
98
services/patient/patient.routes.go
Normal file
98
services/patient/patient.routes.go
Normal file
@@ -0,0 +1,98 @@
|
||||
package patient
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gorilla/mux"
|
||||
"sismedika.com/sas/westone/services/auth"
|
||||
"sismedika.com/sas/westone/types"
|
||||
"sismedika.com/sas/westone/utils"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
store types.PatientStore
|
||||
}
|
||||
|
||||
func NewHandler(store types.PatientStore) *Handler {
|
||||
return &Handler{store: store}
|
||||
}
|
||||
|
||||
func (h *Handler) RegisterRoutes(router *mux.Router) {
|
||||
patientroute := router.PathPrefix("/mdpatient").Subrouter()
|
||||
patientroute.Use(auth.AuthMiddleware)
|
||||
|
||||
patientroute.HandleFunc("/searchpatient", h.handlerSearchPatient).Methods(http.MethodPost)
|
||||
patientroute.HandleFunc("/searchpatientold", h.handlerSearchPatientOld).Methods(http.MethodPost)
|
||||
}
|
||||
|
||||
// SearchPatient searches patients by name, NIK, registration number, DOB, or phone number
|
||||
//
|
||||
// @Summary Search patient listing
|
||||
// @Description Search patients by name, NIK, registration number, DOB, or phone number
|
||||
// @Tags Patient
|
||||
// @Accept json
|
||||
// @Param authorization header string true "Authorization token"
|
||||
// @Param parameter body types.SearchPatientPayload true "parameter"
|
||||
// @Produce json
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Failure 400 {object} map[string]any
|
||||
// @Failure 500 {object} map[string]any
|
||||
// @Router /westone/api/v1/mdpatient/searchpatient [post]
|
||||
func (h *Handler) handlerSearchPatient(w http.ResponseWriter, r *http.Request) {
|
||||
var payload types.SearchPatientPayload
|
||||
if err := utils.ParseJSON(r, &payload); err != nil {
|
||||
utils.WriteError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := utils.Validate.Struct(payload); err != nil {
|
||||
erros := err.(validator.ValidationErrors)
|
||||
utils.WriteError(w, http.StatusBadRequest, fmt.Errorf("invalid payload: %v", erros))
|
||||
return
|
||||
}
|
||||
|
||||
response, err := h.store.SearchPatient(payload.Keyword, payload.Page, payload.Perpage)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
utils.WriteJSON(w, http.StatusOK, response)
|
||||
}
|
||||
|
||||
// SearchPatientOld searches patients by name, NIK, registration number, DOB, or phone number
|
||||
//
|
||||
// @Summary Search patient listing old methods
|
||||
// @Description Search patients by name, NIK, registration number, DOB, or phone number
|
||||
// @Tags Patient
|
||||
// @Accept json
|
||||
// @Param authorization header string true "Authorization token"
|
||||
// @Param parameter body types.SearchPatientPayload true "parameter"
|
||||
// @Produce json
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Failure 400 {object} map[string]any
|
||||
// @Failure 500 {object} map[string]any
|
||||
// @Router /westone/api/v1/mdpatient/searchpatientold [post]
|
||||
func (h *Handler) handlerSearchPatientOld(w http.ResponseWriter, r *http.Request) {
|
||||
var payload types.SearchPatientPayload
|
||||
if err := utils.ParseJSON(r, &payload); err != nil {
|
||||
utils.WriteError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := utils.Validate.Struct(payload); err != nil {
|
||||
erros := err.(validator.ValidationErrors)
|
||||
utils.WriteError(w, http.StatusBadRequest, fmt.Errorf("invalid payload: %v", erros))
|
||||
return
|
||||
}
|
||||
|
||||
response, err := h.store.SearchPatientOld(payload.Keyword, payload.Page, payload.Perpage)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
utils.WriteJSON(w, http.StatusOK, response)
|
||||
}
|
||||
161
services/patient/patient.store.go
Normal file
161
services/patient/patient.store.go
Normal file
@@ -0,0 +1,161 @@
|
||||
package patient
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
"sismedika.com/sas/westone/types"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
db *sqlx.DB
|
||||
}
|
||||
|
||||
func NewStore(db *sqlx.DB) *Store {
|
||||
return &Store{db: db}
|
||||
}
|
||||
|
||||
func (s *Store) GetPatientByID(id int) (*types.Patient, error) {
|
||||
patient := new(types.Patient)
|
||||
|
||||
qry := `
|
||||
SELECT
|
||||
PatientID
|
||||
PatientPersonID,
|
||||
PatientManaginOrganizationID,
|
||||
PatientHISNumber,
|
||||
PatientRegNumber
|
||||
FROM patient
|
||||
WHERE PatientID = ?
|
||||
`
|
||||
if err := s.db.Get(patient, qry, id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return patient, nil
|
||||
}
|
||||
|
||||
func (s *Store) SearchPatient(keyword string, page int, perpage int) ([]types.PatientResult, error) {
|
||||
var list_patient []types.PatientResult
|
||||
var sqlName, sqlNIK, sqlReg, sqlDob, sqlhp string
|
||||
|
||||
// params nama+nik+noreg+dob+nohp
|
||||
if keyword != "" {
|
||||
params := strings.Split(keyword, "+")
|
||||
if len(params) > 0 && params[0] != "" {
|
||||
// sqlName = " AND PersonName LIKE '%" + params[0] + "%' "
|
||||
sqlName = " WHERE MATCH(PersonNameFulltext) AGAINST('" + params[0] + "' IN BOOLEAN MODE) "
|
||||
}
|
||||
if len(params) > 1 && params[1] != "" {
|
||||
sqlNIK = " AND PersonIdentifierValue = '" + params[1] + "' "
|
||||
}
|
||||
if len(params) > 2 && params[2] != "" {
|
||||
sqlReg = " AND PatientRegNumber = '" + params[2] + "' "
|
||||
}
|
||||
if len(params) > 3 && params[3] != "" {
|
||||
sqlDob = " AND PersonBirthDate = '" + params[3] + "' "
|
||||
}
|
||||
if len(params) > 4 && params[4] != "" {
|
||||
sqlhp = " AND PersonTelecomValue = '" + params[4] + "' "
|
||||
}
|
||||
}
|
||||
|
||||
patient_tb := `PatientID, PatientPersonID, PatientManaginOrganizationID, PatientHISNumber, PatientRegNumber`
|
||||
|
||||
person_tb := `PersonID, PersonName, PersonSalutation, PersonPrefix, PersonSuffix, PersonGender, PersonBirthPlace, PersonBirthDate,
|
||||
PersonReligionCode, PersonReligionSystem, PersonBloodTypeCode, PersonBloodTypeSystem, PersonRhesusCode, PersonRhesusSystem,
|
||||
PersonEducationCode, PersonEducationSystem, PersonJobClassCode, PersonJobClassSystem, PersonEtnicityCode, PersonEtnicitySystem,
|
||||
PersonMaritalBirth, PersonMaritalStatus`
|
||||
|
||||
person_address_tb := `PersonAddressID, PersonAddressPersonID, PersonAddressIsDefault, PersonAddressUse, PersonAddressType, PersonAddressText,
|
||||
PersonAddressLine1, PersonAddressLine2, PersonAddressRegionalCd, PersonAddressRT, PersonAddressRW, PersonAddressCity,
|
||||
PersonAddressDistrict, PersonAddressState, PersonAddressCountry`
|
||||
|
||||
person_identifier_tb := `PersonIdentifierID, PersonIdentifierPersonID, PersonIdentifierUse, PersonIdentifierTypeCode,
|
||||
PersonIdentifierTypeSystem, PersonIdentifierCode, PersonIdentifierSystem, PersonIdentifierValue`
|
||||
|
||||
person_telecom_tb := `PersonTelecomID, PersonTelecomPersonID, PersonTelecomSystem, PersonTelecomValue, PersonTelecomUse`
|
||||
|
||||
offset := (page - 1) * perpage
|
||||
sql := `SELECT ` + patient_tb + `,` + person_tb + `,` + person_identifier_tb + `,` + person_address_tb + `,` + person_telecom_tb +
|
||||
` FROM patient
|
||||
JOIN person ON PersonID = PatientPersonID AND PatientIsActive = 'Y'` + sqlDob + sqlReg + `
|
||||
JOIN person_identifier ON PersonIdentifierPersonID = PersonID` + sqlNIK + `
|
||||
JOIN person_telecom ON PersonTelecomPersonID = PersonID` + sqlhp + `
|
||||
JOIN person_address ON PersonAddressPersonID = PersonID
|
||||
` + sqlName + `
|
||||
LIMIT ? OFFSET ?`
|
||||
|
||||
if err := s.db.Select(&list_patient, sql, perpage, offset); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return list_patient, nil
|
||||
}
|
||||
|
||||
func (s *Store) SearchPatientOld(keyword string, page int, perpage int) ([]types.PatientResult, error) {
|
||||
var list_patient []types.PatientResult
|
||||
// var sqlFilter []string
|
||||
var sqlName, sqlNIK, sqlReg, sqlDob, sqlhp string
|
||||
|
||||
// params nama+nik+noreg+dob+nohp
|
||||
if keyword != "" {
|
||||
params := strings.Split(keyword, "+")
|
||||
if len(params) > 0 && params[0] != "" {
|
||||
// sqlFilter = append(sqlFilter, "PersonName LIKE '%"+params[0]+"%'")
|
||||
sqlName = " AND PersonName LIKE '%" + params[0] + "%' "
|
||||
}
|
||||
if len(params) > 1 && params[1] != "" {
|
||||
// sqlFilter = append(sqlFilter, "PersonIdentifierValue = '"+params[1]+"'")
|
||||
sqlNIK = " AND PersonIdentifierValue = '" + params[1] + "' "
|
||||
}
|
||||
if len(params) > 2 && params[2] != "" {
|
||||
// sqlFilter = append(sqlFilter, "PatientRegNumber = '"+params[2]+"'")
|
||||
sqlReg = " AND PatientRegNumber = '" + params[2] + "' "
|
||||
}
|
||||
if len(params) > 3 && params[3] != "" {
|
||||
// sqlFilter = append(sqlFilter, "PersonBirthDate = '"+params[3]+"'")
|
||||
sqlDob = " AND PersonBirthDate = '" + params[3] + "' "
|
||||
}
|
||||
if len(params) > 4 && params[4] != "" {
|
||||
// sqlFilter = append(sqlFilter, "PersonTelecomValue = '"+params[4]+"'")
|
||||
sqlhp = " AND PersonTelecomValue = '" + params[4] + "' "
|
||||
}
|
||||
}
|
||||
|
||||
patient_tb := `PatientID, PatientPersonID, PatientManaginOrganizationID, PatientHISNumber, PatientRegNumber`
|
||||
|
||||
person_tb := `PersonID, PersonName, PersonSalutation, PersonPrefix, PersonSuffix, PersonGender, PersonBirthPlace, PersonBirthDate,
|
||||
PersonReligionCode, PersonReligionSystem, PersonBloodTypeCode, PersonBloodTypeSystem, PersonRhesusCode, PersonRhesusSystem,
|
||||
PersonEducationCode, PersonEducationSystem, PersonJobClassCode, PersonJobClassSystem, PersonEtnicityCode, PersonEtnicitySystem,
|
||||
PersonMaritalBirth, PersonMaritalStatus`
|
||||
|
||||
person_address_tb := `PersonAddressID, PersonAddressPersonID, PersonAddressIsDefault, PersonAddressUse, PersonAddressType, PersonAddressText,
|
||||
PersonAddressLine1, PersonAddressLine2, PersonAddressRegionalCd, PersonAddressRT, PersonAddressRW, PersonAddressCity,
|
||||
PersonAddressDistrict, PersonAddressState, PersonAddressCountry`
|
||||
|
||||
person_identifier_tb := `PersonIdentifierID, PersonIdentifierPersonID, PersonIdentifierUse, PersonIdentifierTypeCode,
|
||||
PersonIdentifierTypeSystem, PersonIdentifierCode, PersonIdentifierSystem, PersonIdentifierValue`
|
||||
|
||||
person_telecom_tb := `PersonTelecomID, PersonTelecomPersonID, PersonTelecomSystem, PersonTelecomValue, PersonTelecomUse`
|
||||
|
||||
offset := (page - 1) * perpage
|
||||
sql := `SELECT ` + patient_tb + `,` + person_tb + `,` + person_identifier_tb + `,` + person_address_tb + `,` + person_telecom_tb +
|
||||
` FROM patient
|
||||
JOIN person ON PersonID = PatientPersonID AND PatientIsActive = 'Y'` + sqlName + sqlDob + sqlReg + `
|
||||
JOIN person_identifier ON PersonIdentifierPersonID = PersonID` + sqlNIK + `
|
||||
JOIN person_telecom ON PersonTelecomPersonID = PersonID` + sqlhp + `
|
||||
JOIN person_address ON PersonAddressPersonID = PersonID
|
||||
LIMIT ? OFFSET ?`
|
||||
|
||||
// if len(sqlFilter) > 0 {
|
||||
// sql += " AND " + strings.Join(sqlFilter, " AND ")
|
||||
// }
|
||||
// sql += " "
|
||||
|
||||
if err := s.db.Select(&list_patient, sql, perpage, offset); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return list_patient, nil
|
||||
}
|
||||
57
services/person/person.routes.go
Normal file
57
services/person/person.routes.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package person
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"sismedika.com/sas/westone/services/auth"
|
||||
"sismedika.com/sas/westone/types"
|
||||
"sismedika.com/sas/westone/utils"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
store types.PersonStore
|
||||
terminology types.TerminologyStore
|
||||
}
|
||||
|
||||
func NewHandler(store types.PersonStore, terminology types.TerminologyStore) *Handler {
|
||||
return &Handler{store: store, terminology: terminology}
|
||||
}
|
||||
|
||||
func (h *Handler) RegisterRoutes(router *mux.Router) {
|
||||
personroute := router.PathPrefix("/mdperson").Subrouter()
|
||||
personroute.Use(auth.AuthMiddleware)
|
||||
|
||||
personroute.HandleFunc("/get/{personID}", h.handleGetPersonByID).Methods(http.MethodGet)
|
||||
}
|
||||
|
||||
func (h *Handler) handleGetPersonByID(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
param, ok := vars["personID"]
|
||||
if !ok {
|
||||
utils.WriteError(w, http.StatusBadRequest, fmt.Errorf("missing params person id"))
|
||||
return
|
||||
}
|
||||
|
||||
personID, err := strconv.Atoi(param)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusBadRequest, fmt.Errorf("invalid params person id"))
|
||||
return
|
||||
}
|
||||
|
||||
person, err := h.store.GetPersonByID(personID)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
json, err := h.getDisplayTerminology(*person)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
utils.WriteJSON(w, http.StatusOK, json)
|
||||
}
|
||||
66
services/person/person.services.go
Normal file
66
services/person/person.services.go
Normal file
@@ -0,0 +1,66 @@
|
||||
package person
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"sismedika.com/sas/westone/types"
|
||||
"sismedika.com/sas/westone/utils"
|
||||
)
|
||||
|
||||
func (h *Handler) getDisplayTerminology(person types.Person) (*types.PersonJSON, error) {
|
||||
ret := new(types.PersonJSON)
|
||||
err := utils.MatchStruct(person, ret)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if person.PersonBloodTypeCode != "" {
|
||||
blood, err := h.terminology.GetTerminologyDisplay(person.PersonBloodTypeCode, person.PersonBloodTypeSystem)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("blood")
|
||||
}
|
||||
ret.PersonBlood = *blood
|
||||
}
|
||||
|
||||
if person.PersonEducationCode != "" {
|
||||
education, err := h.terminology.GetTerminologyDisplay(person.PersonEducationCode, person.PersonEducationSystem)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("edu")
|
||||
}
|
||||
ret.PersonEducation = *education
|
||||
}
|
||||
|
||||
if person.PersonEtnicityCode != "" {
|
||||
etnicity, err := h.terminology.GetTerminologyDisplay(person.PersonEtnicityCode, person.PersonEtnicitySystem)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("etni")
|
||||
}
|
||||
ret.PersonEtnicity = *etnicity
|
||||
}
|
||||
|
||||
if person.PersonJobClassCode != "" {
|
||||
job, err := h.terminology.GetTerminologyDisplay(person.PersonJobClassCode, person.PersonJobClassSystem)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("job")
|
||||
}
|
||||
ret.PersonJobClass = *job
|
||||
}
|
||||
|
||||
if person.PersonReligionCode != "" {
|
||||
religion, err := h.terminology.GetTerminologyDisplay(person.PersonReligionCode, person.PersonReligionSystem)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reli")
|
||||
}
|
||||
ret.PersonReligion = *religion
|
||||
}
|
||||
|
||||
if person.PersonRhesusCode != "" {
|
||||
rhesus, err := h.terminology.GetTerminologyDisplay(person.PersonRhesusCode, person.PersonRhesusSystem)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("rhes")
|
||||
}
|
||||
ret.PersonRhesus = *rhesus
|
||||
}
|
||||
|
||||
return ret, nil
|
||||
}
|
||||
50
services/person/person.store.go
Normal file
50
services/person/person.store.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package person
|
||||
|
||||
import (
|
||||
"github.com/jmoiron/sqlx"
|
||||
"sismedika.com/sas/westone/types"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
db *sqlx.DB
|
||||
}
|
||||
|
||||
func NewStore(db *sqlx.DB) *Store {
|
||||
return &Store{db: db}
|
||||
}
|
||||
|
||||
func (s *Store) GetPersonByID(id int) (*types.Person, error) {
|
||||
person := new(types.Person)
|
||||
|
||||
qry := `
|
||||
SELECT
|
||||
PersonID,
|
||||
PersonName,
|
||||
PersonSalutation,
|
||||
PersonPrefix,
|
||||
PersonSuffix,
|
||||
PersonGender,
|
||||
PersonBirthPlace,
|
||||
PersonBirthDate,
|
||||
PersonReligionCode,
|
||||
PersonReligionSystem,
|
||||
PersonBloodTypeCode,
|
||||
PersonBloodTypeSystem,
|
||||
PersonRhesusCode,
|
||||
PersonRhesusSystem,
|
||||
PersonEducationCode,
|
||||
PersonEducationSystem,
|
||||
PersonJobClassCode,
|
||||
PersonJobClassSystem,
|
||||
PersonEtnicityCode,
|
||||
PersonEtnicitySystem,
|
||||
PersonMaritalBirth,
|
||||
PersonMaritalStatus
|
||||
FROM person WHERE PersonID = ?
|
||||
`
|
||||
if err := s.db.Get(person, qry, id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return person, nil
|
||||
}
|
||||
84
services/product/routes.go
Normal file
84
services/product/routes.go
Normal file
@@ -0,0 +1,84 @@
|
||||
package product
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gorilla/mux"
|
||||
"sismedika.com/sas/westone/types"
|
||||
"sismedika.com/sas/westone/utils"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
store types.ProductStore
|
||||
userStore types.UserStore
|
||||
}
|
||||
|
||||
func NewHandler(store types.ProductStore, userStore types.UserStore) *Handler {
|
||||
return &Handler{store: store, userStore: userStore}
|
||||
}
|
||||
|
||||
func (h *Handler) RegisterRoutes(router *mux.Router) {
|
||||
router.HandleFunc("/products", h.handleGetProducts).Methods(http.MethodGet)
|
||||
router.HandleFunc("/products/{productID}", h.handleGetProduct).Methods(http.MethodGet)
|
||||
|
||||
// admin routes
|
||||
// router.HandleFunc("/products", auth.WithJWTAuth(h.handleCreateProduct)).Methods(http.MethodPost)
|
||||
}
|
||||
|
||||
func (h *Handler) handleGetProducts(w http.ResponseWriter, r *http.Request) {
|
||||
products, err := h.store.GetProducts()
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
utils.WriteJSON(w, http.StatusOK, products)
|
||||
}
|
||||
|
||||
func (h *Handler) handleGetProduct(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
str, ok := vars["productID"]
|
||||
if !ok {
|
||||
utils.WriteError(w, http.StatusBadRequest, fmt.Errorf("missing product ID"))
|
||||
return
|
||||
}
|
||||
|
||||
productID, err := strconv.Atoi(str)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusBadRequest, fmt.Errorf("invalid product ID"))
|
||||
return
|
||||
}
|
||||
|
||||
product, err := h.store.GetProductByID(productID)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
utils.WriteJSON(w, http.StatusOK, product)
|
||||
}
|
||||
|
||||
func (h *Handler) handleCreateProduct(w http.ResponseWriter, r *http.Request) {
|
||||
var product types.CreateProductPayload
|
||||
if err := utils.ParseJSON(r, &product); err != nil {
|
||||
utils.WriteError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := utils.Validate.Struct(product); err != nil {
|
||||
errors := err.(validator.ValidationErrors)
|
||||
utils.WriteError(w, http.StatusBadRequest, fmt.Errorf("invalid payload: %v", errors))
|
||||
return
|
||||
}
|
||||
|
||||
err := h.store.CreateProduct(product)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
utils.WriteJSON(w, http.StatusCreated, product)
|
||||
}
|
||||
157
services/product/routes_test.go
Normal file
157
services/product/routes_test.go
Normal file
@@ -0,0 +1,157 @@
|
||||
package product
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"sismedika.com/sas/westone/types"
|
||||
)
|
||||
|
||||
func TestProductServiceHandlers(t *testing.T) {
|
||||
productStore := &mockProductStore{}
|
||||
userStore := &mockUserStore{}
|
||||
handler := NewHandler(productStore, userStore)
|
||||
|
||||
t.Run("should handle get products", func(t *testing.T) {
|
||||
req, err := http.NewRequest(http.MethodGet, "/products", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
router := mux.NewRouter()
|
||||
|
||||
router.HandleFunc("/products", handler.handleGetProducts).Methods(http.MethodGet)
|
||||
|
||||
router.ServeHTTP(rr, req)
|
||||
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Errorf("expected status code %d, got %d", http.StatusOK, rr.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("should fail if the product ID is not a number", func(t *testing.T) {
|
||||
req, err := http.NewRequest(http.MethodGet, "/products/abc", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
router := mux.NewRouter()
|
||||
|
||||
router.HandleFunc("/products/{productID}", handler.handleGetProduct).Methods(http.MethodGet)
|
||||
|
||||
router.ServeHTTP(rr, req)
|
||||
|
||||
if rr.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected status code %d, got %d", http.StatusBadRequest, rr.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("should handle get product by ID", func(t *testing.T) {
|
||||
req, err := http.NewRequest(http.MethodGet, "/products/42", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
router := mux.NewRouter()
|
||||
|
||||
router.HandleFunc("/products/{productID}", handler.handleGetProduct).Methods(http.MethodGet)
|
||||
|
||||
router.ServeHTTP(rr, req)
|
||||
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Errorf("expected status code %d, got %d", http.StatusOK, rr.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("should fail creating a product if the payload is missing", func(t *testing.T) {
|
||||
req, err := http.NewRequest(http.MethodPost, "/products", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
router := mux.NewRouter()
|
||||
|
||||
router.HandleFunc("/products", handler.handleCreateProduct).Methods(http.MethodPost)
|
||||
|
||||
router.ServeHTTP(rr, req)
|
||||
|
||||
if rr.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected status code %d, got %d", http.StatusBadRequest, rr.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("should handle creating a product", func(t *testing.T) {
|
||||
payload := types.CreateProductPayload{
|
||||
Name: "test",
|
||||
Price: 100,
|
||||
Image: "test.jpg",
|
||||
Description: "test description",
|
||||
Quantity: 10,
|
||||
}
|
||||
|
||||
marshalled, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, "/products", bytes.NewBuffer(marshalled))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
router := mux.NewRouter()
|
||||
|
||||
router.HandleFunc("/products", handler.handleCreateProduct).Methods(http.MethodPost)
|
||||
|
||||
router.ServeHTTP(rr, req)
|
||||
|
||||
if rr.Code != http.StatusCreated {
|
||||
t.Errorf("expected status code %d, got %d", http.StatusCreated, rr.Code)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
type mockProductStore struct{}
|
||||
|
||||
func (m *mockProductStore) GetProductByID(productID int) (*types.Product, error) {
|
||||
return &types.Product{}, nil
|
||||
}
|
||||
|
||||
func (m *mockProductStore) GetProducts() ([]*types.Product, error) {
|
||||
return []*types.Product{}, nil
|
||||
}
|
||||
|
||||
func (m *mockProductStore) CreateProduct(product types.CreateProductPayload) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockProductStore) UpdateProduct(product types.Product) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockProductStore) GetProductsByID(ids []int) ([]types.Product, error) {
|
||||
return []types.Product{}, nil
|
||||
}
|
||||
|
||||
type mockUserStore struct{}
|
||||
|
||||
func (m *mockUserStore) GetUserByID(userID int) (*types.User, error) {
|
||||
return &types.User{}, nil
|
||||
}
|
||||
|
||||
func (m *mockUserStore) CreateUser(user types.User) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockUserStore) SignIn(email string, password string) (*types.User, error) {
|
||||
return &types.User{}, nil
|
||||
}
|
||||
101
services/product/store.go
Normal file
101
services/product/store.go
Normal file
@@ -0,0 +1,101 @@
|
||||
package product
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
"sismedika.com/sas/westone/types"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
db *sqlx.DB
|
||||
}
|
||||
|
||||
func NewStore(db *sqlx.DB) *Store {
|
||||
return &Store{db: db}
|
||||
}
|
||||
|
||||
func (s *Store) GetProductByID(productID int) (*types.Product, error) {
|
||||
product := new(types.Product)
|
||||
query := "SELECT * FROM products WHERE id = ?"
|
||||
|
||||
// sqlx.Get is used for fetching a single record and scanning it into the struct
|
||||
if err := s.db.Get(product, query, productID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return product, nil
|
||||
}
|
||||
|
||||
func (s *Store) GetProductsByID(productIDs []int) ([]types.Product, error) {
|
||||
query, args, err := sqlx.In("SELECT * FROM products WHERE id IN (?)", productIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Rebind the query for the specific database driver (e.g., mysql uses "?", postgres uses "$1", etc.)
|
||||
query = s.db.Rebind(query)
|
||||
|
||||
var products []types.Product
|
||||
err = s.db.Select(&products, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return products, nil
|
||||
}
|
||||
|
||||
func (s *Store) GetProducts() ([]*types.Product, error) {
|
||||
var products []*types.Product
|
||||
query := "SELECT * FROM products"
|
||||
|
||||
// sqlx.Select is used to fetch multiple rows and map them into a slice of structs
|
||||
if err := s.db.Select(&products, query); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return products, nil
|
||||
}
|
||||
|
||||
func (s *Store) CreateProduct(product types.CreateProductPayload) error {
|
||||
query := `INSERT INTO products (name, price, image, description, quantity)
|
||||
VALUES (:name, :price, :image, :description, :quantity)`
|
||||
|
||||
// Using sqlx.NamedExec to map struct fields to named parameters in the query
|
||||
_, err := s.db.NamedExec(query, product)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
func (s *Store) UpdateProduct(product types.Product) error {
|
||||
// Start a new transaction
|
||||
tx, err := s.db.BeginTxx(context.Background(), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Defer rollback to ensure transaction is rolled back in case of an error
|
||||
defer func() {
|
||||
if err != nil {
|
||||
tx.Rollback()
|
||||
}
|
||||
}()
|
||||
|
||||
query := `UPDATE products SET name = :name, price = :price, image = :image,
|
||||
description = :description, quantity = :quantity WHERE id = :id`
|
||||
|
||||
// Using tx.NamedExec to execute the update within the transaction
|
||||
_, err = tx.NamedExec(query, product)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Commit the transaction if everything succeeded
|
||||
if err = tx.Commit(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
54
services/terminology/terminology.routes.go
Normal file
54
services/terminology/terminology.routes.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package terminology
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gorilla/mux"
|
||||
"sismedika.com/sas/westone/services/auth"
|
||||
"sismedika.com/sas/westone/types"
|
||||
"sismedika.com/sas/westone/utils"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
store types.TerminologyStore
|
||||
}
|
||||
|
||||
func NewHandler(store types.TerminologyStore) *Handler {
|
||||
return &Handler{store: store}
|
||||
}
|
||||
|
||||
func (h *Handler) RegisterRoutes(router *mux.Router) {
|
||||
router.HandleFunc("/termicheck", h.checkAPI).Methods(http.MethodGet)
|
||||
termi := router.PathPrefix("/terminology").Subrouter()
|
||||
termi.Use(auth.AuthMiddleware)
|
||||
|
||||
termi.HandleFunc("/getdisplay", h.handleTerminologyDisplay).Methods(http.MethodGet)
|
||||
}
|
||||
|
||||
func (h *Handler) checkAPI(w http.ResponseWriter, _ *http.Request) {
|
||||
utils.WriteJSON(w, http.StatusOK, "Connected")
|
||||
}
|
||||
|
||||
func (h *Handler) handleTerminologyDisplay(w http.ResponseWriter, r *http.Request) {
|
||||
var payload types.GetTerminologyDisplayPayload
|
||||
if err := utils.ParseJSON(r, &payload); err != nil {
|
||||
utils.WriteError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := utils.Validate.Struct(payload); err != nil {
|
||||
erros := err.(validator.ValidationErrors)
|
||||
utils.WriteError(w, http.StatusBadRequest, fmt.Errorf("invalid payload: %v", erros))
|
||||
return
|
||||
}
|
||||
|
||||
response, err := h.store.GetTerminologyDisplay(payload.Code, payload.CodeSystem)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
utils.WriteJSON(w, http.StatusOK, response)
|
||||
}
|
||||
29
services/terminology/terminology.store.go
Normal file
29
services/terminology/terminology.store.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package terminology
|
||||
|
||||
import (
|
||||
"github.com/jmoiron/sqlx"
|
||||
"sismedika.com/sas/westone/types"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
db *sqlx.DB
|
||||
}
|
||||
|
||||
func NewStore(db *sqlx.DB) *Store {
|
||||
return &Store{db: db}
|
||||
}
|
||||
|
||||
func (s *Store) GetTerminologyDisplay(code string, system string) (*types.CodeableTerminology, error) {
|
||||
term := new(types.CodeableTerminology)
|
||||
|
||||
qry := `
|
||||
SELECT code, display, code_system
|
||||
FROM terminology
|
||||
WHERE code = ? AND code_system = ?
|
||||
`
|
||||
if err := s.db.Get(term, qry, code, system); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return term, nil
|
||||
}
|
||||
123
services/user/user.routes.go
Normal file
123
services/user/user.routes.go
Normal file
@@ -0,0 +1,123 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/gorilla/mux"
|
||||
"sismedika.com/sas/westone/services/auth"
|
||||
"sismedika.com/sas/westone/types"
|
||||
"sismedika.com/sas/westone/utils"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
store types.UserStore
|
||||
errorStore types.ErrorLogStore
|
||||
}
|
||||
|
||||
func NewHandler(store types.UserStore, errorStore types.ErrorLogStore) *Handler {
|
||||
return &Handler{
|
||||
store: store,
|
||||
errorStore: errorStore,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) RegisterRoutes(router *mux.Router) {
|
||||
router.HandleFunc("/login", h.handleLogin).Methods("POST")
|
||||
router.HandleFunc("/register", h.handleRegister).Methods("POST")
|
||||
|
||||
// admin routes
|
||||
// router.HandleFunc("/users/{userID}", auth.WithJWTAuth(h.handleGetUser)).Methods(http.MethodGet)
|
||||
}
|
||||
|
||||
func (h *Handler) handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
// var payload types.SignInPayload
|
||||
// if err := utils.ParseJSON(r, &payload); err != nil {
|
||||
// utils.WriteError(w, http.StatusBadRequest, err)
|
||||
// return
|
||||
// }
|
||||
|
||||
// if err := utils.Validate.Struct(payload); err != nil {
|
||||
// errors := err.(validator.ValidationErrors)
|
||||
// utils.WriteError(w, http.StatusBadRequest, fmt.Errorf("invalid payload: %v", errors))
|
||||
// return
|
||||
// }
|
||||
|
||||
// hashedPassword := auth.HashWithMD5(payload.Password)
|
||||
// response, err := h.store.SignIn(payload.Email, hashedPassword)
|
||||
// if err != nil {
|
||||
// var logError *utils.LogError
|
||||
// if errors.As(err, &logError) {
|
||||
// h.errorStore.CreateErrorLog(*logError)
|
||||
// utils.WriteErrorLog(w, http.StatusBadRequest, *logError)
|
||||
// }
|
||||
// return
|
||||
// }
|
||||
// // remoteAddr := r.RemoteAddr
|
||||
// // userAgent := r.UserAgent()
|
||||
// // response.IP = remoteAddr
|
||||
// // response.Agent = userAgent
|
||||
|
||||
// secret := []byte(configs.Envs.JWTSecret)
|
||||
// token, err := auth.CreateJWT(secret, *response)
|
||||
// if err != nil {
|
||||
// utils.WriteError(w, http.StatusInternalServerError, err)
|
||||
// return
|
||||
// }
|
||||
|
||||
// utils.WriteJSONLogin(w, http.StatusOK, response, token, "westone")
|
||||
}
|
||||
|
||||
func (h *Handler) handleRegister(w http.ResponseWriter, r *http.Request) {
|
||||
// var user types.RegisterUserPayload
|
||||
// if err := utils.ParseJSON(r, &user); err != nil {
|
||||
// utils.WriteError(w, http.StatusBadRequest, err)
|
||||
// return
|
||||
// }
|
||||
|
||||
// if err := utils.Validate.Struct(user); err != nil {
|
||||
// errors := err.(validator.ValidationErrors)
|
||||
// utils.WriteError(w, http.StatusBadRequest, fmt.Errorf("invalid payload: %v", errors))
|
||||
// return
|
||||
// }
|
||||
|
||||
// // check if user exists
|
||||
// _, err := h.store.GetUserByEmail(user.Email)
|
||||
// if err == nil {
|
||||
// utils.WriteError(w, http.StatusBadRequest, fmt.Errorf("user with email %s already exists", user.Email))
|
||||
// return
|
||||
// }
|
||||
|
||||
// // hash password
|
||||
// hashedPassword, err := auth.HashPassword(user.Password)
|
||||
// if err != nil {
|
||||
// utils.WriteError(w, http.StatusInternalServerError, err)
|
||||
// return
|
||||
// }
|
||||
|
||||
// err = h.store.CreateUser(types.User{
|
||||
// FirstName: user.FirstName,
|
||||
// LastName: user.LastName,
|
||||
// Email: user.Email,
|
||||
// Password: hashedPassword,
|
||||
// })
|
||||
// if err != nil {
|
||||
// utils.WriteError(w, http.StatusInternalServerError, err)
|
||||
// return
|
||||
// }
|
||||
|
||||
// utils.WriteJSON(w, http.StatusCreated, nil)
|
||||
}
|
||||
|
||||
func (h *Handler) handleGetUser(w http.ResponseWriter, r *http.Request) {
|
||||
claims, ok := r.Context().Value(auth.UserContextKey).(jwt.MapClaims)
|
||||
if !ok {
|
||||
utils.WriteError(w, http.StatusInternalServerError, fmt.Errorf("token not found in context"))
|
||||
return
|
||||
}
|
||||
|
||||
email := claims["M_UserEmail"]
|
||||
|
||||
utils.WriteJSON(w, http.StatusOK, email)
|
||||
}
|
||||
77
services/user/user.routes_test.go
Normal file
77
services/user/user.routes_test.go
Normal file
@@ -0,0 +1,77 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"sismedika.com/sas/westone/types"
|
||||
"sismedika.com/sas/westone/utils"
|
||||
)
|
||||
|
||||
func TestUserServiceHandlers(t *testing.T) {
|
||||
userStore := &mockUserStore{}
|
||||
errorStore := &mockErrorLogStore{}
|
||||
handler := NewHandler(userStore, errorStore)
|
||||
|
||||
t.Run("should fail if the user ID is not a number", func(t *testing.T) {
|
||||
req, err := http.NewRequest(http.MethodGet, "/user/abc", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
router := mux.NewRouter()
|
||||
|
||||
router.HandleFunc("/user/{userID}", handler.handleGetUser).Methods(http.MethodGet)
|
||||
|
||||
router.ServeHTTP(rr, req)
|
||||
|
||||
if rr.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected status code %d, got %d", http.StatusBadRequest, rr.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("should handle get user by ID", func(t *testing.T) {
|
||||
req, err := http.NewRequest(http.MethodGet, "/user/42", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
router := mux.NewRouter()
|
||||
|
||||
router.HandleFunc("/user/{userID}", handler.handleGetUser).Methods(http.MethodGet)
|
||||
|
||||
router.ServeHTTP(rr, req)
|
||||
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Errorf("expected status code %d, got %d", http.StatusOK, rr.Code)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
type mockUserStore struct{}
|
||||
|
||||
func (m *mockUserStore) UpdateUser(u types.User) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockUserStore) SignIn(email string, password string) (*types.User, error) {
|
||||
return &types.User{}, nil
|
||||
}
|
||||
|
||||
func (m *mockUserStore) CreateUser(u types.User) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockUserStore) GetUserByID(id int) (*types.User, error) {
|
||||
return &types.User{}, nil
|
||||
}
|
||||
|
||||
type mockErrorLogStore struct{}
|
||||
|
||||
func (n *mockErrorLogStore) CreateErrorLog(errval utils.LogError) error {
|
||||
return nil
|
||||
}
|
||||
70
services/user/user.store.go
Normal file
70
services/user/user.store.go
Normal file
@@ -0,0 +1,70 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"github.com/jmoiron/sqlx"
|
||||
"sismedika.com/sas/westone/types"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
db *sqlx.DB
|
||||
}
|
||||
|
||||
func NewStore(db *sqlx.DB) *Store {
|
||||
return &Store{db: db}
|
||||
}
|
||||
func (s *Store) CreateUser(user types.User) error {
|
||||
// Start a new transaction
|
||||
// tx, err := s.db.BeginTxx(context.Background(), nil)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
|
||||
// // Defer rollback to ensure the transaction is rolled back in case of an error
|
||||
// defer func() {
|
||||
// if err != nil {
|
||||
// tx.Rollback()
|
||||
// }
|
||||
// }()
|
||||
|
||||
// query := `INSERT INTO users (firstName, lastName, email, password)
|
||||
// VALUES (:firstName, :lastName, :email, :password)`
|
||||
|
||||
// // Using tx.NamedExec to insert the user within the transaction
|
||||
// _, err = tx.NamedExec(query, user)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
|
||||
// // Commit the transaction if everything succeeded
|
||||
// if err = tx.Commit(); err != nil {
|
||||
// return err
|
||||
// }
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) GetUserByID(id int) (*types.User, error) {
|
||||
user := new(types.User)
|
||||
|
||||
qryget := `
|
||||
SELECT
|
||||
M_UserID,
|
||||
M_UserEmail,
|
||||
M_UserEmail as M_UserUsername,
|
||||
M_UserGroupDashboard,
|
||||
1 as M_UserDefaultT_SampleStationID,
|
||||
IFNULL(M_UserFullName, "") as M_StaffName,
|
||||
IFNULL(M_StaffIsCourier, "N") as is_courier,
|
||||
IFNULL(S_SystemsAutoLogoutTime,0) as time_autologout
|
||||
FROM m_user
|
||||
JOIN m_usergroup ON M_UserM_UserGroupID = M_UserGroupID
|
||||
LEFT JOIN m_staff on M_UserM_StaffID = M_StaffID
|
||||
JOIN conf_systems ON S_SystemsIsActive = 'Y'
|
||||
WHERE M_UserID = ?
|
||||
`
|
||||
if err := s.db.Get(user, qryget, id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
36
types/doctor.types.go
Normal file
36
types/doctor.types.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package types
|
||||
|
||||
type DoctorStore interface {
|
||||
SearchDoctor(keyword string, page int, perpage int) ([]DoctorResult, error)
|
||||
}
|
||||
|
||||
type Doctor struct {
|
||||
DoctorID int `json:"DoctorID" db:"DoctorID"`
|
||||
DoctorCode string `json:"DoctorCode" db:"DoctorCode"`
|
||||
DoctorIHSNumber string `json:"DoctorIHSNumber" db:"DoctorIHSNumber"`
|
||||
DoctorPersonID int `json:"DoctorPersonID" db:"DoctorPersonID"`
|
||||
}
|
||||
|
||||
type DoctorJSON struct {
|
||||
DoctorID int `json:"DoctorID" db:"DoctorID"`
|
||||
DoctorCode string `json:"DoctorCode" db:"DoctorCode"`
|
||||
DoctorIHSNumber string `json:"DoctorIHSNumber" db:"DoctorIHSNumber"`
|
||||
DoctorPersonID int `json:"DoctorPersonID" db:"DoctorPersonID"`
|
||||
PersonName string `json:"PersonName" db:"PersonName"`
|
||||
PersonBirthDate string `json:"PersonBirthDate" db:"PersonBirthDate"`
|
||||
PersonIdentifierValue string `json:"PersonIdentifierValue" db:"PersonIdentifierValue"`
|
||||
}
|
||||
|
||||
type SearchDoctorPayload struct {
|
||||
Keyword string `json:"keyword"`
|
||||
Page int `json:"page" validate:"required"`
|
||||
Perpage int `json:"perpage" validate:"required"`
|
||||
}
|
||||
|
||||
type DoctorResult struct {
|
||||
Doctor
|
||||
Person
|
||||
PersonIdentifier
|
||||
PersonAddress
|
||||
PersonTelecom
|
||||
}
|
||||
57
types/oauth.types.go
Normal file
57
types/oauth.types.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package types
|
||||
|
||||
import "github.com/markbates/goth"
|
||||
|
||||
type OauthStore interface {
|
||||
AddGoolgeAccount(user UserGoogle) error
|
||||
CheckGoogleAccountLinked(user UserGoogle) (int, error)
|
||||
GenerateAuthCode(email string, jenis string, userid int) error
|
||||
CompareAuthCode(authcode string, user goth.User, typez string) (int, error)
|
||||
SignInWestone(email string, password string) (*User, error)
|
||||
LogSignIn(email string, ip string, status string, tipe string, provider string) error
|
||||
}
|
||||
|
||||
type UserGoogle struct {
|
||||
M_UserGoogleID int `json:"M_UserGoogleID" db:"M_UserGoogleID"`
|
||||
M_UserGoogleM_UserID int `json:"M_UserGoogleM_UserID" db:"M_UserGoogleM_UserID"`
|
||||
M_UserGoogleEmail string `json:"M_UserGoogleEmail" db:"M_UserGoogleEmail"`
|
||||
M_UserGoogleIdentifier string `json:"M_UserGoogleIdentifier" db:"M_UserGoogleIdentifier"`
|
||||
M_UserGoogleCode string `json:"M_UserGoogleCode" db:"M_UserGoogleCode"`
|
||||
M_UserGoogleToken string `json:"M_UserGoogleToken" db:"M_UserGoogleToken"`
|
||||
M_UserGoogleIsActive string `json:"M_UserGoogleIsActive" db:"M_UserGoogleIsActive"`
|
||||
}
|
||||
|
||||
type AuthCode struct {
|
||||
AuthCodeID int `json:"AuthCodeID" db:"AuthCodeID"`
|
||||
AuthCodeMUserID int `json:"AuthCodeMUserID" db:"AuthCodeMUserID"`
|
||||
AuthCodeUser string `json:"AuthCodeUser" db:"AuthCodeUser"`
|
||||
AuthCodeType string `json:"AuthCodeType" db:"AuthCodeType"`
|
||||
AuthCodeCode string `json:"AuthCodeCode" db:"AuthCodeCode"`
|
||||
AuthCodeIsUsed string `json:"AuthCodeIsUsed" db:"AuthCodeIsUsed"`
|
||||
}
|
||||
|
||||
type AuthCodePayload struct {
|
||||
Code string `json:"code" validate:"required"`
|
||||
}
|
||||
|
||||
type GenerateAuthCode struct {
|
||||
Email string `json:"email" validate:"required"`
|
||||
Types string `json:"type" validate:"required"`
|
||||
UserID int `json:"userid" validate:"required"`
|
||||
}
|
||||
|
||||
type SignInPayload struct {
|
||||
Email string `json:"email" validate:"required,email"`
|
||||
Password string `json:"password" validate:"required,min=6,max=130"`
|
||||
}
|
||||
|
||||
type LogLogin struct {
|
||||
LogLoginMUserEmail string `db:"Log_LoginM_UserEmail" json:"logLoginMUserEmail"`
|
||||
LogLoginDateTime string `db:"Log_LoginDateTime" json:"logLoginDateTime"`
|
||||
LogLoginIP string `db:"Log_LoginIP" json:"logLoginIP"`
|
||||
LogLoginType string `db:"Log_LoginType" json:"logLoginType"`
|
||||
LogLoginStatus string `db:"Log_LoginStatus" json:"logLoginStatus"`
|
||||
LogLoginLogin string `db:"Log_LoginLogin" json:"logLoginLogin"`
|
||||
LogLoginIsActive string `db:"Log_LoginIsActive" json:"logLoginIsActive"`
|
||||
LogLoginLastUpdated string `db:"Log_LoginLastUpdated" json:"logLoginLastUpdated"`
|
||||
}
|
||||
26
types/patient.types.go
Normal file
26
types/patient.types.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package types
|
||||
|
||||
type PatientStore interface {
|
||||
SearchPatient(keyword string, page int, perpage int) ([]PatientResult, error)
|
||||
SearchPatientOld(keyword string, page int, perpage int) ([]PatientResult, error)
|
||||
}
|
||||
type Patient struct {
|
||||
PatientID int `json:"PatientID" db:"PatientID"`
|
||||
PatientPersonID int `json:"PatientPersonID" db:"PatientPersonID"`
|
||||
PatientManaginOrganizationID int `json:"PatientManaginOrganizationID" db:"PatientManaginOrganizationID"`
|
||||
PatientHISNumber string `json:"PatientHISNumber" db:"PatientHISNumber"`
|
||||
PatientRegNumber string `json:"PatientRegNumber" db:"PatientRegNumber"`
|
||||
}
|
||||
|
||||
type SearchPatientPayload struct {
|
||||
Keyword string `json:"keyword"`
|
||||
Page int `json:"page" validate:"required"`
|
||||
Perpage int `json:"perpage" validate:"required"`
|
||||
}
|
||||
type PatientResult struct {
|
||||
Patient
|
||||
Person
|
||||
PersonIdentifier
|
||||
PersonAddress
|
||||
PersonTelecom
|
||||
}
|
||||
86
types/person.types.go
Normal file
86
types/person.types.go
Normal file
@@ -0,0 +1,86 @@
|
||||
package types
|
||||
|
||||
type PersonStore interface {
|
||||
GetPersonByID(id int) (*Person, error)
|
||||
}
|
||||
|
||||
type Person struct {
|
||||
PersonID int `json:"PersonID" db:"PersonID"`
|
||||
PersonName string `json:"PersonName" db:"PersonName"`
|
||||
PersonSalutation string `json:"PersonSalutation" db:"PersonSalutation"`
|
||||
PersonPrefix string `json:"PersonPrefix" db:"PersonPrefix"`
|
||||
PersonSuffix string `json:"PersonSuffix" db:"PersonSuffix"`
|
||||
PersonGender string `json:"PersonGender" db:"PersonGender"`
|
||||
PersonBirthPlace string `json:"PersonBirthPlace" db:"PersonBirthPlace"`
|
||||
PersonBirthDate string `json:"PersonBirthDate" db:"PersonBirthDate"`
|
||||
PersonReligionCode string `json:"PersonReligionCode" db:"PersonReligionCode"`
|
||||
PersonReligionSystem string `json:"PersonReligionSystem" db:"PersonReligionSystem"`
|
||||
PersonBloodTypeCode string `json:"PersonBloodTypeCode" db:"PersonBloodTypeCode"`
|
||||
PersonBloodTypeSystem string `json:"PersonBloodTypeSystem" db:"PersonBloodTypeSystem"`
|
||||
PersonRhesusCode string `json:"PersonRhesusCode" db:"PersonRhesusCode"`
|
||||
PersonRhesusSystem string `json:"PersonRhesusSystem" db:"PersonRhesusSystem"`
|
||||
PersonEducationCode string `json:"PersonEducationCode" db:"PersonEducationCode"`
|
||||
PersonEducationSystem string `json:"PersonEducationSystem" db:"PersonEducationSystem"`
|
||||
PersonJobClassCode string `json:"PersonJobClassCode" db:"PersonJobClassCode"`
|
||||
PersonJobClassSystem string `json:"PersonJobClassSystem" db:"PersonJobClassSystem"`
|
||||
PersonEtnicityCode string `json:"PersonEtnicityCode" db:"PersonEtnicityCode"`
|
||||
PersonEtnicitySystem string `json:"PersonEtnicitySystem" db:"PersonEtnicitySystem"`
|
||||
PersonMaritalBirth string `json:"PersonMaritalBirth" db:"PersonMaritalBirth"`
|
||||
PersonMaritalStatus string `json:"PersonMaritalStatus" db:"PersonMaritalStatus"`
|
||||
}
|
||||
|
||||
type PersonJSON struct {
|
||||
PersonID int `json:"PersonID" db:"PersonID"`
|
||||
PersonName string `json:"PersonName" db:"PersonName"`
|
||||
PersonSalutation string `json:"PersonSalutation" db:"PersonSalutation"`
|
||||
PersonPrefix string `json:"PersonPrefix" db:"PersonPrefix"`
|
||||
PersonSuffix string `json:"PersonSuffix" db:"PersonSuffix"`
|
||||
PersonGender string `json:"PersonGender" db:"PersonGender"`
|
||||
PersonBirthPlace string `json:"PersonBirthPlace" db:"PersonBirthPlace"`
|
||||
PersonBirthDate string `json:"PersonBirthDate" db:"PersonBirthDate"`
|
||||
PersonReligion CodeableTerminology `json:"PersonReligion"`
|
||||
PersonBlood CodeableTerminology `json:"PersonBlood"`
|
||||
PersonRhesus CodeableTerminology `json:"PersonRhesus"`
|
||||
PersonEducation CodeableTerminology `json:"PersonEducation"`
|
||||
PersonJobClass CodeableTerminology `json:"PersonJobClass"`
|
||||
PersonEtnicity CodeableTerminology `json:"PersonEtnicity"`
|
||||
PersonMaritalBirth string `json:"PersonMaritalBirth" db:"PersonMaritalBirth"`
|
||||
PersonMaritalStatus string `json:"PersonMaritalStatus" db:"PersonMaritalStatus"`
|
||||
}
|
||||
|
||||
type PersonIdentifier struct {
|
||||
PersonIdentifierID int `json:"PersonIdentifierID" db:"PersonIdentifierID"`
|
||||
PersonIdentifierPersonID int `json:"PersonIdentifierPersonID" db:"PersonIdentifierPersonID"`
|
||||
PersonIdentifierUse string `json:"PersonIdentifierUse" db:"PersonIdentifierUse"`
|
||||
PersonIdentifierTypeCode string `json:"PersonIdentifierTypeCode" db:"PersonIdentifierTypeCode"`
|
||||
PersonIdentifierTypeSystem string `json:"PersonIdentifierTypeSystem" db:"PersonIdentifierTypeSystem"`
|
||||
PersonIdentifierCode string `json:"PersonIdentifierCode" db:"PersonIdentifierCode"`
|
||||
PersonIdentifierSystem string `json:"PersonIdentifierSystem" db:"PersonIdentifierSystem"`
|
||||
PersonIdentifierValue string `json:"PersonIdentifierValue" db:"PersonIdentifierValue"`
|
||||
}
|
||||
|
||||
type PersonAddress struct {
|
||||
PersonAddressID int `json:"PersonAddressID" db:"PersonAddressID"`
|
||||
PersonAddressPersonID int `json:"PersonAddressPersonID" db:"PersonAddressPersonID"`
|
||||
PersonAddressIsDefault string `json:"PersonAddressIsDefault" db:"PersonAddressIsDefault"`
|
||||
PersonAddressUse string `json:"PersonAddressUse" db:"PersonAddressUse"`
|
||||
PersonAddressType string `json:"PersonAddressType" db:"PersonAddressType"`
|
||||
PersonAddressText string `json:"PersonAddressText" db:"PersonAddressText"`
|
||||
PersonAddressLine1 string `json:"PersonAddressLine1" db:"PersonAddressLine1"`
|
||||
PersonAddressLine2 string `json:"PersonAddressLine2" db:"PersonAddressLine2"`
|
||||
PersonAddressRegionalCd string `json:"PersonAddressRegionalCd" db:"PersonAddressRegionalCd"`
|
||||
PersonAddressRT string `json:"PersonAddressRT" db:"PersonAddressRT"`
|
||||
PersonAddressRW string `json:"PersonAddressRW" db:"PersonAddressRW"`
|
||||
PersonAddressCity string `json:"PersonAddressCity" db:"PersonAddressCity"`
|
||||
PersonAddressDistrict string `json:"PersonAddressDistrict" db:"PersonAddressDistrict"`
|
||||
PersonAddressState string `json:"PersonAddressState" db:"PersonAddressState"`
|
||||
PersonAddressCountry string `json:"PersonAddressCountry" db:"PersonAddressCountry"`
|
||||
}
|
||||
|
||||
type PersonTelecom struct {
|
||||
PersonTelecomID int `json:"PersonTelecomID" db:"PersonTelecomID"`
|
||||
PersonTelecomPersonID int `json:"PersonTelecomPersonID" db:"PersonTelecomPersonID"`
|
||||
PersonTelecomSystem string `json:"PersonTelecomSystem" db:"PersonTelecomSystem"`
|
||||
PersonTelecomValue string `json:"PersonTelecomValue" db:"PersonTelecomValue"`
|
||||
PersonTelecomUse string `json:"PersonTelecomUse" db:"PersonTelecomUse"`
|
||||
}
|
||||
16
types/terminology.types.go
Normal file
16
types/terminology.types.go
Normal file
@@ -0,0 +1,16 @@
|
||||
package types
|
||||
|
||||
type TerminologyStore interface {
|
||||
GetTerminologyDisplay(code string, system string) (*CodeableTerminology, error)
|
||||
}
|
||||
|
||||
type CodeableTerminology struct {
|
||||
CodeSystem string `json:"CodeSystem" db:"code_system"`
|
||||
Code string `json:"Code" db:"code"`
|
||||
Display string `json:"Display" db:"display"`
|
||||
}
|
||||
|
||||
type GetTerminologyDisplayPayload struct {
|
||||
Code string `json:"code" validate:"required"`
|
||||
CodeSystem string `json:"codesystem" validate:"required"`
|
||||
}
|
||||
74
types/types.go
Normal file
74
types/types.go
Normal file
@@ -0,0 +1,74 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"sismedika.com/sas/westone/utils"
|
||||
)
|
||||
|
||||
type Product struct {
|
||||
ID int `db:"id" json:"id"`
|
||||
Name string `db:"name" json:"name"`
|
||||
Description string `db:"description" json:"description"`
|
||||
Image string `db:"image" json:"image"`
|
||||
Price float64 `db:"price" json:"price"`
|
||||
Quantity int `db:"quantity" json:"quantity"`
|
||||
CreatedAt time.Time `db:"createdAt" json:"createdAt"`
|
||||
}
|
||||
|
||||
type CartCheckoutItem struct {
|
||||
ProductID int `db:"productID" json:"productID"`
|
||||
Quantity int `db:"quantity" json:"quantity"`
|
||||
}
|
||||
|
||||
type Order struct {
|
||||
ID int `db:"id" json:"id"`
|
||||
UserID int `db:"userID" json:"userID"`
|
||||
Total float64 `db:"total" json:"total"`
|
||||
Status string `db:"status" json:"status"`
|
||||
Address string `db:"address" json:"address"`
|
||||
CreatedAt time.Time `db:"createdAt" json:"createdAt"`
|
||||
}
|
||||
|
||||
type OrderItem struct {
|
||||
ID int `db:"id" json:"id"`
|
||||
OrderID int `db:"orderID" json:"orderID"`
|
||||
ProductID int `db:"productID" json:"productID"`
|
||||
Quantity int `db:"quantity" json:"quantity"`
|
||||
Price float64 `db:"price" json:"price"`
|
||||
CreatedAt time.Time `db:"createdAt" json:"createdAt"`
|
||||
}
|
||||
|
||||
type ProductStore interface {
|
||||
GetProductByID(id int) (*Product, error)
|
||||
GetProductsByID(ids []int) ([]Product, error)
|
||||
GetProducts() ([]*Product, error)
|
||||
CreateProduct(CreateProductPayload) error
|
||||
UpdateProduct(Product) error
|
||||
}
|
||||
|
||||
type OrderStore interface {
|
||||
CreateOrder(Order) (int, error)
|
||||
CreateOrderItem(OrderItem) error
|
||||
}
|
||||
type CreateProductPayload struct {
|
||||
Name string `json:"name" validate:"required"`
|
||||
Description string `json:"description"`
|
||||
Image string `json:"image"`
|
||||
Price float64 `json:"price" validate:"required"`
|
||||
Quantity int `json:"quantity" validate:"required"`
|
||||
}
|
||||
type CartCheckoutPayload struct {
|
||||
Items []CartCheckoutItem `json:"items" validate:"required"`
|
||||
}
|
||||
|
||||
type ErrorLogStore interface {
|
||||
CreateErrorLog(utils.LogError) error
|
||||
}
|
||||
type DataJWT struct {
|
||||
User
|
||||
Ip string `json:"ip"`
|
||||
Agent string `json:"agent"`
|
||||
Version string `json:"version"`
|
||||
LastLogin string `json:"last-login"`
|
||||
}
|
||||
33
types/user.types.go
Normal file
33
types/user.types.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package types
|
||||
|
||||
// type User struct {
|
||||
// ID int `db:"id" json:"id"`
|
||||
// FirstName string `db:"firstName" json:"firstName"`
|
||||
// LastName string `db:"lastName" json:"lastName"`
|
||||
// Email string `db:"email" json:"email"`
|
||||
// Password string `db:"password" json:"-"`
|
||||
// CreatedAt time.Time `db:"createdAt" json:"createdAt"`
|
||||
// }
|
||||
|
||||
type UserStore interface {
|
||||
GetUserByID(id int) (*User, error)
|
||||
CreateUser(User) error
|
||||
}
|
||||
type RegisterUserPayload struct {
|
||||
FirstName string `json:"firstName" validate:"required"`
|
||||
LastName string `json:"lastName" validate:"required"`
|
||||
Email string `json:"email" validate:"required,email"`
|
||||
Password string `json:"password" validate:"required,min=8,max=130"`
|
||||
}
|
||||
|
||||
type User struct {
|
||||
M_UserID int `json:"M_UserID" db:"M_UserID"`
|
||||
M_UserEmail string `json:"M_UserEmail" db:"M_UserEmail"`
|
||||
M_UserUsername string `json:"M_UserUsername" db:"M_UserUsername"`
|
||||
M_UserGroupDashboard string `json:"M_UserGroupDashboard" db:"M_UserGroupDashboard"`
|
||||
M_UserDefaultTSampleStationID string `json:"M_UserDefaultT_SampleStationID" db:"M_UserDefaultT_SampleStationID"`
|
||||
M_StaffName string `json:"M_StaffName" db:"M_StaffName"`
|
||||
Is_Courier string `json:"is_courier" db:"is_courier"`
|
||||
Time_Autologout string `json:"time_autologout" db:"time_autologout"`
|
||||
Type_Akun string `json:"Type_Akun"`
|
||||
}
|
||||
46
utils/error.log.go
Normal file
46
utils/error.log.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type LogError struct {
|
||||
Code string `json:"code" db:"ErrorLogCode"`
|
||||
TraceID string `json:"trace_id" db:"ErrorTraceID"`
|
||||
Type string `json:"type" db:"ErrorLogType"`
|
||||
Params string `json:"params" db:"ErrorLogParams"`
|
||||
Query string `json:"query" db:"ErrorLogQuery"`
|
||||
Message string `json:"message" db:"ErrorMessage"`
|
||||
TimeStamp string `json:"timestamp" db:"ErrorLogTimestamp"`
|
||||
}
|
||||
|
||||
func (e *LogError) Error() string {
|
||||
return e.Message
|
||||
}
|
||||
|
||||
func (e *LogError) LogError() LogError {
|
||||
return *e
|
||||
}
|
||||
|
||||
func RandomTraceID(n int) string {
|
||||
src := rand.NewSource(time.Now().UnixNano())
|
||||
r := rand.New(src)
|
||||
|
||||
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
|
||||
b := make([]byte, n)
|
||||
for i := range b {
|
||||
b[i] = letterBytes[r.Intn(len(letterBytes))]
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func WriteErrorLog(w http.ResponseWriter, status int, err LogError) {
|
||||
w.Header().Add("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
resp := map[string]any{"status": "ERR", "error": err}
|
||||
json.NewEncoder(w).Encode(resp)
|
||||
}
|
||||
70
utils/utils.go
Normal file
70
utils/utils.go
Normal file
@@ -0,0 +1,70 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
)
|
||||
|
||||
var Validate = validator.New()
|
||||
|
||||
func WriteJSON(w http.ResponseWriter, status int, v any) error {
|
||||
w.Header().Add("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
resp := map[string]any{"status": "OK", "data": v}
|
||||
return json.NewEncoder(w).Encode(resp)
|
||||
}
|
||||
|
||||
func WriteJSONLogin(w http.ResponseWriter, status int, v any, t any, n any) error {
|
||||
w.Header().Add("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
resp := map[string]any{"status": "OK", "user": v, "token": t, "type": n}
|
||||
return json.NewEncoder(w).Encode(resp)
|
||||
}
|
||||
|
||||
func WriteError(w http.ResponseWriter, status int, err error) {
|
||||
w.Header().Add("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
resp := map[string]any{"status": "ERR", "message": err.Error()}
|
||||
json.NewEncoder(w).Encode(resp)
|
||||
}
|
||||
|
||||
func ParseJSON(r *http.Request, v any) error {
|
||||
if r.Body == nil {
|
||||
return fmt.Errorf("missing request body")
|
||||
}
|
||||
|
||||
return json.NewDecoder(r.Body).Decode(v)
|
||||
}
|
||||
|
||||
func GetTokenFromRequest(r *http.Request) string {
|
||||
tokenAuth := r.Header.Get("Authorization")
|
||||
if strings.HasPrefix(tokenAuth, "Bearer ") {
|
||||
return strings.TrimPrefix(tokenAuth, "Bearer ")
|
||||
}
|
||||
|
||||
tokenQuery := r.URL.Query().Get("token")
|
||||
if tokenQuery != "" {
|
||||
return tokenQuery
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func MatchStruct(src interface{}, dst interface{}) error {
|
||||
srcVal := reflect.ValueOf(src)
|
||||
dstVal := reflect.ValueOf(dst).Elem()
|
||||
|
||||
for i := 0; i < srcVal.NumField(); i++ {
|
||||
srcField := srcVal.Type().Field(i)
|
||||
dstField := dstVal.FieldByName(srcField.Name)
|
||||
|
||||
if dstField.IsValid() && dstField.CanSet() && srcField.Type == dstField.Type() {
|
||||
dstField.Set(srcVal.Field(i))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user