Move to Donetick Org, first commit
This commit is contained in:
commit
c13dd9addb
|
@ -0,0 +1 @@
|
||||||
|
donetick.db
|
|
@ -0,0 +1,13 @@
|
||||||
|
FROM golang:1.22
|
||||||
|
|
||||||
|
WORKDIR /usr/src/app
|
||||||
|
|
||||||
|
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
RUN go mod download && go mod verify
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
RUN CGO_ENABLED=1 GOOS=linux go build -ldflags="-s -w " -buildvcs=false -o /donetick-core
|
||||||
|
|
||||||
|
EXPOSE 8080
|
||||||
|
CMD ["donetick-core"]
|
|
@ -0,0 +1,661 @@
|
||||||
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works, specifically designed to ensure
|
||||||
|
cooperation with the community in the case of network server software.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
our General Public Licenses are 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.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
Developers that use our General Public Licenses protect your rights
|
||||||
|
with two steps: (1) assert copyright on the software, and (2) offer
|
||||||
|
you this License which gives you legal permission to copy, distribute
|
||||||
|
and/or modify the software.
|
||||||
|
|
||||||
|
A secondary benefit of defending all users' freedom is that
|
||||||
|
improvements made in alternate versions of the program, if they
|
||||||
|
receive widespread use, become available for other developers to
|
||||||
|
incorporate. Many developers of free software are heartened and
|
||||||
|
encouraged by the resulting cooperation. However, in the case of
|
||||||
|
software used on network servers, this result may fail to come about.
|
||||||
|
The GNU General Public License permits making a modified version and
|
||||||
|
letting the public access it on a server without ever releasing its
|
||||||
|
source code to the public.
|
||||||
|
|
||||||
|
The GNU Affero General Public License is designed specifically to
|
||||||
|
ensure that, in such cases, the modified source code becomes available
|
||||||
|
to the community. It requires the operator of a network server to
|
||||||
|
provide the source code of the modified version running there to the
|
||||||
|
users of that server. Therefore, public use of a modified version, on
|
||||||
|
a publicly accessible server, gives the public access to the source
|
||||||
|
code of the modified version.
|
||||||
|
|
||||||
|
An older license, called the Affero General Public License and
|
||||||
|
published by Affero, was designed to accomplish similar goals. This is
|
||||||
|
a different license, not a version of the Affero GPL, but Affero has
|
||||||
|
released a new version of the Affero GPL which permits relicensing under
|
||||||
|
this license.
|
||||||
|
|
||||||
|
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, if you modify the
|
||||||
|
Program, your modified version must prominently offer all users
|
||||||
|
interacting with it remotely through a computer network (if your version
|
||||||
|
supports such interaction) an opportunity to receive the Corresponding
|
||||||
|
Source of your version by providing access to the Corresponding Source
|
||||||
|
from a network server at no charge, through some standard or customary
|
||||||
|
means of facilitating copying of software. This Corresponding Source
|
||||||
|
shall include the Corresponding Source for any work covered by version 3
|
||||||
|
of the GNU General Public License that is incorporated pursuant to the
|
||||||
|
following paragraph.
|
||||||
|
|
||||||
|
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 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 work with which it is combined will remain governed by version
|
||||||
|
3 of the GNU General Public License.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero 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 your software can interact with users remotely through a computer
|
||||||
|
network, you should also make sure that it provides a way for users to
|
||||||
|
get its source. For example, if your program is a web application, its
|
||||||
|
interface could display a "Source" link that leads users to an archive
|
||||||
|
of the code. There are many ways you could offer source, and different
|
||||||
|
solutions will be better for different programs; see section 13 for the
|
||||||
|
specific requirements.
|
||||||
|
|
||||||
|
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 AGPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
|
@ -0,0 +1,46 @@
|
||||||
|
|
||||||
|
![Logo](assets/image.png)
|
||||||
|
|
||||||
|
|
||||||
|
## Donetick service
|
||||||
|
The Donetick service is the backend of the Donetick project. It handles all the data processing, storage, schedulers, and communication with the frontend.
|
||||||
|
|
||||||
|
## What is Donetick?
|
||||||
|
An open-source, user-friendly app for managing tasks and chores, featuring customizable options to help you and others stay organized.
|
||||||
|
|
||||||
|
## Why I made Donetick?
|
||||||
|
As an avid for open-source, I was eager to create a solution that could benefit the wider community. Donetick started as a personal project to address my own chore management needs, but it has evolved into bigger tool and decide to open source it for anyone seeking a customizable and privacy-focused task management tool
|
||||||
|
|
||||||
|
## Features
|
||||||
|
- Task and Chore Management: Easily create, edit, and manage tasks and chores for yourself or your group.
|
||||||
|
- Shared To-Do Lists: Create "Circles" to collaborate on tasks with family or your group
|
||||||
|
- Assignee Assignment: Assign tasks to specific individuals or rotate them automatically using customizable strategies.
|
||||||
|
- Recurring Tasks: Schedule tasks to repeat daily, weekly, monthly, or yearly, with flexible customization options.
|
||||||
|
- Progress Tracking: Track the completion status of tasks and view historical data.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
1. Clone the repository:
|
||||||
|
2. Navigate to the project directory: `cd donetick`
|
||||||
|
3. Download dependency `go mod download`
|
||||||
|
4. Run locally `go run .`
|
||||||
|
|
||||||
|
## Contributing
|
||||||
|
Contributions are welcome! If you would like to contribute to Donetick, please follow these steps:
|
||||||
|
1. Fork the repository
|
||||||
|
2. Create a new branch: `git checkout -b feature/your-feature-name`
|
||||||
|
3. Make your changes and commit them: `git commit -m 'Add some feature'`
|
||||||
|
4. Push to the branch: `git push origin feature/your-feature-name`
|
||||||
|
5. Submit a pull request
|
||||||
|
|
||||||
|
## Need Help:
|
||||||
|
As a project built while learning Golang, Donetick has evolved organically, and some areas could benefit from refactoring or optimization. I'm particularly interested in contributions that help standardize code patterns, improve performance, or enhance the overall user experience or adding new features!
|
||||||
|
|
||||||
|
## Plans :
|
||||||
|
My goal is to expand Donetick by offering a hosted infrastructure option. This will make it even easier for users to access and utilize Donetick's features without the need for self-hosting.
|
||||||
|
|
||||||
|
While maintaining Donetick's commitment to open source, this hosted option will provide a seamless, out-of-the-box experience for those who prefer a managed solution.
|
||||||
|
|
||||||
|
## License
|
||||||
|
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for more details. I might consider changing it later to something else
|
||||||
|
|
||||||
|
|
Binary file not shown.
After Width: | Height: | Size: 167 KiB |
File diff suppressed because it is too large
Load Diff
After Width: | Height: | Size: 63 KiB |
|
@ -0,0 +1,126 @@
|
||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/spf13/viper"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
Name string `mapstructure:"name" yaml:"name"`
|
||||||
|
Telegram TelegramConfig `mapstructure:"telegram" yaml:"telegram"`
|
||||||
|
Database DatabaseConfig `mapstructure:"database" yaml:"database"`
|
||||||
|
Jwt JwtConfig `mapstructure:"jwt" yaml:"jwt"`
|
||||||
|
Server ServerConfig `mapstructure:"server" yaml:"server"`
|
||||||
|
SchedulerJobs SchedulerConfig `mapstructure:"scheduler_jobs" yaml:"scheduler_jobs"`
|
||||||
|
EmailConfig EmailConfig `mapstructure:"email" yaml:"email"`
|
||||||
|
StripeConfig StripeConfig `mapstructure:"stripe" yaml:"stripe"`
|
||||||
|
IsDoneTickDotCom bool `mapstructure:"is_done_tick_dot_com" yaml:"is_done_tick_dot_com"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type TelegramConfig struct {
|
||||||
|
Token string `mapstructure:"token" yaml:"token"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type DatabaseConfig struct {
|
||||||
|
Type string `mapstructure:"type" yaml:"type"`
|
||||||
|
Host string `mapstructure:"host" yaml:"host"`
|
||||||
|
Port int `mapstructure:"port" yaml:"port"`
|
||||||
|
User string `mapstructure:"user" yaml:"user"`
|
||||||
|
Password string `mapstructure:"password" yaml:"password"`
|
||||||
|
Name string `mapstructure:"name" yaml:"name"`
|
||||||
|
Migration bool `mapstructure:"migration" yaml:"migration"`
|
||||||
|
LogLevel int `mapstructure:"logger" yaml:"logger"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type JwtConfig struct {
|
||||||
|
Secret string `mapstructure:"secret" yaml:"secret"`
|
||||||
|
SessionTime time.Duration `mapstructure:"session_time" yaml:"session_time"`
|
||||||
|
MaxRefresh time.Duration `mapstructure:"max_refresh" yaml:"max_refresh"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ServerConfig struct {
|
||||||
|
Port int `mapstructure:"port" yaml:"port"`
|
||||||
|
RatePeriod time.Duration `mapstructure:"rate_period" yaml:"rate_period"`
|
||||||
|
RateLimit int `mapstructure:"rate_limit" yaml:"rate_limit"`
|
||||||
|
ReadTimeout time.Duration `mapstructure:"read_timeout" yaml:"read_timeout"`
|
||||||
|
WriteTimeout time.Duration `mapstructure:"write_timeout" yaml:"write_timeout"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type SchedulerConfig struct {
|
||||||
|
DueJob time.Duration `mapstructure:"due_job" yaml:"due_job"`
|
||||||
|
OverdueJob time.Duration `mapstructure:"overdue_job" yaml:"overdue_job"`
|
||||||
|
PreDueJob time.Duration `mapstructure:"pre_due_job" yaml:"pre_due_job"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type StripeConfig struct {
|
||||||
|
APIKey string `mapstructure:"api_key"`
|
||||||
|
WhitelistedIPs []string `mapstructure:"whitelisted_ips"`
|
||||||
|
Prices []StripePrices `mapstructure:"prices"`
|
||||||
|
SuccessURL string `mapstructure:"success_url"`
|
||||||
|
CancelURL string `mapstructure:"cancel_url"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type StripePrices struct {
|
||||||
|
PriceID string `mapstructure:"id"`
|
||||||
|
Name string `mapstructure:"name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type EmailConfig struct {
|
||||||
|
Email string `mapstructure:"email"`
|
||||||
|
Key string `mapstructure:"key"`
|
||||||
|
Host string `mapstructure:"host"`
|
||||||
|
Port int `mapstructure:"port"`
|
||||||
|
AppHost string `mapstructure:"appHost"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewConfig() *Config {
|
||||||
|
return &Config{
|
||||||
|
Telegram: TelegramConfig{
|
||||||
|
Token: "",
|
||||||
|
},
|
||||||
|
Database: DatabaseConfig{
|
||||||
|
Type: "sqlite",
|
||||||
|
Migration: true,
|
||||||
|
},
|
||||||
|
Jwt: JwtConfig{
|
||||||
|
Secret: "secret",
|
||||||
|
SessionTime: 7 * 24 * time.Hour,
|
||||||
|
MaxRefresh: 7 * 24 * time.Hour,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func LoadConfig() *Config {
|
||||||
|
// read evniroment variable FORWARD_ENV and see if it's equal local then load local (config/local.yaml) using viper:
|
||||||
|
if os.Getenv("CA_ENV") == "local" {
|
||||||
|
viper.SetConfigName("local")
|
||||||
|
} else if os.Getenv("CA_ENV") == "prod" {
|
||||||
|
viper.SetConfigName("prod")
|
||||||
|
} else {
|
||||||
|
viper.SetConfigName("local")
|
||||||
|
}
|
||||||
|
// get logger and log the current environment:
|
||||||
|
fmt.Printf("--ConfigLoad config for environment: %s ", os.Getenv("CA_ENV"))
|
||||||
|
|
||||||
|
viper.AddConfigPath("./config")
|
||||||
|
viper.SetConfigType("yaml")
|
||||||
|
err := viper.ReadInConfig()
|
||||||
|
// print a useful error:
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var config Config
|
||||||
|
err = viper.Unmarshal(&config)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
fmt.Printf("--ConfigLoad name : %s ", config.Name)
|
||||||
|
|
||||||
|
return &config
|
||||||
|
|
||||||
|
// return LocalConfig()
|
||||||
|
}
|
|
@ -0,0 +1,28 @@
|
||||||
|
name: "local"
|
||||||
|
is_done_tick_dot_com: true
|
||||||
|
telegram:
|
||||||
|
token: ""
|
||||||
|
database:
|
||||||
|
type: "sqlite"
|
||||||
|
migration: true
|
||||||
|
jwt:
|
||||||
|
secret: "secret"
|
||||||
|
session_time: 168h
|
||||||
|
max_refresh: 168h
|
||||||
|
server:
|
||||||
|
port: 8000
|
||||||
|
read_timeout: 2s
|
||||||
|
write_timeout: 1s
|
||||||
|
rate_period: 60s
|
||||||
|
rate_limit: 200
|
||||||
|
|
||||||
|
scheduler_jobs:
|
||||||
|
due_job: 30m
|
||||||
|
overdue_job: 3h
|
||||||
|
pre_due_job: 3h
|
||||||
|
email:
|
||||||
|
host:
|
||||||
|
port:
|
||||||
|
key:
|
||||||
|
email:
|
||||||
|
appHost:
|
|
@ -0,0 +1,22 @@
|
||||||
|
version: '3.3'
|
||||||
|
|
||||||
|
services:
|
||||||
|
app:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
container_name: donetick-core
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
# sqlite database:
|
||||||
|
- ./data:/usr/src/app/data
|
||||||
|
|
||||||
|
ports:
|
||||||
|
- "8085:8000"
|
||||||
|
environment:
|
||||||
|
- CA_ENV=prod
|
||||||
|
hostname: donetick-core
|
||||||
|
command: ["/donetick-core"] # Command to execute your binary inside the container
|
||||||
|
networks:
|
||||||
|
default:
|
|
@ -0,0 +1,14 @@
|
||||||
|
package model
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
uModel "donetick.com/core/internal/user/model"
|
||||||
|
)
|
||||||
|
|
||||||
|
type UserExtended struct {
|
||||||
|
uModel.User
|
||||||
|
Credit int `gorm:"column:amount;->"`
|
||||||
|
SubscriptionStatus *string `gorm:"column:status;<-:false"` // read one column
|
||||||
|
ExpiredAt *time.Time `gorm:"column:expired_at;<-:false"` // read one column
|
||||||
|
}
|
|
@ -0,0 +1,49 @@
|
||||||
|
package user
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
exUser "donetick.com/core/external/user/model"
|
||||||
|
"donetick.com/core/logging"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ExtendedUserRepository struct {
|
||||||
|
db *gorm.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewExtendedUserRepository(db *gorm.DB) *ExtendedUserRepository {
|
||||||
|
return &ExtendedUserRepository{db}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *ExtendedUserRepository) FindFullUserByEmail(ctx context.Context, email string) (*exUser.UserExtended, error) {
|
||||||
|
logger := logging.FromContext(ctx)
|
||||||
|
logger.Debugw("repository.user.FindFullUserByEmail", "email", email)
|
||||||
|
var acc exUser.UserExtended
|
||||||
|
if err := a.db.Table("users").
|
||||||
|
Select("users.*, s.expired_at, s.status , s.customer_id").
|
||||||
|
Joins("LEFT JOIN stripe_customers sc ON sc.user_id = users.id").
|
||||||
|
Joins("LEFT JOIN stripe_subscriptions s ON s.customer_id = sc.customer_id AND s.expired_at > now() OR s.expired_at is null").
|
||||||
|
Where("email = ?", email).
|
||||||
|
First(&acc).Error; err != nil {
|
||||||
|
logger.Error("repository.user.FindFullUserByEmail failed to find", "err", err)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &acc, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *ExtendedUserRepository) FindFullUserByUsername(ctx context.Context, username string) (*exUser.UserExtended, error) {
|
||||||
|
logger := logging.FromContext(ctx)
|
||||||
|
logger.Debugw("repository.user.FindFullUserByUsername", "username", username)
|
||||||
|
var acc exUser.UserExtended
|
||||||
|
if err := a.db.Table("users").
|
||||||
|
Select("users.*, s.expired_at, s.status , s.customer_id").
|
||||||
|
Joins("LEFT JOIN stripe_customers sc ON sc.user_id = users.id").
|
||||||
|
Joins("LEFT JOIN stripe_subscriptions s ON s.customer_id = sc.customer_id AND s.expired_at > now() OR s.expired_at is null").
|
||||||
|
Where("username = ?", username).
|
||||||
|
First(&acc).Error; err != nil {
|
||||||
|
logger.Error("repository.user.FindFullUserByUsername failed to find", "err", err)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &acc, nil
|
||||||
|
}
|
|
@ -0,0 +1,97 @@
|
||||||
|
module donetick.com/core
|
||||||
|
|
||||||
|
go 1.20
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/appleboy/gin-jwt/v2 v2.9.2
|
||||||
|
github.com/gin-contrib/cors v1.7.2
|
||||||
|
github.com/gin-gonic/gin v1.10.0
|
||||||
|
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1
|
||||||
|
github.com/spf13/viper v1.19.0
|
||||||
|
github.com/stripe/stripe-go/v76 v76.25.0
|
||||||
|
github.com/ulule/limiter/v3 v3.11.2
|
||||||
|
go.uber.org/fx v1.22.0
|
||||||
|
go.uber.org/zap v1.26.0
|
||||||
|
golang.org/x/crypto v0.23.0
|
||||||
|
google.golang.org/api v0.183.0
|
||||||
|
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df
|
||||||
|
gorm.io/driver/postgres v1.5.7
|
||||||
|
gorm.io/driver/sqlite v1.5.5
|
||||||
|
gorm.io/gorm v1.25.10
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
cloud.google.com/go/auth v0.5.1 // indirect
|
||||||
|
cloud.google.com/go/auth/oauth2adapt v0.2.2 // indirect
|
||||||
|
cloud.google.com/go/compute/metadata v0.3.0 // indirect
|
||||||
|
github.com/BurntSushi/toml v0.3.1 // indirect
|
||||||
|
github.com/bytedance/sonic v1.11.8 // indirect
|
||||||
|
github.com/bytedance/sonic/loader v0.1.1 // indirect
|
||||||
|
github.com/cloudwego/base64x v0.1.4 // indirect
|
||||||
|
github.com/cloudwego/iasm v0.2.0 // indirect
|
||||||
|
github.com/felixge/httpsnoop v1.0.4 // indirect
|
||||||
|
github.com/fsnotify/fsnotify v1.7.0 // indirect
|
||||||
|
github.com/gabriel-vasile/mimetype v1.4.4 // indirect
|
||||||
|
github.com/gin-contrib/sse v0.1.0 // indirect
|
||||||
|
github.com/go-logr/logr v1.4.1 // indirect
|
||||||
|
github.com/go-logr/stdr v1.2.2 // indirect
|
||||||
|
github.com/go-playground/locales v0.14.1 // indirect
|
||||||
|
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||||
|
github.com/go-playground/validator/v10 v10.20.0 // indirect
|
||||||
|
github.com/goccy/go-json v0.10.3 // indirect
|
||||||
|
github.com/golang-jwt/jwt/v4 v4.5.0 // indirect
|
||||||
|
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
|
||||||
|
github.com/golang/protobuf v1.5.4 // indirect
|
||||||
|
github.com/google/s2a-go v0.1.7 // indirect
|
||||||
|
github.com/google/uuid v1.6.0 // indirect
|
||||||
|
github.com/googleapis/enterprise-certificate-proxy v0.3.2 // indirect
|
||||||
|
github.com/googleapis/gax-go/v2 v2.12.4 // indirect
|
||||||
|
github.com/hashicorp/hcl v1.0.0 // indirect
|
||||||
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
||||||
|
github.com/jackc/pgx/v5 v5.4.3 // indirect
|
||||||
|
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||||
|
github.com/jinzhu/now v1.1.5 // indirect
|
||||||
|
github.com/json-iterator/go v1.1.12 // indirect
|
||||||
|
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
|
||||||
|
github.com/leodido/go-urn v1.4.0 // indirect
|
||||||
|
github.com/magiconair/properties v1.8.7 // indirect
|
||||||
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
|
github.com/mattn/go-sqlite3 v1.14.17 // indirect
|
||||||
|
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||||
|
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||||
|
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
|
||||||
|
github.com/pkg/errors v0.9.1 // indirect
|
||||||
|
github.com/sagikazarmark/locafero v0.4.0 // indirect
|
||||||
|
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
|
||||||
|
github.com/sourcegraph/conc v0.3.0 // indirect
|
||||||
|
github.com/spf13/afero v1.11.0 // indirect
|
||||||
|
github.com/spf13/cast v1.6.0 // indirect
|
||||||
|
github.com/spf13/pflag v1.0.5 // indirect
|
||||||
|
github.com/subosito/gotenv v1.6.0 // indirect
|
||||||
|
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||||
|
github.com/ugorji/go/codec v1.2.12 // indirect
|
||||||
|
go.opencensus.io v0.24.0 // indirect
|
||||||
|
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0 // indirect
|
||||||
|
go.opentelemetry.io/otel v1.24.0 // indirect
|
||||||
|
go.opentelemetry.io/otel/metric v1.24.0 // indirect
|
||||||
|
go.opentelemetry.io/otel/trace v1.24.0 // indirect
|
||||||
|
go.uber.org/dig v1.17.1 // indirect
|
||||||
|
go.uber.org/multierr v1.10.0 // indirect
|
||||||
|
golang.org/x/arch v0.8.0 // indirect
|
||||||
|
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
|
||||||
|
golang.org/x/mod v0.12.0 // indirect
|
||||||
|
golang.org/x/net v0.25.0 // indirect
|
||||||
|
golang.org/x/oauth2 v0.21.0 // indirect
|
||||||
|
golang.org/x/sys v0.20.0 // indirect
|
||||||
|
golang.org/x/text v0.15.0 // indirect
|
||||||
|
golang.org/x/tools v0.13.0 // indirect
|
||||||
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20240528184218-531527333157 // indirect
|
||||||
|
google.golang.org/grpc v1.64.0 // indirect
|
||||||
|
google.golang.org/protobuf v1.34.1 // indirect
|
||||||
|
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
|
||||||
|
gopkg.in/ini.v1 v1.67.0 // indirect
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
|
honnef.co/go/tools v0.0.1-2020.1.4 // indirect
|
||||||
|
)
|
|
@ -0,0 +1,315 @@
|
||||||
|
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||||
|
cloud.google.com/go/auth v0.5.1 h1:0QNO7VThG54LUzKiQxv8C6x1YX7lUrzlAa1nVLF8CIw=
|
||||||
|
cloud.google.com/go/auth v0.5.1/go.mod h1:vbZT8GjzDf3AVqCcQmqeeM32U9HBFc32vVVAbwDsa6s=
|
||||||
|
cloud.google.com/go/auth/oauth2adapt v0.2.2 h1:+TTV8aXpjeChS9M+aTtN/TjdQnzJvmzKFt//oWu7HX4=
|
||||||
|
cloud.google.com/go/auth/oauth2adapt v0.2.2/go.mod h1:wcYjgpZI9+Yu7LyYBg4pqSiaRkfEK3GQcpb7C/uyF1Q=
|
||||||
|
cloud.google.com/go/compute/metadata v0.3.0 h1:Tz+eQXMEqDIKRsmY3cHTL6FVaynIjX2QxYC4trgAKZc=
|
||||||
|
cloud.google.com/go/compute/metadata v0.3.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k=
|
||||||
|
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
|
||||||
|
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||||
|
github.com/appleboy/gin-jwt/v2 v2.9.2 h1:GeS3lm9mb9HMmj7+GNjYUtpp3V1DAQ1TkUFa5poiZ7Y=
|
||||||
|
github.com/appleboy/gin-jwt/v2 v2.9.2/go.mod h1:mxGjKt9Lrx9Xusy1SrnmsCJMZG6UJwmdHN9bN27/QDw=
|
||||||
|
github.com/appleboy/gofight/v2 v2.1.2 h1:VOy3jow4vIK8BRQJoC/I9muxyYlJ2yb9ht2hZoS3rf4=
|
||||||
|
github.com/bytedance/sonic v1.11.8 h1:Zw/j1KfiS+OYTi9lyB3bb0CFxPJVkM17k1wyDG32LRA=
|
||||||
|
github.com/bytedance/sonic v1.11.8/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
|
||||||
|
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
|
||||||
|
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
|
||||||
|
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
|
||||||
|
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
|
||||||
|
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
|
||||||
|
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
|
||||||
|
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
|
||||||
|
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
|
||||||
|
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
|
||||||
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
||||||
|
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||||
|
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||||
|
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
|
||||||
|
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
|
||||||
|
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
|
||||||
|
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
||||||
|
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||||
|
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
|
||||||
|
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
|
||||||
|
github.com/gabriel-vasile/mimetype v1.4.4 h1:QjV6pZ7/XZ7ryI2KuyeEDE8wnh7fHP9YnQy+R0LnH8I=
|
||||||
|
github.com/gabriel-vasile/mimetype v1.4.4/go.mod h1:JwLei5XPtWdGiMFB5Pjle1oEeoSeEuJfJE+TtfvdB/s=
|
||||||
|
github.com/gin-contrib/cors v1.7.2 h1:oLDHxdg8W/XDoN/8zamqk/Drgt4oVZDvaV0YmvVICQw=
|
||||||
|
github.com/gin-contrib/cors v1.7.2/go.mod h1:SUJVARKgQ40dmrzgXEVxj2m7Ig1v1qIboQkPDTQ9t2E=
|
||||||
|
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
||||||
|
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||||
|
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
|
||||||
|
github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
|
||||||
|
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||||
|
github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ=
|
||||||
|
github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||||
|
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||||
|
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||||
|
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||||
|
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.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
|
||||||
|
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
|
||||||
|
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 h1:wG8n/XJQ07TmjbITcGiUaOtXxdrINDz1b0J1w0SzqDc=
|
||||||
|
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1/go.mod h1:A2S0CWkNylc2phvKXWBBdD3K0iGnDBGbzRpISP2zBl8=
|
||||||
|
github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA=
|
||||||
|
github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||||
|
github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg=
|
||||||
|
github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
|
||||||
|
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
||||||
|
github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
|
||||||
|
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE=
|
||||||
|
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
|
||||||
|
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
|
||||||
|
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||||
|
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||||
|
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
|
||||||
|
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
|
||||||
|
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
|
||||||
|
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
|
||||||
|
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
|
||||||
|
github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8=
|
||||||
|
github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
||||||
|
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||||
|
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||||
|
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
|
||||||
|
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||||
|
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||||
|
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
|
github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
|
github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
|
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||||
|
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||||
|
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
|
||||||
|
github.com/google/s2a-go v0.1.7 h1:60BLSyTrOV4/haCDW4zb1guZItoSq8foHCXrAnjBo/o=
|
||||||
|
github.com/google/s2a-go v0.1.7/go.mod h1:50CgR4k1jNlWBu4UfS4AcfhVe1r6pdZPygJ3R8F0Qdw=
|
||||||
|
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
|
github.com/googleapis/enterprise-certificate-proxy v0.3.2 h1:Vie5ybvEvT75RniqhfFxPRy3Bf7vr3h0cechB90XaQs=
|
||||||
|
github.com/googleapis/enterprise-certificate-proxy v0.3.2/go.mod h1:VLSiSSBs/ksPL8kq3OBOQ6WRI2QnaFynd1DCjZ62+V0=
|
||||||
|
github.com/googleapis/gax-go/v2 v2.12.4 h1:9gWcmF85Wvq4ryPFvGFaOgPIs1AQX0d0bcbGw4Z96qg=
|
||||||
|
github.com/googleapis/gax-go/v2 v2.12.4/go.mod h1:KYEYLorsnIGDi/rPC8b5TdlB9kbKoFubselGIoBMCwI=
|
||||||
|
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
|
||||||
|
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
|
||||||
|
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||||
|
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||||
|
github.com/jackc/pgx/v5 v5.4.3 h1:cxFyXhxlvAifxnkKKdlxv8XqUf59tDlYjnV5YYfsJJY=
|
||||||
|
github.com/jackc/pgx/v5 v5.4.3/go.mod h1:Ig06C2Vu0t5qXC60W8sqIthScaEnFvojjj9dSljmHRA=
|
||||||
|
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||||
|
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||||
|
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||||
|
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||||
|
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||||
|
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||||
|
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||||
|
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||||
|
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
|
||||||
|
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
|
||||||
|
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
|
||||||
|
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||||
|
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||||
|
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||||
|
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||||
|
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||||
|
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/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
|
||||||
|
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
|
||||||
|
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||||
|
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||||
|
github.com/mattn/go-sqlite3 v1.14.17 h1:mCRHCLDUBXgpKAqIKsaAaAsrAlbkeomtRFKXh2L6YIM=
|
||||||
|
github.com/mattn/go-sqlite3 v1.14.17/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
|
||||||
|
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
|
||||||
|
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||||
|
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||||
|
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||||
|
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
|
||||||
|
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
|
||||||
|
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/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
||||||
|
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||||
|
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
||||||
|
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
|
||||||
|
github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ=
|
||||||
|
github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4=
|
||||||
|
github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE=
|
||||||
|
github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ=
|
||||||
|
github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
|
||||||
|
github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
|
||||||
|
github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8=
|
||||||
|
github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY=
|
||||||
|
github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0=
|
||||||
|
github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
|
||||||
|
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
||||||
|
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||||
|
github.com/spf13/viper v1.19.0 h1:RWq5SEjt8o25SROyN3z2OrDB9l7RPd3lwTWU8EcEdcI=
|
||||||
|
github.com/spf13/viper v1.19.0/go.mod h1:GQUN9bilAbhU/jgc1bKs99f/suXKeUMct8Adx5+Ntkg=
|
||||||
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||||
|
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||||
|
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||||
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||||
|
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||||
|
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||||
|
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/stripe/stripe-go/v76 v76.25.0 h1:kmDoOTvdQSTQssQzWZQQkgbAR2Q8eXdMWbN/ylNalWA=
|
||||||
|
github.com/stripe/stripe-go/v76 v76.25.0/go.mod h1:rw1MxjlAKKcZ+3FOXgTHgwiOa2ya6CPq6ykpJ0Q6Po4=
|
||||||
|
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
|
||||||
|
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
|
||||||
|
github.com/tidwall/gjson v1.17.0 h1:/Jocvlh98kcTfpN2+JzGQWQcqrPQwDrVEMApx/M5ZwM=
|
||||||
|
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
|
||||||
|
github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs=
|
||||||
|
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||||
|
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||||
|
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
|
||||||
|
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||||
|
github.com/ulule/limiter/v3 v3.11.2 h1:P4yOrxoEMJbOTfRJR2OzjL90oflzYPPmWg+dvwN2tHA=
|
||||||
|
github.com/ulule/limiter/v3 v3.11.2/go.mod h1:QG5GnFOCV+k7lrL5Y8kgEeeflPH3+Cviqlqa8SVSQxI=
|
||||||
|
go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=
|
||||||
|
go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=
|
||||||
|
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0 h1:jq9TW8u3so/bN+JPT166wjOI6/vQPF6Xe7nMNIltagk=
|
||||||
|
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0/go.mod h1:p8pYQP+m5XfbZm9fxtSKAbM6oIllS7s2AfxrChvc7iw=
|
||||||
|
go.opentelemetry.io/otel v1.24.0 h1:0LAOdjNmQeSTzGBzduGe/rU4tZhMwL5rWgtp9Ku5Jfo=
|
||||||
|
go.opentelemetry.io/otel v1.24.0/go.mod h1:W7b9Ozg4nkF5tWI5zsXkaKKDjdVjpD4oAt9Qi/MArHo=
|
||||||
|
go.opentelemetry.io/otel/metric v1.24.0 h1:6EhoGWWK28x1fbpA4tYTOWBkPefTDQnb8WSGXlc88kI=
|
||||||
|
go.opentelemetry.io/otel/metric v1.24.0/go.mod h1:VYhLe1rFfxuTXLgj4CBiyz+9WYBA8pNGJgDcSFRKBco=
|
||||||
|
go.opentelemetry.io/otel/trace v1.24.0 h1:CsKnnL4dUAr/0llH9FKuc698G04IrpWV0MQA/Y1YELI=
|
||||||
|
go.opentelemetry.io/otel/trace v1.24.0/go.mod h1:HPc3Xr/cOApsBI154IU0OI0HJexz+aw5uPdbs3UCjNU=
|
||||||
|
go.uber.org/dig v1.17.1 h1:Tga8Lz8PcYNsWsyHMZ1Vm0OQOUaJNDyvPImgbAu9YSc=
|
||||||
|
go.uber.org/dig v1.17.1/go.mod h1:Us0rSJiThwCv2GteUN0Q7OKvU7n5J4dxZ9JKUXozFdE=
|
||||||
|
go.uber.org/fx v1.22.0 h1:pApUK7yL0OUHMd8vkunWSlLxZVFFk70jR2nKde8X2NM=
|
||||||
|
go.uber.org/fx v1.22.0/go.mod h1:HT2M7d7RHo+ebKGh9NRcrsrHHfpZ60nW3QRubMRfv48=
|
||||||
|
go.uber.org/goleak v1.2.0 h1:xqgm/S+aQvhWFTtR0XK3Jvg7z8kGV8P4X14IzwN3Eqk=
|
||||||
|
go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
|
||||||
|
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||||
|
go.uber.org/zap v1.26.0 h1:sI7k6L95XOKS281NhVKOFCUNIvv9e0w4BF8N3u+tCRo=
|
||||||
|
go.uber.org/zap v1.26.0/go.mod h1:dtElttAiwGvoJ/vj4IwHBS/gXsEu/pZ50mUIRWuG0so=
|
||||||
|
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||||
|
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
|
||||||
|
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
|
||||||
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
|
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||||
|
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||||
|
golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
|
||||||
|
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||||
|
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||||
|
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g=
|
||||||
|
golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k=
|
||||||
|
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||||
|
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
|
||||||
|
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
||||||
|
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
|
||||||
|
golang.org/x/mod v0.12.0 h1:rmsUpXtvNzj340zd98LZ4KntptpfRHwpFOHG188oHXc=
|
||||||
|
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||||
|
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
|
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
|
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
|
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||||
|
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||||
|
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
|
golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||||
|
golang.org/x/net v0.0.0-20210520170846-37e1c6afe023/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||||
|
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
|
||||||
|
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||||
|
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||||
|
golang.org/x/oauth2 v0.21.0 h1:tsimM75w1tF/uws5rbeHzIWxEqElMehnc+iW793zsZs=
|
||||||
|
golang.org/x/oauth2 v0.21.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI=
|
||||||
|
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
|
||||||
|
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
|
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
|
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
|
||||||
|
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
|
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.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
|
golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk=
|
||||||
|
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||||
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
|
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
|
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
|
||||||
|
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||||
|
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
||||||
|
golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||||
|
golang.org/x/tools v0.13.0 h1:Iey4qkscZuv0VvIt8E0neZjtPVQFSc870HQ448QgEmQ=
|
||||||
|
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
|
||||||
|
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/api v0.183.0 h1:PNMeRDwo1pJdgNcFQ9GstuLe/noWKIc89pRWRLMvLwE=
|
||||||
|
google.golang.org/api v0.183.0/go.mod h1:q43adC5/pHoSZTx5h2mSmdF7NcyfW9JuDyIOJAgS9ZQ=
|
||||||
|
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
|
||||||
|
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||||
|
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
|
||||||
|
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
|
||||||
|
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo=
|
||||||
|
google.golang.org/genproto v0.0.0-20240528184218-531527333157 h1:u7WMYrIrVvs0TF5yaKwKNbcJyySYf+HAIFXxWltJOXE=
|
||||||
|
google.golang.org/genproto/googleapis/api v0.0.0-20240415180920-8c6c420018be h1:Zz7rLWqp0ApfsR/l7+zSHhY3PMiH2xqgxlfYfAfNpoU=
|
||||||
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20240528184218-531527333157 h1:Zy9XzmMEflZ/MAaA7vNcoebnRAld7FsPW1EeBB7V0m8=
|
||||||
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20240528184218-531527333157/go.mod h1:EfXuqaE1J41VCDicxHzUDm+8rk+7ZdXzHV0IhO/I6s0=
|
||||||
|
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
|
||||||
|
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
|
||||||
|
google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
|
||||||
|
google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
|
||||||
|
google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc=
|
||||||
|
google.golang.org/grpc v1.64.0 h1:KH3VH9y/MgNQg1dE7b3XfVK0GsPSIzJwdF617gUSbvY=
|
||||||
|
google.golang.org/grpc v1.64.0/go.mod h1:oxjF8E3FBnjp+/gVFYdWacaLDx9na1aqy9oovLpxQYg=
|
||||||
|
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
|
||||||
|
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
|
||||||
|
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
|
||||||
|
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
|
||||||
|
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
|
||||||
|
google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||||
|
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||||
|
google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||||
|
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
|
||||||
|
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
|
||||||
|
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
|
||||||
|
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc h1:2gGKlE2+asNV9m7xrywl36YYNnBG5ZQ0r/BOOxqPpmk=
|
||||||
|
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc/go.mod h1:m7x9LTH6d71AHyAX77c9yqWCCa3UKHcVEj9y7hAtKDk=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||||
|
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
||||||
|
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df h1:n7WqCuqOuCbNr617RXOY0AWRXxgwEyPp2z+p0+hgMuE=
|
||||||
|
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df/go.mod h1:LRQQ+SO6ZHR7tOkpBDuZnXENFzX8qRjMDMyPD6BRkCw=
|
||||||
|
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
|
||||||
|
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gorm.io/driver/postgres v1.5.7 h1:8ptbNJTDbEmhdr62uReG5BGkdQyeasu/FZHxI0IMGnM=
|
||||||
|
gorm.io/driver/postgres v1.5.7/go.mod h1:3e019WlBaYI5o5LIdNV+LyxCMNtLOQETBXL2h4chKpA=
|
||||||
|
gorm.io/driver/sqlite v1.5.5 h1:7MDMtUZhV065SilG62E0MquljeArQZNfJnjd9i9gx3E=
|
||||||
|
gorm.io/driver/sqlite v1.5.5/go.mod h1:6NgQ7sQWAIFsPrJJl1lSNSu2TABh0ZZ/zm5fosATavE=
|
||||||
|
gorm.io/gorm v1.25.10 h1:dQpO+33KalOA+aFYGlK+EfxcI5MbO7EP2yYygwh9h+s=
|
||||||
|
gorm.io/gorm v1.25.10/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
|
||||||
|
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||||
|
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||||
|
honnef.co/go/tools v0.0.1-2020.1.4 h1:UoveltGrhghAA7ePc+e+QYDHXrBps2PqFZiHkGR/xK8=
|
||||||
|
honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k=
|
||||||
|
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
|
||||||
|
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
|
|
@ -0,0 +1,137 @@
|
||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"donetick.com/core/config"
|
||||||
|
uModel "donetick.com/core/internal/user/model"
|
||||||
|
uRepo "donetick.com/core/internal/user/repo"
|
||||||
|
"donetick.com/core/logging"
|
||||||
|
jwt "github.com/appleboy/gin-jwt/v2"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
)
|
||||||
|
|
||||||
|
var identityKey = "id"
|
||||||
|
|
||||||
|
type signIn struct {
|
||||||
|
Username string `form:"username" json:"username" binding:"required"`
|
||||||
|
Password string `form:"password" json:"password" binding:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func CurrentUser(c *gin.Context) (*uModel.User, bool) {
|
||||||
|
data, ok := c.Get(identityKey)
|
||||||
|
if !ok {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
acc, ok := data.(*uModel.User)
|
||||||
|
return acc, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
func MustCurrentUser(c *gin.Context) *uModel.User {
|
||||||
|
acc, ok := CurrentUser(c)
|
||||||
|
if ok {
|
||||||
|
return acc
|
||||||
|
}
|
||||||
|
panic("no account in gin.Context")
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewAuthMiddleware(cfg *config.Config, userRepo *uRepo.UserRepository) (*jwt.GinJWTMiddleware, error) {
|
||||||
|
return jwt.New(&jwt.GinJWTMiddleware{
|
||||||
|
Realm: "test zone",
|
||||||
|
Key: []byte(cfg.Jwt.Secret),
|
||||||
|
Timeout: cfg.Jwt.SessionTime,
|
||||||
|
MaxRefresh: cfg.Jwt.MaxRefresh, // 7 days as long as their token is valid they can refresh it
|
||||||
|
IdentityKey: identityKey,
|
||||||
|
PayloadFunc: func(data interface{}) jwt.MapClaims {
|
||||||
|
if u, ok := data.(*uModel.User); ok {
|
||||||
|
return jwt.MapClaims{
|
||||||
|
identityKey: u.Username,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return jwt.MapClaims{}
|
||||||
|
},
|
||||||
|
IdentityHandler: func(c *gin.Context) interface{} {
|
||||||
|
claims := jwt.ExtractClaims(c)
|
||||||
|
username, ok := claims[identityKey].(string)
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
user, err := userRepo.GetUserByUsername(c.Request.Context(), username)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return user
|
||||||
|
},
|
||||||
|
Authenticator: func(c *gin.Context) (interface{}, error) {
|
||||||
|
provider := c.Value("auth_provider")
|
||||||
|
switch provider {
|
||||||
|
case nil:
|
||||||
|
var req signIn
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
return "", jwt.ErrMissingLoginValues
|
||||||
|
}
|
||||||
|
|
||||||
|
// ctx := cache.WithCacheSkip(c.Request.Context(), true)
|
||||||
|
user, err := userRepo.GetUserByUsername(c.Request.Context(), req.Username)
|
||||||
|
if err != nil || user.Disabled {
|
||||||
|
return nil, jwt.ErrFailedAuthentication
|
||||||
|
}
|
||||||
|
err = Matches(user.Password, req.Password)
|
||||||
|
if err != nil {
|
||||||
|
if err != bcrypt.ErrMismatchedHashAndPassword {
|
||||||
|
logging.FromContext(c).Warnw("middleware.jwt.Authenticator found unknown error when matches password", "err", err)
|
||||||
|
}
|
||||||
|
return nil, jwt.ErrFailedAuthentication
|
||||||
|
}
|
||||||
|
return &uModel.User{
|
||||||
|
ID: user.ID,
|
||||||
|
Username: user.Username,
|
||||||
|
Password: "",
|
||||||
|
Image: user.Image,
|
||||||
|
CreatedAt: user.CreatedAt,
|
||||||
|
UpdatedAt: user.UpdatedAt,
|
||||||
|
Disabled: user.Disabled,
|
||||||
|
CircleID: user.CircleID,
|
||||||
|
}, nil
|
||||||
|
case "3rdPartyAuth":
|
||||||
|
// we should only reach this stage if a handler mannually call authenticator with it's context:
|
||||||
|
|
||||||
|
var authObject *uModel.User
|
||||||
|
v := c.Value("user_account")
|
||||||
|
authObject = v.(*uModel.User)
|
||||||
|
|
||||||
|
return authObject, nil
|
||||||
|
|
||||||
|
default:
|
||||||
|
return nil, jwt.ErrFailedAuthentication
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
Authorizator: func(data interface{}, c *gin.Context) bool {
|
||||||
|
|
||||||
|
if _, ok := data.(*uModel.User); ok {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
},
|
||||||
|
Unauthorized: func(c *gin.Context, code int, message string) {
|
||||||
|
logging.FromContext(c).Info("middleware.jwt.Unauthorized", "code", code, "message", message)
|
||||||
|
c.JSON(code, gin.H{
|
||||||
|
"code": code,
|
||||||
|
"message": message,
|
||||||
|
})
|
||||||
|
},
|
||||||
|
LoginResponse: func(c *gin.Context, code int, token string, expire time.Time) {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"code": code,
|
||||||
|
"token": token,
|
||||||
|
"expire": expire,
|
||||||
|
})
|
||||||
|
},
|
||||||
|
TokenLookup: "header: Authorization",
|
||||||
|
TokenHeadName: "Bearer",
|
||||||
|
TimeFunc: time.Now,
|
||||||
|
})
|
||||||
|
}
|
|
@ -0,0 +1,60 @@
|
||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/base64"
|
||||||
|
"math/big"
|
||||||
|
|
||||||
|
"donetick.com/core/logging"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
)
|
||||||
|
|
||||||
|
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-=[]{}|;':,.<>?/~"
|
||||||
|
|
||||||
|
func EncodePassword(password string) (string, error) {
|
||||||
|
bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return string(bytes), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func Matches(hashedPassword, password string) error {
|
||||||
|
return bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
|
||||||
|
}
|
||||||
|
|
||||||
|
func GenerateRandomPassword(length int) string {
|
||||||
|
// Create a buffer to hold the random bytes.
|
||||||
|
buffer := make([]byte, length)
|
||||||
|
|
||||||
|
// Compute the maximum index for the characters.
|
||||||
|
maxIndex := big.NewInt(int64(len(chars)))
|
||||||
|
|
||||||
|
// Generate random bytes and use them to select characters from the set.
|
||||||
|
for i := 0; i < length; i++ {
|
||||||
|
randomIndex, _ := rand.Int(rand.Reader, maxIndex)
|
||||||
|
buffer[i] = chars[randomIndex.Int64()]
|
||||||
|
}
|
||||||
|
|
||||||
|
return string(buffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
func GenerateEmailResetToken(c *gin.Context) (string, error) {
|
||||||
|
logger := logging.FromContext(c)
|
||||||
|
// Define the length of the token (in bytes). For example, 32 bytes will result in a 44-character base64-encoded token.
|
||||||
|
tokenLength := 32
|
||||||
|
|
||||||
|
// Generate a random byte slice.
|
||||||
|
tokenBytes := make([]byte, tokenLength)
|
||||||
|
_, err := rand.Read(tokenBytes)
|
||||||
|
if err != nil {
|
||||||
|
logger.Errorw("password.GenerateEmailResetToken failed to generate random bytes", "err", err)
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Encode the byte slice to a base64 string.
|
||||||
|
token := base64.URLEncoding.EncodeToString(tokenBytes)
|
||||||
|
|
||||||
|
return token, nil
|
||||||
|
}
|
|
@ -0,0 +1,974 @@
|
||||||
|
package chore
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"html"
|
||||||
|
"log"
|
||||||
|
"math"
|
||||||
|
"math/rand"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
auth "donetick.com/core/internal/authorization"
|
||||||
|
chModel "donetick.com/core/internal/chore/model"
|
||||||
|
chRepo "donetick.com/core/internal/chore/repo"
|
||||||
|
cRepo "donetick.com/core/internal/circle/repo"
|
||||||
|
nRepo "donetick.com/core/internal/notifier/repo"
|
||||||
|
nps "donetick.com/core/internal/notifier/service"
|
||||||
|
telegram "donetick.com/core/internal/notifier/telegram"
|
||||||
|
tRepo "donetick.com/core/internal/thing/repo"
|
||||||
|
uModel "donetick.com/core/internal/user/model"
|
||||||
|
"donetick.com/core/logging"
|
||||||
|
jwt "github.com/appleboy/gin-jwt/v2"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ThingTrigger struct {
|
||||||
|
ID int `json:"thingID" binding:"required"`
|
||||||
|
TriggerState string `json:"triggerState" binding:"required"`
|
||||||
|
Condition string `json:"condition"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ChoreReq struct {
|
||||||
|
Name string `json:"name" binding:"required"`
|
||||||
|
FrequencyType string `json:"frequencyType"`
|
||||||
|
ID int `json:"id"`
|
||||||
|
DueDate string `json:"dueDate"`
|
||||||
|
Assignees []chModel.ChoreAssignees `json:"assignees"`
|
||||||
|
AssignStrategy string `json:"assignStrategy" binding:"required"`
|
||||||
|
AssignedTo int `json:"assignedTo"`
|
||||||
|
IsRolling bool `json:"isRolling"`
|
||||||
|
IsActive bool `json:"isActive"`
|
||||||
|
Frequency int `json:"frequency"`
|
||||||
|
FrequencyMetadata *chModel.FrequencyMetadata `json:"frequencyMetadata"`
|
||||||
|
Notification bool `json:"notification"`
|
||||||
|
NotificationMetadata *chModel.NotificationMetadata `json:"notificationMetadata"`
|
||||||
|
Labels []string `json:"labels"`
|
||||||
|
ThingTrigger *ThingTrigger `json:"thingTrigger"`
|
||||||
|
}
|
||||||
|
type Handler struct {
|
||||||
|
choreRepo *chRepo.ChoreRepository
|
||||||
|
circleRepo *cRepo.CircleRepository
|
||||||
|
notifier *telegram.TelegramNotifier
|
||||||
|
nPlanner *nps.NotificationPlanner
|
||||||
|
nRepo *nRepo.NotificationRepository
|
||||||
|
tRepo *tRepo.ThingRepository
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHandler(cr *chRepo.ChoreRepository, circleRepo *cRepo.CircleRepository, nt *telegram.TelegramNotifier,
|
||||||
|
np *nps.NotificationPlanner, nRepo *nRepo.NotificationRepository, tRepo *tRepo.ThingRepository) *Handler {
|
||||||
|
return &Handler{
|
||||||
|
choreRepo: cr,
|
||||||
|
circleRepo: circleRepo,
|
||||||
|
notifier: nt,
|
||||||
|
nPlanner: np,
|
||||||
|
nRepo: nRepo,
|
||||||
|
tRepo: tRepo,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) getChores(c *gin.Context) {
|
||||||
|
u, ok := auth.CurrentUser(c)
|
||||||
|
if !ok {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting current circle",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
chores, err := h.choreRepo.GetChores(c, u.CircleID, u.ID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting chores",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"res": chores,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) getChore(c *gin.Context) {
|
||||||
|
|
||||||
|
currentUser, ok := auth.CurrentUser(c)
|
||||||
|
if !ok {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting current user",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
rawID := c.Param("id")
|
||||||
|
id, err := strconv.Atoi(rawID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Invalid ID",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
chore, err := h.choreRepo.GetChore(c, id)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting chore",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
isAssignee := false
|
||||||
|
|
||||||
|
for _, assignee := range chore.Assignees {
|
||||||
|
if assignee.UserID == currentUser.ID {
|
||||||
|
isAssignee = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if currentUser.ID != chore.CreatedBy && !isAssignee {
|
||||||
|
c.JSON(403, gin.H{
|
||||||
|
"error": "You are not allowed to view this chore",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"res": chore,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) createChore(c *gin.Context) {
|
||||||
|
logger := logging.FromContext(c)
|
||||||
|
currentUser, ok := auth.CurrentUser(c)
|
||||||
|
|
||||||
|
logger.Debug("Create chore", "currentUser", currentUser)
|
||||||
|
if !ok {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting current user",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Validate chore:
|
||||||
|
var choreReq ChoreReq
|
||||||
|
if err := c.ShouldBindJSON(&choreReq); err != nil {
|
||||||
|
log.Print(err)
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Invalid request",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
circleUsers, err := h.circleRepo.GetCircleUsers(c, currentUser.CircleID)
|
||||||
|
for _, assignee := range choreReq.Assignees {
|
||||||
|
userFound := false
|
||||||
|
for _, circleUser := range circleUsers {
|
||||||
|
if assignee.UserID == circleUser.UserID {
|
||||||
|
userFound = true
|
||||||
|
|
||||||
|
break
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !userFound {
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Assignee not found in circle",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
if choreReq.AssignedTo <= 0 && len(choreReq.Assignees) > 0 {
|
||||||
|
// if the assigned to field is not set, randomly assign the chore to one of the assignees
|
||||||
|
choreReq.AssignedTo = choreReq.Assignees[rand.Intn(len(choreReq.Assignees))].UserID
|
||||||
|
}
|
||||||
|
|
||||||
|
var dueDate *time.Time
|
||||||
|
|
||||||
|
if choreReq.DueDate != "" {
|
||||||
|
rawDueDate, err := time.Parse(time.RFC3339, choreReq.DueDate)
|
||||||
|
rawDueDate = rawDueDate.UTC()
|
||||||
|
dueDate = &rawDueDate
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Invalid date",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
} else {
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Due date is required",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
freqencyMetadataBytes, err := json.Marshal(choreReq.FrequencyMetadata)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error marshalling frequency metadata",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
stringFrequencyMetadata := string(freqencyMetadataBytes)
|
||||||
|
|
||||||
|
notificationMetadataBytes, err := json.Marshal(choreReq.NotificationMetadata)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error marshalling notification metadata",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
stringNotificationMetadata := string(notificationMetadataBytes)
|
||||||
|
|
||||||
|
var stringLabels *string
|
||||||
|
if len(choreReq.Labels) > 0 {
|
||||||
|
var escapedLabels []string
|
||||||
|
for _, label := range choreReq.Labels {
|
||||||
|
escapedLabels = append(escapedLabels, html.EscapeString(label))
|
||||||
|
}
|
||||||
|
|
||||||
|
labels := strings.Join(escapedLabels, ",")
|
||||||
|
stringLabels = &labels
|
||||||
|
}
|
||||||
|
createdChore := &chModel.Chore{
|
||||||
|
|
||||||
|
Name: choreReq.Name,
|
||||||
|
FrequencyType: choreReq.FrequencyType,
|
||||||
|
Frequency: choreReq.Frequency,
|
||||||
|
FrequencyMetadata: &stringFrequencyMetadata,
|
||||||
|
NextDueDate: dueDate,
|
||||||
|
AssignStrategy: choreReq.AssignStrategy,
|
||||||
|
AssignedTo: choreReq.AssignedTo,
|
||||||
|
IsRolling: choreReq.IsRolling,
|
||||||
|
UpdatedBy: currentUser.ID,
|
||||||
|
IsActive: true,
|
||||||
|
Notification: choreReq.Notification,
|
||||||
|
NotificationMetadata: &stringNotificationMetadata,
|
||||||
|
Labels: stringLabels,
|
||||||
|
CreatedBy: currentUser.ID,
|
||||||
|
CreatedAt: time.Now().UTC(),
|
||||||
|
CircleID: currentUser.CircleID,
|
||||||
|
}
|
||||||
|
id, err := h.choreRepo.CreateChore(c, createdChore)
|
||||||
|
createdChore.ID = id
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error creating chore",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var choreAssignees []*chModel.ChoreAssignees
|
||||||
|
for _, assignee := range choreReq.Assignees {
|
||||||
|
choreAssignees = append(choreAssignees, &chModel.ChoreAssignees{
|
||||||
|
ChoreID: id,
|
||||||
|
UserID: assignee.UserID,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.choreRepo.UpdateChoreAssignees(c, choreAssignees); err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error adding chore assignees",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
go func() {
|
||||||
|
h.nPlanner.GenerateNotifications(c, createdChore)
|
||||||
|
}()
|
||||||
|
shouldReturn := HandleThingAssociation(choreReq, h, c, currentUser)
|
||||||
|
if shouldReturn {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"res": id,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) editChore(c *gin.Context) {
|
||||||
|
// logger := logging.FromContext(c)
|
||||||
|
currentUser, ok := auth.CurrentUser(c)
|
||||||
|
if !ok {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting current user",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var choreReq ChoreReq
|
||||||
|
if err := c.ShouldBindJSON(&choreReq); err != nil {
|
||||||
|
log.Print(err)
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Invalid request",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
circleUsers, err := h.circleRepo.GetCircleUsers(c, currentUser.CircleID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting circle users",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
existedChoreAssignees, err := h.choreRepo.GetChoreAssignees(c, choreReq.ID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting chore assignees",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var choreAssigneesToAdd []*chModel.ChoreAssignees
|
||||||
|
var choreAssigneesToDelete []*chModel.ChoreAssignees
|
||||||
|
|
||||||
|
// filter assignees that not in the circle
|
||||||
|
for _, assignee := range choreReq.Assignees {
|
||||||
|
userFound := false
|
||||||
|
for _, circleUser := range circleUsers {
|
||||||
|
if assignee.UserID == circleUser.UserID {
|
||||||
|
userFound = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !userFound {
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Assignee not found in circle",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
userAlreadyAssignee := false
|
||||||
|
for _, existedChoreAssignee := range existedChoreAssignees {
|
||||||
|
if existedChoreAssignee.UserID == assignee.UserID {
|
||||||
|
userAlreadyAssignee = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !userAlreadyAssignee {
|
||||||
|
choreAssigneesToAdd = append(choreAssigneesToAdd, &chModel.ChoreAssignees{
|
||||||
|
ChoreID: choreReq.ID,
|
||||||
|
UserID: assignee.UserID,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// remove assignees if they are not in the assignees list anymore
|
||||||
|
for _, existedChoreAssignee := range existedChoreAssignees {
|
||||||
|
userFound := false
|
||||||
|
for _, assignee := range choreReq.Assignees {
|
||||||
|
if existedChoreAssignee.UserID == assignee.UserID {
|
||||||
|
userFound = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !userFound {
|
||||||
|
choreAssigneesToDelete = append(choreAssigneesToDelete, existedChoreAssignee)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var dueDate *time.Time
|
||||||
|
|
||||||
|
if choreReq.DueDate != "" {
|
||||||
|
rawDueDate, err := time.Parse(time.RFC3339, choreReq.DueDate)
|
||||||
|
rawDueDate = rawDueDate.UTC()
|
||||||
|
dueDate = &rawDueDate
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Invalid date",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// validate assignedTo part of the assignees:
|
||||||
|
assigneeFound := false
|
||||||
|
for _, assignee := range choreReq.Assignees {
|
||||||
|
if assignee.UserID == choreReq.AssignedTo {
|
||||||
|
assigneeFound = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !assigneeFound {
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Assigned to not found in assignees",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if choreReq.AssignedTo <= 0 && len(choreReq.Assignees) > 0 {
|
||||||
|
// if the assigned to field is not set, randomly assign the chore to one of the assignees
|
||||||
|
choreReq.AssignedTo = choreReq.Assignees[rand.Intn(len(choreReq.Assignees))].UserID
|
||||||
|
}
|
||||||
|
oldChore, err := h.choreRepo.GetChore(c, choreReq.ID)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting chore",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if currentUser.ID != oldChore.CreatedBy {
|
||||||
|
c.JSON(403, gin.H{
|
||||||
|
"error": "You are not allowed to edit this chore",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
freqencyMetadataBytes, err := json.Marshal(choreReq.FrequencyMetadata)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error marshalling frequency metadata",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
stringFrequencyMetadata := string(freqencyMetadataBytes)
|
||||||
|
|
||||||
|
notificationMetadataBytes, err := json.Marshal(choreReq.NotificationMetadata)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error marshalling notification metadata",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
stringNotificationMetadata := string(notificationMetadataBytes)
|
||||||
|
|
||||||
|
// escape special characters in labels and store them as a string :
|
||||||
|
var stringLabels *string
|
||||||
|
if len(choreReq.Labels) > 0 {
|
||||||
|
var escapedLabels []string
|
||||||
|
for _, label := range choreReq.Labels {
|
||||||
|
escapedLabels = append(escapedLabels, html.EscapeString(label))
|
||||||
|
}
|
||||||
|
|
||||||
|
labels := strings.Join(escapedLabels, ",")
|
||||||
|
stringLabels = &labels
|
||||||
|
}
|
||||||
|
updatedChore := &chModel.Chore{
|
||||||
|
ID: choreReq.ID,
|
||||||
|
Name: choreReq.Name,
|
||||||
|
FrequencyType: choreReq.FrequencyType,
|
||||||
|
Frequency: choreReq.Frequency,
|
||||||
|
FrequencyMetadata: &stringFrequencyMetadata,
|
||||||
|
// Assignees: &assignees,
|
||||||
|
NextDueDate: dueDate,
|
||||||
|
AssignStrategy: choreReq.AssignStrategy,
|
||||||
|
AssignedTo: choreReq.AssignedTo,
|
||||||
|
IsRolling: choreReq.IsRolling,
|
||||||
|
IsActive: choreReq.IsActive,
|
||||||
|
Notification: choreReq.Notification,
|
||||||
|
NotificationMetadata: &stringNotificationMetadata,
|
||||||
|
Labels: stringLabels,
|
||||||
|
CircleID: oldChore.CircleID,
|
||||||
|
UpdatedBy: currentUser.ID,
|
||||||
|
CreatedBy: oldChore.CreatedBy,
|
||||||
|
CreatedAt: oldChore.CreatedAt,
|
||||||
|
}
|
||||||
|
if err := h.choreRepo.UpsertChore(c, updatedChore); err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error adding chore",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(choreAssigneesToAdd) > 0 {
|
||||||
|
err = h.choreRepo.UpdateChoreAssignees(c, choreAssigneesToAdd)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error updating chore assignees",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(choreAssigneesToDelete) > 0 {
|
||||||
|
err = h.choreRepo.DeleteChoreAssignees(c, choreAssigneesToDelete)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error deleting chore assignees",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
go func() {
|
||||||
|
h.nPlanner.GenerateNotifications(c, updatedChore)
|
||||||
|
}()
|
||||||
|
if oldChore.ThingChore.ThingID != 0 {
|
||||||
|
// TODO: Add check to see if dissociation is necessary
|
||||||
|
h.tRepo.DissociateThingWithChore(c, oldChore.ThingChore.ThingID, oldChore.ID)
|
||||||
|
|
||||||
|
}
|
||||||
|
shouldReturn := HandleThingAssociation(choreReq, h, c, currentUser)
|
||||||
|
if shouldReturn {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"message": "Chore added successfully",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func HandleThingAssociation(choreReq ChoreReq, h *Handler, c *gin.Context, currentUser *uModel.User) bool {
|
||||||
|
if choreReq.ThingTrigger != nil {
|
||||||
|
thing, err := h.tRepo.GetThingByID(c, choreReq.ThingTrigger.ID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting thing",
|
||||||
|
})
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if thing.UserID != currentUser.ID {
|
||||||
|
c.JSON(403, gin.H{
|
||||||
|
"error": "You are not allowed to trigger this thing",
|
||||||
|
})
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if err := h.tRepo.AssociateThingWithChore(c, choreReq.ThingTrigger.ID, choreReq.ID, choreReq.ThingTrigger.TriggerState, choreReq.ThingTrigger.Condition); err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error associating thing with chore",
|
||||||
|
})
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) deleteChore(c *gin.Context) {
|
||||||
|
// logger := logging.FromContext(c)
|
||||||
|
currentUser, ok := auth.CurrentUser(c)
|
||||||
|
if !ok {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting current user",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
rawID := c.Param("id")
|
||||||
|
id, err := strconv.Atoi(rawID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Invalid ID",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// check if the user is the owner of the chore before deleting
|
||||||
|
if err := h.choreRepo.IsChoreOwner(c, id, currentUser.ID); err != nil {
|
||||||
|
c.JSON(403, gin.H{
|
||||||
|
"error": "You are not allowed to delete this chore",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.choreRepo.DeleteChore(c, id); err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error deleting chore",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.nRepo.DeleteAllChoreNotifications(id)
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"message": "Chore deleted successfully",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// func (h *Handler) createChore(c *gin.Context) {
|
||||||
|
// logger := logging.FromContext(c)
|
||||||
|
// currentUser, ok := auth.CurrentUser(c)
|
||||||
|
|
||||||
|
// logger.Debug("Create chore", "currentUser", currentUser)
|
||||||
|
// if !ok {
|
||||||
|
// c.JSON(500, gin.H{
|
||||||
|
// "error": "Error getting current user",
|
||||||
|
// })
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
// id, err := h.choreRepo.CreateChore(currentUser.ID, currentUser.CircleID)
|
||||||
|
// if err != nil {
|
||||||
|
// c.JSON(500, gin.H{
|
||||||
|
// "error": "Error creating chore",
|
||||||
|
// })
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
|
||||||
|
// c.JSON(200, gin.H{
|
||||||
|
// "res": id,
|
||||||
|
// })
|
||||||
|
// }
|
||||||
|
|
||||||
|
func (h *Handler) updateAssignee(c *gin.Context) {
|
||||||
|
rawID := c.Param("id")
|
||||||
|
id, err := strconv.Atoi(rawID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Invalid ID",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
type AssigneeReq struct {
|
||||||
|
AssignedTo int `json:"assignedTo" binding:"required"`
|
||||||
|
UpdatedBy int `json:"updatedBy" binding:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var assigneeReq AssigneeReq
|
||||||
|
if err := c.ShouldBindJSON(&assigneeReq); err != nil {
|
||||||
|
log.Print(err)
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Invalid request",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
chore, err := h.choreRepo.GetChore(c, id)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting chore",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// confirm that the assignee is one of the assignees:
|
||||||
|
assigneeFound := false
|
||||||
|
for _, assignee := range chore.Assignees {
|
||||||
|
|
||||||
|
if assignee.UserID == assigneeReq.AssignedTo {
|
||||||
|
assigneeFound = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !assigneeFound {
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Assignee not found in assignees",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
chore.UpdatedBy = assigneeReq.UpdatedBy
|
||||||
|
chore.AssignedTo = assigneeReq.AssignedTo
|
||||||
|
if err := h.choreRepo.UpsertChore(c, chore); err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error updating assignee",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"res": chore,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) skipChore(c *gin.Context) {
|
||||||
|
rawID := c.Param("id")
|
||||||
|
id, err := strconv.Atoi(rawID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Invalid ID",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
chore, err := h.choreRepo.GetChore(c, id)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting chore",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
newDueDate, err := scheduleNextDueDate(chore, chore.NextDueDate.UTC())
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error scheduling next due date",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
chore.NextDueDate = newDueDate
|
||||||
|
if err := h.choreRepo.UpsertChore(c, chore); err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error skipping chore",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := h.choreRepo.UpsertChore(c, chore); err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error skipping chore",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"res": chore,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) updateDueDate(c *gin.Context) {
|
||||||
|
currentUser, ok := auth.CurrentUser(c)
|
||||||
|
if !ok {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting current user",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
type DueDateReq struct {
|
||||||
|
DueDate string `json:"dueDate" binding:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var dueDateReq DueDateReq
|
||||||
|
if err := c.ShouldBindJSON(&dueDateReq); err != nil {
|
||||||
|
log.Print(err)
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Invalid request",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
rawID := c.Param("id")
|
||||||
|
id, err := strconv.Atoi(rawID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Invalid ID",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
rawDueDate, err := time.Parse(time.RFC3339, dueDateReq.DueDate)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Invalid date",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
dueDate := rawDueDate.UTC()
|
||||||
|
chore, err := h.choreRepo.GetChore(c, id)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting chore",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
chore.NextDueDate = &dueDate
|
||||||
|
chore.UpdatedBy = currentUser.ID
|
||||||
|
if err := h.choreRepo.UpsertChore(c, chore); err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error updating due date",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"res": chore,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
func (h *Handler) completeChore(c *gin.Context) {
|
||||||
|
type CompleteChoreReq struct {
|
||||||
|
Note string `json:"note"`
|
||||||
|
}
|
||||||
|
var req CompleteChoreReq
|
||||||
|
currentUser, ok := auth.CurrentUser(c)
|
||||||
|
if !ok {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting current user",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
completeChoreID := c.Param("id")
|
||||||
|
var completedDate time.Time
|
||||||
|
rawCompletedDate := c.Query("completedDate")
|
||||||
|
if rawCompletedDate == "" {
|
||||||
|
completedDate = time.Now().UTC()
|
||||||
|
} else {
|
||||||
|
var err error
|
||||||
|
completedDate, err = time.Parse(time.RFC3339, rawCompletedDate)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Invalid date",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var additionalNotes *string
|
||||||
|
_ = c.ShouldBind(&req)
|
||||||
|
|
||||||
|
if req.Note != "" {
|
||||||
|
additionalNotes = &req.Note
|
||||||
|
}
|
||||||
|
|
||||||
|
id, err := strconv.Atoi(completeChoreID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Invalid ID",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
chore, err := h.choreRepo.GetChore(c, id)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting chore",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
nextDueDate, err := scheduleNextDueDate(chore, completedDate)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Error scheduling next due date: %s", err)
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error scheduling next due date",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
choreHistory, err := h.choreRepo.GetChoreHistory(c, chore.ID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting chore history",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
nextAssignedTo, err := checkNextAssignee(chore, choreHistory, currentUser.ID)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Error checking next assignee: %s", err)
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error checking next assignee",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.choreRepo.CompleteChore(c, chore, additionalNotes, currentUser.ID, nextDueDate, completedDate, nextAssignedTo); err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error completing chore",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
updatedChore, err := h.choreRepo.GetChore(c, id)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting chore",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
go func() {
|
||||||
|
h.notifier.SendChoreCompletion(c, chore, []*uModel.User{currentUser})
|
||||||
|
h.nPlanner.GenerateNotifications(c, updatedChore)
|
||||||
|
}()
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"res": updatedChore,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) GetChoreHistory(c *gin.Context) {
|
||||||
|
rawID := c.Param("id")
|
||||||
|
id, err := strconv.Atoi(rawID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Invalid ID",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
choreHistory, err := h.choreRepo.GetChoreHistory(c, id)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting chore history",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"res": choreHistory,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkNextAssignee(chore *chModel.Chore, choresHistory []*chModel.ChoreHistory, performerID int) (int, error) {
|
||||||
|
// copy the history to avoid modifying the original:
|
||||||
|
history := make([]*chModel.ChoreHistory, len(choresHistory))
|
||||||
|
copy(history, choresHistory)
|
||||||
|
|
||||||
|
assigneesMap := map[int]bool{}
|
||||||
|
for _, assignee := range chore.Assignees {
|
||||||
|
assigneesMap[assignee.UserID] = true
|
||||||
|
}
|
||||||
|
var nextAssignee int
|
||||||
|
if len(history) == 0 {
|
||||||
|
// if there is no history, just assume the current operation as the first
|
||||||
|
history = append(history, &chModel.ChoreHistory{
|
||||||
|
AssignedTo: performerID,
|
||||||
|
})
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
switch chore.AssignStrategy {
|
||||||
|
case "least_assigned":
|
||||||
|
// find the assignee with the least number of chores
|
||||||
|
assigneeChores := map[int]int{}
|
||||||
|
for _, performer := range chore.Assignees {
|
||||||
|
assigneeChores[performer.UserID] = 0
|
||||||
|
}
|
||||||
|
for _, history := range history {
|
||||||
|
if ok := assigneesMap[history.AssignedTo]; !ok {
|
||||||
|
// calculate the number of chores assigned to each assignee
|
||||||
|
assigneeChores[history.AssignedTo]++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
minChores := math.MaxInt64
|
||||||
|
for assignee, numChores := range assigneeChores {
|
||||||
|
// if this is the first assignee or if the number of
|
||||||
|
// chores assigned to this assignee is less than the current minimum
|
||||||
|
if numChores < minChores {
|
||||||
|
minChores = numChores
|
||||||
|
// set the next assignee to this assignee
|
||||||
|
nextAssignee = assignee
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case "least_completed":
|
||||||
|
// find the assignee who has completed the least number of chores
|
||||||
|
assigneeChores := map[int]int{}
|
||||||
|
for _, performer := range chore.Assignees {
|
||||||
|
assigneeChores[performer.UserID] = 0
|
||||||
|
}
|
||||||
|
for _, history := range history {
|
||||||
|
// calculate the number of chores completed by each assignee
|
||||||
|
assigneeChores[history.CompletedBy]++
|
||||||
|
}
|
||||||
|
|
||||||
|
// max Int value
|
||||||
|
minChores := math.MaxInt64
|
||||||
|
for assignee, numChores := range assigneeChores {
|
||||||
|
// if this is the first assignee or if the number of
|
||||||
|
// chores completed by this assignee is less than the current minimum
|
||||||
|
if numChores < minChores {
|
||||||
|
minChores = numChores
|
||||||
|
// set the next assignee to this assignee
|
||||||
|
nextAssignee = assignee
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case "random":
|
||||||
|
nextAssignee = chore.Assignees[rand.Intn(len(chore.Assignees))].UserID
|
||||||
|
case "keep_last_assigned":
|
||||||
|
// keep the last assignee
|
||||||
|
nextAssignee = history[len(history)-1].AssignedTo
|
||||||
|
|
||||||
|
default:
|
||||||
|
return chore.AssignedTo, fmt.Errorf("invalid assign strategy")
|
||||||
|
|
||||||
|
}
|
||||||
|
return nextAssignee, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func Routes(router *gin.Engine, h *Handler, auth *jwt.GinJWTMiddleware) {
|
||||||
|
|
||||||
|
choresRoutes := router.Group("chores")
|
||||||
|
choresRoutes.Use(auth.MiddlewareFunc())
|
||||||
|
{
|
||||||
|
choresRoutes.GET("/", h.getChores)
|
||||||
|
choresRoutes.PUT("/", h.editChore)
|
||||||
|
choresRoutes.POST("/", h.createChore)
|
||||||
|
choresRoutes.GET("/:id", h.getChore)
|
||||||
|
choresRoutes.GET("/:id/history", h.GetChoreHistory)
|
||||||
|
choresRoutes.POST("/:id/do", h.completeChore)
|
||||||
|
choresRoutes.POST("/:id/skip", h.skipChore)
|
||||||
|
choresRoutes.PUT("/:id/assignee", h.updateAssignee)
|
||||||
|
choresRoutes.PUT("/:id/dueDate", h.updateDueDate)
|
||||||
|
choresRoutes.DELETE("/:id", h.deleteChore)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,72 @@
|
||||||
|
package model
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
tModel "donetick.com/core/internal/thing/model"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Chore struct {
|
||||||
|
ID int `json:"id" gorm:"primary_key"`
|
||||||
|
Name string `json:"name" gorm:"column:name"` // Chore description
|
||||||
|
FrequencyType string `json:"frequencyType" gorm:"column:frequency_type"` // "daily", "weekly", "monthly", "yearly", "adaptive",or "custom"
|
||||||
|
Frequency int `json:"frequency" gorm:"column:frequency"` // Number of days, weeks, months, or years between chores
|
||||||
|
FrequencyMetadata *string `json:"frequencyMetadata" gorm:"column:frequency_meta"` // Additional frequency information
|
||||||
|
NextDueDate *time.Time `json:"nextDueDate" gorm:"column:next_due_date;index"` // When the chore is due
|
||||||
|
IsRolling bool `json:"isRolling" gorm:"column:is_rolling"` // Whether the chore is rolling
|
||||||
|
AssignedTo int `json:"assignedTo" gorm:"column:assigned_to"` // Who the chore is assigned to
|
||||||
|
Assignees []ChoreAssignees `json:"assignees" gorm:"foreignkey:ChoreID;references:ID"` // Assignees of the chore
|
||||||
|
AssignStrategy string `json:"assignStrategy" gorm:"column:assign_strategy"` // How the chore is assigned
|
||||||
|
IsActive bool `json:"isActive" gorm:"column:is_active"` // Whether the chore is active
|
||||||
|
Notification bool `json:"notification" gorm:"column:notification"` // Whether the chore has notification
|
||||||
|
NotificationMetadata *string `json:"notificationMetadata" gorm:"column:notification_meta"` // Additional notification information
|
||||||
|
Labels *string `json:"labels" gorm:"column:labels"` // Labels for the chore
|
||||||
|
CircleID int `json:"circleId" gorm:"column:circle_id;index"` // The circle this chore is in
|
||||||
|
CreatedAt time.Time `json:"createdAt" gorm:"column:created_at"` // When the chore was created
|
||||||
|
UpdatedAt time.Time `json:"updatedAt" gorm:"column:updated_at"` // When the chore was last updated
|
||||||
|
CreatedBy int `json:"createdBy" gorm:"column:created_by"` // Who created the chore
|
||||||
|
UpdatedBy int `json:"updatedBy" gorm:"column:updated_by"` // Who last updated the chore
|
||||||
|
ThingChore tModel.ThingChore `json:"thingChore" gorm:"foreignkey:chore_id;references:id;<-:false"` // ThingChore relationship
|
||||||
|
}
|
||||||
|
type ChoreAssignees struct {
|
||||||
|
ID int `json:"-" gorm:"primary_key"`
|
||||||
|
ChoreID int `json:"-" gorm:"column:chore_id;uniqueIndex:idx_chore_user"` // The chore this assignee is for
|
||||||
|
UserID int `json:"userId" gorm:"column:user_id;uniqueIndex:idx_chore_user"` // The user this assignee is for
|
||||||
|
}
|
||||||
|
type ChoreHistory struct {
|
||||||
|
ID int `json:"id" gorm:"primary_key"` // Unique identifier
|
||||||
|
ChoreID int `json:"choreId" gorm:"column:chore_id"` // The chore this history is for
|
||||||
|
CompletedAt time.Time `json:"completedAt" gorm:"column:completed_at"` // When the chore was completed
|
||||||
|
CompletedBy int `json:"completedBy" gorm:"column:completed_by"` // Who completed the chore
|
||||||
|
AssignedTo int `json:"assignedTo" gorm:"column:assigned_to"` // Who the chore was assigned to
|
||||||
|
Note *string `json:"notes" gorm:"column:notes"` // Notes about the chore
|
||||||
|
DueDate *time.Time `json:"dueDate" gorm:"column:due_date"` // When the chore was due
|
||||||
|
}
|
||||||
|
|
||||||
|
type FrequencyMetadata struct {
|
||||||
|
Days []*string `json:"days,omitempty"`
|
||||||
|
Months []*string `json:"months,omitempty"`
|
||||||
|
Unit *string `json:"unit,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type NotificationMetadata struct {
|
||||||
|
DueDate bool `json:"dueDate,omitempty"`
|
||||||
|
Completion bool `json:"completion,omitempty"`
|
||||||
|
Nagging bool `json:"nagging,omitempty"`
|
||||||
|
PreDue bool `json:"predue,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Tag struct {
|
||||||
|
ID int `json:"-" gorm:"primary_key"`
|
||||||
|
Name string `json:"name" gorm:"column:name;unique"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// type ChoreTag struct {
|
||||||
|
// ChoreID int `json:"choreId" gorm:"primaryKey;autoIncrement:false"`
|
||||||
|
// TagID int `json:"tagId" gorm:"primaryKey;autoIncrement:false"`
|
||||||
|
// }
|
||||||
|
|
||||||
|
// type CircleTag struct {
|
||||||
|
// CircleID int `json:"circleId" gorm:"primaryKey;autoIncrement:false"`
|
||||||
|
// TagID int `json:"tagId" gorm:"primaryKey;autoIncrement:false"`
|
||||||
|
// }
|
|
@ -0,0 +1,216 @@
|
||||||
|
package chore
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
config "donetick.com/core/config"
|
||||||
|
chModel "donetick.com/core/internal/chore/model"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ChoreRepository struct {
|
||||||
|
db *gorm.DB
|
||||||
|
dbType string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewChoreRepository(db *gorm.DB, cfg *config.Config) *ChoreRepository {
|
||||||
|
return &ChoreRepository{db: db, dbType: cfg.Database.Type}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ChoreRepository) UpsertChore(c context.Context, chore *chModel.Chore) error {
|
||||||
|
return r.db.WithContext(c).Model(&chore).Save(chore).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ChoreRepository) UpdateChores(c context.Context, chores []*chModel.Chore) error {
|
||||||
|
return r.db.WithContext(c).Save(&chores).Error
|
||||||
|
}
|
||||||
|
func (r *ChoreRepository) CreateChore(c context.Context, chore *chModel.Chore) (int, error) {
|
||||||
|
if err := r.db.WithContext(c).Create(chore).Error; err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return chore.ID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ChoreRepository) GetChore(c context.Context, choreID int) (*chModel.Chore, error) {
|
||||||
|
var chore chModel.Chore
|
||||||
|
if err := r.db.Debug().WithContext(c).Model(&chModel.Chore{}).Preload("Assignees").Preload("ThingChore").First(&chore, choreID).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &chore, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ChoreRepository) GetChores(c context.Context, circleID int, userID int) ([]*chModel.Chore, error) {
|
||||||
|
var chores []*chModel.Chore
|
||||||
|
// if err := r.db.WithContext(c).Preload("Assignees").Where("is_active = ?", true).Order("next_due_date asc").Find(&chores, "circle_id = ?", circleID).Error; err != nil {
|
||||||
|
if err := r.db.WithContext(c).Preload("Assignees").Joins("left join chore_assignees on chores.id = chore_assignees.chore_id").Where("chores.circle_id = ? AND (chores.created_by = ? OR chore_assignees.user_id = ?)", circleID, userID, userID).Group("chores.id").Order("next_due_date asc").Find(&chores, "circle_id = ?", circleID).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return chores, nil
|
||||||
|
}
|
||||||
|
func (r *ChoreRepository) DeleteChore(c context.Context, id int) error {
|
||||||
|
r.db.WithContext(c).Where("chore_id = ?", id).Delete(&chModel.ChoreAssignees{})
|
||||||
|
return r.db.WithContext(c).Delete(&chModel.Chore{}, id).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ChoreRepository) SoftDelete(c context.Context, id int, userID int) error {
|
||||||
|
return r.db.WithContext(c).Model(&chModel.Chore{}).Where("id = ?", id).Where("created_by = ? ", userID).Update("is_active", false).Error
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ChoreRepository) IsChoreOwner(c context.Context, choreID int, userID int) error {
|
||||||
|
var chore chModel.Chore
|
||||||
|
err := r.db.WithContext(c).Model(&chModel.Chore{}).Where("id = ? AND created_by = ?", choreID, userID).First(&chore).Error
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// func (r *ChoreRepository) ListChores(circleID int) ([]*chModel.Chore, error) {
|
||||||
|
// var chores []*Chore
|
||||||
|
// if err := r.db.WithContext(c).Find(&chores).Where("is_active = ?", true).Order("next_due_date").Error; err != nil {
|
||||||
|
// return nil, err
|
||||||
|
// }
|
||||||
|
// return chores, nil
|
||||||
|
// }
|
||||||
|
|
||||||
|
func (r *ChoreRepository) CompleteChore(c context.Context, chore *chModel.Chore, note *string, userID int, dueDate *time.Time, completedDate time.Time, nextAssignedTo int) error {
|
||||||
|
err := r.db.WithContext(c).Transaction(func(tx *gorm.DB) error {
|
||||||
|
ch := &chModel.ChoreHistory{
|
||||||
|
ChoreID: chore.ID,
|
||||||
|
CompletedAt: completedDate,
|
||||||
|
CompletedBy: userID,
|
||||||
|
AssignedTo: chore.AssignedTo,
|
||||||
|
DueDate: chore.NextDueDate,
|
||||||
|
Note: note,
|
||||||
|
}
|
||||||
|
if err := tx.Create(ch).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
updates := map[string]interface{}{}
|
||||||
|
updates["next_due_date"] = dueDate
|
||||||
|
|
||||||
|
if dueDate != nil {
|
||||||
|
updates["assigned_to"] = nextAssignedTo
|
||||||
|
} else {
|
||||||
|
updates["is_active"] = false
|
||||||
|
}
|
||||||
|
// Perform the update operation once, using the prepared updates map.
|
||||||
|
if err := tx.Model(&chModel.Chore{}).Where("id = ?", chore.ID).Updates(updates).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ChoreRepository) GetChoreHistory(c context.Context, choreID int) ([]*chModel.ChoreHistory, error) {
|
||||||
|
var histories []*chModel.ChoreHistory
|
||||||
|
if err := r.db.WithContext(c).Where("chore_id = ?", choreID).Order("completed_at desc").Find(&histories).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return histories, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ChoreRepository) UpdateChoreAssignees(c context.Context, assignees []*chModel.ChoreAssignees) error {
|
||||||
|
return r.db.WithContext(c).Save(&assignees).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ChoreRepository) DeleteChoreAssignees(c context.Context, choreAssignees []*chModel.ChoreAssignees) error {
|
||||||
|
return r.db.WithContext(c).Delete(&choreAssignees).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ChoreRepository) GetChoreAssignees(c context.Context, choreID int) ([]*chModel.ChoreAssignees, error) {
|
||||||
|
var assignees []*chModel.ChoreAssignees
|
||||||
|
if err := r.db.WithContext(c).Find(&assignees, "chore_id = ?", choreID).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return assignees, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ChoreRepository) RemoveChoreAssigneeByCircleID(c context.Context, userID int, circleID int) error {
|
||||||
|
return r.db.WithContext(c).Where("user_id = ? AND chore_id IN (SELECT id FROM chores WHERE circle_id = ? and created_by != ?)", userID, circleID, userID).Delete(&chModel.ChoreAssignees{}).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
// func (r *ChoreRepository) getChoreDueToday(circleID int) ([]*chModel.Chore, error) {
|
||||||
|
// var chores []*Chore
|
||||||
|
// if err := r.db.WithContext(c).Where("next_due_date <= ?", time.Now().UTC()).Find(&chores).Error; err != nil {
|
||||||
|
// return nil, err
|
||||||
|
// }
|
||||||
|
// return chores, nil
|
||||||
|
// }
|
||||||
|
|
||||||
|
func (r *ChoreRepository) GetAllActiveChores(c context.Context) ([]*chModel.Chore, error) {
|
||||||
|
var chores []*chModel.Chore
|
||||||
|
// query := r.db.WithContext(c).Table("chores").Joins("left join notifications n on n.chore_id = chores.id and n.scheduled_for < chores.next_due_date")
|
||||||
|
// if err := query.Where("chores.is_active = ? and chores.notification = ? and (n.is_sent = ? or n.is_sent is null)", true, true, false).Find(&chores).Error; err != nil {
|
||||||
|
// return nil, err
|
||||||
|
// }
|
||||||
|
return chores, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ChoreRepository) GetChoresForNotification(c context.Context) ([]*chModel.Chore, error) {
|
||||||
|
var chores []*chModel.Chore
|
||||||
|
query := r.db.WithContext(c).Table("chores").Joins("left join notifications n on n.chore_id = chores.id and n.scheduled_for = chores.next_due_date and n.type = 1")
|
||||||
|
if err := query.Where("chores.is_active = ? and chores.notification = ? and n.id is null", true, true).Find(&chores).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return chores, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// func (r *ChoreReposity) GetOverdueChoresForNotification(c context.Context, overdueDuration time.Duration, everyDuration time.Duration, untilDuration time.Duration) ([]*chModel.Chore, error) {
|
||||||
|
// var chores []*chModel.Chore
|
||||||
|
// query := r.db.Debug().WithContext(c).Table("chores").Select("chores.*, MAX(n.created_at) as max_notification_created_at").Joins("left join notifications n on n.chore_id = chores.id and n.scheduled_for = chores.next_due_date and n.type = 2")
|
||||||
|
// if err := query.Where("chores.is_active = ? and chores.notification = ? and chores.next_due_date < ? and chores.next_due_date > ?", true, true, time.Now().Add(overdueDuration).UTC(), time.Now().Add(untilDuration).UTC()).Where(readJSONBooleanField(r.dbType, "chores.notification_meta", "nagging")).Having("MAX(n.created_at) is null or MAX(n.created_at) < ?", time.Now().Add(everyDuration).UTC()).Group("chores.id").Find(&chores).Error; err != nil {
|
||||||
|
// return nil, err
|
||||||
|
// }
|
||||||
|
// return chores, nil
|
||||||
|
// }
|
||||||
|
|
||||||
|
func (r *ChoreRepository) GetOverdueChoresForNotification(c context.Context, overdueFor time.Duration, everyDuration time.Duration, untilDuration time.Duration) ([]*chModel.Chore, error) {
|
||||||
|
var chores []*chModel.Chore
|
||||||
|
now := time.Now().UTC()
|
||||||
|
overdueTime := now.Add(-overdueFor)
|
||||||
|
everyTime := now.Add(-everyDuration)
|
||||||
|
untilTime := now.Add(-untilDuration)
|
||||||
|
|
||||||
|
query := r.db.Debug().WithContext(c).
|
||||||
|
Table("chores").
|
||||||
|
Select("chores.*, MAX(n.created_at) as max_notification_created_at").
|
||||||
|
Joins("left join notifications n on n.chore_id = chores.id and n.type = 2").
|
||||||
|
Where("chores.is_active = ? AND chores.notification = ? AND chores.next_due_date < ? AND chores.next_due_date > ?", true, true, overdueTime, untilTime).
|
||||||
|
Where(readJSONBooleanField(r.dbType, "chores.notification_meta", "nagging")).
|
||||||
|
Group("chores.id").
|
||||||
|
Having("MAX(n.created_at) IS NULL OR MAX(n.created_at) < ?", everyTime)
|
||||||
|
|
||||||
|
if err := query.Find(&chores).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return chores, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// a predue notfication is a notification send before the due date in 6 hours, 3 hours :
|
||||||
|
func (r *ChoreRepository) GetPreDueChoresForNotification(c context.Context, preDueDuration time.Duration, everyDuration time.Duration) ([]*chModel.Chore, error) {
|
||||||
|
var chores []*chModel.Chore
|
||||||
|
query := r.db.WithContext(c).Table("chores").Select("chores.*, MAX(n.created_at) as max_notification_created_at").Joins("left join notifications n on n.chore_id = chores.id and n.scheduled_for = chores.next_due_date and n.type = 3")
|
||||||
|
if err := query.Where("chores.is_active = ? and chores.notification = ? and chores.next_due_date > ? and chores.next_due_date < ?", true, true, time.Now().UTC(), time.Now().Add(everyDuration*2).UTC()).Where(readJSONBooleanField(r.dbType, "chores.notification_meta", "predue")).Having("MAX(n.created_at) is null or MAX(n.created_at) < ?", time.Now().Add(everyDuration).UTC()).Group("chores.id").Find(&chores).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return chores, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func readJSONBooleanField(dbType string, columnName string, fieldName string) string {
|
||||||
|
if dbType == "postgres" {
|
||||||
|
return fmt.Sprintf("(%s::json->>'%s')::boolean", columnName, fieldName)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("JSON_EXTRACT(%s, '$.%s')", columnName, fieldName)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ChoreRepository) SetDueDate(c context.Context, choreID int, dueDate time.Time) error {
|
||||||
|
return r.db.WithContext(c).Model(&chModel.Chore{}).Where("id = ?", choreID).Update("next_due_date", dueDate).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ChoreRepository) SetDueDateIfNotExisted(c context.Context, choreID int, dueDate time.Time) error {
|
||||||
|
return r.db.WithContext(c).Model(&chModel.Chore{}).Where("id = ? and next_due_date is null", choreID).Update("next_due_date", dueDate).Error
|
||||||
|
}
|
|
@ -0,0 +1,145 @@
|
||||||
|
package chore
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"math/rand"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
chModel "donetick.com/core/internal/chore/model"
|
||||||
|
)
|
||||||
|
|
||||||
|
func scheduleNextDueDate(chore *chModel.Chore, completedDate time.Time) (*time.Time, error) {
|
||||||
|
// if Chore is rolling then the next due date calculated from the completed date, otherwise it's calculated from the due date
|
||||||
|
var nextDueDate time.Time
|
||||||
|
var baseDate time.Time
|
||||||
|
var frequencyMetadata chModel.FrequencyMetadata
|
||||||
|
err := json.Unmarshal([]byte(*chore.FrequencyMetadata), &frequencyMetadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("error unmarshalling frequency metadata")
|
||||||
|
}
|
||||||
|
if chore.FrequencyType == "once" {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if chore.NextDueDate != nil {
|
||||||
|
// no due date set, use the current date
|
||||||
|
|
||||||
|
baseDate = chore.NextDueDate.UTC()
|
||||||
|
} else {
|
||||||
|
baseDate = completedDate.UTC()
|
||||||
|
}
|
||||||
|
if chore.IsRolling && chore.NextDueDate.Before(completedDate) {
|
||||||
|
// we need to check if chore due date is before the completed date to handle this senario:
|
||||||
|
// if user trying to complete chore due in future (multiple time for insance) due date will be calculated
|
||||||
|
// from the last completed date and due date change only in seconds.
|
||||||
|
// this make sure that the due date is always in future if the chore is rolling
|
||||||
|
|
||||||
|
baseDate = completedDate.UTC()
|
||||||
|
}
|
||||||
|
|
||||||
|
if chore.FrequencyType == "daily" {
|
||||||
|
nextDueDate = baseDate.AddDate(0, 0, 1)
|
||||||
|
} else if chore.FrequencyType == "weekly" {
|
||||||
|
nextDueDate = baseDate.AddDate(0, 0, 7)
|
||||||
|
} else if chore.FrequencyType == "monthly" {
|
||||||
|
nextDueDate = baseDate.AddDate(0, 1, 0)
|
||||||
|
} else if chore.FrequencyType == "yearly" {
|
||||||
|
nextDueDate = baseDate.AddDate(1, 0, 0)
|
||||||
|
} else if chore.FrequencyType == "adaptive" {
|
||||||
|
// TODO: calculate next due date based on the history of the chore
|
||||||
|
// calculate the difference between the due date and now in days:
|
||||||
|
diff := completedDate.UTC().Sub(chore.NextDueDate.UTC())
|
||||||
|
nextDueDate = completedDate.UTC().Add(diff)
|
||||||
|
} else if chore.FrequencyType == "once" {
|
||||||
|
// if the chore is a one-time chore, then the next due date is nil
|
||||||
|
} else if chore.FrequencyType == "interval" {
|
||||||
|
// calculate the difference between the due date and now in days:
|
||||||
|
if *frequencyMetadata.Unit == "hours" {
|
||||||
|
nextDueDate = baseDate.UTC().Add(time.Hour * time.Duration(chore.Frequency))
|
||||||
|
} else if *frequencyMetadata.Unit == "days" {
|
||||||
|
nextDueDate = baseDate.UTC().AddDate(0, 0, chore.Frequency)
|
||||||
|
} else if *frequencyMetadata.Unit == "weeks" {
|
||||||
|
nextDueDate = baseDate.UTC().AddDate(0, 0, chore.Frequency*7)
|
||||||
|
} else if *frequencyMetadata.Unit == "months" {
|
||||||
|
nextDueDate = baseDate.UTC().AddDate(0, chore.Frequency, 0)
|
||||||
|
} else if *frequencyMetadata.Unit == "years" {
|
||||||
|
nextDueDate = baseDate.UTC().AddDate(chore.Frequency, 0, 0)
|
||||||
|
} else {
|
||||||
|
|
||||||
|
return nil, fmt.Errorf("invalid frequency unit, cannot calculate next due date")
|
||||||
|
}
|
||||||
|
} else if chore.FrequencyType == "days_of_the_week" {
|
||||||
|
// TODO : this logic is bad, need to be refactored and be better.
|
||||||
|
// coding at night is almost always bad idea.
|
||||||
|
// calculate the difference between the due date and now in days:
|
||||||
|
var frequencyMetadata chModel.FrequencyMetadata
|
||||||
|
err := json.Unmarshal([]byte(*chore.FrequencyMetadata), &frequencyMetadata)
|
||||||
|
if err != nil {
|
||||||
|
|
||||||
|
return nil, fmt.Errorf("error unmarshalling frequency metadata")
|
||||||
|
}
|
||||||
|
//we can only assign to days of the week that part of the frequency metadata.days
|
||||||
|
//it's array of days of the week, for example ["monday", "tuesday", "wednesday"]
|
||||||
|
|
||||||
|
// we need to find the next day of the week in the frequency metadata.days that we can schedule
|
||||||
|
// if this the last or there is only one. will use same otherwise find the next one:
|
||||||
|
|
||||||
|
// find the index of the chore day in the frequency metadata.days
|
||||||
|
// loop for next 7 days from the base, if the day in the frequency metadata.days then we can schedule it:
|
||||||
|
for i := 1; i <= 7; i++ {
|
||||||
|
nextDueDate = baseDate.AddDate(0, 0, i)
|
||||||
|
nextDay := strings.ToLower(nextDueDate.Weekday().String())
|
||||||
|
for _, day := range frequencyMetadata.Days {
|
||||||
|
if strings.ToLower(*day) == nextDay {
|
||||||
|
nextDate := nextDueDate.UTC()
|
||||||
|
return &nextDate, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if chore.FrequencyType == "day_of_the_month" {
|
||||||
|
var frequencyMetadata chModel.FrequencyMetadata
|
||||||
|
err := json.Unmarshal([]byte(*chore.FrequencyMetadata), &frequencyMetadata)
|
||||||
|
if err != nil {
|
||||||
|
|
||||||
|
return nil, fmt.Errorf("error unmarshalling frequency metadata")
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 1; i <= 12; i++ {
|
||||||
|
nextDueDate = baseDate.AddDate(0, i, 0)
|
||||||
|
// set the date to the first day of the month:
|
||||||
|
nextDueDate = time.Date(nextDueDate.Year(), nextDueDate.Month(), chore.Frequency, nextDueDate.Hour(), nextDueDate.Minute(), 0, 0, nextDueDate.Location())
|
||||||
|
nextMonth := strings.ToLower(nextDueDate.Month().String())
|
||||||
|
for _, month := range frequencyMetadata.Months {
|
||||||
|
if *month == nextMonth {
|
||||||
|
nextDate := nextDueDate.UTC()
|
||||||
|
return &nextDate, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if chore.FrequencyType == "no_repeat" {
|
||||||
|
return nil, nil
|
||||||
|
} else if chore.FrequencyType == "trigger" {
|
||||||
|
// if the chore is a trigger chore, then the next due date is nil
|
||||||
|
return nil, nil
|
||||||
|
} else {
|
||||||
|
return nil, fmt.Errorf("invalid frequency type, cannot calculate next due date")
|
||||||
|
}
|
||||||
|
return &nextDueDate, nil
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func RemoveAssigneeAndReassign(chore *chModel.Chore, userID int) {
|
||||||
|
for i, assignee := range chore.Assignees {
|
||||||
|
if assignee.UserID == userID {
|
||||||
|
chore.Assignees = append(chore.Assignees[:i], chore.Assignees[i+1:]...)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(chore.Assignees) == 0 {
|
||||||
|
chore.AssignedTo = chore.CreatedBy
|
||||||
|
} else {
|
||||||
|
chore.AssignedTo = chore.Assignees[rand.Intn(len(chore.Assignees))].UserID
|
||||||
|
}
|
||||||
|
chore.UpdatedAt = time.Now()
|
||||||
|
}
|
|
@ -0,0 +1,442 @@
|
||||||
|
package circle
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
auth "donetick.com/core/internal/authorization"
|
||||||
|
"donetick.com/core/internal/chore"
|
||||||
|
chRepo "donetick.com/core/internal/chore/repo"
|
||||||
|
cModel "donetick.com/core/internal/circle/model"
|
||||||
|
cRepo "donetick.com/core/internal/circle/repo"
|
||||||
|
uModel "donetick.com/core/internal/user/model"
|
||||||
|
uRepo "donetick.com/core/internal/user/repo"
|
||||||
|
"donetick.com/core/logging"
|
||||||
|
jwt "github.com/appleboy/gin-jwt/v2"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Handler struct {
|
||||||
|
circleRepo *cRepo.CircleRepository
|
||||||
|
userRepo *uRepo.UserRepository
|
||||||
|
choreRepo *chRepo.ChoreRepository
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHandler(cr *cRepo.CircleRepository, ur *uRepo.UserRepository, c *chRepo.ChoreRepository) *Handler {
|
||||||
|
return &Handler{
|
||||||
|
circleRepo: cr,
|
||||||
|
userRepo: ur,
|
||||||
|
choreRepo: c,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) GetCircleMembers(c *gin.Context) {
|
||||||
|
// Get the circle ID from the JWT
|
||||||
|
log := logging.FromContext(c)
|
||||||
|
currentUser, ok := auth.CurrentUser(c)
|
||||||
|
if !ok {
|
||||||
|
log.Error("Error getting current user")
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting current user",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get all the members of the circle
|
||||||
|
members, err := h.circleRepo.GetCircleUsers(c, currentUser.CircleID)
|
||||||
|
if err != nil {
|
||||||
|
log.Error("Error getting circle members:", err)
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting circle members",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"res": members,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) JoinCircle(c *gin.Context) {
|
||||||
|
// Get the circle ID from the JWT
|
||||||
|
log := logging.FromContext(c)
|
||||||
|
log.Debug("handlder.go: JoinCircle")
|
||||||
|
currentUser, ok := auth.CurrentUser(c)
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting current user",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
requestedCircleID := c.Query("invite_code")
|
||||||
|
if requestedCircleID == "" {
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Invalid request",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
circle, err := h.circleRepo.GetCircleByInviteCode(c, requestedCircleID)
|
||||||
|
|
||||||
|
if circle.ID == currentUser.CircleID {
|
||||||
|
c.JSON(409, gin.H{
|
||||||
|
"error": "You are already a member of this circle",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add the user to the circle
|
||||||
|
err = h.circleRepo.AddUserToCircle(c, &cModel.UserCircle{
|
||||||
|
CircleID: circle.ID,
|
||||||
|
UserID: currentUser.ID,
|
||||||
|
Role: "member",
|
||||||
|
IsActive: false,
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
log.Error("Error adding user to circle:", err)
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error adding user to circle",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"res": "User Requested to join circle successfully",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) LeaveCircle(c *gin.Context) {
|
||||||
|
log := logging.FromContext(c)
|
||||||
|
log.Debug("handler.go: LeaveCircle")
|
||||||
|
currentUser, ok := auth.CurrentUser(c)
|
||||||
|
if !ok {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting current user",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rawCircleID := c.Query("circle_id")
|
||||||
|
circleID, err := strconv.Atoi(rawCircleID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Invalid request",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
orginalCircleID, err := h.circleRepo.GetUserOriginalCircle(c, currentUser.ID)
|
||||||
|
if err != nil {
|
||||||
|
log.Error("Error getting user original circle:", err)
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting user original circle",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// START : HANDLE USER LEAVING CIRCLE
|
||||||
|
// bulk update chores:
|
||||||
|
if err := handleUserLeavingCircle(h, c, currentUser, orginalCircleID); err != nil {
|
||||||
|
log.Error("Error handling user leaving circle:", err)
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error handling user leaving circle",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// END: HANDLE USER LEAVING CIRCLE
|
||||||
|
|
||||||
|
err = h.circleRepo.LeaveCircleByUserID(c, circleID, currentUser.ID)
|
||||||
|
if err != nil {
|
||||||
|
log.Error("Error leaving circle:", err)
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error leaving circle",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.userRepo.UpdateUserCircle(c, currentUser.ID, orginalCircleID); err != nil {
|
||||||
|
log.Error("Error updating user circle:", err)
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error updating user circle",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"res": "User left circle successfully",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleUserLeavingCircle(h *Handler, c *gin.Context, leavingUser *uModel.User, orginalCircleID int) error {
|
||||||
|
userAssignedCircleChores, err := h.choreRepo.GetChores(c, leavingUser.CircleID, leavingUser.ID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, ch := range userAssignedCircleChores {
|
||||||
|
|
||||||
|
if ch.CreatedBy == leavingUser.ID && ch.AssignedTo != leavingUser.ID {
|
||||||
|
ch.AssignedTo = leavingUser.ID
|
||||||
|
ch.UpdatedAt = time.Now()
|
||||||
|
ch.UpdatedBy = leavingUser.ID
|
||||||
|
ch.CircleID = orginalCircleID
|
||||||
|
} else if ch.CreatedBy != leavingUser.ID && ch.AssignedTo == leavingUser.ID {
|
||||||
|
chore.RemoveAssigneeAndReassign(ch, leavingUser.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
h.choreRepo.UpdateChores(c, userAssignedCircleChores)
|
||||||
|
h.choreRepo.RemoveChoreAssigneeByCircleID(c, leavingUser.ID, leavingUser.CircleID)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) DeleteCircleMember(c *gin.Context) {
|
||||||
|
log := logging.FromContext(c)
|
||||||
|
log.Debug("handler.go: DeleteCircleMember")
|
||||||
|
currentUser, ok := auth.CurrentUser(c)
|
||||||
|
if !ok {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting current user",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rawCircleID := c.Param("id")
|
||||||
|
circleID, err := strconv.Atoi(rawCircleID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Invalid request",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rawMemeberIDToDeleted := c.Query("member_id")
|
||||||
|
memberIDToDeleted, err := strconv.Atoi(rawMemeberIDToDeleted)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Invalid request",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
admins, err := h.circleRepo.GetCircleAdmins(c, circleID)
|
||||||
|
if err != nil {
|
||||||
|
log.Error("Error getting circle admins:", err)
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting circle admins",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
isAdmin := false
|
||||||
|
for _, admin := range admins {
|
||||||
|
if admin.UserID == currentUser.ID {
|
||||||
|
isAdmin = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !isAdmin {
|
||||||
|
c.JSON(403, gin.H{
|
||||||
|
"error": "You are not an admin of this circle",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
orginalCircleID, err := h.circleRepo.GetUserOriginalCircle(c, memberIDToDeleted)
|
||||||
|
if handleUserLeavingCircle(h, c, &uModel.User{ID: memberIDToDeleted, CircleID: circleID}, orginalCircleID) != nil {
|
||||||
|
log.Error("Error handling user leaving circle:", err)
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error handling user leaving circle",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = h.circleRepo.DeleteMemberByID(c, circleID, memberIDToDeleted)
|
||||||
|
if err != nil {
|
||||||
|
log.Error("Error deleting circle member:", err)
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error deleting circle member",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"res": "User deleted from circle successfully",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) GetUserCircles(c *gin.Context) {
|
||||||
|
log := logging.FromContext(c)
|
||||||
|
currentUser, ok := auth.CurrentUser(c)
|
||||||
|
if !ok {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting current user",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
circles, err := h.circleRepo.GetUserCircles(c, currentUser.ID)
|
||||||
|
if err != nil {
|
||||||
|
log.Error("Error getting user circles:", err)
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting user circles",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"res": circles,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) GetPendingCircleMembers(c *gin.Context) {
|
||||||
|
log := logging.FromContext(c)
|
||||||
|
currentUser, ok := auth.CurrentUser(c)
|
||||||
|
if !ok {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting current user",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
currentMemebers, err := h.circleRepo.GetCircleUsers(c, currentUser.CircleID)
|
||||||
|
if err != nil {
|
||||||
|
log.Error("Error getting circle members:", err)
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting circle members",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// confirm that the current user is an admin:
|
||||||
|
isAdmin := false
|
||||||
|
for _, member := range currentMemebers {
|
||||||
|
if member.UserID == currentUser.ID && member.Role == "admin" {
|
||||||
|
isAdmin = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !isAdmin {
|
||||||
|
c.JSON(403, gin.H{
|
||||||
|
"error": "You are not an admin of this circle",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
members, err := h.circleRepo.GetPendingJoinRequests(c, currentUser.CircleID)
|
||||||
|
if err != nil {
|
||||||
|
log.Error("Error getting pending circle members:", err)
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting pending circle members",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"res": members,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) AcceptJoinRequest(c *gin.Context) {
|
||||||
|
log := logging.FromContext(c)
|
||||||
|
currentUser, ok := auth.CurrentUser(c)
|
||||||
|
if !ok {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting current user",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
rawRequestID := c.Query("requestId")
|
||||||
|
requestID, err := strconv.Atoi(rawRequestID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Invalid request",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
currentMemebers, err := h.circleRepo.GetCircleUsers(c, currentUser.CircleID)
|
||||||
|
if err != nil {
|
||||||
|
log.Error("Error getting circle members:", err)
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting circle members",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// confirm that the current user is an admin:
|
||||||
|
isAdmin := false
|
||||||
|
for _, member := range currentMemebers {
|
||||||
|
if member.UserID == currentUser.ID && member.Role == "admin" {
|
||||||
|
isAdmin = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !isAdmin {
|
||||||
|
c.JSON(403, gin.H{
|
||||||
|
"error": "You are not an admin of this circle",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
pendingRequests, err := h.circleRepo.GetPendingJoinRequests(c, currentUser.CircleID)
|
||||||
|
if err != nil {
|
||||||
|
log.Error("Error getting pending circle members:", err)
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting pending circle members",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
isActiveRequest := false
|
||||||
|
var requestedCircle *cModel.UserCircleDetail
|
||||||
|
for _, request := range pendingRequests {
|
||||||
|
if request.ID == requestID {
|
||||||
|
requestedCircle = request
|
||||||
|
isActiveRequest = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !isActiveRequest {
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Invalid request",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = h.circleRepo.AcceptJoinRequest(c, currentUser.CircleID, requestID)
|
||||||
|
if err != nil {
|
||||||
|
log.Error("Error accepting join request:", err)
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error accepting join request",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.userRepo.UpdateUserCircle(c, requestedCircle.UserID, currentUser.CircleID); err != nil {
|
||||||
|
log.Error("Error updating user circle:", err)
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error updating user circle",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"res": "Join request accepted successfully",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func Routes(router *gin.Engine, h *Handler, auth *jwt.GinJWTMiddleware) {
|
||||||
|
log.Println("Registering routes")
|
||||||
|
|
||||||
|
circleRoutes := router.Group("circles")
|
||||||
|
circleRoutes.Use(auth.MiddlewareFunc())
|
||||||
|
{
|
||||||
|
circleRoutes.GET("/members", h.GetCircleMembers)
|
||||||
|
circleRoutes.GET("/members/requests", h.GetPendingCircleMembers)
|
||||||
|
circleRoutes.PUT("/members/requests/accept", h.AcceptJoinRequest)
|
||||||
|
circleRoutes.GET("/", h.GetUserCircles)
|
||||||
|
circleRoutes.POST("/join", h.JoinCircle)
|
||||||
|
circleRoutes.DELETE("/leave", h.LeaveCircle)
|
||||||
|
circleRoutes.DELETE("/:id/members/delete", h.DeleteCircleMember)
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,35 @@
|
||||||
|
package circle
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
type Circle struct {
|
||||||
|
ID int `json:"id" gorm:"primary_key"` // Unique identifier
|
||||||
|
Name string `json:"name" gorm:"column:name"` // Full name
|
||||||
|
CreatedBy int `json:"created_by" gorm:"column:created_by"` // Created by
|
||||||
|
CreatedAt time.Time `json:"created_at" gorm:"column:created_at"` // Created at
|
||||||
|
UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at"` // Updated at
|
||||||
|
InviteCode string `json:"invite_code" gorm:"column:invite_code"` // Invite code
|
||||||
|
Disabled bool `json:"disabled" gorm:"column:disabled"` // Disabled
|
||||||
|
}
|
||||||
|
|
||||||
|
type CircleDetail struct {
|
||||||
|
Circle
|
||||||
|
UserRole string `json:"userRole" gorm:"column:role"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type UserCircle struct {
|
||||||
|
ID int `json:"id" gorm:"primary_key"` // Unique identifier
|
||||||
|
UserID int `json:"userId" gorm:"column:user_id"` // User ID
|
||||||
|
CircleID int `json:"circleId" gorm:"column:circle_id"` // Circle ID
|
||||||
|
Role string `json:"role" gorm:"column:role"` // Role
|
||||||
|
IsActive bool `json:"isActive" gorm:"column:is_active;default:false"`
|
||||||
|
CreatedAt time.Time `json:"createdAt" gorm:"column:created_at"` // Created at
|
||||||
|
UpdatedAt time.Time `json:"updatedAt" gorm:"column:updated_at"` // Updated at
|
||||||
|
}
|
||||||
|
|
||||||
|
type UserCircleDetail struct {
|
||||||
|
UserCircle
|
||||||
|
Username string `json:"username" gorm:"column:username"`
|
||||||
|
DisplayName string `json:"displayName" gorm:"column:display_name"`
|
||||||
|
ChatID int `json:"chatID" gorm:"column:chat_id"`
|
||||||
|
}
|
|
@ -0,0 +1,117 @@
|
||||||
|
package repo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
cModel "donetick.com/core/internal/circle/model"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ICircleRepository interface {
|
||||||
|
CreateCircle(circle *cModel.Circle) error
|
||||||
|
AddUserToCircle(circleUser *cModel.UserCircle) error
|
||||||
|
GetCircleUsers(circleID int) ([]*cModel.UserCircle, error)
|
||||||
|
GetUserCircles(userID int) ([]*cModel.Circle, error)
|
||||||
|
DeleteUserFromCircle(circleID, userID int) error
|
||||||
|
ChangeUserRole(circleID, userID int, role string) error
|
||||||
|
GetCircleByInviteCode(inviteCode string) (*cModel.Circle, error)
|
||||||
|
GetCircleByID(circleID int) (*cModel.Circle, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type CircleRepository struct {
|
||||||
|
db *gorm.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCircleRepository(db *gorm.DB) *CircleRepository {
|
||||||
|
return &CircleRepository{db}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *CircleRepository) CreateCircle(c context.Context, circle *cModel.Circle) (*cModel.Circle, error) {
|
||||||
|
if err := r.db.WithContext(c).Save(&circle).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return circle, nil
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *CircleRepository) AddUserToCircle(c context.Context, circleUser *cModel.UserCircle) error {
|
||||||
|
return r.db.WithContext(c).Save(circleUser).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *CircleRepository) GetCircleUsers(c context.Context, circleID int) ([]*cModel.UserCircleDetail, error) {
|
||||||
|
var circleUsers []*cModel.UserCircleDetail
|
||||||
|
// join user table to get user details like username and display name:
|
||||||
|
if err := r.db.WithContext(c).Raw("SELECT * FROM user_circles LEFT JOIN users on users.id = user_circles.user_id WHERE user_circles.circle_id = ?", circleID).Scan(&circleUsers).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return circleUsers, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *CircleRepository) GetPendingJoinRequests(c context.Context, circleID int) ([]*cModel.UserCircleDetail, error) {
|
||||||
|
var pendingRequests []*cModel.UserCircleDetail
|
||||||
|
if err := r.db.WithContext(c).Raw("SELECT *, user_circles.id as id FROM user_circles LEFT JOIN users on users.id = user_circles.user_id WHERE user_circles.circle_id = ? AND user_circles.is_active = false", circleID).Scan(&pendingRequests).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return pendingRequests, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *CircleRepository) AcceptJoinRequest(c context.Context, circleID, requestID int) error {
|
||||||
|
|
||||||
|
return r.db.WithContext(c).Model(&cModel.UserCircle{}).Where("circle_id = ? AND id = ?", circleID, requestID).Update("is_active", true).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *CircleRepository) GetUserCircles(c context.Context, userID int) ([]*cModel.CircleDetail, error) {
|
||||||
|
var circles []*cModel.CircleDetail
|
||||||
|
if err := r.db.WithContext(c).Raw("SELECT circles.*, user_circles.role as role, user_circles.created_at uc_created_at FROM circles Left JOIN user_circles on circles.id = user_circles.circle_id WHERE user_circles.user_id = ? ORDER BY uc_created_at desc", userID).Scan(&circles).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return circles, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *CircleRepository) DeleteUserFromCircle(c context.Context, circleID, userID int) error {
|
||||||
|
return r.db.WithContext(c).Where("circle_id = ? AND user_id = ?", circleID, userID).Delete(&cModel.UserCircle{}).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *CircleRepository) ChangeUserRole(c context.Context, circleID, userID int, role int) error {
|
||||||
|
return r.db.WithContext(c).Model(&cModel.UserCircle{}).Where("circle_id = ? AND user_id = ?", circleID, userID).Update("role", role).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *CircleRepository) GetCircleByInviteCode(c context.Context, inviteCode string) (*cModel.Circle, error) {
|
||||||
|
var circle cModel.Circle
|
||||||
|
if err := r.db.WithContext(c).Where("invite_code = ?", inviteCode).First(&circle).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &circle, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *CircleRepository) GetCircleByID(c context.Context, circleID int) (*cModel.Circle, error) {
|
||||||
|
var circle cModel.Circle
|
||||||
|
if err := r.db.WithContext(c).First(&circle, circleID).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &circle, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *CircleRepository) LeaveCircleByUserID(c context.Context, circleID, userID int) error {
|
||||||
|
return r.db.WithContext(c).Where("circle_id = ? AND user_id = ? AND role != 'admin'", circleID, userID).Delete(&cModel.UserCircle{}).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *CircleRepository) GetUserOriginalCircle(c context.Context, userID int) (int, error) {
|
||||||
|
var circleID int
|
||||||
|
if err := r.db.WithContext(c).Raw("SELECT circle_id FROM user_circles WHERE user_id = ? AND role = 'admin'", userID).Scan(&circleID).Error; err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return circleID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *CircleRepository) DeleteMemberByID(c context.Context, circleID, userID int) error {
|
||||||
|
return r.db.WithContext(c).Where("circle_id = ? AND user_id = ?", circleID, userID).Delete(&cModel.UserCircle{}).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *CircleRepository) GetCircleAdmins(c context.Context, circleID int) ([]*cModel.UserCircleDetail, error) {
|
||||||
|
var circleAdmins []*cModel.UserCircleDetail
|
||||||
|
if err := r.db.WithContext(c).Raw("SELECT * FROM user_circles LEFT JOIN users on users.id = user_circles.user_id WHERE user_circles.circle_id = ? AND user_circles.role = 'admin'", circleID).Scan(&circleAdmins).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return circleAdmins, nil
|
||||||
|
}
|
|
@ -0,0 +1,44 @@
|
||||||
|
package database
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gorm.io/driver/postgres"
|
||||||
|
"gorm.io/driver/sqlite" // Sqlite driver based on CGO
|
||||||
|
"gorm.io/gorm/logger"
|
||||||
|
|
||||||
|
// "github.com/glebarez/sqlite" // Pure go SQLite driver, checkout https://github.com/glebarez/sqlite for details
|
||||||
|
"donetick.com/core/config"
|
||||||
|
"donetick.com/core/logging"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewDatabase(cfg *config.Config) (*gorm.DB, error) {
|
||||||
|
var db *gorm.DB
|
||||||
|
var err error
|
||||||
|
switch cfg.Database.Type {
|
||||||
|
case "postgres":
|
||||||
|
dsn := fmt.Sprintf("host=%s port=%v user=%s password=%s dbname=%s sslmode=disable TimeZone=Asia/Shanghai", cfg.Database.Host, cfg.Database.Port, cfg.Database.User, cfg.Database.Password, cfg.Database.Name)
|
||||||
|
for i := 0; i <= 30; i++ {
|
||||||
|
db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{
|
||||||
|
Logger: logger.Default.LogMode(logger.Info),
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
logging.DefaultLogger().Warnf("failed to open database: %v", err)
|
||||||
|
time.Sleep(500 * time.Millisecond)
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
|
||||||
|
db, err = gorm.Open(sqlite.Open("donetick.db"), &gorm.Config{})
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return db, nil
|
||||||
|
}
|
|
@ -0,0 +1,509 @@
|
||||||
|
package email
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"donetick.com/core/config"
|
||||||
|
gomail "gopkg.in/gomail.v2"
|
||||||
|
)
|
||||||
|
|
||||||
|
type EmailSender struct {
|
||||||
|
client *gomail.Dialer
|
||||||
|
appHost string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewEmailSender(conf *config.Config) *EmailSender {
|
||||||
|
|
||||||
|
client := gomail.NewDialer(conf.EmailConfig.Host, conf.EmailConfig.Port, conf.EmailConfig.Email, conf.EmailConfig.Key)
|
||||||
|
|
||||||
|
// format conf.EmailConfig.Host and port :
|
||||||
|
|
||||||
|
// auth := smtp.PlainAuth("", conf.EmailConfig.Email, conf.EmailConfig.Password, host)
|
||||||
|
return &EmailSender{
|
||||||
|
|
||||||
|
client: client,
|
||||||
|
appHost: conf.EmailConfig.AppHost,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (es *EmailSender) SendVerificationEmail(to, code string) error {
|
||||||
|
// msg := []byte(fmt.Sprintf("To: %s\r\nSubject: %s\r\n\r\n%s\r\n", to, subject, body))
|
||||||
|
msg := gomail.NewMessage()
|
||||||
|
msg.SetHeader("From", "no-reply@donetick.com")
|
||||||
|
msg.SetHeader("To", to)
|
||||||
|
msg.SetHeader("Subject", "Welcome to Donetick! Verifiy you email")
|
||||||
|
// text/html for a html email
|
||||||
|
htmlBody := `
|
||||||
|
<!--
|
||||||
|
********************************************************
|
||||||
|
* This email was built using Tabular.
|
||||||
|
* Create emails, that look perfect in every inbox.
|
||||||
|
* For more information, visit https://tabular.email
|
||||||
|
********************************************************
|
||||||
|
-->
|
||||||
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||||
|
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" lang="en"><head>
|
||||||
|
<title></title>
|
||||||
|
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
|
||||||
|
<!--[if !mso]><!-->
|
||||||
|
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||||
|
<!--<![endif]-->
|
||||||
|
<meta name="x-apple-disable-message-reformatting" content="">
|
||||||
|
<meta content="target-densitydpi=device-dpi" name="viewport">
|
||||||
|
<meta content="true" name="HandheldFriendly">
|
||||||
|
<meta content="width=device-width" name="viewport">
|
||||||
|
<meta name="format-detection" content="telephone=no, date=no, address=no, email=no, url=no">
|
||||||
|
<style type="text/css">
|
||||||
|
table {
|
||||||
|
border-collapse: separate;
|
||||||
|
table-layout: fixed;
|
||||||
|
mso-table-lspace: 0pt;
|
||||||
|
mso-table-rspace: 0pt
|
||||||
|
}
|
||||||
|
table td {
|
||||||
|
border-collapse: collapse
|
||||||
|
}
|
||||||
|
.ExternalClass {
|
||||||
|
width: 100%
|
||||||
|
}
|
||||||
|
.ExternalClass,
|
||||||
|
.ExternalClass p,
|
||||||
|
.ExternalClass span,
|
||||||
|
.ExternalClass font,
|
||||||
|
.ExternalClass td,
|
||||||
|
.ExternalClass div {
|
||||||
|
line-height: 100%
|
||||||
|
}
|
||||||
|
body, a, li, p, h1, h2, h3 {
|
||||||
|
-ms-text-size-adjust: 100%;
|
||||||
|
-webkit-text-size-adjust: 100%;
|
||||||
|
}
|
||||||
|
html {
|
||||||
|
-webkit-text-size-adjust: none !important
|
||||||
|
}
|
||||||
|
body, #innerTable {
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
-moz-osx-font-smoothing: grayscale
|
||||||
|
}
|
||||||
|
#innerTable img+div {
|
||||||
|
display: none;
|
||||||
|
display: none !important
|
||||||
|
}
|
||||||
|
img {
|
||||||
|
Margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
-ms-interpolation-mode: bicubic
|
||||||
|
}
|
||||||
|
h1, h2, h3, p, a {
|
||||||
|
line-height: 1;
|
||||||
|
overflow-wrap: normal;
|
||||||
|
white-space: normal;
|
||||||
|
word-break: break-word
|
||||||
|
}
|
||||||
|
a {
|
||||||
|
text-decoration: none
|
||||||
|
}
|
||||||
|
h1, h2, h3, p {
|
||||||
|
min-width: 100%!important;
|
||||||
|
width: 100%!important;
|
||||||
|
max-width: 100%!important;
|
||||||
|
display: inline-block!important;
|
||||||
|
border: 0;
|
||||||
|
padding: 0;
|
||||||
|
margin: 0
|
||||||
|
}
|
||||||
|
a[x-apple-data-detectors] {
|
||||||
|
color: inherit !important;
|
||||||
|
text-decoration: none !important;
|
||||||
|
font-size: inherit !important;
|
||||||
|
font-family: inherit !important;
|
||||||
|
font-weight: inherit !important;
|
||||||
|
line-height: inherit !important
|
||||||
|
}
|
||||||
|
a[href^="mailto"],
|
||||||
|
a[href^="tel"],
|
||||||
|
a[href^="sms"] {
|
||||||
|
color: inherit;
|
||||||
|
text-decoration: none
|
||||||
|
}
|
||||||
|
@media (min-width: 481px) {
|
||||||
|
.hd { display: none!important }
|
||||||
|
}
|
||||||
|
@media (max-width: 480px) {
|
||||||
|
.hm { display: none!important }
|
||||||
|
}
|
||||||
|
[style*="Inter Tight"] {font-family: 'Inter Tight', BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif !important;} [style*="Albert Sans"] {font-family: 'Albert Sans', BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif !important;}
|
||||||
|
@media only screen and (min-width: 481px) {.t20{width:720px!important}.t27{padding:40px 60px 50px!important}.t29{padding:40px 60px 50px!important;width:680px!important}.t43{width:600px!important}.t53,.t61{width:580px!important}.t65{width:600px!important}.t78{padding-left:0!important;padding-right:0!important}.t80{padding-left:0!important;padding-right:0!important;width:400px!important}.t84,.t94{width:600px!important}}
|
||||||
|
</style>
|
||||||
|
<style type="text/css" media="screen and (min-width:481px)">.moz-text-html .t20{width:720px!important}.moz-text-html .t27{padding:40px 60px 50px!important}.moz-text-html .t29{padding:40px 60px 50px!important;width:680px!important}.moz-text-html .t43{width:600px!important}.moz-text-html .t53,.moz-text-html .t61{width:580px!important}.moz-text-html .t65{width:600px!important}.moz-text-html .t78{padding-left:0!important;padding-right:0!important}.moz-text-html .t80{padding-left:0!important;padding-right:0!important;width:400px!important}.moz-text-html .t84,.moz-text-html .t94{width:600px!important}</style>
|
||||||
|
<!--[if !mso]><!-->
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Inter+Tight:wght@400;600&family=Albert+Sans:wght@800&display=swap" rel="stylesheet" type="text/css">
|
||||||
|
<!--<![endif]-->
|
||||||
|
<!--[if mso]>
|
||||||
|
<style type="text/css">
|
||||||
|
td.t20{width:800px !important}td.t27{padding:40px 60px 50px !important}td.t29{padding:40px 60px 50px !important;width:800px !important}td.t43,td.t53{width:600px !important}td.t61{width:580px !important}td.t65{width:600px !important}td.t78,td.t80{padding-left:0 !important;padding-right:0 !important}td.t84,td.t94{width:600px !important}
|
||||||
|
</style>
|
||||||
|
<![endif]-->
|
||||||
|
<!--[if mso]>
|
||||||
|
<xml>
|
||||||
|
<o:OfficeDocumentSettings>
|
||||||
|
<o:AllowPNG/>
|
||||||
|
<o:PixelsPerInch>96</o:PixelsPerInch>
|
||||||
|
</o:OfficeDocumentSettings>
|
||||||
|
</xml>
|
||||||
|
<![endif]-->
|
||||||
|
</head>
|
||||||
|
<body class="t0" style="min-width:100%;Marg
|
||||||
|
if you did not sign up with Donetick please Ignore this email. in:0px;padding:0px;background-color:#FFFFFF;"><div class="t1" style="background-color:#FFFFFF;"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" align="center"><tbody><tr><td class="t130" style="font-size:0;line-height:0;mso-line-height-rule:exactly;" valign="top" align="center">
|
||||||
|
<!--[if mso]>
|
||||||
|
<v:background xmlns:v="urn:schemas-microsoft-com:vml" fill="true" stroke="false">
|
||||||
|
<v:fill color="#FFFFFF"/>
|
||||||
|
</v:background>
|
||||||
|
<![endif]-->
|
||||||
|
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" align="center" id="innerTable"><tbody><tr><td>
|
||||||
|
<table class="t118" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr>
|
||||||
|
|
||||||
|
<!--<![endif]-->
|
||||||
|
<!--[if mso]><td class="t119" style="width:400px;padding:40px 40px 40px 40px;"><![endif]-->
|
||||||
|
</tr></tbody></table><table role="presentation" width="100%" cellpadding="0" cellspacing="0"></table></td>
|
||||||
|
</tr></tbody></table>
|
||||||
|
</td></tr><tr><td>
|
||||||
|
<table class="t10" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr>
|
||||||
|
<!--[if !mso]><!--><td class="t11" style="background-color:#FFFFFF;width:400px;">
|
||||||
|
<!--<![endif]-->
|
||||||
|
<!--[if mso]><td class="t11" style="background-color:#FFFFFF;width:400px;"><![endif]-->
|
||||||
|
<table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tbody><tr><td>
|
||||||
|
<table class="t19" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr>
|
||||||
|
<!--[if !mso]><!--><td class="t20" style="background-color:#404040;width:400px;padding:40px 40px 40px 40px;">
|
||||||
|
<!--<![endif]-->
|
||||||
|
<!--[if mso]><td class="t20" style="background-color:#404040;width:480px;padding:40px 40px 40px 40px;"><![endif]-->
|
||||||
|
<table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tbody><tr><td>
|
||||||
|
<table class="t103" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr>
|
||||||
|
<!--[if !mso]><!--><td class="t104" style="width:200px;">
|
||||||
|
<!--<![endif]-->
|
||||||
|
<!--[if mso]><td class="t104" style="width:200px;"><![endif]-->
|
||||||
|
<div style="font-size:0px;"><img class="t110" style="display:block;border:0;height:auto;width:100%;Margin:0;max-width:100%;" width="200" height="179.5" alt="" src="https://835a1b8e-557a-4713-8f1c-104febdb8808.b-cdn.net/e/30b4288c-4e67-4e3b-9527-1fc4c4ec2fdf/df3f012a-c060-4d59-b5fd-54a57dae1916.png"></div></td>
|
||||||
|
</tr></tbody></table>
|
||||||
|
</td></tr></tbody></table></td>
|
||||||
|
</tr></tbody></table>
|
||||||
|
</td></tr><tr><td>
|
||||||
|
<table class="t28" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr>
|
||||||
|
<!--[if !mso]><!--><td class="t29" style="width:420px;padding:30px 30px 40px 30px;">
|
||||||
|
<!--<![endif]-->
|
||||||
|
<!--[if mso]><td class="t29" style="width:480px;padding:30px 30px 40px 30px;"><![endif]-->
|
||||||
|
<table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tbody><tr><td>
|
||||||
|
<table class="t42" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr>
|
||||||
|
<!--[if !mso]><!--><td class="t43" style="width:480px;">
|
||||||
|
<!--<![endif]-->
|
||||||
|
<!--[if mso]><td class="t43" style="width:480px;"><![endif]-->
|
||||||
|
<h1 class="t49" style="margin:0;Margin:0;font-family:BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif,'Albert Sans';line-height:35px;font-weight:800;font-style:normal;font-size:30px;text-decoration:none;text-transform:none;letter-spacing:-1.2px;direction:ltr;color:#333333;text-align:center;mso-line-height-rule:exactly;mso-text-raise:2px;">Welcome to Donetick!</h1></td>
|
||||||
|
</tr></tbody></table>
|
||||||
|
</td></tr><tr><td><div class="t41" style="mso-line-height-rule:exactly;mso-line-height-alt:16px;line-height:16px;font-size:1px;display:block;"> </div></td></tr><tr><td><p class="t39" style="margin:0;Margin:0;font-family:BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif,'Inter Tight';line-height:21px;font-weight:400;font-style:normal;font-size:14px;text-decoration:none;text-transform:none;direction:ltr;color:#555555;text-align:center;mso-line-height-rule:exactly;mso-text-raise:2px;">Thank you for joining us. We're excited to have you on board.To complete your registration, click the button below</p></td></tr><tr><td><div class="t31" style="mso-line-height-rule:exactly;mso-line-height-alt:30px;line-height:30px;font-size:1px;display:block;"> </div></td></tr><tr><td>
|
||||||
|
<table class="t52" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr>
|
||||||
|
<!--[if !mso]><!--><td class="t53" style="background-color:#06b6d4;overflow:hidden;width:460px;text-align:center;line-height:24px;mso-line-height-rule:exactly;mso-text-raise:2px;padding:10px 10px 10px 10px;border-radius:10px 10px 10px 10px;">
|
||||||
|
<!--<![endif]-->
|
||||||
|
<!--[if mso]><td class="t53" style="background-color:#06b6d4;overflow:hidden;width:480px;text-align:center;line-height:24px;mso-line-height-rule:exactly;mso-text-raise:2px;padding:10px 10px 10px 10px;border-radius:10px 10px 10px 10px;"><![endif]-->
|
||||||
|
<a class="t59" href="{{verifyURL}}" style="display:block;margin:0;Margin:0;font-family:BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif,'Inter Tight';line-height:24px;font-weight:600;font-style:normal;font-size:16px;text-decoration:none;direction:ltr;color:#FFFFFF;text-align:center;mso-line-height-rule:exactly;mso-text-raise:2px;" target="_blank">Complete your registration</a></td>
|
||||||
|
</tr></tbody></table>
|
||||||
|
</td></tr><tr><td><div class="t62" style="mso-line-height-rule:exactly;mso-line-height-alt:12px;line-height:12px;font-size:1px;display:block;"> </div></td></tr><tr><td>
|
||||||
|
<table class="t64" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr>
|
||||||
|
<!--[if !mso]><!--><td class="t65" style="width:480px;">
|
||||||
|
<!--<![endif]-->
|
||||||
|
<!--[if mso]><td class="t65" style="width:480px;"><![endif]-->
|
||||||
|
<p class="t71" style="margin:0;Margin:0;font-family:BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif,'Inter Tight';line-height:21px;font-weight:400;font-style:normal;font-size:14px;text-decoration:none;text-transform:none;direction:ltr;color:#555555;text-align:center;mso-line-height-rule:exactly;mso-text-raise:2px;"> </p></td>
|
||||||
|
</tr></tbody></table>
|
||||||
|
</td></tr></tbody></table></td>
|
||||||
|
</tr></tbody></table>
|
||||||
|
</td></tr></tbody></table></td>
|
||||||
|
</tr></tbody></table>
|
||||||
|
</td></tr><tr><td><div class="t4" style="mso-line-height-rule:exactly;mso-line-height-alt:30px;line-height:30px;font-size:1px;display:block;"> </div></td></tr><tr><td>
|
||||||
|
<table class="t79" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr>
|
||||||
|
<!--[if !mso]><!--><td class="t80" style="width:320px;padding:0 40px 0 40px;">
|
||||||
|
<!--<![endif]-->
|
||||||
|
<!--[if mso]><td class="t80" style="width:400px;padding:0 40px 0 40px;"><![endif]-->
|
||||||
|
<table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tbody><tr><td>
|
||||||
|
<table class="t93" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr>
|
||||||
|
<!--[if !mso]><!--><td class="t94" style="width:480px;">
|
||||||
|
<!--<![endif]-->
|
||||||
|
<!--[if mso]><td class="t94" style="width:480px;"><![endif]-->
|
||||||
|
<p class="t100" style="margin:0;Margin:0;font-family:BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif,'Inter Tight';line-height:18px;font-weight:400;font-style:normal;font-size:12px;text-decoration:none;text-transform:none;direction:ltr;color:#555555;text-align:center;mso-line-height-rule:exactly;mso-text-raise:2px;">if you did not sign up with Donetick please Ignore this email. </p></td>
|
||||||
|
</tr></tbody></table>
|
||||||
|
</td></tr><tr><td><div class="t81" style="mso-line-height-rule:exactly;mso-line-height-alt:8px;line-height:8px;font-size:1px;display:block;"> </div></td></tr><tr><td>
|
||||||
|
<table class="t83" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr>
|
||||||
|
<!--[if !mso]><!--><td class="t84" style="width:480px;">
|
||||||
|
<!--<![endif]-->
|
||||||
|
<!--[if mso]><td class="t84" style="width:480px;"><![endif]-->
|
||||||
|
<p class="t90" style="margin:0;Margin:0;font-family:BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif,'Inter Tight';line-height:18px;font-weight:400;font-style:normal;font-size:12px;text-decoration:none;text-transform:none;direction:ltr;color:#555555;text-align:center;mso-line-height-rule:exactly;mso-text-raise:2px;">Favoro LLC. All rights reserved</p></td>
|
||||||
|
</tr></tbody></table>
|
||||||
|
</td></tr></tbody></table></td>
|
||||||
|
</tr></tbody></table>
|
||||||
|
</td></tr><tr><td><div class="t73" style="mso-line-height-rule:exactly;mso-line-height-alt:100px;line-height:100px;font-size:1px;display:block;"> </div></td></tr></tbody></table></div>
|
||||||
|
|
||||||
|
</body></html>
|
||||||
|
`
|
||||||
|
u := es.appHost + "/verify?c=" + encodeEmailAndCode(to, code)
|
||||||
|
htmlBody = strings.Replace(htmlBody, "{{verifyURL}}", u, 1)
|
||||||
|
|
||||||
|
msg.SetBody("text/html", htmlBody)
|
||||||
|
|
||||||
|
err := es.client.DialAndSend(msg)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func (es *EmailSender) SendResetPasswordEmail(c context.Context, to, code string) error {
|
||||||
|
msg := gomail.NewMessage()
|
||||||
|
msg.SetHeader("From", "no-reply@donetick.com")
|
||||||
|
msg.SetHeader("To", to)
|
||||||
|
msg.SetHeader("Subject", "Donetick! Password Reset")
|
||||||
|
htmlBody := `
|
||||||
|
<!--
|
||||||
|
********************************************************
|
||||||
|
* This email was built using Tabular.
|
||||||
|
* Create emails, that look perfect in every inbox.
|
||||||
|
* For more information, visit https://tabular.email
|
||||||
|
********************************************************
|
||||||
|
-->
|
||||||
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||||
|
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" lang="en"><head>
|
||||||
|
<title></title>
|
||||||
|
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
|
||||||
|
<!--[if !mso]><!-->
|
||||||
|
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||||
|
<!--<![endif]-->
|
||||||
|
<meta name="x-apple-disable-message-reformatting" content="">
|
||||||
|
<meta content="target-densitydpi=device-dpi" name="viewport">
|
||||||
|
<meta content="true" name="HandheldFriendly">
|
||||||
|
<meta content="width=device-width" name="viewport">
|
||||||
|
<meta name="format-detection" content="telephone=no, date=no, address=no, email=no, url=no">
|
||||||
|
<style type="text/css">
|
||||||
|
table {
|
||||||
|
border-collapse: separate;
|
||||||
|
table-layout: fixed;
|
||||||
|
mso-table-lspace: 0pt;
|
||||||
|
mso-table-rspace: 0pt
|
||||||
|
}
|
||||||
|
table td {
|
||||||
|
border-collapse: collapse
|
||||||
|
}
|
||||||
|
.ExternalClass {
|
||||||
|
width: 100%
|
||||||
|
}
|
||||||
|
.ExternalClass,
|
||||||
|
.ExternalClass p,
|
||||||
|
.ExternalClass span,
|
||||||
|
.ExternalClass font,
|
||||||
|
.ExternalClass td,
|
||||||
|
.ExternalClass div {
|
||||||
|
line-height: 100%
|
||||||
|
}
|
||||||
|
body, a, li, p, h1, h2, h3 {
|
||||||
|
-ms-text-size-adjust: 100%;
|
||||||
|
-webkit-text-size-adjust: 100%;
|
||||||
|
}
|
||||||
|
html {
|
||||||
|
-webkit-text-size-adjust: none !important
|
||||||
|
}
|
||||||
|
body, #innerTable {
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
-moz-osx-font-smoothing: grayscale
|
||||||
|
}
|
||||||
|
#innerTable img+div {
|
||||||
|
display: none;
|
||||||
|
display: none !important
|
||||||
|
}
|
||||||
|
img {
|
||||||
|
Margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
-ms-interpolation-mode: bicubic
|
||||||
|
}
|
||||||
|
h1, h2, h3, p, a {
|
||||||
|
line-height: 1;
|
||||||
|
overflow-wrap: normal;
|
||||||
|
white-space: normal;
|
||||||
|
word-break: break-word
|
||||||
|
}
|
||||||
|
a {
|
||||||
|
text-decoration: none
|
||||||
|
}
|
||||||
|
h1, h2, h3, p {
|
||||||
|
min-width: 100%!important;
|
||||||
|
width: 100%!important;
|
||||||
|
max-width: 100%!important;
|
||||||
|
display: inline-block!important;
|
||||||
|
border: 0;
|
||||||
|
padding: 0;
|
||||||
|
margin: 0
|
||||||
|
}
|
||||||
|
a[x-apple-data-detectors] {
|
||||||
|
color: inherit !important;
|
||||||
|
text-decoration: none !important;
|
||||||
|
font-size: inherit !important;
|
||||||
|
font-family: inherit !important;
|
||||||
|
font-weight: inherit !important;
|
||||||
|
line-height: inherit !important
|
||||||
|
}
|
||||||
|
a[href^="mailto"],
|
||||||
|
a[href^="tel"],
|
||||||
|
a[href^="sms"] {
|
||||||
|
color: inherit;
|
||||||
|
text-decoration: none
|
||||||
|
}
|
||||||
|
@media (min-width: 481px) {
|
||||||
|
.hd { display: none!important }
|
||||||
|
}
|
||||||
|
@media (max-width: 480px) {
|
||||||
|
.hm { display: none!important }
|
||||||
|
}
|
||||||
|
[style*="Inter Tight"] {font-family: 'Inter Tight', BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif !important;} [style*="Albert Sans"] {font-family: 'Albert Sans', BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif !important;}
|
||||||
|
@media only screen and (min-width: 481px) {.t20{width:720px!important}.t27{padding:40px 60px 50px!important}.t29{padding:40px 60px 50px!important;width:680px!important}.t43{width:600px!important}.t53,.t61{width:580px!important}.t65{width:600px!important}.t78{padding-left:0!important;padding-right:0!important}.t80{padding-left:0!important;padding-right:0!important;width:400px!important}.t84,.t94{width:600px!important}}
|
||||||
|
</style>
|
||||||
|
<style type="text/css" media="screen and (min-width:481px)">.moz-text-html .t20{width:720px!important}.moz-text-html .t27{padding:40px 60px 50px!important}.moz-text-html .t29{padding:40px 60px 50px!important;width:680px!important}.moz-text-html .t43{width:600px!important}.moz-text-html .t53,.moz-text-html .t61{width:580px!important}.moz-text-html .t65{width:600px!important}.moz-text-html .t78{padding-left:0!important;padding-right:0!important}.moz-text-html .t80{padding-left:0!important;padding-right:0!important;width:400px!important}.moz-text-html .t84,.moz-text-html .t94{width:600px!important}</style>
|
||||||
|
<!--[if !mso]><!-->
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Inter+Tight:wght@400;600&family=Albert+Sans:wght@800&display=swap" rel="stylesheet" type="text/css">
|
||||||
|
<!--<![endif]-->
|
||||||
|
<!--[if mso]>
|
||||||
|
<style type="text/css">
|
||||||
|
td.t20{width:800px !important}td.t27{padding:40px 60px 50px !important}td.t29{padding:40px 60px 50px !important;width:800px !important}td.t43,td.t53{width:600px !important}td.t61{width:580px !important}td.t65{width:600px !important}td.t78,td.t80{padding-left:0 !important;padding-right:0 !important}td.t84,td.t94{width:600px !important}
|
||||||
|
</style>
|
||||||
|
<![endif]-->
|
||||||
|
<!--[if mso]>
|
||||||
|
<xml>
|
||||||
|
<o:OfficeDocumentSettings>
|
||||||
|
<o:AllowPNG/>
|
||||||
|
<o:PixelsPerInch>96</o:PixelsPerInch>
|
||||||
|
</o:OfficeDocumentSettings>
|
||||||
|
</xml>
|
||||||
|
<![endif]-->
|
||||||
|
</head>
|
||||||
|
<body class="t0" style="min-width:100%;Marg
|
||||||
|
if you did not sign up with Donetick please Ignore this email. in:0px;padding:0px;background-color:#FFFFFF;"><div class="t1" style="background-color:#FFFFFF;"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" align="center"><tbody><tr><td class="t130" style="font-size:0;line-height:0;mso-line-height-rule:exactly;" valign="top" align="center">
|
||||||
|
<!--[if mso]>
|
||||||
|
<v:background xmlns:v="urn:schemas-microsoft-com:vml" fill="true" stroke="false">
|
||||||
|
<v:fill color="#FFFFFF"/>
|
||||||
|
</v:background>
|
||||||
|
<![endif]-->
|
||||||
|
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" align="center" id="innerTable"><tbody><tr><td>
|
||||||
|
<table class="t118" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr>
|
||||||
|
|
||||||
|
<!--<![endif]-->
|
||||||
|
<!--[if mso]><td class="t119" style="width:400px;padding:40px 40px 40px 40px;"><![endif]-->
|
||||||
|
</tr></tbody></table><table role="presentation" width="100%" cellpadding="0" cellspacing="0"></table></td>
|
||||||
|
</tr></tbody></table>
|
||||||
|
</td></tr><tr><td>
|
||||||
|
<table class="t10" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr>
|
||||||
|
<!--[if !mso]><!--><td class="t11" style="background-color:#FFFFFF;width:400px;">
|
||||||
|
<!--<![endif]-->
|
||||||
|
<!--[if mso]><td class="t11" style="background-color:#FFFFFF;width:400px;"><![endif]-->
|
||||||
|
<table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tbody><tr><td>
|
||||||
|
<table class="t19" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr>
|
||||||
|
<!--[if !mso]><!--><td class="t20" style="background-color:#404040;width:400px;padding:40px 40px 40px 40px;">
|
||||||
|
<!--<![endif]-->
|
||||||
|
<!--[if mso]><td class="t20" style="background-color:#404040;width:480px;padding:40px 40px 40px 40px;"><![endif]-->
|
||||||
|
<table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tbody><tr><td>
|
||||||
|
<table class="t103" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr>
|
||||||
|
<!--[if !mso]><!--><td class="t104" style="width:200px;">
|
||||||
|
<!--<![endif]-->
|
||||||
|
<!--[if mso]><td class="t104" style="width:200px;"><![endif]-->
|
||||||
|
<div style="font-size:0px;"><img class="t110" style="display:block;border:0;height:auto;width:100%;Margin:0;max-width:100%;" width="200" height="179.5" alt="" src="https://835a1b8e-557a-4713-8f1c-104febdb8808.b-cdn.net/e/30b4288c-4e67-4e3b-9527-1fc4c4ec2fdf/df3f012a-c060-4d59-b5fd-54a57dae1916.png"></div></td>
|
||||||
|
</tr></tbody></table>
|
||||||
|
</td></tr></tbody></table></td>
|
||||||
|
</tr></tbody></table>
|
||||||
|
</td></tr><tr><td>
|
||||||
|
<table class="t28" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr>
|
||||||
|
<!--[if !mso]><!--><td class="t29" style="width:420px;padding:30px 30px 40px 30px;">
|
||||||
|
<!--<![endif]-->
|
||||||
|
<!--[if mso]><td class="t29" style="width:480px;padding:30px 30px 40px 30px;"><![endif]-->
|
||||||
|
<table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tbody><tr><td>
|
||||||
|
<table class="t42" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr>
|
||||||
|
<!--[if !mso]><!--><td class="t43" style="width:480px;">
|
||||||
|
<!--<![endif]-->
|
||||||
|
<!--[if mso]><td class="t43" style="width:480px;"><![endif]-->
|
||||||
|
<h1 class="t49" style="margin:0;Margin:0;font-family:BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif,'Albert Sans';line-height:35px;font-weight:800;font-style:normal;font-size:30px;text-decoration:none;text-transform:none;letter-spacing:-1.2px;direction:ltr;color:#333333;text-align:center;mso-line-height-rule:exactly;mso-text-raise:2px;">Someone forgot their password 😔</h1></td>
|
||||||
|
</tr></tbody></table>
|
||||||
|
</td></tr><tr><td><div class="t41" style="mso-line-height-rule:exactly;mso-line-height-alt:16px;line-height:16px;font-size:1px;display:block;"> </div></td></tr><tr><td><p class="t39" style="margin:0;Margin:0;font-family:BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif,'Inter Tight';line-height:21px;font-weight:400;font-style:normal;font-size:14px;text-decoration:none;text-transform:none;direction:ltr;color:#555555;text-align:center;mso-line-height-rule:exactly;mso-text-raise:2px;">We have received a password reset request for this email address. If you initiated this request, please click the button below to reset your password. Otherwise, you may safely ignore this email.</p></td></tr><tr><td><div class="t31" style="mso-line-height-rule:exactly;mso-line-height-alt:30px;line-height:30px;font-size:1px;display:block;"> </div></td></tr><tr><td>
|
||||||
|
<table class="t52" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr>
|
||||||
|
<!--[if !mso]><!--><td class="t53" style="background-color:#06b6d4;overflow:hidden;width:460px;text-align:center;line-height:24px;mso-line-height-rule:exactly;mso-text-raise:2px;padding:10px 10px 10px 10px;border-radius:10px 10px 10px 10px;">
|
||||||
|
<!--<![endif]-->
|
||||||
|
<!--[if mso]><td class="t53" style="background-color:#06b6d4;overflow:hidden;width:480px;text-align:center;line-height:24px;mso-line-height-rule:exactly;mso-text-raise:2px;padding:10px 10px 10px 10px;border-radius:10px 10px 10px 10px;"><![endif]-->
|
||||||
|
<a class="t59" href="{{verifyURL}}" style="display:block;margin:0;Margin:0;font-family:BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif,'Inter Tight';line-height:24px;font-weight:600;font-style:normal;font-size:16px;text-decoration:none;direction:ltr;color:#FFFFFF;text-align:center;mso-line-height-rule:exactly;mso-text-raise:2px;" target="_blank">Reset your Password</a></td>
|
||||||
|
</tr></tbody></table>
|
||||||
|
</td></tr><tr><td><div class="t62" style="mso-line-height-rule:exactly;mso-line-height-alt:12px;line-height:12px;font-size:1px;display:block;"> </div></td></tr><tr><td>
|
||||||
|
<table class="t64" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr>
|
||||||
|
<!--[if !mso]><!--><td class="t65" style="width:480px;">
|
||||||
|
<!--<![endif]-->
|
||||||
|
<!--[if mso]><td class="t65" style="width:480px;"><![endif]-->
|
||||||
|
<p class="t71" style="margin:0;Margin:0;font-family:BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif,'Inter Tight';line-height:21px;font-weight:400;font-style:normal;font-size:14px;text-decoration:none;text-transform:none;direction:ltr;color:#555555;text-align:center;mso-line-height-rule:exactly;mso-text-raise:2px;"> </p></td>
|
||||||
|
</tr></tbody></table>
|
||||||
|
</td></tr></tbody></table></td>
|
||||||
|
</tr></tbody></table>
|
||||||
|
</td></tr></tbody></table></td>
|
||||||
|
</tr></tbody></table>
|
||||||
|
</td></tr><tr><td><div class="t4" style="mso-line-height-rule:exactly;mso-line-height-alt:30px;line-height:30px;font-size:1px;display:block;"> </div></td></tr><tr><td>
|
||||||
|
<table class="t79" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr>
|
||||||
|
<!--[if !mso]><!--><td class="t80" style="width:320px;padding:0 40px 0 40px;">
|
||||||
|
<!--<![endif]-->
|
||||||
|
<!--[if mso]><td class="t80" style="width:400px;padding:0 40px 0 40px;"><![endif]-->
|
||||||
|
<table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tbody><tr><td>
|
||||||
|
<table class="t93" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr>
|
||||||
|
<!--[if !mso]><!--><td class="t94" style="width:480px;">
|
||||||
|
<!--<![endif]-->
|
||||||
|
<!--[if mso]><td class="t94" style="width:480px;"><![endif]-->
|
||||||
|
<p class="t100" style="margin:0;Margin:0;font-family:BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif,'Inter Tight';line-height:18px;font-weight:400;font-style:normal;font-size:12px;text-decoration:none;text-transform:none;direction:ltr;color:#555555;text-align:center;mso-line-height-rule:exactly;mso-text-raise:2px;">if you did not sign up with Donetick please Ignore this email. </p></td>
|
||||||
|
</tr></tbody></table>
|
||||||
|
</td></tr><tr><td><div class="t81" style="mso-line-height-rule:exactly;mso-line-height-alt:8px;line-height:8px;font-size:1px;display:block;"> </div></td></tr><tr><td>
|
||||||
|
<table class="t83" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr>
|
||||||
|
<!--[if !mso]><!--><td class="t84" style="width:480px;">
|
||||||
|
<!--<![endif]-->
|
||||||
|
<!--[if mso]><td class="t84" style="width:480px;"><![endif]-->
|
||||||
|
<p class="t90" style="margin:0;Margin:0;font-family:BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif,'Inter Tight';line-height:18px;font-weight:400;font-style:normal;font-size:12px;text-decoration:none;text-transform:none;direction:ltr;color:#555555;text-align:center;mso-line-height-rule:exactly;mso-text-raise:2px;">Favoro LLC. All rights reserved</p></td>
|
||||||
|
</tr></tbody></table>
|
||||||
|
</td></tr></tbody></table></td>
|
||||||
|
</tr></tbody></table>
|
||||||
|
</td></tr><tr><td><div class="t73" style="mso-line-height-rule:exactly;mso-line-height-alt:100px;line-height:100px;font-size:1px;display:block;"> </div></td></tr></tbody></table></div>
|
||||||
|
|
||||||
|
</body></html>
|
||||||
|
`
|
||||||
|
u := es.appHost + "/password/update?c=" + encodeEmailAndCode(to, code)
|
||||||
|
|
||||||
|
// logging.FromContext(c).Infof("Reset password URL: %s", u)
|
||||||
|
htmlBody = strings.Replace(htmlBody, "{{verifyURL}}", u, 1)
|
||||||
|
|
||||||
|
msg.SetBody("text/html", htmlBody)
|
||||||
|
|
||||||
|
err := es.client.DialAndSend(msg)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// func (es *EmailSender) SendFeedbackRequestEmail(to, code string) error {
|
||||||
|
// // msg := []byte(fmt.Sprintf("To: %s\r\nSubject: %s\r\n\r\n%s\r\n", to, subject, body))
|
||||||
|
// msg := gomail.NewMessage()
|
||||||
|
|
||||||
|
// }
|
||||||
|
func encodeEmailAndCode(email, code string) string {
|
||||||
|
data := email + ":" + code
|
||||||
|
return base64.StdEncoding.EncodeToString([]byte(data))
|
||||||
|
}
|
||||||
|
|
||||||
|
func DecodeEmailAndCode(encoded string) (string, string, error) {
|
||||||
|
data, err := base64.StdEncoding.DecodeString(encoded)
|
||||||
|
if err != nil {
|
||||||
|
return "", "", err
|
||||||
|
}
|
||||||
|
parts := string(data)
|
||||||
|
split := strings.Split(parts, ":")
|
||||||
|
if len(split) != 2 {
|
||||||
|
return "", "", fmt.Errorf("Invalid format")
|
||||||
|
}
|
||||||
|
return split[0], split[1], nil
|
||||||
|
}
|
|
@ -0,0 +1,15 @@
|
||||||
|
package model
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
type Notification struct {
|
||||||
|
ID int `json:"id" gorm:"primaryKey"`
|
||||||
|
ChoreID int `json:"chore_id" gorm:"column:chore_id"`
|
||||||
|
UserID int `json:"user_id" gorm:"column:user_id"`
|
||||||
|
TargetID string `json:"target_id" gorm:"column:target_id"`
|
||||||
|
Text string `json:"text" gorm:"column:text"`
|
||||||
|
IsSent bool `json:"is_sent" gorm:"column:is_sent;index;default:false"`
|
||||||
|
TypeID int `json:"type" gorm:"column:type"`
|
||||||
|
ScheduledFor time.Time `json:"scheduled_for" gorm:"column:scheduled_for;index"`
|
||||||
|
CreatedAt time.Time `json:"created_at" gorm:"column:created_at"`
|
||||||
|
}
|
|
@ -0,0 +1,43 @@
|
||||||
|
package user
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
nModel "donetick.com/core/internal/notifier/model"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type NotificationRepository struct {
|
||||||
|
db *gorm.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewNotificationRepository(db *gorm.DB) *NotificationRepository {
|
||||||
|
return &NotificationRepository{db}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *NotificationRepository) DeleteAllChoreNotifications(choreID int) error {
|
||||||
|
return r.db.Where("chore_id = ?", choreID).Delete(&nModel.Notification{}).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *NotificationRepository) BatchInsertNotifications(notifications []*nModel.Notification) error {
|
||||||
|
return r.db.Create(¬ifications).Error
|
||||||
|
}
|
||||||
|
func (r *NotificationRepository) MarkNotificationsAsSent(notifications []*nModel.Notification) error {
|
||||||
|
// Extract IDs from notifications
|
||||||
|
var ids []int
|
||||||
|
for _, notification := range notifications {
|
||||||
|
ids = append(ids, notification.ID)
|
||||||
|
}
|
||||||
|
// Use the extracted IDs in the Where clause
|
||||||
|
return r.db.Model(&nModel.Notification{}).Where("id IN (?)", ids).Update("is_sent", true).Error
|
||||||
|
}
|
||||||
|
func (r *NotificationRepository) GetPendingNotificaiton(c context.Context, lookback time.Duration) ([]*nModel.Notification, error) {
|
||||||
|
var notifications []*nModel.Notification
|
||||||
|
start := time.Now().UTC().Add(-lookback)
|
||||||
|
end := time.Now().UTC()
|
||||||
|
if err := r.db.Debug().Where("is_sent = ? AND scheduled_for < ? AND scheduled_for > ?", false, end, start).Find(¬ifications).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return notifications, nil
|
||||||
|
}
|
|
@ -0,0 +1,89 @@
|
||||||
|
package notifier
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"log"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"donetick.com/core/config"
|
||||||
|
chRepo "donetick.com/core/internal/chore/repo"
|
||||||
|
nRepo "donetick.com/core/internal/notifier/repo"
|
||||||
|
notifier "donetick.com/core/internal/notifier/telegram"
|
||||||
|
uRepo "donetick.com/core/internal/user/repo"
|
||||||
|
"donetick.com/core/logging"
|
||||||
|
)
|
||||||
|
|
||||||
|
type keyType string
|
||||||
|
|
||||||
|
const (
|
||||||
|
SchedulerKey keyType = "scheduler"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Scheduler struct {
|
||||||
|
choreRepo *chRepo.ChoreRepository
|
||||||
|
userRepo *uRepo.UserRepository
|
||||||
|
stopChan chan bool
|
||||||
|
notifier *notifier.TelegramNotifier
|
||||||
|
notificationRepo *nRepo.NotificationRepository
|
||||||
|
SchedulerJobs config.SchedulerConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewScheduler(cfg *config.Config, ur *uRepo.UserRepository, cr *chRepo.ChoreRepository, n *notifier.TelegramNotifier, nr *nRepo.NotificationRepository) *Scheduler {
|
||||||
|
return &Scheduler{
|
||||||
|
choreRepo: cr,
|
||||||
|
userRepo: ur,
|
||||||
|
stopChan: make(chan bool),
|
||||||
|
notifier: n,
|
||||||
|
notificationRepo: nr,
|
||||||
|
SchedulerJobs: cfg.SchedulerJobs,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Scheduler) Start(c context.Context) {
|
||||||
|
log := logging.FromContext(c)
|
||||||
|
log.Debug("Scheduler started")
|
||||||
|
go s.runScheduler(c, " NOTIFICATION_SCHEDULER ", s.loadAndSendNotificationJob, 3*time.Minute)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Scheduler) loadAndSendNotificationJob(c context.Context) (time.Duration, error) {
|
||||||
|
log := logging.FromContext(c)
|
||||||
|
startTime := time.Now()
|
||||||
|
getAllPendingNotifications, err := s.notificationRepo.GetPendingNotificaiton(c, time.Minute*15)
|
||||||
|
log.Debug("Getting pending notifications", " count ", len(getAllPendingNotifications))
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
log.Error("Error getting pending notifications")
|
||||||
|
return time.Since(startTime), err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, notification := range getAllPendingNotifications {
|
||||||
|
s.notifier.SendNotification(c, notification)
|
||||||
|
notification.IsSent = true
|
||||||
|
}
|
||||||
|
|
||||||
|
s.notificationRepo.MarkNotificationsAsSent(getAllPendingNotifications)
|
||||||
|
return time.Since(startTime), nil
|
||||||
|
}
|
||||||
|
func (s *Scheduler) runScheduler(c context.Context, jobName string, job func(c context.Context) (time.Duration, error), interval time.Duration) {
|
||||||
|
|
||||||
|
for {
|
||||||
|
logging.FromContext(c).Debug("Scheduler running ", jobName, " time", time.Now().String())
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-s.stopChan:
|
||||||
|
log.Println("Scheduler stopped")
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
elapsedTime, err := job(c)
|
||||||
|
if err != nil {
|
||||||
|
logging.FromContext(c).Error("Error running scheduler job", err)
|
||||||
|
}
|
||||||
|
logging.FromContext(c).Debug("Scheduler job completed", jobName, " time", elapsedTime.String())
|
||||||
|
}
|
||||||
|
time.Sleep(interval)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Scheduler) Stop() {
|
||||||
|
s.stopChan <- true
|
||||||
|
}
|
|
@ -0,0 +1,149 @@
|
||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
chModel "donetick.com/core/internal/chore/model"
|
||||||
|
cModel "donetick.com/core/internal/circle/model"
|
||||||
|
cRepo "donetick.com/core/internal/circle/repo"
|
||||||
|
nModel "donetick.com/core/internal/notifier/model"
|
||||||
|
nRepo "donetick.com/core/internal/notifier/repo"
|
||||||
|
"donetick.com/core/logging"
|
||||||
|
)
|
||||||
|
|
||||||
|
type NotificationPlanner struct {
|
||||||
|
nRepo *nRepo.NotificationRepository
|
||||||
|
cRepo *cRepo.CircleRepository
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewNotificationPlanner(nr *nRepo.NotificationRepository, cr *cRepo.CircleRepository) *NotificationPlanner {
|
||||||
|
return &NotificationPlanner{nRepo: nr,
|
||||||
|
cRepo: cr,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (n *NotificationPlanner) GenerateNotifications(c context.Context, chore *chModel.Chore) bool {
|
||||||
|
log := logging.FromContext(c)
|
||||||
|
circleMembers, err := n.cRepo.GetCircleUsers(c, chore.CircleID)
|
||||||
|
assignees := make([]*cModel.UserCircleDetail, 0)
|
||||||
|
for _, member := range circleMembers {
|
||||||
|
if member.ID == chore.AssignedTo {
|
||||||
|
assignees = append(assignees, member)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
log.Error("Error getting circle members", err)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
n.nRepo.DeleteAllChoreNotifications(chore.ID)
|
||||||
|
notifications := make([]*nModel.Notification, 0)
|
||||||
|
if !chore.Notification || chore.FrequencyType == "trigger" {
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
var mt *chModel.NotificationMetadata
|
||||||
|
if err := json.Unmarshal([]byte(*chore.NotificationMetadata), &mt); err != nil {
|
||||||
|
log.Error("Error unmarshalling notification metadata", err)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if mt.DueDate {
|
||||||
|
notifications = append(notifications, generateDueNotifications(chore, assignees)...)
|
||||||
|
}
|
||||||
|
if mt.PreDue {
|
||||||
|
notifications = append(notifications, generatePreDueNotifications(chore, assignees)...)
|
||||||
|
}
|
||||||
|
if mt.Nagging {
|
||||||
|
notifications = append(notifications, generateOverdueNotifications(chore, assignees)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
n.nRepo.BatchInsertNotifications(notifications)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func generateDueNotifications(chore *chModel.Chore, users []*cModel.UserCircleDetail) []*nModel.Notification {
|
||||||
|
var assignee *cModel.UserCircleDetail
|
||||||
|
notifications := make([]*nModel.Notification, 0)
|
||||||
|
for _, user := range users {
|
||||||
|
if user.ID == chore.AssignedTo {
|
||||||
|
assignee = user
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, user := range users {
|
||||||
|
|
||||||
|
notification := &nModel.Notification{
|
||||||
|
ChoreID: chore.ID,
|
||||||
|
IsSent: false,
|
||||||
|
ScheduledFor: *chore.NextDueDate,
|
||||||
|
CreatedAt: time.Now().UTC(),
|
||||||
|
TypeID: 1,
|
||||||
|
UserID: user.ID,
|
||||||
|
TargetID: fmt.Sprint(user.ChatID),
|
||||||
|
Text: fmt.Sprintf("📅 Reminder: '%s' is due today and assigned to %s.", chore.Name, assignee.DisplayName),
|
||||||
|
}
|
||||||
|
notifications = append(notifications, notification)
|
||||||
|
}
|
||||||
|
|
||||||
|
return notifications
|
||||||
|
}
|
||||||
|
|
||||||
|
func generatePreDueNotifications(chore *chModel.Chore, users []*cModel.UserCircleDetail) []*nModel.Notification {
|
||||||
|
var assignee *cModel.UserCircleDetail
|
||||||
|
for _, user := range users {
|
||||||
|
if user.ID == chore.AssignedTo {
|
||||||
|
assignee = user
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
notifications := make([]*nModel.Notification, 0)
|
||||||
|
for _, user := range users {
|
||||||
|
notification := &nModel.Notification{
|
||||||
|
ChoreID: chore.ID,
|
||||||
|
IsSent: false,
|
||||||
|
ScheduledFor: *chore.NextDueDate,
|
||||||
|
CreatedAt: time.Now().UTC().Add(-time.Hour * 3),
|
||||||
|
TypeID: 3,
|
||||||
|
UserID: user.ID,
|
||||||
|
TargetID: fmt.Sprint(user.ChatID),
|
||||||
|
Text: fmt.Sprintf("📢 Heads up! Chore '%s' is due soon (on %s) and assigned to %s.", chore.Name, chore.NextDueDate.Format("January 2nd"), assignee.DisplayName),
|
||||||
|
}
|
||||||
|
notifications = append(notifications, notification)
|
||||||
|
|
||||||
|
}
|
||||||
|
return notifications
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func generateOverdueNotifications(chore *chModel.Chore, users []*cModel.UserCircleDetail) []*nModel.Notification {
|
||||||
|
var assignee *cModel.UserCircleDetail
|
||||||
|
for _, user := range users {
|
||||||
|
if user.ID == chore.AssignedTo {
|
||||||
|
assignee = user
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
notifications := make([]*nModel.Notification, 0)
|
||||||
|
for _, hours := range []int{24, 48, 72} {
|
||||||
|
scheduleTime := chore.NextDueDate.Add(time.Hour * time.Duration(hours))
|
||||||
|
for _, user := range users {
|
||||||
|
notification := &nModel.Notification{
|
||||||
|
ChoreID: chore.ID,
|
||||||
|
IsSent: false,
|
||||||
|
ScheduledFor: scheduleTime,
|
||||||
|
CreatedAt: time.Now().UTC(),
|
||||||
|
TypeID: 2,
|
||||||
|
UserID: user.ID,
|
||||||
|
TargetID: fmt.Sprint(user.ChatID),
|
||||||
|
Text: fmt.Sprintf("🚨 '%s' is now %d hours overdue. Please complete it as soon as possible. (Assigned to %s)", chore.Name, hours, assignee.DisplayName),
|
||||||
|
}
|
||||||
|
notifications = append(notifications, notification)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return notifications
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,127 @@
|
||||||
|
package telegram
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"donetick.com/core/config"
|
||||||
|
chModel "donetick.com/core/internal/chore/model"
|
||||||
|
nModel "donetick.com/core/internal/notifier/model"
|
||||||
|
uModel "donetick.com/core/internal/user/model"
|
||||||
|
"donetick.com/core/logging"
|
||||||
|
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
type TelegramNotifier struct {
|
||||||
|
bot *tgbotapi.BotAPI
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewTelegramNotifier(config *config.Config) *TelegramNotifier {
|
||||||
|
bot, err := tgbotapi.NewBotAPI(config.Telegram.Token)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println("Error creating bot: ", err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return &TelegramNotifier{
|
||||||
|
bot: bot,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tn *TelegramNotifier) SendChoreReminder(c context.Context, chore *chModel.Chore, users []*uModel.User) {
|
||||||
|
for _, user := range users {
|
||||||
|
var assignee *uModel.User
|
||||||
|
if user.ID == chore.AssignedTo {
|
||||||
|
if user.ChatID == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
assignee = user
|
||||||
|
text := fmt.Sprintf("*%s* is due today and assigned to *%s*", chore.Name, assignee.DisplayName)
|
||||||
|
msg := tgbotapi.NewMessage(user.ChatID, text)
|
||||||
|
msg.ParseMode = "Markdown"
|
||||||
|
_, err := tn.bot.Send(msg)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println("Error sending message to user: ", err)
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tn *TelegramNotifier) SendChoreCompletion(c context.Context, chore *chModel.Chore, users []*uModel.User) {
|
||||||
|
log := logging.FromContext(c)
|
||||||
|
for _, user := range users {
|
||||||
|
if user.ChatID == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
text := fmt.Sprintf("🎉 '%s' is completed! is off the list, %s! 🌟 ", chore.Name, user.DisplayName)
|
||||||
|
msg := tgbotapi.NewMessage(user.ChatID, text)
|
||||||
|
msg.ParseMode = "Markdown"
|
||||||
|
_, err := tn.bot.Send(msg)
|
||||||
|
if err != nil {
|
||||||
|
log.Error("Error sending message to user: ", err)
|
||||||
|
log.Debug("Error sending message, chore: ", chore.Name, " user: ", user.DisplayName, " chatID: ", user.ChatID, " user id: ", user.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tn *TelegramNotifier) SendChoreOverdue(c context.Context, chore *chModel.Chore, users []*uModel.User) {
|
||||||
|
log := logging.FromContext(c)
|
||||||
|
for _, user := range users {
|
||||||
|
if user.ChatID == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
text := fmt.Sprintf("*%s* is overdue and assigned to *%s*", chore.Name, user.DisplayName)
|
||||||
|
msg := tgbotapi.NewMessage(user.ChatID, text)
|
||||||
|
msg.ParseMode = "Markdown"
|
||||||
|
_, err := tn.bot.Send(msg)
|
||||||
|
if err != nil {
|
||||||
|
log.Error("Error sending message to user: ", err)
|
||||||
|
log.Debug("Error sending message, chore: ", chore.Name, " user: ", user.DisplayName, " chatID: ", user.ChatID, " user id: ", user.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tn *TelegramNotifier) SendChorePreDue(c context.Context, chore *chModel.Chore, users []*uModel.User) {
|
||||||
|
log := logging.FromContext(c)
|
||||||
|
for _, user := range users {
|
||||||
|
if user.ID != chore.AssignedTo {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if user.ChatID == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
text := fmt.Sprintf("*%s* is due tomorrow and assigned to *%s*", chore.Name, user.DisplayName)
|
||||||
|
msg := tgbotapi.NewMessage(user.ChatID, text)
|
||||||
|
msg.ParseMode = "Markdown"
|
||||||
|
_, err := tn.bot.Send(msg)
|
||||||
|
if err != nil {
|
||||||
|
log.Error("Error sending message to user: ", err)
|
||||||
|
log.Debug("Error sending message, chore: ", chore.Name, " user: ", user.DisplayName, " chatID: ", user.ChatID, " user id: ", user.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tn *TelegramNotifier) SendNotification(c context.Context, notification *nModel.Notification) {
|
||||||
|
|
||||||
|
log := logging.FromContext(c)
|
||||||
|
if notification.TargetID == "" {
|
||||||
|
log.Error("Notification target ID is empty")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
chatID, err := strconv.ParseInt(notification.TargetID, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
log.Error("Error parsing chatID: ", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
msg := tgbotapi.NewMessage(chatID, notification.Text)
|
||||||
|
msg.ParseMode = "Markdown"
|
||||||
|
_, err = tn.bot.Send(msg)
|
||||||
|
if err != nil {
|
||||||
|
log.Error("Error sending message to user: ", err)
|
||||||
|
log.Debug("Error sending message, notification: ", notification.Text, " chatID: ", chatID)
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,281 @@
|
||||||
|
package thing
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
auth "donetick.com/core/internal/authorization"
|
||||||
|
chRepo "donetick.com/core/internal/chore/repo"
|
||||||
|
cRepo "donetick.com/core/internal/circle/repo"
|
||||||
|
nRepo "donetick.com/core/internal/notifier/repo"
|
||||||
|
nps "donetick.com/core/internal/notifier/service"
|
||||||
|
tModel "donetick.com/core/internal/thing/model"
|
||||||
|
tRepo "donetick.com/core/internal/thing/repo"
|
||||||
|
"donetick.com/core/logging"
|
||||||
|
jwt "github.com/appleboy/gin-jwt/v2"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Handler struct {
|
||||||
|
choreRepo *chRepo.ChoreRepository
|
||||||
|
circleRepo *cRepo.CircleRepository
|
||||||
|
nPlanner *nps.NotificationPlanner
|
||||||
|
nRepo *nRepo.NotificationRepository
|
||||||
|
tRepo *tRepo.ThingRepository
|
||||||
|
}
|
||||||
|
|
||||||
|
type ThingRequest struct {
|
||||||
|
ID int `json:"id"`
|
||||||
|
Name string `json:"name" binding:"required"`
|
||||||
|
Type string `json:"type" binding:"required"`
|
||||||
|
State string `json:"state"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHandler(cr *chRepo.ChoreRepository, circleRepo *cRepo.CircleRepository,
|
||||||
|
np *nps.NotificationPlanner, nRepo *nRepo.NotificationRepository, tRepo *tRepo.ThingRepository) *Handler {
|
||||||
|
return &Handler{
|
||||||
|
choreRepo: cr,
|
||||||
|
circleRepo: circleRepo,
|
||||||
|
nPlanner: np,
|
||||||
|
nRepo: nRepo,
|
||||||
|
tRepo: tRepo,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) CreateThing(c *gin.Context) {
|
||||||
|
log := logging.FromContext(c)
|
||||||
|
currentUser, ok := auth.CurrentUser(c)
|
||||||
|
if !ok {
|
||||||
|
c.JSON(401, gin.H{"error": "Unauthorized"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var req ThingRequest
|
||||||
|
if err := c.BindJSON(&req); err != nil {
|
||||||
|
c.JSON(400, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
thing := &tModel.Thing{
|
||||||
|
Name: req.Name,
|
||||||
|
UserID: currentUser.ID,
|
||||||
|
Type: req.Type,
|
||||||
|
State: req.State,
|
||||||
|
}
|
||||||
|
if !isValidThingState(thing) {
|
||||||
|
c.JSON(400, gin.H{"error": "Invalid state"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Debug("Creating thing", thing)
|
||||||
|
if err := h.tRepo.UpsertThing(c, thing); err != nil {
|
||||||
|
c.JSON(500, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(201, gin.H{
|
||||||
|
"res": thing,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) UpdateThingState(c *gin.Context) {
|
||||||
|
currentUser, ok := auth.CurrentUser(c)
|
||||||
|
if !ok {
|
||||||
|
c.JSON(401, gin.H{"error": "Unauthorized"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
thingIDRaw := c.Param("id")
|
||||||
|
thingID, err := strconv.Atoi(thingIDRaw)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(400, gin.H{"error": "Invalid thing id"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
val := c.Query("value")
|
||||||
|
if val == "" {
|
||||||
|
c.JSON(400, gin.H{"error": "state or increment query param is required"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
thing, err := h.tRepo.GetThingByID(c, thingID)
|
||||||
|
if thing.UserID != currentUser.ID {
|
||||||
|
c.JSON(403, gin.H{"error": "Forbidden"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{"error": "Unable to find thing"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
thing.State = val
|
||||||
|
if !isValidThingState(thing) {
|
||||||
|
c.JSON(400, gin.H{"error": "Invalid state"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.tRepo.UpdateThingState(c, thing); err != nil {
|
||||||
|
c.JSON(500, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
shouldReturn := EvaluateTriggerAndScheduleDueDate(h, c, thing)
|
||||||
|
if shouldReturn {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"res": thing,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func EvaluateTriggerAndScheduleDueDate(h *Handler, c *gin.Context, thing *tModel.Thing) bool {
|
||||||
|
thingChores, err := h.tRepo.GetThingChoresByThingId(c, thing.ID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{"error": err.Error()})
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
for _, tc := range thingChores {
|
||||||
|
triggered := EvaluateThingChore(tc, thing.State)
|
||||||
|
if triggered {
|
||||||
|
h.choreRepo.SetDueDateIfNotExisted(c, tc.ChoreID, time.Now().UTC())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) UpdateThing(c *gin.Context) {
|
||||||
|
currentUser, ok := auth.CurrentUser(c)
|
||||||
|
if !ok {
|
||||||
|
c.JSON(401, gin.H{"error": "Unauthorized"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var req ThingRequest
|
||||||
|
if err := c.BindJSON(&req); err != nil {
|
||||||
|
c.JSON(400, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
thing, err := h.tRepo.GetThingByID(c, req.ID)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{"error": "Unable to find thing"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if thing.UserID != currentUser.ID {
|
||||||
|
c.JSON(403, gin.H{"error": "Forbidden"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
thing.Name = req.Name
|
||||||
|
thing.Type = req.Type
|
||||||
|
if req.State != "" {
|
||||||
|
thing.State = req.State
|
||||||
|
if !isValidThingState(thing) {
|
||||||
|
c.JSON(400, gin.H{"error": "Invalid state"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.tRepo.UpsertThing(c, thing); err != nil {
|
||||||
|
c.JSON(500, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"res": thing,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) GetAllThings(c *gin.Context) {
|
||||||
|
currentUser, ok := auth.CurrentUser(c)
|
||||||
|
if !ok {
|
||||||
|
c.JSON(401, gin.H{"error": "Unauthorized"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
things, err := h.tRepo.GetUserThings(c, currentUser.ID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"res": things,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) GetThingHistory(c *gin.Context) {
|
||||||
|
currentUser, ok := auth.CurrentUser(c)
|
||||||
|
if !ok {
|
||||||
|
c.JSON(401, gin.H{"error": "Unauthorized"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
thingIDRaw := c.Param("id")
|
||||||
|
thingID, err := strconv.Atoi(thingIDRaw)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(400, gin.H{"error": "Invalid thing id"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
thing, err := h.tRepo.GetThingByID(c, thingID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{"error": "Unable to find thing"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if thing.UserID != currentUser.ID {
|
||||||
|
c.JSON(403, gin.H{"error": "Forbidden"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
offsetRaw := c.Query("offset")
|
||||||
|
offset, err := strconv.Atoi(offsetRaw)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(400, gin.H{"error": "Invalid offset"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
history, err := h.tRepo.GetThingHistoryWithOffset(c, thingID, offset, 10)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"res": history,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) DeleteThing(c *gin.Context) {
|
||||||
|
currentUser, ok := auth.CurrentUser(c)
|
||||||
|
if !ok {
|
||||||
|
c.JSON(401, gin.H{"error": "Unauthorized"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
thingIDRaw := c.Param("id")
|
||||||
|
thingID, err := strconv.Atoi(thingIDRaw)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(400, gin.H{"error": "Invalid thing id"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
thing, err := h.tRepo.GetThingByID(c, thingID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{"error": "Unable to find thing"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if thing.UserID != currentUser.ID {
|
||||||
|
c.JSON(403, gin.H{"error": "Forbidden"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := h.tRepo.DeleteThing(c, thingID); err != nil {
|
||||||
|
c.JSON(500, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(200, gin.H{})
|
||||||
|
}
|
||||||
|
func Routes(r *gin.Engine, h *Handler, auth *jwt.GinJWTMiddleware) {
|
||||||
|
|
||||||
|
thingRoutes := r.Group("things")
|
||||||
|
thingRoutes.Use(auth.MiddlewareFunc())
|
||||||
|
{
|
||||||
|
thingRoutes.POST("", h.CreateThing)
|
||||||
|
thingRoutes.PUT("/:id/state", h.UpdateThingState)
|
||||||
|
thingRoutes.PUT("", h.UpdateThing)
|
||||||
|
thingRoutes.GET("", h.GetAllThings)
|
||||||
|
thingRoutes.GET("/:id/history", h.GetThingHistory)
|
||||||
|
thingRoutes.DELETE("/:id", h.DeleteThing)
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,57 @@
|
||||||
|
package thing
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
tModel "donetick.com/core/internal/thing/model"
|
||||||
|
)
|
||||||
|
|
||||||
|
func isValidThingState(thing *tModel.Thing) bool {
|
||||||
|
switch thing.Type {
|
||||||
|
case "number":
|
||||||
|
_, err := strconv.Atoi(thing.State)
|
||||||
|
return err == nil
|
||||||
|
case "text":
|
||||||
|
return true
|
||||||
|
case "boolean":
|
||||||
|
return thing.State == "true" || thing.State == "false"
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func EvaluateThingChore(tchore *tModel.ThingChore, newState string) bool {
|
||||||
|
if tchore.Condition == "" {
|
||||||
|
return newState == tchore.TriggerState
|
||||||
|
}
|
||||||
|
|
||||||
|
switch tchore.Condition {
|
||||||
|
case "eq":
|
||||||
|
return newState == tchore.TriggerState
|
||||||
|
case "neq":
|
||||||
|
return newState != tchore.TriggerState
|
||||||
|
}
|
||||||
|
|
||||||
|
newStateInt, err := strconv.Atoi(newState)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
TargetStateInt, err := strconv.Atoi(tchore.TriggerState)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
switch tchore.Condition {
|
||||||
|
case "gt":
|
||||||
|
return newStateInt > TargetStateInt
|
||||||
|
case "lt":
|
||||||
|
return newStateInt < TargetStateInt
|
||||||
|
case "gte":
|
||||||
|
return newStateInt >= TargetStateInt
|
||||||
|
case "lte":
|
||||||
|
return newStateInt <= TargetStateInt
|
||||||
|
default:
|
||||||
|
return newState == tchore.TriggerState
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,30 @@
|
||||||
|
package model
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
type Thing struct {
|
||||||
|
ID int `json:"id" gorm:"primary_key"`
|
||||||
|
UserID int `json:"userID" gorm:"column:user_id"`
|
||||||
|
CircleID int `json:"circleId" gorm:"column:circle_id"`
|
||||||
|
Name string `json:"name" gorm:"column:name"`
|
||||||
|
State string `json:"state" gorm:"column:state"`
|
||||||
|
Type string `json:"type" gorm:"column:type"`
|
||||||
|
ThingChores []ThingChore `json:"thingChores" gorm:"foreignkey:ThingID;references:ID"`
|
||||||
|
UpdatedAt *time.Time `json:"updatedAt" gorm:"column:updated_at"`
|
||||||
|
CreatedAt *time.Time `json:"createdAt" gorm:"column:created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ThingHistory struct {
|
||||||
|
ID int `json:"id" gorm:"primary_key"`
|
||||||
|
ThingID int `json:"thingId" gorm:"column:thing_id"`
|
||||||
|
State string `json:"state" gorm:"column:state"`
|
||||||
|
UpdatedAt *time.Time `json:"updatedAt" gorm:"column:updated_at"`
|
||||||
|
CreatedAt *time.Time `json:"createdAt" gorm:"column:created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ThingChore struct {
|
||||||
|
ThingID int `json:"thingId" gorm:"column:thing_id;primaryKey;uniqueIndex:idx_thing_user"`
|
||||||
|
ChoreID int `json:"choreId" gorm:"column:chore_id;primaryKey;uniqueIndex:idx_thing_user"`
|
||||||
|
TriggerState string `json:"triggerState" gorm:"column:trigger_state"`
|
||||||
|
Condition string `json:"condition" gorm:"column:condition"`
|
||||||
|
}
|
|
@ -0,0 +1,117 @@
|
||||||
|
package chore
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
config "donetick.com/core/config"
|
||||||
|
tModel "donetick.com/core/internal/thing/model"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ThingRepository struct {
|
||||||
|
db *gorm.DB
|
||||||
|
dbType string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewThingRepository(db *gorm.DB, cfg *config.Config) *ThingRepository {
|
||||||
|
return &ThingRepository{db: db, dbType: cfg.Database.Type}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ThingRepository) UpsertThing(c context.Context, thing *tModel.Thing) error {
|
||||||
|
return r.db.WithContext(c).Model(&thing).Save(thing).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ThingRepository) UpdateThingState(c context.Context, thing *tModel.Thing) error {
|
||||||
|
// update the state of the thing where the id is the same:
|
||||||
|
if err := r.db.WithContext(c).Model(&thing).Where("id = ?", thing.ID).Updates(map[string]interface{}{
|
||||||
|
"state": thing.State,
|
||||||
|
"updated_at": time.Now().UTC(),
|
||||||
|
}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
// Create history Record of the thing :
|
||||||
|
createdAt := time.Now().UTC()
|
||||||
|
thingHistory := &tModel.ThingHistory{
|
||||||
|
ThingID: thing.ID,
|
||||||
|
State: thing.State,
|
||||||
|
CreatedAt: &createdAt,
|
||||||
|
UpdatedAt: &createdAt,
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := r.db.WithContext(c).Create(thingHistory).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func (r *ThingRepository) GetThingByID(c context.Context, thingID int) (*tModel.Thing, error) {
|
||||||
|
var thing tModel.Thing
|
||||||
|
if err := r.db.WithContext(c).Model(&tModel.Thing{}).Preload("ThingChores").First(&thing, thingID).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &thing, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ThingRepository) GetThingByChoreID(c context.Context, choreID int) (*tModel.Thing, error) {
|
||||||
|
var thing tModel.Thing
|
||||||
|
if err := r.db.WithContext(c).Model(&tModel.Thing{}).Joins("left join thing_chores on things.id = thing_chores.thing_id").First(&thing, "thing_chores.chore_id = ?", choreID).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &thing, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ThingRepository) AssociateThingWithChore(c context.Context, thingID int, choreID int, triggerState string, condition string) error {
|
||||||
|
|
||||||
|
return r.db.WithContext(c).Save(&tModel.ThingChore{ThingID: thingID, ChoreID: choreID, TriggerState: triggerState, Condition: condition}).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ThingRepository) DissociateThingWithChore(c context.Context, thingID int, choreID int) error {
|
||||||
|
return r.db.WithContext(c).Where("thing_id = ? AND chore_id = ?", thingID, choreID).Delete(&tModel.ThingChore{}).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ThingRepository) GetThingHistoryWithOffset(c context.Context, thingID int, offset int, limit int) ([]*tModel.ThingHistory, error) {
|
||||||
|
var thingHistory []*tModel.ThingHistory
|
||||||
|
if err := r.db.WithContext(c).Model(&tModel.ThingHistory{}).Where("thing_id = ?", thingID).Order("created_at desc").Offset(offset).Limit(limit).Find(&thingHistory).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return thingHistory, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ThingRepository) GetUserThings(c context.Context, userID int) ([]*tModel.Thing, error) {
|
||||||
|
var things []*tModel.Thing
|
||||||
|
if err := r.db.WithContext(c).Model(&tModel.Thing{}).Where("user_id = ?", userID).Find(&things).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return things, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ThingRepository) DeleteThing(c context.Context, thingID int) error {
|
||||||
|
// one transaction to delete the thing and its history :
|
||||||
|
return r.db.WithContext(c).Transaction(func(tx *gorm.DB) error {
|
||||||
|
if err := r.db.WithContext(c).Where("thing_id = ?", thingID).Delete(&tModel.ThingHistory{}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := r.db.WithContext(c).Delete(&tModel.Thing{}, thingID).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// get ThingChores by thingID:
|
||||||
|
func (r *ThingRepository) GetThingChoresByThingId(c context.Context, thingID int) ([]*tModel.ThingChore, error) {
|
||||||
|
var thingChores []*tModel.ThingChore
|
||||||
|
if err := r.db.WithContext(c).Model(&tModel.ThingChore{}).Where("thing_id = ?", thingID).Find(&thingChores).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return thingChores, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// func (r *ThingRepository) GetChoresByThingId(c context.Context, thingID int) ([]*chModel.Chore, error) {
|
||||||
|
// var chores []*chModel.Chore
|
||||||
|
// if err := r.db.WithContext(c).Model(&chModel.Chore{}).Joins("left join thing_chores on chores.id = thing_chores.chore_id").Where("thing_chores.thing_id = ?", thingID).Find(&chores).Error; err != nil {
|
||||||
|
// return nil, err
|
||||||
|
// }
|
||||||
|
// return chores, nil
|
||||||
|
// }
|
|
@ -0,0 +1,175 @@
|
||||||
|
package thing
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"donetick.com/core/config"
|
||||||
|
chRepo "donetick.com/core/internal/chore/repo"
|
||||||
|
cRepo "donetick.com/core/internal/circle/repo"
|
||||||
|
tModel "donetick.com/core/internal/thing/model"
|
||||||
|
tRepo "donetick.com/core/internal/thing/repo"
|
||||||
|
uRepo "donetick.com/core/internal/user/repo"
|
||||||
|
"donetick.com/core/internal/utils"
|
||||||
|
"donetick.com/core/logging"
|
||||||
|
jwt "github.com/appleboy/gin-jwt/v2"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Webhook struct {
|
||||||
|
choreRepo *chRepo.ChoreRepository
|
||||||
|
circleRepo *cRepo.CircleRepository
|
||||||
|
thingRepo *tRepo.ThingRepository
|
||||||
|
userRepo *uRepo.UserRepository
|
||||||
|
tRepo *tRepo.ThingRepository
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewWebhook(cr *chRepo.ChoreRepository, circleRepo *cRepo.CircleRepository,
|
||||||
|
thingRepo *tRepo.ThingRepository, userRepo *uRepo.UserRepository, tRepo *tRepo.ThingRepository) *Webhook {
|
||||||
|
return &Webhook{
|
||||||
|
choreRepo: cr,
|
||||||
|
circleRepo: circleRepo,
|
||||||
|
thingRepo: thingRepo,
|
||||||
|
userRepo: userRepo,
|
||||||
|
tRepo: tRepo,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Webhook) UpdateThingState(c *gin.Context) {
|
||||||
|
thing, shouldReturn := validateUserAndThing(c, h)
|
||||||
|
if shouldReturn {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
state := c.Query("state")
|
||||||
|
if state == "" {
|
||||||
|
c.JSON(400, gin.H{"error": "Invalid state value"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
thing.State = state
|
||||||
|
if !isValidThingState(thing) {
|
||||||
|
c.JSON(400, gin.H{"error": "Invalid state for thing"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.thingRepo.UpdateThingState(c, thing); err != nil {
|
||||||
|
c.JSON(500, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(200, gin.H{})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Webhook) ChangeThingState(c *gin.Context) {
|
||||||
|
thing, shouldReturn := validateUserAndThing(c, h)
|
||||||
|
if shouldReturn {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
addRemoveRaw := c.Query("op")
|
||||||
|
setRaw := c.Query("set")
|
||||||
|
|
||||||
|
if addRemoveRaw == "" && setRaw == "" {
|
||||||
|
c.JSON(400, gin.H{"error": "Invalid increment value"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var xValue int
|
||||||
|
var err error
|
||||||
|
if addRemoveRaw != "" {
|
||||||
|
xValue, err = strconv.Atoi(addRemoveRaw)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(400, gin.H{"error": "Invalid increment value"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
currentState, err := strconv.Atoi(thing.State)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(400, gin.H{"error": "Invalid state for thing"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
newState := currentState + xValue
|
||||||
|
thing.State = strconv.Itoa(newState)
|
||||||
|
}
|
||||||
|
if setRaw != "" {
|
||||||
|
thing.State = setRaw
|
||||||
|
}
|
||||||
|
|
||||||
|
if !isValidThingState(thing) {
|
||||||
|
c.JSON(400, gin.H{"error": "Invalid state for thing"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := h.thingRepo.UpdateThingState(c, thing); err != nil {
|
||||||
|
c.JSON(500, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
shouldReturn1 := WebhookEvaluateTriggerAndScheduleDueDate(h, c, thing)
|
||||||
|
if shouldReturn1 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(200, gin.H{"state": thing.State})
|
||||||
|
}
|
||||||
|
|
||||||
|
func WebhookEvaluateTriggerAndScheduleDueDate(h *Webhook, c *gin.Context, thing *tModel.Thing) bool {
|
||||||
|
// handler should be interface to not duplicate both WebhookEvaluateTriggerAndScheduleDueDate and EvaluateTriggerAndScheduleDueDate
|
||||||
|
// this is bad code written Saturday at 2:25 AM
|
||||||
|
|
||||||
|
log := logging.FromContext(c)
|
||||||
|
|
||||||
|
thingChores, err := h.tRepo.GetThingChoresByThingId(c, thing.ID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{"error": err.Error()})
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
for _, tc := range thingChores {
|
||||||
|
triggered := EvaluateThingChore(tc, thing.State)
|
||||||
|
if triggered {
|
||||||
|
errSave := h.choreRepo.SetDueDate(c, tc.ChoreID, time.Now().UTC())
|
||||||
|
if errSave != nil {
|
||||||
|
log.Error("Error setting due date for chore ", errSave)
|
||||||
|
log.Error("Chore ID ", tc.ChoreID, " Thing ID ", thing.ID, " State ", thing.State)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateUserAndThing(c *gin.Context, h *Webhook) (*tModel.Thing, bool) {
|
||||||
|
apiToken := c.GetHeader("secretkey")
|
||||||
|
if apiToken == "" {
|
||||||
|
c.JSON(401, gin.H{"error": "Unauthorized"})
|
||||||
|
return nil, true
|
||||||
|
}
|
||||||
|
thingID, err := strconv.Atoi(c.Param("id"))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(400, gin.H{"error": err.Error()})
|
||||||
|
return nil, true
|
||||||
|
}
|
||||||
|
user, err := h.userRepo.GetUserByToken(c, apiToken)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(401, gin.H{"error": "Unauthorized"})
|
||||||
|
return nil, true
|
||||||
|
}
|
||||||
|
thing, err := h.thingRepo.GetThingByID(c, thingID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(400, gin.H{"error": "Invalid thing id"})
|
||||||
|
return nil, true
|
||||||
|
}
|
||||||
|
if thing.UserID != user.ID {
|
||||||
|
c.JSON(401, gin.H{"error": "Unauthorized"})
|
||||||
|
return nil, true
|
||||||
|
}
|
||||||
|
return thing, false
|
||||||
|
}
|
||||||
|
|
||||||
|
func Webhooks(cfg *config.Config, w *Webhook, r *gin.Engine, auth *jwt.GinJWTMiddleware) {
|
||||||
|
|
||||||
|
thingsAPI := r.Group("webhooks/things")
|
||||||
|
|
||||||
|
thingsAPI.Use(utils.TimeoutMiddleware(cfg.Server.WriteTimeout))
|
||||||
|
{
|
||||||
|
thingsAPI.GET("/:id/state/change", w.ChangeThingState)
|
||||||
|
thingsAPI.GET("/:id/state", w.UpdateThingState)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,511 @@
|
||||||
|
package user
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"fmt"
|
||||||
|
"html"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
auth "donetick.com/core/internal/authorization"
|
||||||
|
cModel "donetick.com/core/internal/circle/model"
|
||||||
|
cRepo "donetick.com/core/internal/circle/repo"
|
||||||
|
"donetick.com/core/internal/email"
|
||||||
|
uModel "donetick.com/core/internal/user/model"
|
||||||
|
uRepo "donetick.com/core/internal/user/repo"
|
||||||
|
"donetick.com/core/internal/utils"
|
||||||
|
"donetick.com/core/logging"
|
||||||
|
jwt "github.com/appleboy/gin-jwt/v2"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
limiter "github.com/ulule/limiter/v3"
|
||||||
|
"google.golang.org/api/googleapi"
|
||||||
|
"google.golang.org/api/oauth2/v1"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Handler struct {
|
||||||
|
userRepo *uRepo.UserRepository
|
||||||
|
circleRepo *cRepo.CircleRepository
|
||||||
|
jwtAuth *jwt.GinJWTMiddleware
|
||||||
|
email *email.EmailSender
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHandler(ur *uRepo.UserRepository, cr *cRepo.CircleRepository, jwtAuth *jwt.GinJWTMiddleware, email *email.EmailSender) *Handler {
|
||||||
|
return &Handler{
|
||||||
|
userRepo: ur,
|
||||||
|
circleRepo: cr,
|
||||||
|
jwtAuth: jwtAuth,
|
||||||
|
email: email,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) GetAllUsers() gin.HandlerFunc {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
currentUser, ok := auth.CurrentUser(c)
|
||||||
|
if !ok {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting current user",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
users, err := h.userRepo.GetAllUsers(c, currentUser.CircleID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting users",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"res": users,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) signUp(c *gin.Context) {
|
||||||
|
|
||||||
|
type SignUpReq struct {
|
||||||
|
Username string `json:"username" binding:"required,min=4,max=20"`
|
||||||
|
Password string `json:"password" binding:"required,min=8,max=45"`
|
||||||
|
DisplayName string `json:"displayName"`
|
||||||
|
}
|
||||||
|
var signupReq SignUpReq
|
||||||
|
if err := c.BindJSON(&signupReq); err != nil {
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Invalid request",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if signupReq.DisplayName == "" {
|
||||||
|
signupReq.DisplayName = signupReq.Username
|
||||||
|
}
|
||||||
|
password, err := auth.EncodePassword(signupReq.Password)
|
||||||
|
signupReq.Username = html.EscapeString(signupReq.Username)
|
||||||
|
signupReq.DisplayName = html.EscapeString(signupReq.DisplayName)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error encoding password",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var insertedUser *uModel.User
|
||||||
|
if insertedUser, err = h.userRepo.CreateUser(c, &uModel.User{
|
||||||
|
Username: signupReq.Username,
|
||||||
|
Password: password,
|
||||||
|
DisplayName: signupReq.DisplayName,
|
||||||
|
CreatedAt: time.Now(),
|
||||||
|
UpdatedAt: time.Now(),
|
||||||
|
}); err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error creating user",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// var userCircle *circle.Circle
|
||||||
|
// var userRole string
|
||||||
|
userCircle, err := h.circleRepo.CreateCircle(c, &cModel.Circle{
|
||||||
|
Name: signupReq.DisplayName + "'s circle",
|
||||||
|
CreatedAt: time.Now(),
|
||||||
|
UpdatedAt: time.Now(),
|
||||||
|
InviteCode: utils.GenerateInviteCode(c),
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error creating circle",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.circleRepo.AddUserToCircle(c, &cModel.UserCircle{
|
||||||
|
UserID: insertedUser.ID,
|
||||||
|
CircleID: userCircle.ID,
|
||||||
|
Role: "admin",
|
||||||
|
IsActive: true,
|
||||||
|
CreatedAt: time.Now(),
|
||||||
|
UpdatedAt: time.Now(),
|
||||||
|
}); err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error adding user to circle",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
insertedUser.CircleID = userCircle.ID
|
||||||
|
if err := h.userRepo.UpdateUser(c, insertedUser); err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error updating user",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(201, gin.H{})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) GetUserProfile(c *gin.Context) {
|
||||||
|
user, ok := auth.CurrentUser(c)
|
||||||
|
if !ok {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting user",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"res": user,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) thirdPartyAuthCallback(c *gin.Context) {
|
||||||
|
|
||||||
|
// read :provider from path param, if param is google check the token with google if it's valid and fetch the user details:
|
||||||
|
logger := logging.FromContext(c)
|
||||||
|
provider := c.Param("provider")
|
||||||
|
logger.Infow("account.handler.thirdPartyAuthCallback", "provider", provider)
|
||||||
|
|
||||||
|
if provider == "google" {
|
||||||
|
c.Set("auth_provider", "3rdPartyAuth")
|
||||||
|
type OAuthRequest struct {
|
||||||
|
Token string `json:"token" binding:"required"`
|
||||||
|
Provider string `json:"provider" binding:"required"`
|
||||||
|
}
|
||||||
|
var body OAuthRequest
|
||||||
|
if err := c.ShouldBindJSON(&body); err != nil {
|
||||||
|
logger.Errorw("account.handler.thirdPartyAuthCallback failed to bind", "err", err)
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{
|
||||||
|
"error": "Invalid request",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// logger.Infow("account.handler.thirdPartyAuthCallback", "token", token)
|
||||||
|
service, err := oauth2.New(http.DefaultClient)
|
||||||
|
|
||||||
|
// tokenInfo, err := service.Tokeninfo().AccessToken(token).Do()
|
||||||
|
userinfo, err := service.Userinfo.Get().Do(googleapi.QueryParameter("access_token", body.Token))
|
||||||
|
logger.Infow("account.handler.thirdPartyAuthCallback", "tokenInfo", userinfo)
|
||||||
|
if err != nil {
|
||||||
|
logger.Errorw("account.handler.thirdPartyAuthCallback failed to get token info", "err", err)
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{
|
||||||
|
"error": "Invalid token",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
acc, err := h.userRepo.FindByEmail(c, userinfo.Email)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
// create a random password for the user using crypto/rand:
|
||||||
|
password := auth.GenerateRandomPassword(12)
|
||||||
|
encodedPassword, err := auth.EncodePassword(password)
|
||||||
|
acc = &uModel.User{
|
||||||
|
Username: userinfo.Id,
|
||||||
|
Email: userinfo.Email,
|
||||||
|
Image: userinfo.Picture,
|
||||||
|
Password: encodedPassword,
|
||||||
|
DisplayName: userinfo.GivenName,
|
||||||
|
Provider: 2,
|
||||||
|
}
|
||||||
|
createdUser, err := h.userRepo.CreateUser(c, acc)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{
|
||||||
|
"error": "Unable to create user",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
|
||||||
|
}
|
||||||
|
// Create Circle for the user:
|
||||||
|
userCircle, err := h.circleRepo.CreateCircle(c, &cModel.Circle{
|
||||||
|
Name: userinfo.GivenName + "'s circle",
|
||||||
|
CreatedAt: time.Now(),
|
||||||
|
UpdatedAt: time.Now(),
|
||||||
|
InviteCode: utils.GenerateInviteCode(c),
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error creating circle",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.circleRepo.AddUserToCircle(c, &cModel.UserCircle{
|
||||||
|
UserID: createdUser.ID,
|
||||||
|
CircleID: userCircle.ID,
|
||||||
|
Role: "admin",
|
||||||
|
IsActive: true,
|
||||||
|
CreatedAt: time.Now(),
|
||||||
|
UpdatedAt: time.Now(),
|
||||||
|
}); err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error adding user to circle",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
createdUser.CircleID = userCircle.ID
|
||||||
|
if err := h.userRepo.UpdateUser(c, createdUser); err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error updating user",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// use auth to generate a token for the user:
|
||||||
|
c.Set("user_account", acc)
|
||||||
|
h.jwtAuth.Authenticator(c)
|
||||||
|
tokenString, expire, err := h.jwtAuth.TokenGenerator(acc)
|
||||||
|
if err != nil {
|
||||||
|
logger.Errorw("Unable to Generate a Token")
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{
|
||||||
|
"error": "Unable to Generate a Token",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"token": tokenString, "expire": expire})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) resetPassword(c *gin.Context) {
|
||||||
|
log := logging.FromContext(c)
|
||||||
|
type ResetPasswordReq struct {
|
||||||
|
Email string `json:"email" binding:"required,email"`
|
||||||
|
}
|
||||||
|
var req ResetPasswordReq
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{
|
||||||
|
"error": "Invalid request",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
user, err := h.userRepo.FindByEmail(c, req.Email)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{
|
||||||
|
"error": "User not found",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if user.Provider != 0 {
|
||||||
|
// user create account thought login with Gmail. they can reset the password they just need to login with google again
|
||||||
|
c.JSON(
|
||||||
|
http.StatusForbidden,
|
||||||
|
gin.H{
|
||||||
|
"error": "User account created with google login. Please login with google",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// generate a random password:
|
||||||
|
token, err := auth.GenerateEmailResetToken(c)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{
|
||||||
|
"error": "Unable to generate token",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = h.userRepo.SetPasswordResetToken(c, req.Email, token)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{
|
||||||
|
"error": "Unable to generate password",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// send an email to the user with the new password:
|
||||||
|
err = h.email.SendResetPasswordEmail(c, req.Email, token)
|
||||||
|
if err != nil {
|
||||||
|
log.Errorw("account.handler.resetPassword failed to send email", "err", err)
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{
|
||||||
|
"error": "Unable to send email",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// send an email to the user with the new password:
|
||||||
|
c.JSON(http.StatusOK, gin.H{})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) updateUserPassword(c *gin.Context) {
|
||||||
|
logger := logging.FromContext(c)
|
||||||
|
// read the code from query param:
|
||||||
|
code := c.Query("c")
|
||||||
|
email, code, err := email.DecodeEmailAndCode(code)
|
||||||
|
if err != nil {
|
||||||
|
logger.Errorw("account.handler.verify failed to decode email and code", "err", err)
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{
|
||||||
|
"error": "Invalid code",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
|
||||||
|
}
|
||||||
|
// read password from body:
|
||||||
|
type RequestBody struct {
|
||||||
|
Password string `json:"password" binding:"required,min=8,max=32"`
|
||||||
|
}
|
||||||
|
var body RequestBody
|
||||||
|
if err := c.ShouldBindJSON(&body); err != nil {
|
||||||
|
logger.Errorw("user.handler.resetAccountPassword failed to bind", "err", err)
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{
|
||||||
|
"error": "Invalid request",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
|
||||||
|
}
|
||||||
|
password, err := auth.EncodePassword(body.Password)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{
|
||||||
|
"error": "Unable to process password",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = h.userRepo.UpdatePasswordByToken(c.Request.Context(), email, code, password)
|
||||||
|
if err != nil {
|
||||||
|
logger.Errorw("account.handler.resetAccountPassword failed to reset password", "err", err)
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{
|
||||||
|
"error": "Unable to reset password",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{})
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) UpdateUserDetails(c *gin.Context) {
|
||||||
|
type UpdateUserReq struct {
|
||||||
|
DisplayName *string `json:"displayName" binding:"omitempty"`
|
||||||
|
ChatID *int64 `json:"chatID" binding:"omitempty"`
|
||||||
|
Image *string `json:"image" binding:"omitempty"`
|
||||||
|
}
|
||||||
|
user, ok := auth.CurrentUser(c)
|
||||||
|
if !ok {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error getting user",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var req UpdateUserReq
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"error": "Invalid request",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// update non-nil fields:
|
||||||
|
if req.DisplayName != nil {
|
||||||
|
user.DisplayName = *req.DisplayName
|
||||||
|
}
|
||||||
|
if req.ChatID != nil {
|
||||||
|
user.ChatID = *req.ChatID
|
||||||
|
}
|
||||||
|
if req.Image != nil {
|
||||||
|
user.Image = *req.Image
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.userRepo.UpdateUser(c, user); err != nil {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"error": "Error updating user",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(200, user)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) CreateLongLivedToken(c *gin.Context) {
|
||||||
|
currentUser, ok := auth.CurrentUser(c)
|
||||||
|
if !ok {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get current user"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
type TokenRequest struct {
|
||||||
|
Name string `json:"name" binding:"required"`
|
||||||
|
}
|
||||||
|
var req TokenRequest
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 1: Generate a secure random number
|
||||||
|
randomBytes := make([]byte, 16) // 128 bits are enough for strong randomness
|
||||||
|
_, err := rand.Read(randomBytes)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate random part of the token"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
timestamp := time.Now().Unix()
|
||||||
|
hashInput := fmt.Sprintf("%s:%d:%x", currentUser.Username, timestamp, randomBytes)
|
||||||
|
hash := sha256.Sum256([]byte(hashInput))
|
||||||
|
|
||||||
|
token := hex.EncodeToString(hash[:])
|
||||||
|
|
||||||
|
tokenModel, err := h.userRepo.StoreAPIToken(c, currentUser.ID, req.Name, token)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to store the token"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, gin.H{"res": tokenModel})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) GetAllUserToken(c *gin.Context) {
|
||||||
|
currentUser, ok := auth.CurrentUser(c)
|
||||||
|
if !ok {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get current user"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
tokens, err := h.userRepo.GetAllUserTokens(c, currentUser.ID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get user tokens"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, gin.H{"res": tokens})
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) DeleteUserToken(c *gin.Context) {
|
||||||
|
currentUser, ok := auth.CurrentUser(c)
|
||||||
|
if !ok {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get current user"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
tokenID := c.Param("id")
|
||||||
|
|
||||||
|
err := h.userRepo.DeleteAPIToken(c, currentUser.ID, tokenID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete the token"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, gin.H{})
|
||||||
|
}
|
||||||
|
|
||||||
|
func Routes(router *gin.Engine, h *Handler, auth *jwt.GinJWTMiddleware, limiter *limiter.Limiter) {
|
||||||
|
|
||||||
|
userRoutes := router.Group("users")
|
||||||
|
userRoutes.Use(auth.MiddlewareFunc(), utils.RateLimitMiddleware(limiter))
|
||||||
|
{
|
||||||
|
userRoutes.GET("/", h.GetAllUsers())
|
||||||
|
userRoutes.GET("/profile", h.GetUserProfile)
|
||||||
|
userRoutes.PUT("", h.UpdateUserDetails)
|
||||||
|
userRoutes.POST("/tokens", h.CreateLongLivedToken)
|
||||||
|
userRoutes.GET("/tokens", h.GetAllUserToken)
|
||||||
|
userRoutes.DELETE("/tokens/:id", h.DeleteUserToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
authRoutes := router.Group("auth")
|
||||||
|
authRoutes.Use(utils.RateLimitMiddleware(limiter))
|
||||||
|
{
|
||||||
|
authRoutes.POST("/", h.signUp)
|
||||||
|
authRoutes.POST("login", auth.LoginHandler)
|
||||||
|
authRoutes.GET("refresh", auth.RefreshHandler)
|
||||||
|
authRoutes.POST("/:provider/callback", h.thirdPartyAuthCallback)
|
||||||
|
authRoutes.POST("reset", h.resetPassword)
|
||||||
|
authRoutes.POST("password", h.updateUserPassword)
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,38 @@
|
||||||
|
package user
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
type User struct {
|
||||||
|
ID int `json:"id" gorm:"primary_key"` // Unique identifier
|
||||||
|
DisplayName string `json:"displayName" gorm:"column:display_name"` // Display name
|
||||||
|
Username string `json:"username" gorm:"column:username;unique"` // Username (unique)
|
||||||
|
Email string `json:"email" gorm:"column:email;unique"` // Email (unique)
|
||||||
|
Provider int `json:"provider" gorm:"column:provider"` // Provider
|
||||||
|
Password string `json:"-" gorm:"column:password"` // Password
|
||||||
|
CircleID int `json:"circleID" gorm:"column:circle_id"` // Circle ID
|
||||||
|
ChatID int64 `json:"chatID" gorm:"column:chat_id"` // Telegram chat ID
|
||||||
|
Image string `json:"image" gorm:"column:image"` // Image
|
||||||
|
CreatedAt time.Time `json:"created_at" gorm:"column:created_at"` // Created at
|
||||||
|
UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at"` // Updated at
|
||||||
|
Disabled bool `json:"disabled" gorm:"column:disabled"` // Disabled
|
||||||
|
// Email string `json:"email" gorm:"column:email"` // Email
|
||||||
|
CustomerID *string `gorm:"column:customer_id;<-:false"` // read one column
|
||||||
|
Subscription *string `json:"subscription" gorm:"column:subscription;<-:false"` // read one column
|
||||||
|
Expiration *string `json:"expiration" gorm:"column:expiration;<-:false"` // read one column
|
||||||
|
}
|
||||||
|
|
||||||
|
type UserPasswordReset struct {
|
||||||
|
ID int `gorm:"column:id"`
|
||||||
|
UserID int `gorm:"column:user_id"`
|
||||||
|
Email string `gorm:"column:email"`
|
||||||
|
Token string `gorm:"column:token"`
|
||||||
|
ExpirationDate time.Time `gorm:"column:expiration_date"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type APIToken struct {
|
||||||
|
ID int `json:"id" gorm:"primary_key"` // Unique identifier
|
||||||
|
Name string `json:"name" gorm:"column:name;unique"` // Name (unique)
|
||||||
|
UserID int `json:"userId" gorm:"column:user_id;index"` // Index on userID
|
||||||
|
Token string `json:"token" gorm:"column:token;index"` // Index on token
|
||||||
|
CreatedAt time.Time `json:"createdAt" gorm:"column:created_at"`
|
||||||
|
}
|
|
@ -0,0 +1,160 @@
|
||||||
|
package user
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"donetick.com/core/config"
|
||||||
|
uModel "donetick.com/core/internal/user/model"
|
||||||
|
"donetick.com/core/logging"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type IUserRepository interface {
|
||||||
|
GetUserByUsername(username string) (*uModel.User, error)
|
||||||
|
GetUser(id int) (*uModel.User, error)
|
||||||
|
GetAllUsers() ([]*uModel.User, error)
|
||||||
|
CreateUser(user *uModel.User) error
|
||||||
|
UpdateUser(user *uModel.User) error
|
||||||
|
UpdateUserCircle(userID, circleID int) error
|
||||||
|
FindByEmail(email string) (*uModel.User, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type UserRepository struct {
|
||||||
|
db *gorm.DB
|
||||||
|
isDonetickDotCom bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUserRepository(db *gorm.DB, cfg *config.Config) *UserRepository {
|
||||||
|
return &UserRepository{db, cfg.IsDoneTickDotCom}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *UserRepository) GetAllUsers(c context.Context, circleID int) ([]*uModel.User, error) {
|
||||||
|
var users []*uModel.User
|
||||||
|
if err := r.db.WithContext(c).Where("circle_id = ?", circleID).Find(&users).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return users, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *UserRepository) GetAllUsersForSystemOnly(c context.Context) ([]*uModel.User, error) {
|
||||||
|
var users []*uModel.User
|
||||||
|
if err := r.db.WithContext(c).Find(&users).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return users, nil
|
||||||
|
}
|
||||||
|
func (r *UserRepository) CreateUser(c context.Context, user *uModel.User) (*uModel.User, error) {
|
||||||
|
if err := r.db.WithContext(c).Save(user).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return user, nil
|
||||||
|
}
|
||||||
|
func (r *UserRepository) GetUserByUsername(c context.Context, username string) (*uModel.User, error) {
|
||||||
|
var user *uModel.User
|
||||||
|
if r.isDonetickDotCom {
|
||||||
|
if err := r.db.WithContext(c).Table("users u").Select("u.*, ss.status as subscription, ss.expired_at as expiration").Joins("left join stripe_customers sc on sc.user_id = u.id ").Joins("left join stripe_subscriptions ss on sc.customer_id = ss.customer_id").Where("username = ?", username).First(&user).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if err := r.db.WithContext(c).Where("username = ?", username).First(&user).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return user, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *UserRepository) UpdateUser(c context.Context, user *uModel.User) error {
|
||||||
|
return r.db.WithContext(c).Save(user).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *UserRepository) UpdateUserCircle(c context.Context, userID, circleID int) error {
|
||||||
|
return r.db.WithContext(c).Model(&uModel.User{}).Where("id = ?", userID).Update("circle_id", circleID).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *UserRepository) FindByEmail(c context.Context, email string) (*uModel.User, error) {
|
||||||
|
var user *uModel.User
|
||||||
|
if err := r.db.WithContext(c).Where("email = ?", email).First(&user).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return user, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *UserRepository) SetPasswordResetToken(c context.Context, email, token string) error {
|
||||||
|
// confirm user exists with email:
|
||||||
|
user, err := r.FindByEmail(c, email)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
// save new token:
|
||||||
|
if err := r.db.WithContext(c).Model(&uModel.UserPasswordReset{}).Save(&uModel.UserPasswordReset{
|
||||||
|
UserID: user.ID,
|
||||||
|
Token: token,
|
||||||
|
Email: email,
|
||||||
|
ExpirationDate: time.Now().UTC().Add(time.Hour * 24),
|
||||||
|
}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *UserRepository) UpdatePasswordByToken(ctx context.Context, email string, token string, password string) error {
|
||||||
|
logger := logging.FromContext(ctx)
|
||||||
|
|
||||||
|
logger.Debugw("account.db.UpdatePasswordByToken", "email", email)
|
||||||
|
upr := &uModel.UserPasswordReset{
|
||||||
|
Email: email,
|
||||||
|
Token: token,
|
||||||
|
}
|
||||||
|
result := r.db.WithContext(ctx).Where("email = ?", email).Where("token = ?", token).Delete(upr)
|
||||||
|
if result.RowsAffected <= 0 {
|
||||||
|
return fmt.Errorf("invalid token")
|
||||||
|
}
|
||||||
|
// find account by email and update password:
|
||||||
|
chain := r.db.WithContext(ctx).Model(&uModel.User{}).Where("email = ?", email).UpdateColumns(map[string]interface{}{"password": password})
|
||||||
|
if chain.Error != nil {
|
||||||
|
return chain.Error
|
||||||
|
}
|
||||||
|
if chain.RowsAffected == 0 {
|
||||||
|
return fmt.Errorf("account not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *UserRepository) StoreAPIToken(c context.Context, userID int, name string, tokenCode string) (*uModel.APIToken, error) {
|
||||||
|
token := &uModel.APIToken{
|
||||||
|
UserID: userID,
|
||||||
|
Name: name,
|
||||||
|
Token: tokenCode,
|
||||||
|
CreatedAt: time.Now().UTC(),
|
||||||
|
}
|
||||||
|
if err := r.db.WithContext(c).Model(&uModel.APIToken{}).Save(
|
||||||
|
token).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
|
||||||
|
}
|
||||||
|
return token, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *UserRepository) GetUserByToken(c context.Context, token string) (*uModel.User, error) {
|
||||||
|
var user *uModel.User
|
||||||
|
if err := r.db.WithContext(c).Table("users u").Select("u.*").Joins("left join api_tokens at on at.user_id = u.id").Where("at.token = ?", token).First(&user).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return user, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *UserRepository) GetAllUserTokens(c context.Context, userID int) ([]*uModel.APIToken, error) {
|
||||||
|
var tokens []*uModel.APIToken
|
||||||
|
if err := r.db.WithContext(c).Where("user_id = ?", userID).Find(&tokens).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return tokens, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *UserRepository) DeleteAPIToken(c context.Context, userID int, tokenID string) error {
|
||||||
|
return r.db.WithContext(c).Where("id = ? AND user_id = ?", tokenID, userID).Delete(&uModel.APIToken{}).Error
|
||||||
|
}
|
|
@ -0,0 +1,28 @@
|
||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/base64"
|
||||||
|
|
||||||
|
crand "crypto/rand"
|
||||||
|
|
||||||
|
"donetick.com/core/logging"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func GenerateInviteCode(c *gin.Context) string {
|
||||||
|
logger := logging.FromContext(c)
|
||||||
|
// Define the length of the token (in bytes). For example, 32 bytes will result in a 44-character base64-encoded token.
|
||||||
|
tokenLength := 12
|
||||||
|
|
||||||
|
// Generate a random byte slice.
|
||||||
|
tokenBytes := make([]byte, tokenLength)
|
||||||
|
_, err := crand.Read(tokenBytes)
|
||||||
|
if err != nil {
|
||||||
|
logger.Errorw("utility.GenerateEmailResetToken failed to generate random bytes", "err", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Encode the byte slice to a base64 string.
|
||||||
|
token := base64.URLEncoding.EncodeToString(tokenBytes)
|
||||||
|
|
||||||
|
return token
|
||||||
|
}
|
|
@ -0,0 +1,72 @@
|
||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"donetick.com/core/config"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/ulule/limiter/v3"
|
||||||
|
"github.com/ulule/limiter/v3/drivers/store/memory"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
XRequestIdKey = "X-Request-ID" // request id header key
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewRateLimiter(cfg *config.Config) *limiter.Limiter {
|
||||||
|
|
||||||
|
store := memory.NewStore()
|
||||||
|
|
||||||
|
// rate, err := limiter.NewRateFromFormatted("10-H")
|
||||||
|
rate := limiter.Rate{
|
||||||
|
Period: cfg.Server.RatePeriod,
|
||||||
|
Limit: int64(cfg.Server.RateLimit),
|
||||||
|
}
|
||||||
|
|
||||||
|
// Then, create the limiter instance which takes the store and the rate as arguments.
|
||||||
|
// Now, you can give this instance to any supported middleware.
|
||||||
|
return limiter.New(store, rate)
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// wrapper ratelimiter and have it as a middkewatr function:
|
||||||
|
func RateLimitMiddleware(limiter *limiter.Limiter) gin.HandlerFunc {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
// Use the IP as the key, which is the client IP.
|
||||||
|
// And set the expiration time to 10 seconds.
|
||||||
|
context, err := limiter.Get(c.Request.Context(), c.ClientIP())
|
||||||
|
if err != nil {
|
||||||
|
panic(err) // perhaps handle this nicer
|
||||||
|
}
|
||||||
|
// Check if the client is ratelimited.
|
||||||
|
if context.Reached {
|
||||||
|
c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"message": "Too many requests"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Add a header in response to inform the current quota.
|
||||||
|
c.Header("X-RateLimit-Limit", strconv.FormatInt(context.Limit, 10))
|
||||||
|
// Add a header in response to inform the remaining quota.
|
||||||
|
c.Header("X-RateLimit-Remaining", strconv.FormatInt(context.Remaining, 10))
|
||||||
|
// Add a header in response to inform the time to wait before retry.
|
||||||
|
c.Header("X-RateLimit-Reset", strconv.FormatInt(context.Reset, 10))
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TimeoutMiddleware(timeout time.Duration) gin.HandlerFunc {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
ctx, cancel := context.WithTimeout(c.Request.Context(), timeout)
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
if ctx.Err() == context.DeadlineExceeded {
|
||||||
|
c.AbortWithStatus(http.StatusGatewayTimeout)
|
||||||
|
}
|
||||||
|
cancel()
|
||||||
|
}()
|
||||||
|
c.Request = c.Request.WithContext(ctx)
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,95 @@
|
||||||
|
package logging
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"go.uber.org/zap"
|
||||||
|
"go.uber.org/zap/zapcore"
|
||||||
|
)
|
||||||
|
|
||||||
|
type contextKey = string
|
||||||
|
|
||||||
|
const loggerKey = contextKey("logger")
|
||||||
|
|
||||||
|
var (
|
||||||
|
defaultLogger *zap.SugaredLogger
|
||||||
|
defaultLoggerOnce sync.Once
|
||||||
|
)
|
||||||
|
|
||||||
|
var conf = &Config{
|
||||||
|
Encoding: "console",
|
||||||
|
Level: zapcore.InfoLevel,
|
||||||
|
Development: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
Encoding string
|
||||||
|
Level zapcore.Level
|
||||||
|
Development bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetConfig sets given logging configs for DefaultLogger's logger.
|
||||||
|
// Must set configs before calling DefaultLogger()
|
||||||
|
func SetConfig(c *Config) {
|
||||||
|
conf = &Config{
|
||||||
|
Encoding: c.Encoding,
|
||||||
|
Level: c.Level,
|
||||||
|
Development: c.Development,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func SetLevel(l zapcore.Level) {
|
||||||
|
conf.Level = l
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewLogger creates a new logger with the given log level
|
||||||
|
func NewLogger(conf *Config) *zap.SugaredLogger {
|
||||||
|
ec := zap.NewProductionEncoderConfig()
|
||||||
|
ec.EncodeTime = zapcore.ISO8601TimeEncoder
|
||||||
|
cfg := zap.Config{
|
||||||
|
Encoding: conf.Encoding,
|
||||||
|
EncoderConfig: ec,
|
||||||
|
Level: zap.NewAtomicLevelAt(conf.Level),
|
||||||
|
Development: conf.Development,
|
||||||
|
OutputPaths: []string{"stdout"},
|
||||||
|
ErrorOutputPaths: []string{"stderr"},
|
||||||
|
}
|
||||||
|
logger, err := cfg.Build()
|
||||||
|
if err != nil {
|
||||||
|
logger = zap.NewNop()
|
||||||
|
}
|
||||||
|
return logger.Sugar()
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultLogger returns the default logger for the package.
|
||||||
|
func DefaultLogger() *zap.SugaredLogger {
|
||||||
|
defaultLoggerOnce.Do(func() {
|
||||||
|
defaultLogger = NewLogger(conf)
|
||||||
|
})
|
||||||
|
return defaultLogger
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithLogger creates a new context with the provided logger attached.
|
||||||
|
func WithLogger(ctx context.Context, logger *zap.SugaredLogger) context.Context {
|
||||||
|
if gCtx, ok := ctx.(*gin.Context); ok {
|
||||||
|
ctx = gCtx.Request.Context()
|
||||||
|
}
|
||||||
|
return context.WithValue(ctx, loggerKey, logger)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FromContext returns the logger stored in the context. If no such logger
|
||||||
|
// exists, a default logger is returned.
|
||||||
|
func FromContext(ctx context.Context) *zap.SugaredLogger {
|
||||||
|
if ctx == nil {
|
||||||
|
return DefaultLogger()
|
||||||
|
}
|
||||||
|
if gCtx, ok := ctx.(*gin.Context); ok && gCtx != nil {
|
||||||
|
ctx = gCtx.Request.Context()
|
||||||
|
}
|
||||||
|
if logger, ok := ctx.Value(loggerKey).(*zap.SugaredLogger); ok {
|
||||||
|
return logger
|
||||||
|
}
|
||||||
|
return DefaultLogger()
|
||||||
|
}
|
|
@ -0,0 +1,139 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"donetick.com/core/config"
|
||||||
|
"github.com/gin-contrib/cors"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"go.uber.org/fx"
|
||||||
|
"go.uber.org/zap/zapcore"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
auth "donetick.com/core/internal/authorization"
|
||||||
|
"donetick.com/core/internal/chore"
|
||||||
|
chRepo "donetick.com/core/internal/chore/repo"
|
||||||
|
"donetick.com/core/internal/circle"
|
||||||
|
cRepo "donetick.com/core/internal/circle/repo"
|
||||||
|
"donetick.com/core/internal/database"
|
||||||
|
"donetick.com/core/internal/email"
|
||||||
|
notifier "donetick.com/core/internal/notifier"
|
||||||
|
nRepo "donetick.com/core/internal/notifier/repo"
|
||||||
|
nps "donetick.com/core/internal/notifier/service"
|
||||||
|
telegram "donetick.com/core/internal/notifier/telegram"
|
||||||
|
"donetick.com/core/internal/thing"
|
||||||
|
tRepo "donetick.com/core/internal/thing/repo"
|
||||||
|
"donetick.com/core/internal/user"
|
||||||
|
uRepo "donetick.com/core/internal/user/repo"
|
||||||
|
"donetick.com/core/internal/utils"
|
||||||
|
"donetick.com/core/logging"
|
||||||
|
"donetick.com/core/migration"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
logging.SetConfig(&logging.Config{
|
||||||
|
Encoding: "console",
|
||||||
|
Level: zapcore.Level(zapcore.DebugLevel),
|
||||||
|
Development: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
app := fx.New(
|
||||||
|
fx.Supply(config.LoadConfig()),
|
||||||
|
fx.Supply(logging.DefaultLogger().Desugar()),
|
||||||
|
|
||||||
|
// fx.Provide(config.NewConfig),
|
||||||
|
fx.Provide(auth.NewAuthMiddleware),
|
||||||
|
|
||||||
|
// fx.Provide(NewBot),
|
||||||
|
fx.Provide(database.NewDatabase),
|
||||||
|
fx.Provide(chRepo.NewChoreRepository),
|
||||||
|
fx.Provide(chore.NewHandler),
|
||||||
|
fx.Provide(uRepo.NewUserRepository),
|
||||||
|
fx.Provide(user.NewHandler),
|
||||||
|
fx.Provide(cRepo.NewCircleRepository),
|
||||||
|
fx.Provide(circle.NewHandler),
|
||||||
|
|
||||||
|
fx.Provide(nRepo.NewNotificationRepository),
|
||||||
|
fx.Provide(nps.NewNotificationPlanner),
|
||||||
|
|
||||||
|
// add notifier
|
||||||
|
fx.Provide(telegram.NewTelegramNotifier),
|
||||||
|
|
||||||
|
// Rate limiter
|
||||||
|
fx.Provide(utils.NewRateLimiter),
|
||||||
|
|
||||||
|
// add email sender:
|
||||||
|
fx.Provide(email.NewEmailSender),
|
||||||
|
// add handlers also
|
||||||
|
fx.Provide(newServer),
|
||||||
|
fx.Provide(notifier.NewScheduler),
|
||||||
|
|
||||||
|
// things
|
||||||
|
fx.Provide(tRepo.NewThingRepository),
|
||||||
|
|
||||||
|
fx.Provide(thing.NewWebhook),
|
||||||
|
fx.Provide(thing.NewHandler),
|
||||||
|
|
||||||
|
// fx.Invoke(RunApp),
|
||||||
|
fx.Invoke(
|
||||||
|
chore.Routes,
|
||||||
|
user.Routes,
|
||||||
|
circle.Routes,
|
||||||
|
thing.Routes,
|
||||||
|
thing.Webhooks,
|
||||||
|
|
||||||
|
func(r *gin.Engine) {},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
if err := app.Err(); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
app.Run()
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func newServer(lc fx.Lifecycle, cfg *config.Config, db *gorm.DB, notifier *notifier.Scheduler) *gin.Engine {
|
||||||
|
gin.SetMode(gin.DebugMode)
|
||||||
|
// log when http request is made:
|
||||||
|
|
||||||
|
r := gin.New()
|
||||||
|
srv := &http.Server{
|
||||||
|
Addr: fmt.Sprintf(":%d", cfg.Server.Port),
|
||||||
|
Handler: r,
|
||||||
|
ReadTimeout: cfg.Server.ReadTimeout,
|
||||||
|
WriteTimeout: cfg.Server.WriteTimeout,
|
||||||
|
}
|
||||||
|
config := cors.DefaultConfig()
|
||||||
|
config.AllowAllOrigins = true
|
||||||
|
config.AllowCredentials = true
|
||||||
|
config.AddAllowHeaders("Authorization", "secretkey")
|
||||||
|
r.Use(cors.New(config))
|
||||||
|
|
||||||
|
lc.Append(fx.Hook{
|
||||||
|
OnStart: func(context.Context) error {
|
||||||
|
if cfg.Database.Migration {
|
||||||
|
migration.Migration(db)
|
||||||
|
}
|
||||||
|
notifier.Start(context.Background())
|
||||||
|
go func() {
|
||||||
|
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||||
|
log.Fatalf("listen: %s\n", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
OnStop: func(context.Context) error {
|
||||||
|
if err := srv.Shutdown(context.Background()); err != nil {
|
||||||
|
log.Fatalf("Server Shutdown: %s", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
return r
|
||||||
|
}
|
|
@ -0,0 +1,29 @@
|
||||||
|
package migration
|
||||||
|
|
||||||
|
import (
|
||||||
|
chModel "donetick.com/core/internal/chore/model"
|
||||||
|
cModel "donetick.com/core/internal/circle/model"
|
||||||
|
nModel "donetick.com/core/internal/notifier/model"
|
||||||
|
tModel "donetick.com/core/internal/thing/model"
|
||||||
|
uModel "donetick.com/core/internal/user/model"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Migration(db *gorm.DB) error {
|
||||||
|
if err := db.AutoMigrate(uModel.User{}, chModel.Chore{},
|
||||||
|
chModel.ChoreHistory{},
|
||||||
|
cModel.Circle{},
|
||||||
|
cModel.UserCircle{},
|
||||||
|
chModel.ChoreAssignees{},
|
||||||
|
nModel.Notification{},
|
||||||
|
uModel.UserPasswordReset{},
|
||||||
|
tModel.Thing{},
|
||||||
|
tModel.ThingChore{},
|
||||||
|
tModel.ThingHistory{},
|
||||||
|
uModel.APIToken{},
|
||||||
|
); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
Loading…
Reference in New Issue