feat: implement Phase 1 (auth) and Phase 2 (faves CRUD) foundation

Go backend with server-rendered HTML/HTMX frontend, SQLite database,
and filesystem image storage. Self-hostable single-binary architecture.

Phase 1 — Authentication & project foundation:
- Argon2id password hashing with timing-attack prevention
- Session management with cookie-based auth and periodic cleanup
- Login, signup (open/requests/closed modes), logout, forced password reset
- CSRF double-submit cookie pattern with HTMX auto-inclusion
- Proxy-aware real IP extraction (WireGuard/Tailscale support)
- Configurable base path for subdomain and subpath deployment
- Rate limiting on auth endpoints with background cleanup
- Security headers (CSP, X-Frame-Options, Referrer-Policy)
- Structured logging with slog, graceful shutdown
- Pico CSS + HTMX vendored and embedded via go:embed

Phase 2 — Faves CRUD with tags and images:
- Full CRUD for favorites with ownership checks
- Image upload with EXIF stripping, resize to 1920px, UUID filenames
- Tag system with HTMX autocomplete (prefix search, popularity-sorted)
- Privacy controls (public/private per fave, user-configurable default)
- Tag browsing, pagination, batch tag loading (avoids N+1)
- OpenGraph meta tags on public fave detail pages

Includes code quality pass: extracted shared helpers, fixed signup
request persistence bug, plugged rate limiter memory leak, removed
dead code, and logged previously-swallowed errors.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ole-Morten Duesund 2026-03-29 15:55:22 +02:00
commit fc1f7259c5
52 changed files with 5459 additions and 0 deletions

27
.gitignore vendored Normal file
View file

@ -0,0 +1,27 @@
# Build artifacts
/favoritter
/dist/
# Data (database and uploads)
/data/
# Go
*.exe
*.test
*.out
/vendor/
# IDE
.vscode/
.idea/
*.swp
*.swo
*~
# OS
.DS_Store
Thumbs.db
# Environment
.env
*.env.local

661
LICENSE Normal file
View file

@ -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/>.

182
cmd/favoritter/main.go Normal file
View file

@ -0,0 +1,182 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package main
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"kode.naiv.no/olemd/favoritter/internal/config"
"kode.naiv.no/olemd/favoritter/internal/database"
"kode.naiv.no/olemd/favoritter/internal/handler"
"kode.naiv.no/olemd/favoritter/internal/middleware"
"kode.naiv.no/olemd/favoritter/internal/render"
"kode.naiv.no/olemd/favoritter/internal/store"
)
var (
version = "dev"
buildDate = "unknown"
)
func main() {
// Handle -healthcheck flag for container health checks.
if len(os.Args) > 1 && os.Args[1] == "-healthcheck" {
runHealthCheck()
return
}
// Handle -version flag.
if len(os.Args) > 1 && os.Args[1] == "-version" {
fmt.Printf("favoritter %s (built %s)\n", version, buildDate)
return
}
cfg := config.Load()
// Set up structured logging.
logLevel := slog.LevelInfo
if cfg.DevMode {
logLevel = slog.LevelDebug
}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: logLevel}))
slog.SetDefault(logger)
slog.Info("starting favoritter", "version", version, "build_date", buildDate)
// Open database and run migrations.
db, err := database.Open(cfg.DBPath)
if err != nil {
slog.Error("failed to open database", "error", err)
os.Exit(1)
}
defer db.Close()
if err := database.Migrate(db); err != nil {
slog.Error("failed to run migrations", "error", err)
os.Exit(1)
}
// Initialize stores.
users := store.NewUserStore(db)
sessions := store.NewSessionStore(db)
settings := store.NewSettingsStore(db)
faves := store.NewFaveStore(db)
tags := store.NewTagStore(db)
signupRequests := store.NewSignupRequestStore(db)
sessions.SetLifetime(cfg.SessionLifetime)
// Ensure initial admin user exists.
if err := users.EnsureAdmin(cfg.AdminUsername, cfg.AdminPassword); err != nil {
slog.Error("failed to ensure admin user", "error", err)
os.Exit(1)
}
// Initialize template renderer.
renderer, err := render.New(cfg)
if err != nil {
slog.Error("failed to initialize templates", "error", err)
os.Exit(1)
}
// Configure Argon2 parameters from config.
store.Argon2Memory = cfg.Argon2Memory
store.Argon2Time = cfg.Argon2Time
store.Argon2Parallelism = cfg.Argon2Parallelism
// Build the handler with all dependencies.
h := handler.New(handler.Deps{
Config: cfg,
Users: users,
Sessions: sessions,
Settings: settings,
Faves: faves,
Tags: tags,
SignupRequests: signupRequests,
Renderer: renderer,
})
// Build the middleware chain.
mux := h.Routes()
chain := middleware.Chain(
mux,
middleware.Recovery,
middleware.SecurityHeaders,
middleware.BasePath(cfg.BasePath),
middleware.RealIP(cfg.TrustedProxies),
middleware.RequestLogger,
middleware.SessionLoader(sessions, users),
middleware.CSRFProtection(cfg),
)
srv := &http.Server{
Addr: cfg.Listen,
Handler: chain,
ReadTimeout: 15 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 60 * time.Second,
}
// Start background cleanup goroutines.
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go sessions.CleanupLoop(ctx, 1*time.Hour)
go h.RateLimiterCleanupLoop(ctx, 5*time.Minute)
// Start the server in a goroutine.
errCh := make(chan error, 1)
go func() {
slog.Info("listening", "addr", cfg.Listen, "base_path", cfg.BasePath)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
errCh <- err
}
}()
// Wait for interrupt signal or server error.
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
select {
case sig := <-quit:
slog.Info("shutting down", "signal", sig)
case err := <-errCh:
slog.Error("server error", "error", err)
}
// Graceful shutdown with 10-second timeout.
cancel()
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer shutdownCancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
slog.Error("shutdown error", "error", err)
}
slog.Info("stopped")
}
// runHealthCheck performs a health check by hitting the local health endpoint.
// It reads the configured listen address to determine the correct port.
func runHealthCheck() {
cfg := config.Load()
addr := cfg.Listen
// If addr is just ":port", use localhost.
if len(addr) > 0 && addr[0] == ':' {
addr = "127.0.0.1" + addr
}
resp, err := http.Get("http://" + addr + cfg.BasePath + "/health")
if err != nil {
os.Exit(1)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
os.Exit(1)
}
}

20
go.mod Normal file
View file

@ -0,0 +1,20 @@
module kode.naiv.no/olemd/favoritter
go 1.26.1
require (
github.com/google/uuid v1.6.0
golang.org/x/crypto v0.49.0
modernc.org/sqlite v1.48.0
)
require (
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
golang.org/x/sys v0.42.0 // indirect
modernc.org/libc v1.70.0 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect
)

53
go.sum Normal file
View file

@ -0,0 +1,53 @@
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
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/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
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/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=
golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
modernc.org/cc/v4 v4.27.1 h1:9W30zRlYrefrDV2JE2O8VDtJ1yPGownxciz5rrbQZis=
modernc.org/cc/v4 v4.27.1/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
modernc.org/ccgo/v4 v4.32.0 h1:hjG66bI/kqIPX1b2yT6fr/jt+QedtP2fqojG2VrFuVw=
modernc.org/ccgo/v4 v4.32.0/go.mod h1:6F08EBCx5uQc38kMGl+0Nm0oWczoo1c7cgpzEry7Uc0=
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/gc/v3 v3.1.2 h1:ZtDCnhonXSZexk/AYsegNRV1lJGgaNZJuKjJSWKyEqo=
modernc.org/gc/v3 v3.1.2/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
modernc.org/libc v1.70.0 h1:U58NawXqXbgpZ/dcdS9kMshu08aiA6b7gusEusqzNkw=
modernc.org/libc v1.70.0/go.mod h1:OVmxFGP1CI/Z4L3E0Q3Mf1PDE0BucwMkcXjjLntvHJo=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/sqlite v1.48.0 h1:ElZyLop3Q2mHYk5IFPPXADejZrlHu7APbpB0sF78bq4=
modernc.org/sqlite v1.48.0/go.mod h1:hWjRO6Tj/5Ik8ieqxQybiEOUXy0NJFNp2tpvVpKlvig=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=

205
internal/config/config.go Normal file
View file

@ -0,0 +1,205 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// Package config loads application configuration from environment variables.
package config
import (
"log/slog"
"net"
"net/url"
"os"
"strconv"
"strings"
"time"
)
// Config holds all application configuration.
type Config struct {
// Database
DBPath string
// Server
Listen string
BasePath string
ExternalURL string
TrustedProxies []*net.IPNet
// Uploads
UploadDir string
MaxUploadSize int64
// Security
SessionLifetime time.Duration
Argon2Memory uint32
Argon2Time uint32
Argon2Parallelism uint8
RateLimit int
// Admin
AdminUsername string
AdminPassword string
// Site
SiteName string
DevMode bool
}
// Load reads configuration from environment variables with sensible defaults.
func Load() *Config {
cfg := &Config{
DBPath: envOr("FAVORITTER_DB_PATH", "./data/favoritter.db"),
Listen: envOr("FAVORITTER_LISTEN", ":8080"),
BasePath: envOr("FAVORITTER_BASE_PATH", "/"),
ExternalURL: os.Getenv("FAVORITTER_EXTERNAL_URL"),
UploadDir: envOr("FAVORITTER_UPLOAD_DIR", "./data/uploads"),
MaxUploadSize: envInt64("FAVORITTER_MAX_UPLOAD_SIZE", 10<<20), // 10MB
SessionLifetime: envDuration("FAVORITTER_SESSION_LIFETIME", 720*time.Hour),
Argon2Memory: uint32(envInt("FAVORITTER_ARGON2_MEMORY", 65536)),
Argon2Time: uint32(envInt("FAVORITTER_ARGON2_TIME", 3)),
Argon2Parallelism: uint8(envInt("FAVORITTER_ARGON2_PARALLELISM", 2)),
RateLimit: envInt("FAVORITTER_RATE_LIMIT", 60),
AdminUsername: os.Getenv("FAVORITTER_ADMIN_USERNAME"),
AdminPassword: os.Getenv("FAVORITTER_ADMIN_PASSWORD"),
SiteName: envOr("FAVORITTER_SITE_NAME", "Favoritter"),
DevMode: envBool("FAVORITTER_DEV_MODE", false),
}
// Normalize base path: ensure it starts with / and doesn't end with /.
cfg.BasePath = normalizePath(cfg.BasePath)
// Normalize external URL: strip trailing slash.
cfg.ExternalURL = strings.TrimRight(cfg.ExternalURL, "/")
// Parse trusted proxies.
cfg.TrustedProxies = parseCIDRs(envOr("FAVORITTER_TRUSTED_PROXIES", "127.0.0.1"))
return cfg
}
// BaseURL returns the external base URL for generating absolute URLs.
// If EXTERNAL_URL is set, it's used directly. Otherwise, falls back to
// constructing from the request (caller should pass the Host header).
func (c *Config) BaseURL(requestHost string) string {
if c.ExternalURL != "" {
return c.ExternalURL
}
// Fallback: construct from request host.
// Assume HTTPS unless we know otherwise.
return "https://" + requestHost + c.BasePath
}
// IsExternalURLConfigured returns true if an explicit external URL was set.
func (c *Config) IsExternalURLConfigured() bool {
return c.ExternalURL != ""
}
// ExternalHostname returns the hostname from the external URL, or empty string.
func (c *Config) ExternalHostname() string {
if c.ExternalURL == "" {
return ""
}
u, err := url.Parse(c.ExternalURL)
if err != nil {
return ""
}
return u.Hostname()
}
func normalizePath(p string) string {
if p == "" || p == "/" {
return ""
}
if !strings.HasPrefix(p, "/") {
p = "/" + p
}
return strings.TrimRight(p, "/")
}
func parseCIDRs(s string) []*net.IPNet {
var nets []*net.IPNet
for _, part := range strings.Split(s, ",") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
// If no CIDR notation, add /32 for IPv4 or /128 for IPv6.
if !strings.Contains(part, "/") {
ip := net.ParseIP(part)
if ip == nil {
slog.Warn("invalid trusted proxy IP, skipping", "ip", part)
continue
}
if ip.To4() != nil {
part += "/32"
} else {
part += "/128"
}
}
_, ipNet, err := net.ParseCIDR(part)
if err != nil {
slog.Warn("invalid trusted proxy CIDR, skipping", "cidr", part, "error", err)
continue
}
nets = append(nets, ipNet)
}
return nets
}
func envOr(key, fallback string) string {
if v := os.Getenv(key); v != "" {
return v
}
return fallback
}
func envInt(key string, fallback int) int {
v := os.Getenv(key)
if v == "" {
return fallback
}
n, err := strconv.Atoi(v)
if err != nil {
slog.Warn("invalid integer env var, using default", "key", key, "value", v, "default", fallback)
return fallback
}
return n
}
func envInt64(key string, fallback int64) int64 {
v := os.Getenv(key)
if v == "" {
return fallback
}
n, err := strconv.ParseInt(v, 10, 64)
if err != nil {
slog.Warn("invalid int64 env var, using default", "key", key, "value", v, "default", fallback)
return fallback
}
return n
}
func envDuration(key string, fallback time.Duration) time.Duration {
v := os.Getenv(key)
if v == "" {
return fallback
}
d, err := time.ParseDuration(v)
if err != nil {
slog.Warn("invalid duration env var, using default", "key", key, "value", v, "default", fallback)
return fallback
}
return d
}
func envBool(key string, fallback bool) bool {
v := os.Getenv(key)
if v == "" {
return fallback
}
b, err := strconv.ParseBool(v)
if err != nil {
slog.Warn("invalid bool env var, using default", "key", key, "value", v, "default", fallback)
return fallback
}
return b
}

View file

@ -0,0 +1,129 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// Package database manages the SQLite connection, PRAGMAs, and schema migrations.
package database
import (
"database/sql"
"embed"
"fmt"
"log/slog"
"os"
"path/filepath"
"sort"
"strings"
_ "modernc.org/sqlite"
)
//go:embed migrations/*.sql
var migrationsFS embed.FS
// Open creates a new SQLite database connection with recommended PRAGMAs
// for WAL mode, foreign keys, and performance tuning.
func Open(dbPath string) (*sql.DB, error) {
// Ensure the directory for the database file exists.
dir := filepath.Dir(dbPath)
if err := os.MkdirAll(dir, 0750); err != nil {
return nil, fmt.Errorf("create db directory: %w", err)
}
db, err := sql.Open("sqlite", dbPath)
if err != nil {
return nil, fmt.Errorf("open sqlite: %w", err)
}
// Apply recommended PRAGMAs. These must be set per-connection, and since
// database/sql may open multiple connections, we use ConnInitHook via DSN
// parameters where possible. However, journal_mode persists at the db level.
pragmas := []string{
"PRAGMA journal_mode = WAL",
"PRAGMA busy_timeout = 5000",
"PRAGMA synchronous = NORMAL",
"PRAGMA foreign_keys = ON",
"PRAGMA cache_size = -20000",
}
for _, p := range pragmas {
if _, err := db.Exec(p); err != nil {
db.Close()
return nil, fmt.Errorf("set pragma %q: %w", p, err)
}
}
// SQLite works best with a single writer connection.
db.SetMaxOpenConns(1)
slog.Info("database opened", "path", dbPath)
return db, nil
}
// Migrate runs all pending SQL migrations in order. Migrations are embedded
// SQL files named with a numeric prefix (e.g. 001_initial.sql). Each migration
// runs within a transaction.
func Migrate(db *sql.DB) error {
// Create the migrations tracking table if it doesn't exist.
_, err := db.Exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT PRIMARY KEY,
applied_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
)`)
if err != nil {
return fmt.Errorf("create schema_migrations table: %w", err)
}
// Read all migration files.
entries, err := migrationsFS.ReadDir("migrations")
if err != nil {
return fmt.Errorf("read migrations dir: %w", err)
}
// Sort by filename to ensure correct order.
sort.Slice(entries, func(i, j int) bool {
return entries[i].Name() < entries[j].Name()
})
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") {
continue
}
name := entry.Name()
// Check if this migration has already been applied.
var count int
if err := db.QueryRow("SELECT COUNT(*) FROM schema_migrations WHERE version = ?", name).Scan(&count); err != nil {
return fmt.Errorf("check migration %s: %w", name, err)
}
if count > 0 {
continue
}
// Read and execute the migration in a transaction.
content, err := migrationsFS.ReadFile("migrations/" + name)
if err != nil {
return fmt.Errorf("read migration %s: %w", name, err)
}
tx, err := db.Begin()
if err != nil {
return fmt.Errorf("begin tx for %s: %w", name, err)
}
if _, err := tx.Exec(string(content)); err != nil {
tx.Rollback()
return fmt.Errorf("execute migration %s: %w", name, err)
}
if _, err := tx.Exec("INSERT INTO schema_migrations (version) VALUES (?)", name); err != nil {
tx.Rollback()
return fmt.Errorf("record migration %s: %w", name, err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit migration %s: %w", name, err)
}
slog.Info("applied migration", "version", name)
}
return nil
}

View file

@ -0,0 +1,72 @@
-- Initial schema for Favoritter.
-- Creates core tables: users, sessions, signup_requests, faves, tags, fave_tags, site_settings.
CREATE TABLE users (
id INTEGER PRIMARY KEY,
username TEXT NOT NULL UNIQUE COLLATE NOCASE,
display_name TEXT NOT NULL DEFAULT '',
bio TEXT NOT NULL DEFAULT '',
avatar_path TEXT NOT NULL DEFAULT '',
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user' CHECK (role IN ('user', 'admin')),
profile_visibility TEXT NOT NULL DEFAULT 'public' CHECK (profile_visibility IN ('public', 'limited')),
default_fave_privacy TEXT NOT NULL DEFAULT 'public' CHECK (default_fave_privacy IN ('public', 'private')),
must_reset_password INTEGER NOT NULL DEFAULT 0,
disabled INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
);
CREATE TABLE sessions (
token TEXT PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
expires_at TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
);
CREATE INDEX idx_sessions_user_id ON sessions(user_id);
CREATE INDEX idx_sessions_expires ON sessions(expires_at);
CREATE TABLE signup_requests (
id INTEGER PRIMARY KEY,
username TEXT NOT NULL UNIQUE COLLATE NOCASE,
password_hash TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected')),
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
reviewed_at TEXT,
reviewed_by INTEGER REFERENCES users(id)
);
CREATE TABLE faves (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
description TEXT NOT NULL,
url TEXT NOT NULL DEFAULT '',
image_path TEXT NOT NULL DEFAULT '',
privacy TEXT NOT NULL DEFAULT 'public' CHECK (privacy IN ('public', 'private')),
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
);
CREATE INDEX idx_faves_user_id ON faves(user_id);
CREATE INDEX idx_faves_privacy ON faves(privacy);
CREATE INDEX idx_faves_created ON faves(created_at);
CREATE TABLE tags (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE COLLATE NOCASE
);
CREATE TABLE fave_tags (
fave_id INTEGER NOT NULL REFERENCES faves(id) ON DELETE CASCADE,
tag_id INTEGER NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
PRIMARY KEY (fave_id, tag_id)
);
CREATE INDEX idx_fave_tags_tag_id ON fave_tags(tag_id);
CREATE TABLE site_settings (
id INTEGER PRIMARY KEY CHECK (id = 1),
site_name TEXT NOT NULL DEFAULT 'Favoritter',
site_description TEXT NOT NULL DEFAULT '',
signup_mode TEXT NOT NULL DEFAULT 'open' CHECK (signup_mode IN ('open', 'requests', 'closed')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
);
INSERT INTO site_settings (id) VALUES (1);

299
internal/handler/auth.go Normal file
View file

@ -0,0 +1,299 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package handler
import (
"errors"
"log/slog"
"net/http"
"regexp"
"strings"
"kode.naiv.no/olemd/favoritter/internal/middleware"
"kode.naiv.no/olemd/favoritter/internal/render"
"kode.naiv.no/olemd/favoritter/internal/store"
)
var usernameRegexp = regexp.MustCompile(`^[a-zA-Z0-9_-]{2,30}$`)
func (h *Handler) handleLoginGet(w http.ResponseWriter, r *http.Request) {
// If already logged in, redirect to home.
if middleware.UserFromContext(r.Context()) != nil {
http.Redirect(w, r, h.deps.Config.BasePath+"/", http.StatusSeeOther)
return
}
h.deps.Renderer.Page(w, r, "login", render.PageData{
Title: "Logg inn",
})
}
func (h *Handler) handleLoginPost(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
h.flash(w, r, "login", "Ugyldig forespørsel.", "error", nil)
return
}
username := strings.TrimSpace(r.FormValue("username"))
password := r.FormValue("password")
user, err := h.deps.Users.Authenticate(username, password)
if err != nil {
if errors.Is(err, store.ErrInvalidCredentials) || errors.Is(err, store.ErrUserDisabled) {
h.flash(w, r, "login", "Feil brukernavn eller passord.", "error", nil)
return
}
slog.Error("login authentication error", "error", err)
h.flash(w, r, "login", "Noe gikk galt. Prøv igjen.", "error", nil)
return
}
token, err := h.deps.Sessions.Create(user.ID)
if err != nil {
slog.Error("session create error", "error", err)
h.flash(w, r, "login", "Noe gikk galt. Prøv igjen.", "error", nil)
return
}
h.setSessionCookie(w, r, token)
// If user must reset password, redirect there.
if user.MustResetPassword {
http.Redirect(w, r, h.deps.Config.BasePath+"/reset-password", http.StatusSeeOther)
return
}
http.Redirect(w, r, h.deps.Config.BasePath+"/", http.StatusSeeOther)
}
func (h *Handler) handleSignupGet(w http.ResponseWriter, r *http.Request) {
if middleware.UserFromContext(r.Context()) != nil {
http.Redirect(w, r, h.deps.Config.BasePath+"/", http.StatusSeeOther)
return
}
settings, err := h.deps.Settings.Get()
if err != nil {
slog.Error("get settings error", "error", err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
h.deps.Renderer.Page(w, r, "signup", render.PageData{
Title: "Registrer",
Data: map[string]string{"Mode": settings.SignupMode},
})
}
func (h *Handler) handleSignupPost(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
h.flash(w, r, "signup", "Ugyldig forespørsel.", "error", signupData("open"))
return
}
settings, err := h.deps.Settings.Get()
if err != nil {
slog.Error("get settings error", "error", err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
if settings.SignupClosed() {
h.flash(w, r, "signup", "Registrering er stengt.", "error", signupData("closed"))
return
}
username := strings.TrimSpace(r.FormValue("username"))
password := r.FormValue("password")
passwordConfirm := r.FormValue("password_confirm")
// Validate input.
if !usernameRegexp.MatchString(username) {
h.flash(w, r, "signup", "Ugyldig brukernavn. Bruk 2-30 tegn: bokstaver, tall, bindestrek, understrek.", "error", signupData(settings.SignupMode))
return
}
if len(password) < 8 {
h.flash(w, r, "signup", "Passordet må være minst 8 tegn.", "error", signupData(settings.SignupMode))
return
}
if password != passwordConfirm {
h.flash(w, r, "signup", "Passordene er ikke like.", "error", signupData(settings.SignupMode))
return
}
if settings.SignupRequests() {
// Create a signup request for admin approval.
err := h.createSignupRequest(username, password)
if err != nil {
if errors.Is(err, store.ErrUserExists) {
h.flash(w, r, "signup", "Brukernavnet er allerede i bruk.", "error", signupData(settings.SignupMode))
return
}
slog.Error("signup request error", "error", err)
h.flash(w, r, "signup", "Noe gikk galt. Prøv igjen.", "error", signupData(settings.SignupMode))
return
}
h.flash(w, r, "login", "Forespørselen din er sendt. En administrator vil gjennomgå den.", "info", nil)
return
}
// Open signup — create user directly.
user, err := h.deps.Users.Create(username, password, "user")
if err != nil {
if errors.Is(err, store.ErrUserExists) {
h.flash(w, r, "signup", "Brukernavnet er allerede i bruk.", "error", signupData(settings.SignupMode))
return
}
slog.Error("user create error", "error", err)
h.flash(w, r, "signup", "Noe gikk galt. Prøv igjen.", "error", signupData(settings.SignupMode))
return
}
// Auto-login after signup.
token, err := h.deps.Sessions.Create(user.ID)
if err != nil {
slog.Error("session create error", "error", err)
http.Redirect(w, r, h.deps.Config.BasePath+"/login", http.StatusSeeOther)
return
}
h.setSessionCookie(w, r, token)
http.Redirect(w, r, h.deps.Config.BasePath+"/", http.StatusSeeOther)
}
func (h *Handler) handleLogout(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie(middleware.SessionCookieName)
if err == nil {
if delErr := h.deps.Sessions.Delete(cookie.Value); delErr != nil {
slog.Error("session delete error", "error", delErr)
}
}
middleware.ClearSessionCookie(w)
http.Redirect(w, r, h.deps.Config.BasePath+"/login", http.StatusSeeOther)
}
func (h *Handler) handleResetPasswordGet(w http.ResponseWriter, r *http.Request) {
user := middleware.UserFromContext(r.Context())
if user == nil {
http.Redirect(w, r, h.deps.Config.BasePath+"/login", http.StatusSeeOther)
return
}
if !user.MustResetPassword {
http.Redirect(w, r, h.deps.Config.BasePath+"/", http.StatusSeeOther)
return
}
h.deps.Renderer.Page(w, r, "reset_password", render.PageData{
Title: "Endre passord",
})
}
func (h *Handler) handleResetPasswordPost(w http.ResponseWriter, r *http.Request) {
user := middleware.UserFromContext(r.Context())
if user == nil {
http.Redirect(w, r, h.deps.Config.BasePath+"/login", http.StatusSeeOther)
return
}
if err := r.ParseForm(); err != nil {
h.flash(w, r, "reset_password", "Ugyldig forespørsel.", "error", nil)
return
}
password := r.FormValue("password")
passwordConfirm := r.FormValue("password_confirm")
if len(password) < 8 {
h.flash(w, r, "reset_password", "Passordet må være minst 8 tegn.", "error", nil)
return
}
if password != passwordConfirm {
h.flash(w, r, "reset_password", "Passordene er ikke like.", "error", nil)
return
}
if err := h.deps.Users.UpdatePassword(user.ID, password); err != nil {
slog.Error("update password error", "error", err)
h.flash(w, r, "reset_password", "Noe gikk galt. Prøv igjen.", "error", nil)
return
}
if delErr := h.deps.Sessions.DeleteAllForUser(user.ID); delErr != nil {
slog.Error("session cleanup error", "error", delErr)
}
// Create a fresh session.
token, err := h.deps.Sessions.Create(user.ID)
if err != nil {
slog.Error("session create error", "error", err)
http.Redirect(w, r, h.deps.Config.BasePath+"/login", http.StatusSeeOther)
return
}
h.setSessionCookie(w, r, token)
http.Redirect(w, r, h.deps.Config.BasePath+"/", http.StatusSeeOther)
}
func (h *Handler) handleHome(w http.ResponseWriter, r *http.Request) {
h.deps.Renderer.Page(w, r, "home", render.PageData{})
}
func (h *Handler) handleHealth(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"status":"ok"}`))
}
// setSessionCookie sets the session cookie with appropriate flags for
// both local and remote proxy deployments.
func (h *Handler) setSessionCookie(w http.ResponseWriter, r *http.Request, token string) {
cookie := &http.Cookie{
Name: "session",
Value: token,
Path: "/",
MaxAge: int(h.deps.Config.SessionLifetime.Seconds()),
HttpOnly: true,
Secure: middleware.IsSecureRequest(r, h.deps.Config),
SameSite: http.SameSiteLaxMode,
}
// Set domain from external URL if configured.
if hostname := h.deps.Config.ExternalHostname(); hostname != "" {
cookie.Domain = hostname
}
http.SetCookie(w, cookie)
}
// flash renders a page with a flash message.
func (h *Handler) flash(w http.ResponseWriter, r *http.Request, page, message, flashType string, data any) {
h.deps.Renderer.Page(w, r, page, render.PageData{
Flash: message,
FlashType: flashType,
Data: data,
})
}
func signupData(mode string) map[string]string {
return map[string]string{"Mode": mode}
}
func (h *Handler) createSignupRequest(username, password string) error {
// Check if username is already taken by an existing user.
_, err := h.deps.Users.GetByUsername(username)
if err == nil {
return store.ErrUserExists
}
err = h.deps.SignupRequests.Create(username, password)
if errors.Is(err, store.ErrSignupRequestExists) {
return store.ErrUserExists
}
return err
}

416
internal/handler/fave.go Normal file
View file

@ -0,0 +1,416 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package handler
import (
"errors"
"log/slog"
"net/http"
"strconv"
"strings"
"kode.naiv.no/olemd/favoritter/internal/image"
"kode.naiv.no/olemd/favoritter/internal/middleware"
"kode.naiv.no/olemd/favoritter/internal/render"
"kode.naiv.no/olemd/favoritter/internal/store"
)
const defaultPageSize = 24
// handleFaveList shows the current user's faves.
func (h *Handler) handleFaveList(w http.ResponseWriter, r *http.Request) {
user := middleware.UserFromContext(r.Context())
page := queryInt(r, "page", 1)
offset := (page - 1) * defaultPageSize
faves, total, err := h.deps.Faves.ListByUser(user.ID, defaultPageSize, offset)
if err != nil {
slog.Error("list faves error", "error", err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
// Load tags for each fave.
if err := h.deps.Faves.LoadTags(faves); err != nil {
slog.Error("load tags error", "error", err)
}
totalPages := (total + defaultPageSize - 1) / defaultPageSize
h.deps.Renderer.Page(w, r, "fave_list", render.PageData{
Title: "Mine favoritter",
Data: map[string]any{
"Faves": faves,
"Page": page,
"TotalPages": totalPages,
"Total": total,
},
})
}
// handleFaveNew shows the form for creating a new fave.
func (h *Handler) handleFaveNew(w http.ResponseWriter, r *http.Request) {
user := middleware.UserFromContext(r.Context())
h.deps.Renderer.Page(w, r, "fave_form", render.PageData{
Title: "Ny favoritt",
Data: map[string]any{
"IsNew": true,
"DefaultPrivacy": user.DefaultFavePrivacy,
},
})
}
// handleFaveCreate processes the form for creating a new fave.
func (h *Handler) handleFaveCreate(w http.ResponseWriter, r *http.Request) {
user := middleware.UserFromContext(r.Context())
if err := r.ParseMultipartForm(h.deps.Config.MaxUploadSize); err != nil {
h.flash(w, r, "fave_form", "Filen er for stor.", "error", map[string]any{"IsNew": true})
return
}
description := strings.TrimSpace(r.FormValue("description"))
url := strings.TrimSpace(r.FormValue("url"))
privacy := r.FormValue("privacy")
tagStr := r.FormValue("tags")
if description == "" {
h.flash(w, r, "fave_form", "Beskrivelse er påkrevd.", "error", map[string]any{
"IsNew": true, "Description": description, "URL": url, "Tags": tagStr, "Privacy": privacy,
})
return
}
if privacy != "public" && privacy != "private" {
privacy = user.DefaultFavePrivacy
}
// Handle image upload.
var imagePath string
file, header, err := r.FormFile("image")
if err == nil {
defer file.Close()
result, err := image.Process(file, header, h.deps.Config.UploadDir)
if err != nil {
slog.Error("image process error", "error", err)
h.flash(w, r, "fave_form", "Kunne ikke behandle bildet. Sjekk at filen er et gyldig bilde (JPEG, PNG, GIF eller WebP).", "error", map[string]any{
"IsNew": true, "Description": description, "URL": url, "Tags": tagStr, "Privacy": privacy,
})
return
}
imagePath = result.Filename
}
// Create the fave.
fave, err := h.deps.Faves.Create(user.ID, description, url, imagePath, privacy)
if err != nil {
slog.Error("create fave error", "error", err)
h.flash(w, r, "fave_form", "Noe gikk galt. Prøv igjen.", "error", map[string]any{"IsNew": true})
return
}
// Set tags.
if tagStr != "" {
tags := parseTags(tagStr)
if err := h.deps.Tags.SetFaveTags(fave.ID, tags); err != nil {
slog.Error("set tags error", "error", err)
}
}
http.Redirect(w, r, h.deps.Config.BasePath+"/faves/"+strconv.FormatInt(fave.ID, 10), http.StatusSeeOther)
}
// handleFaveDetail shows a single fave.
func (h *Handler) handleFaveDetail(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
fave, err := h.deps.Faves.GetByID(id)
if err != nil {
if errors.Is(err, store.ErrFaveNotFound) {
http.NotFound(w, r)
return
}
slog.Error("get fave error", "error", err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
// Check access: private faves are only visible to their owner.
user := middleware.UserFromContext(r.Context())
if fave.Privacy == "private" && (user == nil || user.ID != fave.UserID) {
http.NotFound(w, r)
return
}
// Load tags.
tags, err := h.deps.Tags.ForFave(fave.ID)
if err != nil {
slog.Error("load tags error", "error", err)
}
fave.Tags = tags
h.deps.Renderer.Page(w, r, "fave_detail", render.PageData{
Title: fave.Description,
Data: map[string]any{
"Fave": fave,
"IsOwner": user != nil && user.ID == fave.UserID,
},
})
}
// handleFaveEdit shows the edit form for a fave.
func (h *Handler) handleFaveEdit(w http.ResponseWriter, r *http.Request) {
user := middleware.UserFromContext(r.Context())
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
fave, err := h.deps.Faves.GetByID(id)
if err != nil {
if errors.Is(err, store.ErrFaveNotFound) {
http.NotFound(w, r)
return
}
slog.Error("get fave error", "error", err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
// Only the owner can edit.
if user.ID != fave.UserID {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
tags, _ := h.deps.Tags.ForFave(fave.ID)
fave.Tags = tags
tagNames := make([]string, len(tags))
for i, t := range tags {
tagNames[i] = t.Name
}
h.deps.Renderer.Page(w, r, "fave_form", render.PageData{
Title: "Rediger favoritt",
Data: map[string]any{
"IsNew": false,
"Fave": fave,
"Description": fave.Description,
"URL": fave.URL,
"Privacy": fave.Privacy,
"Tags": strings.Join(tagNames, ", "),
},
})
}
// handleFaveUpdate processes the edit form.
func (h *Handler) handleFaveUpdate(w http.ResponseWriter, r *http.Request) {
user := middleware.UserFromContext(r.Context())
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
fave, err := h.deps.Faves.GetByID(id)
if err != nil {
if errors.Is(err, store.ErrFaveNotFound) {
http.NotFound(w, r)
return
}
slog.Error("get fave error", "error", err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
if user.ID != fave.UserID {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
if err := r.ParseMultipartForm(h.deps.Config.MaxUploadSize); err != nil {
h.flash(w, r, "fave_form", "Filen er for stor.", "error", map[string]any{"IsNew": false, "Fave": fave})
return
}
description := strings.TrimSpace(r.FormValue("description"))
url := strings.TrimSpace(r.FormValue("url"))
privacy := r.FormValue("privacy")
tagStr := r.FormValue("tags")
if description == "" {
h.flash(w, r, "fave_form", "Beskrivelse er påkrevd.", "error", map[string]any{"IsNew": false, "Fave": fave})
return
}
if privacy != "public" && privacy != "private" {
privacy = fave.Privacy
}
// Handle image upload (optional on edit).
imagePath := fave.ImagePath
file, header, err := r.FormFile("image")
if err == nil {
defer file.Close()
result, err := image.Process(file, header, h.deps.Config.UploadDir)
if err != nil {
slog.Error("image process error", "error", err)
h.flash(w, r, "fave_form", "Kunne ikke behandle bildet. Sjekk at filen er et gyldig bilde (JPEG, PNG, GIF eller WebP).", "error", map[string]any{"IsNew": false, "Fave": fave})
return
}
if fave.ImagePath != "" {
if delErr := image.Delete(h.deps.Config.UploadDir, fave.ImagePath); delErr != nil {
slog.Error("image delete error", "error", delErr)
}
}
imagePath = result.Filename
}
// Check if user wants to remove the existing image.
if r.FormValue("remove_image") == "1" && imagePath != "" {
if delErr := image.Delete(h.deps.Config.UploadDir, imagePath); delErr != nil {
slog.Error("image delete error", "error", delErr)
}
imagePath = ""
}
if err := h.deps.Faves.Update(id, description, url, imagePath, privacy); err != nil {
slog.Error("update fave error", "error", err)
h.flash(w, r, "fave_form", "Noe gikk galt. Prøv igjen.", "error", map[string]any{"IsNew": false, "Fave": fave})
return
}
// Update tags.
tags := parseTags(tagStr)
if err := h.deps.Tags.SetFaveTags(id, tags); err != nil {
slog.Error("set tags error", "error", err)
}
http.Redirect(w, r, h.deps.Config.BasePath+"/faves/"+strconv.FormatInt(id, 10), http.StatusSeeOther)
}
// handleFaveDelete deletes a fave.
func (h *Handler) handleFaveDelete(w http.ResponseWriter, r *http.Request) {
user := middleware.UserFromContext(r.Context())
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
fave, err := h.deps.Faves.GetByID(id)
if err != nil {
if errors.Is(err, store.ErrFaveNotFound) {
http.NotFound(w, r)
return
}
slog.Error("get fave error", "error", err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
if user.ID != fave.UserID {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
if fave.ImagePath != "" {
if delErr := image.Delete(h.deps.Config.UploadDir, fave.ImagePath); delErr != nil {
slog.Error("image delete error", "error", delErr)
}
}
if err := h.deps.Faves.Delete(id); err != nil {
slog.Error("delete fave error", "error", err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
// If this was an HTMX request, return empty (the element is removed).
if r.Header.Get("HX-Request") == "true" {
w.WriteHeader(http.StatusOK)
return
}
http.Redirect(w, r, h.deps.Config.BasePath+"/faves", http.StatusSeeOther)
}
// handleTagSearch handles tag autocomplete HTMX requests.
func (h *Handler) handleTagSearch(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query().Get("q")
tags, err := h.deps.Tags.Search(q, 10)
if err != nil {
slog.Error("tag search error", "error", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := h.deps.Renderer.Partial(w, "tag_suggestions", tags); err != nil {
slog.Error("render tag suggestions error", "error", err)
}
}
// handleTagBrowse shows all public faves with a given tag.
func (h *Handler) handleTagBrowse(w http.ResponseWriter, r *http.Request) {
tagName := r.PathValue("name")
page := queryInt(r, "page", 1)
offset := (page - 1) * defaultPageSize
faves, total, err := h.deps.Faves.ListByTag(tagName, defaultPageSize, offset)
if err != nil {
slog.Error("list by tag error", "error", err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
if err := h.deps.Faves.LoadTags(faves); err != nil {
slog.Error("load tags error", "error", err)
}
totalPages := (total + defaultPageSize - 1) / defaultPageSize
h.deps.Renderer.Page(w, r, "tag_browse", render.PageData{
Title: "Merkelapp: " + tagName,
Data: map[string]any{
"TagName": tagName,
"Faves": faves,
"Page": page,
"TotalPages": totalPages,
"Total": total,
},
})
}
// parseTags splits a comma-separated tag string into individual tag names.
func parseTags(s string) []string {
parts := strings.Split(s, ",")
var tags []string
for _, p := range parts {
p = strings.TrimSpace(p)
if p != "" {
tags = append(tags, p)
}
}
return tags
}
// queryInt parses an integer query parameter with a default.
func queryInt(r *http.Request, key string, fallback int) int {
v := r.URL.Query().Get(key)
n, err := strconv.Atoi(v)
if err != nil || n < 1 {
return fallback
}
return n
}

107
internal/handler/handler.go Normal file
View file

@ -0,0 +1,107 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// Package handler contains HTTP handlers for all web and API routes.
package handler
import (
"context"
"io/fs"
"net/http"
"time"
"kode.naiv.no/olemd/favoritter/internal/config"
"kode.naiv.no/olemd/favoritter/internal/middleware"
"kode.naiv.no/olemd/favoritter/internal/render"
"kode.naiv.no/olemd/favoritter/internal/store"
"kode.naiv.no/olemd/favoritter/web"
)
// Deps bundles all dependencies injected into handlers.
type Deps struct {
Config *config.Config
Users *store.UserStore
Sessions *store.SessionStore
Settings *store.SettingsStore
Faves *store.FaveStore
Tags *store.TagStore
SignupRequests *store.SignupRequestStore
Renderer *render.Renderer
}
// Handler holds all HTTP handler methods and their dependencies.
type Handler struct {
deps Deps
rateLimiter *middleware.RateLimiter
}
// New creates a new Handler with the given dependencies.
func New(deps Deps) *Handler {
return &Handler{
deps: deps,
rateLimiter: middleware.NewRateLimiter(deps.Config.RateLimit),
}
}
// RateLimiterCleanupLoop periodically evicts stale rate limiter entries.
func (h *Handler) RateLimiterCleanupLoop(ctx context.Context, interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
h.rateLimiter.Cleanup()
}
}
}
// Routes registers all routes on a new ServeMux and returns it.
func (h *Handler) Routes() *http.ServeMux {
mux := http.NewServeMux()
// Static files (served from embedded filesystem).
staticFS, err := fs.Sub(web.StaticFS, "static")
if err != nil {
panic("embedded static filesystem missing: " + err.Error())
}
mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.FS(staticFS))))
// Uploaded images (served from the filesystem upload directory).
mux.Handle("GET /uploads/", http.StripPrefix("/uploads/",
http.FileServer(http.Dir(h.deps.Config.UploadDir))))
// Health check.
mux.HandleFunc("GET /health", h.handleHealth)
// Auth routes (rate-limited).
mux.Handle("POST /login", h.rateLimiter.Limit(http.HandlerFunc(h.handleLoginPost)))
mux.Handle("POST /signup", h.rateLimiter.Limit(http.HandlerFunc(h.handleSignupPost)))
mux.HandleFunc("GET /login", h.handleLoginGet)
mux.HandleFunc("GET /signup", h.handleSignupGet)
mux.HandleFunc("POST /logout", h.handleLogout)
// Password reset (for must-reset-password flow).
mux.HandleFunc("GET /reset-password", h.handleResetPasswordGet)
mux.HandleFunc("POST /reset-password", h.handleResetPasswordPost)
// Home page.
mux.HandleFunc("GET /{$}", h.handleHome)
// Faves — authenticated routes use requireLogin wrapper.
requireLogin := middleware.RequireLogin(h.deps.Config.BasePath)
mux.Handle("GET /faves", requireLogin(http.HandlerFunc(h.handleFaveList)))
mux.Handle("GET /faves/new", requireLogin(http.HandlerFunc(h.handleFaveNew)))
mux.Handle("POST /faves", requireLogin(http.HandlerFunc(h.handleFaveCreate)))
mux.HandleFunc("GET /faves/{id}", h.handleFaveDetail)
mux.Handle("GET /faves/{id}/edit", requireLogin(http.HandlerFunc(h.handleFaveEdit)))
mux.Handle("POST /faves/{id}", requireLogin(http.HandlerFunc(h.handleFaveUpdate)))
mux.Handle("DELETE /faves/{id}", requireLogin(http.HandlerFunc(h.handleFaveDelete)))
// Tags.
mux.HandleFunc("GET /tags/search", h.handleTagSearch)
mux.HandleFunc("GET /tags/{name}", h.handleTagBrowse)
return mux
}

154
internal/image/image.go Normal file
View file

@ -0,0 +1,154 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// Package image handles uploaded image validation, processing, and storage.
// It strips EXIF metadata by re-encoding images and resizes to a maximum width.
package image
import (
"fmt"
"image"
"image/jpeg"
"image/png"
"io"
"mime/multipart"
"os"
"path/filepath"
"strings"
"github.com/google/uuid"
// Register image format decoders.
_ "image/gif"
)
const (
MaxWidth = 1920
JPEGQuality = 85
)
// AllowedTypes maps MIME types to file extensions.
var AllowedTypes = map[string]string{
"image/jpeg": ".jpg",
"image/png": ".png",
"image/gif": ".gif",
"image/webp": ".webp",
}
// ProcessResult holds the result of processing an uploaded image.
type ProcessResult struct {
Filename string // UUID-based filename with extension
Path string // Full path where the image was saved
}
// Process validates, re-encodes (stripping EXIF), and optionally resizes an
// uploaded image. It saves the result to uploadDir with a UUID filename.
//
// Re-encoding to JPEG or PNG strips all EXIF metadata including GPS coordinates,
// which is important for user privacy.
func Process(file multipart.File, header *multipart.FileHeader, uploadDir string) (*ProcessResult, error) {
// Validate content type.
contentType := header.Header.Get("Content-Type")
ext, ok := AllowedTypes[contentType]
if !ok {
return nil, fmt.Errorf("unsupported image type: %s (allowed: JPEG, PNG, GIF, WebP)", contentType)
}
// Decode the image — this also validates it's a real image.
img, format, err := image.Decode(file)
if err != nil {
return nil, fmt.Errorf("invalid image: %w", err)
}
// Resize if wider than MaxWidth, maintaining aspect ratio.
img = resizeIfNeeded(img)
// Generate UUID filename.
filename := uuid.New().String() + ext
// Ensure upload directory exists.
if err := os.MkdirAll(uploadDir, 0750); err != nil {
return nil, fmt.Errorf("create upload dir: %w", err)
}
fullPath := filepath.Join(uploadDir, filename)
outFile, err := os.Create(fullPath)
if err != nil {
return nil, fmt.Errorf("create output file: %w", err)
}
defer outFile.Close()
// Re-encode the image, which strips all EXIF metadata.
if err := encode(outFile, img, format, ext); err != nil {
os.Remove(fullPath)
return nil, fmt.Errorf("encode image: %w", err)
}
return &ProcessResult{
Filename: filename,
Path: fullPath,
}, nil
}
// Delete removes an uploaded image file.
func Delete(uploadDir, filename string) error {
if filename == "" {
return nil
}
path := filepath.Join(uploadDir, filename)
// Only delete if the file is actually inside the upload directory
// to prevent path traversal.
absPath, err := filepath.Abs(path)
if err != nil {
return err
}
absDir, err := filepath.Abs(uploadDir)
if err != nil {
return err
}
if !strings.HasPrefix(absPath, absDir+string(filepath.Separator)) {
return fmt.Errorf("path traversal detected")
}
return os.Remove(absPath)
}
// encode writes the image in the appropriate format.
// GIF and WebP are re-encoded as PNG since Go's stdlib can decode but not
// encode GIF animations or WebP. This is acceptable — we prioritize EXIF
// stripping over format preservation.
func encode(w io.Writer, img image.Image, format, ext string) error {
switch {
case format == "jpeg" || ext == ".jpg":
return jpeg.Encode(w, img, &jpeg.Options{Quality: JPEGQuality})
default:
// PNG for everything else (png, gif, webp).
return png.Encode(w, img)
}
}
// resizeIfNeeded scales the image down if it exceeds MaxWidth.
// Uses nearest-neighbor for simplicity — good enough for a favorites app.
func resizeIfNeeded(img image.Image) image.Image {
bounds := img.Bounds()
w := bounds.Dx()
h := bounds.Dy()
if w <= MaxWidth {
return img
}
newW := MaxWidth
newH := h * MaxWidth / w
dst := image.NewRGBA(image.Rect(0, 0, newW, newH))
// Simple bilinear-ish downscale by sampling.
for y := 0; y < newH; y++ {
for x := 0; x < newW; x++ {
srcX := x * w / newW
srcY := y * h / newH
dst.Set(x, y, img.At(srcX+bounds.Min.X, srcY+bounds.Min.Y))
}
}
return dst
}

View file

@ -0,0 +1,58 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package middleware
import (
"context"
"errors"
"net/http"
"kode.naiv.no/olemd/favoritter/internal/store"
)
const SessionCookieName = "session"
// ClearSessionCookie sets an expired session cookie to remove it from the client.
func ClearSessionCookie(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{
Name: SessionCookieName,
Value: "",
Path: "/",
MaxAge: -1,
HttpOnly: true,
})
}
// SessionLoader loads the user from the session cookie on every request.
// If the session is valid, the user is attached to the request context.
func SessionLoader(sessions *store.SessionStore, users *store.UserStore) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie(SessionCookieName)
if err != nil {
next.ServeHTTP(w, r)
return
}
session, err := sessions.Validate(cookie.Value)
if err != nil {
if errors.Is(err, store.ErrSessionNotFound) {
ClearSessionCookie(w)
}
next.ServeHTTP(w, r)
return
}
user, err := users.GetByID(session.UserID)
if err != nil || user.Disabled {
sessions.Delete(cookie.Value)
ClearSessionCookie(w)
next.ServeHTTP(w, r)
return
}
ctx := context.WithValue(r.Context(), userKey, user)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}

View file

@ -0,0 +1,36 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package middleware
import (
"net/http"
"strings"
)
// BasePath strips a configured path prefix from incoming requests so the
// router sees paths without the prefix. This enables deployment at both
// faves.example.com (basePath="") and example.com/faves (basePath="/faves").
func BasePath(prefix string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
if prefix == "" {
return next
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Strip the prefix from the URL path.
if strings.HasPrefix(r.URL.Path, prefix) {
r.URL.Path = strings.TrimPrefix(r.URL.Path, prefix)
if r.URL.Path == "" {
r.URL.Path = "/"
}
// Also update RawPath if present.
if r.URL.RawPath != "" {
r.URL.RawPath = strings.TrimPrefix(r.URL.RawPath, prefix)
if r.URL.RawPath == "" {
r.URL.RawPath = "/"
}
}
}
next.ServeHTTP(w, r)
})
}
}

View file

@ -0,0 +1,61 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package middleware
import (
"context"
"net/http"
"kode.naiv.no/olemd/favoritter/internal/model"
)
type contextKey string
const (
userKey contextKey = "user"
csrfTokenKey contextKey = "csrf_token"
realIPKey contextKey = "real_ip"
)
// UserFromContext returns the authenticated user from the request context, or nil.
func UserFromContext(ctx context.Context) *model.User {
u, _ := ctx.Value(userKey).(*model.User)
return u
}
// CSRFTokenFromContext returns the CSRF token from the request context.
func CSRFTokenFromContext(ctx context.Context) string {
s, _ := ctx.Value(csrfTokenKey).(string)
return s
}
// RealIPFromContext returns the real client IP from the request context.
func RealIPFromContext(ctx context.Context) string {
s, _ := ctx.Value(realIPKey).(string)
return s
}
// RequireLogin redirects to the login page if no user is authenticated.
func RequireLogin(basePath string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if UserFromContext(r.Context()) == nil {
http.Redirect(w, r, basePath+"/login", http.StatusSeeOther)
return
}
next.ServeHTTP(w, r)
})
}
}
// RequireAdmin returns 403 if the user is not an admin.
func RequireAdmin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := UserFromContext(r.Context())
if user == nil || !user.IsAdmin() {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}

View file

@ -0,0 +1,93 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package middleware
import (
"context"
"crypto/rand"
"encoding/hex"
"net/http"
"strings"
"kode.naiv.no/olemd/favoritter/internal/config"
)
const (
csrfCookieName = "csrf_token"
csrfFormField = "csrf_token"
csrfHeaderName = "X-CSRF-Token"
)
// CSRFProtection implements double-submit cookie pattern for CSRF prevention.
// A token is stored in a cookie and must also be submitted in a form field
// or header on state-changing requests (POST, PUT, DELETE, PATCH).
func CSRFProtection(cfg *config.Config) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Read or generate the CSRF token.
token := ""
if cookie, err := r.Cookie(csrfCookieName); err == nil {
token = cookie.Value
}
if token == "" {
token = generateCSRFToken()
secure := IsSecureRequest(r, cfg)
http.SetCookie(w, &http.Cookie{
Name: csrfCookieName,
Value: token,
Path: "/",
HttpOnly: false, // JS needs to read it for HTMX hx-headers
Secure: secure,
SameSite: http.SameSiteLaxMode,
})
}
// Attach token to context for templates.
ctx := context.WithValue(r.Context(), csrfTokenKey, token)
r = r.WithContext(ctx)
// Validate on state-changing methods.
if isStateChangingMethod(r.Method) {
// Skip CSRF check for API routes that use Bearer auth (future).
if !strings.HasPrefix(r.URL.Path, "/api/") {
submitted := r.FormValue(csrfFormField)
if submitted == "" {
submitted = r.Header.Get(csrfHeaderName)
}
if submitted != token {
http.Error(w, "CSRF token mismatch", http.StatusForbidden)
return
}
}
}
next.ServeHTTP(w, r)
})
}
}
func isStateChangingMethod(method string) bool {
switch method {
case http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodPatch:
return true
}
return false
}
func generateCSRFToken() string {
b := make([]byte, 32)
rand.Read(b)
return hex.EncodeToString(b)
}
// IsSecureRequest determines if the original client request used HTTPS,
// checking X-Forwarded-Proto from trusted proxies.
func IsSecureRequest(r *http.Request, cfg *config.Config) bool {
if cfg.ExternalURL != "" {
return strings.HasPrefix(cfg.ExternalURL, "https://")
}
if proto := r.Header.Get("X-Forwarded-Proto"); proto != "" {
return proto == "https"
}
return r.TLS != nil
}

View file

@ -0,0 +1,38 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package middleware
import (
"log/slog"
"net/http"
"time"
)
// responseWriter wraps http.ResponseWriter to capture the status code.
type responseWriter struct {
http.ResponseWriter
statusCode int
}
func (rw *responseWriter) WriteHeader(code int) {
rw.statusCode = code
rw.ResponseWriter.WriteHeader(code)
}
// RequestLogger logs each HTTP request with method, path, status, and duration.
func RequestLogger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rw := &responseWriter{ResponseWriter: w, statusCode: http.StatusOK}
next.ServeHTTP(rw, r)
slog.Debug("request",
"method", r.Method,
"path", r.URL.Path,
"status", rw.statusCode,
"duration", time.Since(start),
"ip", RealIPFromContext(r.Context()),
)
})
}

View file

@ -0,0 +1,15 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// Package middleware provides HTTP middleware for auth, security, and request processing.
package middleware
import "net/http"
// Chain wraps a handler with a stack of middleware, applied in order
// (the last middleware listed is the outermost wrapper).
func Chain(h http.Handler, middlewares ...func(http.Handler) http.Handler) http.Handler {
for _, m := range middlewares {
h = m(h)
}
return h
}

View file

@ -0,0 +1,89 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package middleware
import (
"net/http"
"sync"
"time"
)
// RateLimiter implements a simple per-IP token bucket rate limiter for
// protecting auth endpoints from brute-force attacks.
type RateLimiter struct {
mu sync.Mutex
visitors map[string]*bucket
rate int
window time.Duration
}
type bucket struct {
tokens int
lastReset time.Time
}
// NewRateLimiter creates a rate limiter that allows `rate` requests per minute per IP.
func NewRateLimiter(rate int) *RateLimiter {
return &RateLimiter{
visitors: make(map[string]*bucket),
rate: rate,
window: time.Minute,
}
}
// Limit wraps a handler with rate limiting based on the real client IP.
func (rl *RateLimiter) Limit(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip := RealIPFromContext(r.Context())
if ip == "" {
ip = r.RemoteAddr
}
if !rl.allow(ip) {
http.Error(w, "Too many requests. Please try again later.", http.StatusTooManyRequests)
return
}
next.ServeHTTP(w, r)
})
}
func (rl *RateLimiter) allow(ip string) bool {
rl.mu.Lock()
defer rl.mu.Unlock()
now := time.Now()
b, ok := rl.visitors[ip]
if !ok {
rl.visitors[ip] = &bucket{tokens: rl.rate - 1, lastReset: now}
return true
}
// Reset tokens if the window has passed.
if now.Sub(b.lastReset) >= rl.window {
b.tokens = rl.rate - 1
b.lastReset = now
return true
}
if b.tokens <= 0 {
return false
}
b.tokens--
return true
}
// Cleanup removes stale entries. Call periodically from a goroutine.
func (rl *RateLimiter) Cleanup() {
rl.mu.Lock()
defer rl.mu.Unlock()
now := time.Now()
for ip, b := range rl.visitors {
if now.Sub(b.lastReset) >= 2*rl.window {
delete(rl.visitors, ip)
}
}
}

View file

@ -0,0 +1,68 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package middleware
import (
"context"
"net"
"net/http"
"strings"
)
// RealIP extracts the real client IP from X-Forwarded-For, but only if the
// direct connection comes from a trusted proxy. This is essential when Caddy
// runs on a different machine (e.g. connected via WireGuard/Tailscale).
func RealIP(trustedProxies []*net.IPNet) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip := extractRealIP(r, trustedProxies)
ctx := context.WithValue(r.Context(), realIPKey, ip)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
func extractRealIP(r *http.Request, trusted []*net.IPNet) string {
// Get the direct connection IP.
directIP, _, _ := net.SplitHostPort(r.RemoteAddr)
if directIP == "" {
directIP = r.RemoteAddr
}
// Only trust X-Forwarded-For if the direct connection is from a trusted proxy.
if !isTrusted(directIP, trusted) {
return directIP
}
// Parse X-Forwarded-For: client, proxy1, proxy2
// The rightmost non-trusted IP is the real client.
xff := r.Header.Get("X-Forwarded-For")
if xff == "" {
return directIP
}
ips := strings.Split(xff, ",")
// Walk from right to left, finding the first non-trusted IP.
for i := len(ips) - 1; i >= 0; i-- {
ip := strings.TrimSpace(ips[i])
if !isTrusted(ip, trusted) {
return ip
}
}
// All IPs in the chain are trusted; use the leftmost.
return strings.TrimSpace(ips[0])
}
func isTrusted(ipStr string, nets []*net.IPNet) bool {
ip := net.ParseIP(ipStr)
if ip == nil {
return false
}
for _, n := range nets {
if n.Contains(ip) {
return true
}
}
return false
}

View file

@ -0,0 +1,27 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package middleware
import (
"log/slog"
"net/http"
"runtime/debug"
)
// Recovery catches panics in HTTP handlers and returns a 500 error
// instead of crashing the server.
func Recovery(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
slog.Error("panic recovered",
"error", err,
"path", r.URL.Path,
"stack", string(debug.Stack()),
)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}

View file

@ -0,0 +1,24 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package middleware
import "net/http"
// SecurityHeaders adds security-related HTTP headers to every response.
func SecurityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
h.Set("X-Content-Type-Options", "nosniff")
h.Set("X-Frame-Options", "DENY")
h.Set("Referrer-Policy", "strict-origin-when-cross-origin")
h.Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
// CSP allows inline styles from Pico CSS and scripts from self only.
// The 'unsafe-inline' for style-src is needed for Pico CSS.
h.Set("Content-Security-Policy",
"default-src 'self'; "+
"style-src 'self' 'unsafe-inline'; "+
"img-src 'self' data:; "+
"frame-ancestors 'none'")
next.ServeHTTP(w, r)
})
}

26
internal/model/fave.go Normal file
View file

@ -0,0 +1,26 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package model
import "time"
type Fave struct {
ID int64
UserID int64
Description string
URL string
ImagePath string
Privacy string
Tags []Tag
CreatedAt time.Time
UpdatedAt time.Time
// Joined fields for display.
Username string
DisplayName string
}
// IsPublic returns true if the fave is publicly visible.
func (f *Fave) IsPublic() bool {
return f.Privacy == "public"
}

12
internal/model/session.go Normal file
View file

@ -0,0 +1,12 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package model
import "time"
type Session struct {
Token string
UserID int64
ExpiresAt time.Time
CreatedAt time.Time
}

View file

@ -0,0 +1,27 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package model
import "time"
type SiteSettings struct {
SiteName string
SiteDescription string
SignupMode string
UpdatedAt time.Time
}
// SignupOpen returns true if self-registration is allowed.
func (s *SiteSettings) SignupOpen() bool {
return s.SignupMode == "open"
}
// SignupRequests returns true if signup requires admin approval.
func (s *SiteSettings) SignupRequests() bool {
return s.SignupMode == "requests"
}
// SignupClosed returns true if no new signups are allowed.
func (s *SiteSettings) SignupClosed() bool {
return s.SignupMode == "closed"
}

8
internal/model/tag.go Normal file
View file

@ -0,0 +1,8 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package model
type Tag struct {
ID int64
Name string
}

34
internal/model/user.go Normal file
View file

@ -0,0 +1,34 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package model
import "time"
type User struct {
ID int64
Username string
DisplayName string
Bio string
AvatarPath string
PasswordHash string
Role string
ProfileVisibility string
DefaultFavePrivacy string
MustResetPassword bool
Disabled bool
CreatedAt time.Time
UpdatedAt time.Time
}
// IsAdmin returns true if the user has the admin role.
func (u *User) IsAdmin() bool {
return u.Role == "admin"
}
// DisplayNameOrUsername returns the display name if set, otherwise the username.
func (u *User) DisplayNameOrUsername() string {
if u.DisplayName != "" {
return u.DisplayName
}
return u.Username
}

193
internal/render/render.go Normal file
View file

@ -0,0 +1,193 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// Package render provides HTML template rendering with layout support.
package render
import (
"fmt"
"html/template"
"io"
"io/fs"
"log/slog"
"net/http"
"os"
"path/filepath"
"strings"
"kode.naiv.no/olemd/favoritter/internal/config"
"kode.naiv.no/olemd/favoritter/internal/middleware"
"kode.naiv.no/olemd/favoritter/internal/model"
"kode.naiv.no/olemd/favoritter/internal/store"
"kode.naiv.no/olemd/favoritter/web"
)
// Renderer parses and executes HTML templates.
type Renderer struct {
templates map[string]*template.Template
cfg *config.Config
}
// PageData holds data passed to page templates.
type PageData struct {
Title string
User *model.User
CSRFToken string
BasePath string
SiteName string
Flash string
FlashType string // "success", "error", "info"
ExternalURL string
Data any
}
// New creates a Renderer, parsing all templates from the embedded filesystem.
func New(cfg *config.Config) (*Renderer, error) {
r := &Renderer{
cfg: cfg,
}
if err := r.parseTemplates(); err != nil {
return nil, err
}
return r, nil
}
func (r *Renderer) parseTemplates() error {
r.templates = make(map[string]*template.Template)
var templateFS fs.FS
if r.cfg.DevMode {
// In dev mode, read templates from disk for live reload.
templateFS = os.DirFS(filepath.Join("web", "templates"))
} else {
sub, err := fs.Sub(web.TemplatesFS, "templates")
if err != nil {
return fmt.Errorf("sub templates fs: %w", err)
}
templateFS = sub
}
funcMap := r.templateFuncs()
// Parse the base layout.
baseLayout, err := template.New("base.html").Funcs(funcMap).ParseFS(templateFS, "layouts/base.html")
if err != nil {
return fmt.Errorf("parse base layout: %w", err)
}
// Parse each page template with the base layout.
pages, err := fs.Glob(templateFS, "pages/*.html")
if err != nil {
return fmt.Errorf("glob pages: %w", err)
}
for _, page := range pages {
name := strings.TrimPrefix(page, "pages/")
name = strings.TrimSuffix(name, ".html")
t, err := baseLayout.Clone()
if err != nil {
return fmt.Errorf("clone base for %s: %w", name, err)
}
_, err = t.ParseFS(templateFS, page)
if err != nil {
return fmt.Errorf("parse page %s: %w", name, err)
}
r.templates[name] = t
}
// Parse partial templates (for HTMX responses).
partials, err := fs.Glob(templateFS, "partials/*.html")
if err != nil {
return fmt.Errorf("glob partials: %w", err)
}
for _, partial := range partials {
name := "partial:" + strings.TrimPrefix(partial, "partials/")
name = strings.TrimSuffix(name, ".html")
t, err := template.New(filepath.Base(partial)).Funcs(funcMap).ParseFS(templateFS, partial)
if err != nil {
return fmt.Errorf("parse partial %s: %w", name, err)
}
r.templates[name] = t
}
slog.Info("templates loaded", "pages", len(pages), "partials", len(partials))
return nil
}
// Page renders a full page with the base layout.
func (r *Renderer) Page(w http.ResponseWriter, req *http.Request, name string, data PageData) {
if r.cfg.DevMode {
// Reparse templates on every request in dev mode.
if err := r.parseTemplates(); err != nil {
slog.Error("template reparse failed", "error", err)
http.Error(w, "Template error", http.StatusInternalServerError)
return
}
}
// Populate common data from context.
data.User = middleware.UserFromContext(req.Context())
data.CSRFToken = middleware.CSRFTokenFromContext(req.Context())
data.BasePath = r.cfg.BasePath
data.SiteName = r.cfg.SiteName
data.ExternalURL = r.cfg.ExternalURL
t, ok := r.templates[name]
if !ok {
slog.Error("template not found", "name", name)
http.Error(w, "Template not found", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := t.ExecuteTemplate(w, "base.html", data); err != nil {
slog.Error("template execute failed", "name", name, "error", err)
}
}
// Partial renders a partial template (for HTMX responses).
func (r *Renderer) Partial(w io.Writer, name string, data any) error {
key := "partial:" + name
t, ok := r.templates[key]
if !ok {
return fmt.Errorf("partial template %q not found", name)
}
return t.Execute(w, data)
}
func (r *Renderer) templateFuncs() template.FuncMap {
return template.FuncMap{
// basePath returns the configured base path for URL construction.
"basePath": func() string {
return r.cfg.BasePath
},
// externalURL returns the configured external URL.
"externalURL": func() string {
return r.cfg.ExternalURL
},
// truncate truncates a string to n characters.
"truncate": func(n int, s string) string {
if len(s) <= n {
return s
}
return s[:n] + "..."
},
// join joins strings with a separator.
"join": strings.Join,
// contains checks if a string contains a substring.
"contains": strings.Contains,
// add returns a + b.
"add": func(a, b int) int { return a + b },
// subtract returns a - b.
"subtract": func(a, b int) int { return a - b },
// maxTags returns the maximum number of tags per fave.
"maxTags": func() int { return store.MaxTagsPerFave },
}
}

276
internal/store/fave.go Normal file
View file

@ -0,0 +1,276 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package store
import (
"database/sql"
"errors"
"fmt"
"strings"
"time"
"kode.naiv.no/olemd/favoritter/internal/model"
)
var ErrFaveNotFound = errors.New("fave not found")
type FaveStore struct {
db *sql.DB
}
func NewFaveStore(db *sql.DB) *FaveStore {
return &FaveStore{db: db}
}
// Create inserts a new fave and returns it with its ID populated.
func (s *FaveStore) Create(userID int64, description, url, imagePath, privacy string) (*model.Fave, error) {
result, err := s.db.Exec(
`INSERT INTO faves (user_id, description, url, image_path, privacy)
VALUES (?, ?, ?, ?, ?)`,
userID, description, url, imagePath, privacy,
)
if err != nil {
return nil, fmt.Errorf("insert fave: %w", err)
}
id, _ := result.LastInsertId()
return s.GetByID(id)
}
// GetByID returns a fave by its ID, including joined user info.
func (s *FaveStore) GetByID(id int64) (*model.Fave, error) {
f := &model.Fave{}
var createdAt, updatedAt string
err := s.db.QueryRow(
`SELECT f.id, f.user_id, f.description, f.url, f.image_path, f.privacy,
f.created_at, f.updated_at, u.username, u.display_name
FROM faves f
JOIN users u ON u.id = f.user_id
WHERE f.id = ?`, id,
).Scan(
&f.ID, &f.UserID, &f.Description, &f.URL, &f.ImagePath, &f.Privacy,
&createdAt, &updatedAt, &f.Username, &f.DisplayName,
)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrFaveNotFound
}
if err != nil {
return nil, fmt.Errorf("query fave: %w", err)
}
f.CreatedAt, _ = time.Parse(time.RFC3339, createdAt)
f.UpdatedAt, _ = time.Parse(time.RFC3339, updatedAt)
return f, nil
}
// Update modifies an existing fave's fields.
func (s *FaveStore) Update(id int64, description, url, imagePath, privacy string) error {
_, err := s.db.Exec(
`UPDATE faves SET description = ?, url = ?, image_path = ?, privacy = ?,
updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')
WHERE id = ?`,
description, url, imagePath, privacy, id,
)
return err
}
// Delete removes a fave by its ID. The cascade will clean up fave_tags.
func (s *FaveStore) Delete(id int64) error {
result, err := s.db.Exec("DELETE FROM faves WHERE id = ?", id)
if err != nil {
return err
}
n, _ := result.RowsAffected()
if n == 0 {
return ErrFaveNotFound
}
return nil
}
// ListByUser returns all faves for a user (both public and private),
// ordered by newest first, with pagination.
func (s *FaveStore) ListByUser(userID int64, limit, offset int) ([]*model.Fave, int, error) {
var total int
err := s.db.QueryRow("SELECT COUNT(*) FROM faves WHERE user_id = ?", userID).Scan(&total)
if err != nil {
return nil, 0, err
}
rows, err := s.db.Query(
`SELECT f.id, f.user_id, f.description, f.url, f.image_path, f.privacy,
f.created_at, f.updated_at, u.username, u.display_name
FROM faves f
JOIN users u ON u.id = f.user_id
WHERE f.user_id = ?
ORDER BY f.created_at DESC
LIMIT ? OFFSET ?`,
userID, limit, offset,
)
if err != nil {
return nil, 0, err
}
defer rows.Close()
faves, err := s.scanFaves(rows)
return faves, total, err
}
// ListPublicByUser returns only public faves for a user, with pagination.
func (s *FaveStore) ListPublicByUser(userID int64, limit, offset int) ([]*model.Fave, int, error) {
var total int
err := s.db.QueryRow(
"SELECT COUNT(*) FROM faves WHERE user_id = ? AND privacy = 'public'", userID,
).Scan(&total)
if err != nil {
return nil, 0, err
}
rows, err := s.db.Query(
`SELECT f.id, f.user_id, f.description, f.url, f.image_path, f.privacy,
f.created_at, f.updated_at, u.username, u.display_name
FROM faves f
JOIN users u ON u.id = f.user_id
WHERE f.user_id = ? AND f.privacy = 'public'
ORDER BY f.created_at DESC
LIMIT ? OFFSET ?`,
userID, limit, offset,
)
if err != nil {
return nil, 0, err
}
defer rows.Close()
faves, err := s.scanFaves(rows)
return faves, total, err
}
// ListPublic returns all public faves across all users, with pagination.
func (s *FaveStore) ListPublic(limit, offset int) ([]*model.Fave, int, error) {
var total int
err := s.db.QueryRow("SELECT COUNT(*) FROM faves WHERE privacy = 'public'").Scan(&total)
if err != nil {
return nil, 0, err
}
rows, err := s.db.Query(
`SELECT f.id, f.user_id, f.description, f.url, f.image_path, f.privacy,
f.created_at, f.updated_at, u.username, u.display_name
FROM faves f
JOIN users u ON u.id = f.user_id
WHERE f.privacy = 'public'
ORDER BY f.created_at DESC
LIMIT ? OFFSET ?`,
limit, offset,
)
if err != nil {
return nil, 0, err
}
defer rows.Close()
faves, err := s.scanFaves(rows)
return faves, total, err
}
// ListByTag returns all public faves with a given tag, with pagination.
func (s *FaveStore) ListByTag(tagName string, limit, offset int) ([]*model.Fave, int, error) {
var total int
err := s.db.QueryRow(
`SELECT COUNT(*) FROM faves f
JOIN fave_tags ft ON ft.fave_id = f.id
JOIN tags t ON t.id = ft.tag_id
WHERE t.name = ? AND f.privacy = 'public'`, tagName,
).Scan(&total)
if err != nil {
return nil, 0, err
}
rows, err := s.db.Query(
`SELECT f.id, f.user_id, f.description, f.url, f.image_path, f.privacy,
f.created_at, f.updated_at, u.username, u.display_name
FROM faves f
JOIN users u ON u.id = f.user_id
JOIN fave_tags ft ON ft.fave_id = f.id
JOIN tags t ON t.id = ft.tag_id
WHERE t.name = ? AND f.privacy = 'public'
ORDER BY f.created_at DESC
LIMIT ? OFFSET ?`,
tagName, limit, offset,
)
if err != nil {
return nil, 0, err
}
defer rows.Close()
faves, err := s.scanFaves(rows)
return faves, total, err
}
// Count returns the total number of faves.
func (s *FaveStore) Count() (int, error) {
var n int
err := s.db.QueryRow("SELECT COUNT(*) FROM faves").Scan(&n)
return n, err
}
// LoadTags populates the Tags field on each fave.
func (s *FaveStore) LoadTags(faves []*model.Fave) error {
if len(faves) == 0 {
return nil
}
// Build a map for fast lookup.
faveMap := make(map[int64]*model.Fave, len(faves))
ids := make([]any, len(faves))
placeholders := make([]string, len(faves))
for i, f := range faves {
faveMap[f.ID] = f
ids[i] = f.ID
placeholders[i] = "?"
}
query := fmt.Sprintf(
`SELECT ft.fave_id, t.id, t.name
FROM fave_tags ft
JOIN tags t ON t.id = ft.tag_id
WHERE ft.fave_id IN (%s)
ORDER BY t.name COLLATE NOCASE`,
strings.Join(placeholders, ","),
)
rows, err := s.db.Query(query, ids...)
if err != nil {
return fmt.Errorf("load tags: %w", err)
}
defer rows.Close()
for rows.Next() {
var faveID int64
var tag model.Tag
if err := rows.Scan(&faveID, &tag.ID, &tag.Name); err != nil {
return fmt.Errorf("scan tag: %w", err)
}
if f, ok := faveMap[faveID]; ok {
f.Tags = append(f.Tags, tag)
}
}
return rows.Err()
}
func (s *FaveStore) scanFaves(rows *sql.Rows) ([]*model.Fave, error) {
var faves []*model.Fave
for rows.Next() {
f := &model.Fave{}
var createdAt, updatedAt string
err := rows.Scan(
&f.ID, &f.UserID, &f.Description, &f.URL, &f.ImagePath, &f.Privacy,
&createdAt, &updatedAt, &f.Username, &f.DisplayName,
)
if err != nil {
return nil, fmt.Errorf("scan fave: %w", err)
}
f.CreatedAt, _ = time.Parse(time.RFC3339, createdAt)
f.UpdatedAt, _ = time.Parse(time.RFC3339, updatedAt)
faves = append(faves, f)
}
return faves, rows.Err()
}

180
internal/store/fave_test.go Normal file
View file

@ -0,0 +1,180 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package store
import (
"testing"
)
func TestFaveCRUD(t *testing.T) {
db := testDB(t)
users := NewUserStore(db)
faves := NewFaveStore(db)
tags := NewTagStore(db)
Argon2Memory = 1024
Argon2Time = 1
defer func() { Argon2Memory = 65536; Argon2Time = 3 }()
// Create a user first.
user, err := users.Create("testuser", "password123", "user")
if err != nil {
t.Fatalf("create user: %v", err)
}
// Create a fave.
fave, err := faves.Create(user.ID, "Blade Runner 2049", "https://example.com", "", "public")
if err != nil {
t.Fatalf("create fave: %v", err)
}
if fave.Description != "Blade Runner 2049" {
t.Errorf("description = %q, want %q", fave.Description, "Blade Runner 2049")
}
if fave.Username != "testuser" {
t.Errorf("username = %q, want %q", fave.Username, "testuser")
}
// Get by ID.
got, err := faves.GetByID(fave.ID)
if err != nil {
t.Fatalf("get fave: %v", err)
}
if got.Description != fave.Description {
t.Errorf("got description = %q, want %q", got.Description, fave.Description)
}
// Update.
err = faves.Update(fave.ID, "Blade Runner 2049 (Final Cut)", "https://example.com/br2049", "", "private")
if err != nil {
t.Fatalf("update fave: %v", err)
}
updated, _ := faves.GetByID(fave.ID)
if updated.Description != "Blade Runner 2049 (Final Cut)" {
t.Errorf("updated description = %q", updated.Description)
}
if updated.Privacy != "private" {
t.Errorf("updated privacy = %q, want private", updated.Privacy)
}
// Set tags.
err = tags.SetFaveTags(fave.ID, []string{"film", "sci-fi", "favoritt"})
if err != nil {
t.Fatalf("set tags: %v", err)
}
faveTags, err := tags.ForFave(fave.ID)
if err != nil {
t.Fatalf("for fave: %v", err)
}
if len(faveTags) != 3 {
t.Errorf("tag count = %d, want 3", len(faveTags))
}
// List by user.
list, total, err := faves.ListByUser(user.ID, 10, 0)
if err != nil {
t.Fatalf("list by user: %v", err)
}
if total != 1 || len(list) != 1 {
t.Errorf("list by user: total=%d, len=%d", total, len(list))
}
// Load tags for list.
err = faves.LoadTags(list)
if err != nil {
t.Fatalf("load tags: %v", err)
}
if len(list[0].Tags) != 3 {
t.Errorf("loaded tags = %d, want 3", len(list[0].Tags))
}
// Public list should be empty (fave is now private).
pubList, pubTotal, err := faves.ListPublicByUser(user.ID, 10, 0)
if err != nil {
t.Fatalf("list public: %v", err)
}
if pubTotal != 0 || len(pubList) != 0 {
t.Errorf("public list should be empty: total=%d, len=%d", pubTotal, len(pubList))
}
// Delete.
err = faves.Delete(fave.ID)
if err != nil {
t.Fatalf("delete fave: %v", err)
}
_, err = faves.GetByID(fave.ID)
if err != ErrFaveNotFound {
t.Errorf("deleted fave error = %v, want ErrFaveNotFound", err)
}
}
func TestListByTag(t *testing.T) {
db := testDB(t)
users := NewUserStore(db)
faves := NewFaveStore(db)
tags := NewTagStore(db)
Argon2Memory = 1024
Argon2Time = 1
defer func() { Argon2Memory = 65536; Argon2Time = 3 }()
user, _ := users.Create("testuser", "password123", "user")
// Create two public faves with overlapping tags.
f1, _ := faves.Create(user.ID, "Fave 1", "", "", "public")
f2, _ := faves.Create(user.ID, "Fave 2", "", "", "public")
f3, _ := faves.Create(user.ID, "Private Fave", "", "", "private")
tags.SetFaveTags(f1.ID, []string{"music", "jazz"})
tags.SetFaveTags(f2.ID, []string{"music", "rock"})
tags.SetFaveTags(f3.ID, []string{"music", "secret"})
// ListByTag only returns public faves.
list, total, err := faves.ListByTag("music", 10, 0)
if err != nil {
t.Fatalf("list by tag: %v", err)
}
if total != 2 {
t.Errorf("total = %d, want 2 (private fave should be excluded)", total)
}
if len(list) != 2 {
t.Errorf("len = %d, want 2", len(list))
}
}
func TestFavePagination(t *testing.T) {
db := testDB(t)
users := NewUserStore(db)
faves := NewFaveStore(db)
Argon2Memory = 1024
Argon2Time = 1
defer func() { Argon2Memory = 65536; Argon2Time = 3 }()
user, _ := users.Create("testuser", "password123", "user")
// Create 5 faves.
for i := 0; i < 5; i++ {
faves.Create(user.ID, "Fave "+string(rune('A'+i)), "", "", "public")
}
// Page 1 with limit 2.
page1, total, err := faves.ListByUser(user.ID, 2, 0)
if err != nil {
t.Fatalf("page 1: %v", err)
}
if total != 5 {
t.Errorf("total = %d, want 5", total)
}
if len(page1) != 2 {
t.Errorf("page 1 len = %d, want 2", len(page1))
}
// Page 3 with limit 2 should have 1 item.
page3, _, err := faves.ListByUser(user.ID, 2, 4)
if err != nil {
t.Fatalf("page 3: %v", err)
}
if len(page3) != 1 {
t.Errorf("page 3 len = %d, want 1", len(page3))
}
}

119
internal/store/session.go Normal file
View file

@ -0,0 +1,119 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package store
import (
"context"
"crypto/rand"
"database/sql"
"encoding/hex"
"errors"
"fmt"
"log/slog"
"time"
"kode.naiv.no/olemd/favoritter/internal/model"
)
var ErrSessionNotFound = errors.New("session not found")
type SessionStore struct {
db *sql.DB
lifetime time.Duration
}
func NewSessionStore(db *sql.DB) *SessionStore {
return &SessionStore{db: db, lifetime: 720 * time.Hour} // default 30 days
}
// SetLifetime configures the session lifetime.
func (s *SessionStore) SetLifetime(d time.Duration) {
s.lifetime = d
}
// Create generates a new session token for the given user.
func (s *SessionStore) Create(userID int64) (string, error) {
tokenBytes := make([]byte, 32)
if _, err := rand.Read(tokenBytes); err != nil {
return "", fmt.Errorf("generate session token: %w", err)
}
token := hex.EncodeToString(tokenBytes)
expiresAt := time.Now().UTC().Add(s.lifetime)
_, err := s.db.Exec(
`INSERT INTO sessions (token, user_id, expires_at) VALUES (?, ?, ?)`,
token, userID, expiresAt.Format(time.RFC3339),
)
if err != nil {
return "", fmt.Errorf("insert session: %w", err)
}
return token, nil
}
// Validate checks if a session token is valid and not expired.
// Returns the session if valid.
func (s *SessionStore) Validate(token string) (*model.Session, error) {
var session model.Session
var expiresAt, createdAt string
err := s.db.QueryRow(
`SELECT token, user_id, expires_at, created_at
FROM sessions WHERE token = ?`, token,
).Scan(&session.Token, &session.UserID, &expiresAt, &createdAt)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrSessionNotFound
}
if err != nil {
return nil, fmt.Errorf("query session: %w", err)
}
session.ExpiresAt, _ = time.Parse(time.RFC3339, expiresAt)
session.CreatedAt, _ = time.Parse(time.RFC3339, createdAt)
if time.Now().UTC().After(session.ExpiresAt) {
// Session has expired — delete it.
s.Delete(token)
return nil, ErrSessionNotFound
}
return &session, nil
}
// Delete removes a session by its token.
func (s *SessionStore) Delete(token string) error {
_, err := s.db.Exec("DELETE FROM sessions WHERE token = ?", token)
return err
}
// DeleteAllForUser removes all sessions for a given user (e.g., on password change).
func (s *SessionStore) DeleteAllForUser(userID int64) error {
_, err := s.db.Exec("DELETE FROM sessions WHERE user_id = ?", userID)
return err
}
// CleanupLoop periodically removes expired sessions. It runs until the
// context is canceled.
func (s *SessionStore) CleanupLoop(ctx context.Context, interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
result, err := s.db.Exec(
`DELETE FROM sessions WHERE expires_at < strftime('%Y-%m-%dT%H:%M:%SZ', 'now')`,
)
if err != nil {
slog.Error("session cleanup failed", "error", err)
continue
}
n, _ := result.RowsAffected()
if n > 0 {
slog.Info("cleaned up expired sessions", "count", n)
}
}
}
}

View file

@ -0,0 +1,46 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package store
import (
"database/sql"
"fmt"
"time"
"kode.naiv.no/olemd/favoritter/internal/model"
)
type SettingsStore struct {
db *sql.DB
}
func NewSettingsStore(db *sql.DB) *SettingsStore {
return &SettingsStore{db: db}
}
// Get returns the current site settings.
func (s *SettingsStore) Get() (*model.SiteSettings, error) {
var settings model.SiteSettings
var updatedAt string
err := s.db.QueryRow(
`SELECT site_name, site_description, signup_mode, updated_at
FROM site_settings WHERE id = 1`,
).Scan(&settings.SiteName, &settings.SiteDescription, &settings.SignupMode, &updatedAt)
if err != nil {
return nil, fmt.Errorf("query site settings: %w", err)
}
settings.UpdatedAt, _ = time.Parse(time.RFC3339, updatedAt)
return &settings, nil
}
// Update updates the site settings.
func (s *SettingsStore) Update(siteName, siteDescription, signupMode string) error {
_, err := s.db.Exec(
`UPDATE site_settings SET site_name = ?, site_description = ?, signup_mode = ?,
updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')
WHERE id = 1`,
siteName, siteDescription, signupMode,
)
return err
}

View file

@ -0,0 +1,47 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package store
import (
"database/sql"
"errors"
"fmt"
"strings"
)
var ErrSignupRequestExists = errors.New("signup request already exists")
type SignupRequestStore struct {
db *sql.DB
}
func NewSignupRequestStore(db *sql.DB) *SignupRequestStore {
return &SignupRequestStore{db: db}
}
// Create stores a pending signup request with a hashed password.
func (s *SignupRequestStore) Create(username, password string) error {
hash, err := hashPassword(password)
if err != nil {
return fmt.Errorf("hash password: %w", err)
}
_, err = s.db.Exec(
`INSERT INTO signup_requests (username, password_hash) VALUES (?, ?)`,
username, hash,
)
if err != nil {
if strings.Contains(err.Error(), "UNIQUE constraint failed") {
return ErrSignupRequestExists
}
return fmt.Errorf("insert signup request: %w", err)
}
return nil
}
// PendingCount returns the number of pending signup requests.
func (s *SignupRequestStore) PendingCount() (int, error) {
var n int
err := s.db.QueryRow("SELECT COUNT(*) FROM signup_requests WHERE status = 'pending'").Scan(&n)
return n, err
}

240
internal/store/tag.go Normal file
View file

@ -0,0 +1,240 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package store
import (
"database/sql"
"errors"
"fmt"
"strings"
"kode.naiv.no/olemd/favoritter/internal/model"
)
const (
MaxTagsPerFave = 20
MaxTagLength = 50
)
var ErrTagNotFound = errors.New("tag not found")
type TagStore struct {
db *sql.DB
}
func NewTagStore(db *sql.DB) *TagStore {
return &TagStore{db: db}
}
// Search returns tags matching a prefix query, for autocomplete.
// Results are ordered by how many faves use each tag (most popular first).
func (s *TagStore) Search(query string, limit int) ([]model.Tag, error) {
query = strings.TrimSpace(strings.ToLower(query))
if query == "" {
return nil, nil
}
rows, err := s.db.Query(
`SELECT t.id, t.name
FROM tags t
LEFT JOIN fave_tags ft ON ft.tag_id = t.id
WHERE t.name LIKE ? || '%'
GROUP BY t.id
ORDER BY COUNT(ft.fave_id) DESC, t.name COLLATE NOCASE
LIMIT ?`,
query, limit,
)
if err != nil {
return nil, fmt.Errorf("search tags: %w", err)
}
defer rows.Close()
return scanTags(rows)
}
func scanTags(rows *sql.Rows) ([]model.Tag, error) {
var tags []model.Tag
for rows.Next() {
var t model.Tag
if err := rows.Scan(&t.ID, &t.Name); err != nil {
return nil, err
}
tags = append(tags, t)
}
return tags, rows.Err()
}
// GetOrCreate returns an existing tag by name, or creates it if it doesn't exist.
// Tag names are normalized to lowercase and trimmed.
func (s *TagStore) GetOrCreate(name string) (*model.Tag, error) {
name = NormalizeTagName(name)
if name == "" {
return nil, fmt.Errorf("empty tag name")
}
if len(name) > MaxTagLength {
return nil, fmt.Errorf("tag name too long (max %d characters)", MaxTagLength)
}
// Try to find existing tag first (COLLATE NOCASE handles case).
var tag model.Tag
err := s.db.QueryRow("SELECT id, name FROM tags WHERE name = ?", name).Scan(&tag.ID, &tag.Name)
if err == nil {
return &tag, nil
}
if !errors.Is(err, sql.ErrNoRows) {
return nil, err
}
// Create new tag.
result, err := s.db.Exec("INSERT INTO tags (name) VALUES (?)", name)
if err != nil {
// Race condition: another request may have created it.
if strings.Contains(err.Error(), "UNIQUE constraint failed") {
err2 := s.db.QueryRow("SELECT id, name FROM tags WHERE name = ?", name).Scan(&tag.ID, &tag.Name)
if err2 != nil {
return nil, err2
}
return &tag, nil
}
return nil, err
}
tag.ID, _ = result.LastInsertId()
tag.Name = name
return &tag, nil
}
// GetByID returns a tag by ID.
func (s *TagStore) GetByID(id int64) (*model.Tag, error) {
var tag model.Tag
err := s.db.QueryRow("SELECT id, name FROM tags WHERE id = ?", id).Scan(&tag.ID, &tag.Name)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrTagNotFound
}
return &tag, err
}
// GetByName returns a tag by its name (case-insensitive).
func (s *TagStore) GetByName(name string) (*model.Tag, error) {
var tag model.Tag
err := s.db.QueryRow("SELECT id, name FROM tags WHERE name = ?", name).Scan(&tag.ID, &tag.Name)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrTagNotFound
}
return &tag, err
}
// AttachToFave links a tag to a fave. No-op if already attached.
func (s *TagStore) AttachToFave(faveID, tagID int64) error {
_, err := s.db.Exec(
"INSERT OR IGNORE INTO fave_tags (fave_id, tag_id) VALUES (?, ?)",
faveID, tagID,
)
return err
}
// DetachFromFave removes a tag from a fave.
func (s *TagStore) DetachFromFave(faveID, tagID int64) error {
_, err := s.db.Exec(
"DELETE FROM fave_tags WHERE fave_id = ? AND tag_id = ?",
faveID, tagID,
)
return err
}
// SetFaveTags replaces all tags on a fave with the given tag names.
// Creates new tags as needed. Enforces MaxTagsPerFave.
func (s *TagStore) SetFaveTags(faveID int64, tagNames []string) error {
if len(tagNames) > MaxTagsPerFave {
tagNames = tagNames[:MaxTagsPerFave]
}
// Remove all existing tags for this fave.
if _, err := s.db.Exec("DELETE FROM fave_tags WHERE fave_id = ?", faveID); err != nil {
return err
}
// Attach new tags.
for _, name := range tagNames {
name = NormalizeTagName(name)
if name == "" {
continue
}
tag, err := s.GetOrCreate(name)
if err != nil {
return fmt.Errorf("get or create tag %q: %w", name, err)
}
if err := s.AttachToFave(faveID, tag.ID); err != nil {
return fmt.Errorf("attach tag %q: %w", name, err)
}
}
return nil
}
// ForFave returns all tags attached to a fave.
func (s *TagStore) ForFave(faveID int64) ([]model.Tag, error) {
rows, err := s.db.Query(
`SELECT t.id, t.name FROM tags t
JOIN fave_tags ft ON ft.tag_id = t.id
WHERE ft.fave_id = ?
ORDER BY t.name COLLATE NOCASE`,
faveID,
)
if err != nil {
return nil, err
}
defer rows.Close()
return scanTags(rows)
}
// ListAll returns all tags ordered by name.
func (s *TagStore) ListAll() ([]model.Tag, error) {
rows, err := s.db.Query("SELECT id, name FROM tags ORDER BY name COLLATE NOCASE")
if err != nil {
return nil, err
}
defer rows.Close()
return scanTags(rows)
}
// Rename changes a tag's name. Returns error if the new name already exists.
func (s *TagStore) Rename(id int64, newName string) error {
newName = NormalizeTagName(newName)
if newName == "" {
return fmt.Errorf("empty tag name")
}
_, err := s.db.Exec("UPDATE tags SET name = ? WHERE id = ?", newName, id)
return err
}
// Delete removes a tag and all its fave associations (via cascade).
func (s *TagStore) Delete(id int64) error {
// fave_tags rows are cleaned up by ON DELETE CASCADE.
result, err := s.db.Exec("DELETE FROM tags WHERE id = ?", id)
if err != nil {
return err
}
n, _ := result.RowsAffected()
if n == 0 {
return ErrTagNotFound
}
return nil
}
// CleanupOrphans removes tags that are not attached to any faves.
func (s *TagStore) CleanupOrphans() (int64, error) {
result, err := s.db.Exec(
`DELETE FROM tags WHERE id NOT IN (SELECT DISTINCT tag_id FROM fave_tags)`,
)
if err != nil {
return 0, err
}
return result.RowsAffected()
}
// NormalizeTagName lowercases and trims a tag name.
func NormalizeTagName(name string) string {
return strings.TrimSpace(strings.ToLower(name))
}

173
internal/store/tag_test.go Normal file
View file

@ -0,0 +1,173 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package store
import (
"testing"
)
func TestTagGetOrCreate(t *testing.T) {
db := testDB(t)
tags := NewTagStore(db)
// Create a new tag.
tag1, err := tags.GetOrCreate("Film")
if err != nil {
t.Fatalf("get or create: %v", err)
}
if tag1.Name != "film" {
t.Errorf("name = %q, want %q (should be normalized to lowercase)", tag1.Name, "film")
}
// Get the same tag again (case-insensitive).
tag2, err := tags.GetOrCreate("FILM")
if err != nil {
t.Fatalf("get or create duplicate: %v", err)
}
if tag2.ID != tag1.ID {
t.Errorf("duplicate tag got different ID: %d vs %d", tag2.ID, tag1.ID)
}
}
func TestTagSearch(t *testing.T) {
db := testDB(t)
tags := NewTagStore(db)
users := NewUserStore(db)
faves := NewFaveStore(db)
Argon2Memory = 1024
Argon2Time = 1
defer func() { Argon2Memory = 65536; Argon2Time = 3 }()
user, _ := users.Create("testuser", "password123", "user")
// Create some tags via faves to give them usage counts.
f1, _ := faves.Create(user.ID, "F1", "", "", "public")
f2, _ := faves.Create(user.ID, "F2", "", "", "public")
tags.SetFaveTags(f1.ID, []string{"music", "movies", "misc"})
tags.SetFaveTags(f2.ID, []string{"music", "manga"})
// Search for "mu" should return "music" first (2 faves) then nothing else.
results, err := tags.Search("mu", 10)
if err != nil {
t.Fatalf("search: %v", err)
}
if len(results) != 1 {
t.Fatalf("search results = %d, want 1", len(results))
}
if results[0].Name != "music" {
t.Errorf("first result = %q, want %q", results[0].Name, "music")
}
// Search for "m" should return music (2), manga (1), misc (1), movies (1).
results, err = tags.Search("m", 10)
if err != nil {
t.Fatalf("search: %v", err)
}
if len(results) != 4 {
t.Errorf("search results = %d, want 4", len(results))
}
// Music should be first due to highest usage count.
if results[0].Name != "music" {
t.Errorf("first result = %q, want %q (most used)", results[0].Name, "music")
}
// Empty search returns nothing.
results, err = tags.Search("", 10)
if err != nil {
t.Fatalf("empty search: %v", err)
}
if len(results) != 0 {
t.Errorf("empty search results = %d, want 0", len(results))
}
}
func TestTagSetFaveTagsLimit(t *testing.T) {
db := testDB(t)
tags := NewTagStore(db)
users := NewUserStore(db)
faves := NewFaveStore(db)
Argon2Memory = 1024
Argon2Time = 1
defer func() { Argon2Memory = 65536; Argon2Time = 3 }()
user, _ := users.Create("testuser", "password123", "user")
fave, _ := faves.Create(user.ID, "Test", "", "", "public")
// Try to set more than MaxTagsPerFave tags.
manyTags := make([]string, 30)
for i := range manyTags {
manyTags[i] = "tag" + string(rune('a'+i%26))
}
err := tags.SetFaveTags(fave.ID, manyTags)
if err != nil {
t.Fatalf("set many tags: %v", err)
}
attached, _ := tags.ForFave(fave.ID)
if len(attached) > MaxTagsPerFave {
t.Errorf("attached %d tags, max should be %d", len(attached), MaxTagsPerFave)
}
}
func TestTagCleanupOrphans(t *testing.T) {
db := testDB(t)
tags := NewTagStore(db)
users := NewUserStore(db)
faves := NewFaveStore(db)
Argon2Memory = 1024
Argon2Time = 1
defer func() { Argon2Memory = 65536; Argon2Time = 3 }()
user, _ := users.Create("testuser", "password123", "user")
fave, _ := faves.Create(user.ID, "Test", "", "", "public")
tags.SetFaveTags(fave.ID, []string{"keep", "orphan"})
// Remove the fave — "keep" and "orphan" are now orphaned.
faves.Delete(fave.ID)
removed, err := tags.CleanupOrphans()
if err != nil {
t.Fatalf("cleanup: %v", err)
}
if removed != 2 {
t.Errorf("removed = %d, want 2", removed)
}
all, _ := tags.ListAll()
if len(all) != 0 {
t.Errorf("remaining tags = %d, want 0", len(all))
}
}
func TestTagRenameAndDelete(t *testing.T) {
db := testDB(t)
tags := NewTagStore(db)
tag, _ := tags.GetOrCreate("oldname")
err := tags.Rename(tag.ID, "NewName")
if err != nil {
t.Fatalf("rename: %v", err)
}
renamed, _ := tags.GetByID(tag.ID)
if renamed.Name != "newname" {
t.Errorf("renamed = %q, want %q", renamed.Name, "newname")
}
err = tags.Delete(tag.ID)
if err != nil {
t.Fatalf("delete: %v", err)
}
_, err = tags.GetByID(tag.ID)
if err != ErrTagNotFound {
t.Errorf("deleted tag error = %v, want ErrTagNotFound", err)
}
}

326
internal/store/user.go Normal file
View file

@ -0,0 +1,326 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package store
import (
"crypto/rand"
"crypto/subtle"
"database/sql"
"encoding/base64"
"errors"
"fmt"
"log/slog"
"strings"
"time"
"golang.org/x/crypto/argon2"
"kode.naiv.no/olemd/favoritter/internal/model"
)
// Argon2id parameters. Defaults match OWASP recommendations.
var (
Argon2Memory uint32 = 65536 // 64 MB
Argon2Time uint32 = 3
Argon2Parallelism uint8 = 2
Argon2KeyLength uint32 = 32
Argon2SaltLength = 16
)
var (
ErrUserNotFound = errors.New("user not found")
ErrUserExists = errors.New("username already taken")
ErrUserDisabled = errors.New("user account is disabled")
ErrInvalidCredentials = errors.New("invalid username or password")
)
type UserStore struct {
db *sql.DB
}
func NewUserStore(db *sql.DB) *UserStore {
return &UserStore{db: db}
}
// Create creates a new user with the given username and plaintext password.
func (s *UserStore) Create(username, password, role string) (*model.User, error) {
hash, err := hashPassword(password)
if err != nil {
return nil, fmt.Errorf("hash password: %w", err)
}
result, err := s.db.Exec(
`INSERT INTO users (username, password_hash, role) VALUES (?, ?, ?)`,
username, hash, role,
)
if err != nil {
if strings.Contains(err.Error(), "UNIQUE constraint failed") {
return nil, ErrUserExists
}
return nil, fmt.Errorf("insert user: %w", err)
}
id, _ := result.LastInsertId()
return s.GetByID(id)
}
// CreateWithReset creates a new user that must reset their password on first login.
func (s *UserStore) CreateWithReset(username, tempPassword, role string) (*model.User, error) {
hash, err := hashPassword(tempPassword)
if err != nil {
return nil, fmt.Errorf("hash password: %w", err)
}
result, err := s.db.Exec(
`INSERT INTO users (username, password_hash, role, must_reset_password) VALUES (?, ?, ?, 1)`,
username, hash, role,
)
if err != nil {
if strings.Contains(err.Error(), "UNIQUE constraint failed") {
return nil, ErrUserExists
}
return nil, fmt.Errorf("insert user: %w", err)
}
id, _ := result.LastInsertId()
return s.GetByID(id)
}
// Authenticate verifies credentials and returns the user if valid.
func (s *UserStore) Authenticate(username, password string) (*model.User, error) {
user, err := s.GetByUsername(username)
if err != nil {
if errors.Is(err, ErrUserNotFound) {
// Still do a dummy hash comparison to prevent timing attacks.
dummyHash(password)
return nil, ErrInvalidCredentials
}
return nil, err
}
if user.Disabled {
return nil, ErrUserDisabled
}
if !verifyPassword(password, user.PasswordHash) {
return nil, ErrInvalidCredentials
}
return user, nil
}
// GetByID retrieves a user by their ID.
func (s *UserStore) GetByID(id int64) (*model.User, error) {
return scanUserFrom(s.db.QueryRow(
`SELECT id, username, display_name, bio, avatar_path, password_hash,
role, profile_visibility, default_fave_privacy,
must_reset_password, disabled, created_at, updated_at
FROM users WHERE id = ?`, id,
))
}
// GetByUsername retrieves a user by their username (case-insensitive).
func (s *UserStore) GetByUsername(username string) (*model.User, error) {
return scanUserFrom(s.db.QueryRow(
`SELECT id, username, display_name, bio, avatar_path, password_hash,
role, profile_visibility, default_fave_privacy,
must_reset_password, disabled, created_at, updated_at
FROM users WHERE username = ?`, username,
))
}
// UpdatePassword changes a user's password and clears the must_reset_password flag.
func (s *UserStore) UpdatePassword(userID int64, newPassword string) error {
hash, err := hashPassword(newPassword)
if err != nil {
return fmt.Errorf("hash password: %w", err)
}
_, err = s.db.Exec(
`UPDATE users SET password_hash = ?, must_reset_password = 0,
updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')
WHERE id = ?`,
hash, userID,
)
return err
}
// UpdateProfile updates a user's profile fields.
func (s *UserStore) UpdateProfile(userID int64, displayName, bio, profileVisibility, defaultFavePrivacy string) error {
_, err := s.db.Exec(
`UPDATE users SET display_name = ?, bio = ?, profile_visibility = ?,
default_fave_privacy = ?,
updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')
WHERE id = ?`,
displayName, bio, profileVisibility, defaultFavePrivacy, userID,
)
return err
}
// UpdateAvatar updates a user's avatar path.
func (s *UserStore) UpdateAvatar(userID int64, avatarPath string) error {
_, err := s.db.Exec(
`UPDATE users SET avatar_path = ?,
updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')
WHERE id = ?`,
avatarPath, userID,
)
return err
}
// SetDisabled enables or disables a user account.
func (s *UserStore) SetDisabled(userID int64, disabled bool) error {
val := 0
if disabled {
val = 1
}
_, err := s.db.Exec(
`UPDATE users SET disabled = ?,
updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')
WHERE id = ?`,
val, userID,
)
return err
}
// ListAll returns all users, ordered by username.
func (s *UserStore) ListAll() ([]*model.User, error) {
rows, err := s.db.Query(
`SELECT id, username, display_name, bio, avatar_path, password_hash,
role, profile_visibility, default_fave_privacy,
must_reset_password, disabled, created_at, updated_at
FROM users ORDER BY username COLLATE NOCASE`,
)
if err != nil {
return nil, err
}
defer rows.Close()
var users []*model.User
for rows.Next() {
u, err := scanUserFrom(rows)
if err != nil {
return nil, err
}
users = append(users, u)
}
return users, rows.Err()
}
// Count returns the total number of users.
func (s *UserStore) Count() (int, error) {
var n int
err := s.db.QueryRow("SELECT COUNT(*) FROM users").Scan(&n)
return n, err
}
// EnsureAdmin creates the initial admin user if no users exist yet.
// This is called on startup with the configured admin credentials.
func (s *UserStore) EnsureAdmin(username, password string) error {
if username == "" || password == "" {
// No admin credentials configured — only skip if users already exist.
count, err := s.Count()
if err != nil {
return err
}
if count == 0 {
slog.Warn("no admin credentials configured and no users exist — set FAVORITTER_ADMIN_USERNAME and FAVORITTER_ADMIN_PASSWORD")
}
return nil
}
// Check if this admin already exists.
_, err := s.GetByUsername(username)
if err == nil {
return nil // Already exists.
}
if !errors.Is(err, ErrUserNotFound) {
return err
}
_, err = s.Create(username, password, "admin")
if err != nil {
return fmt.Errorf("create admin user: %w", err)
}
slog.Info("created initial admin user", "username", username)
return nil
}
// scanner is implemented by both *sql.Row and *sql.Rows.
type scanner interface {
Scan(dest ...any) error
}
func scanUserFrom(s scanner) (*model.User, error) {
u := &model.User{}
var createdAt, updatedAt string
err := s.Scan(
&u.ID, &u.Username, &u.DisplayName, &u.Bio, &u.AvatarPath,
&u.PasswordHash, &u.Role, &u.ProfileVisibility, &u.DefaultFavePrivacy,
&u.MustResetPassword, &u.Disabled, &createdAt, &updatedAt,
)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrUserNotFound
}
if err != nil {
return nil, fmt.Errorf("scan user: %w", err)
}
u.CreatedAt, _ = time.Parse(time.RFC3339, createdAt)
u.UpdatedAt, _ = time.Parse(time.RFC3339, updatedAt)
return u, nil
}
// Password hashing with Argon2id.
// Format: $argon2id$v=19$m=65536,t=3,p=2$<salt>$<hash>
func hashPassword(password string) (string, error) {
salt := make([]byte, Argon2SaltLength)
if _, err := rand.Read(salt); err != nil {
return "", fmt.Errorf("generate salt: %w", err)
}
hash := argon2.IDKey([]byte(password), salt, Argon2Time, Argon2Memory, Argon2Parallelism, Argon2KeyLength)
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version,
Argon2Memory, Argon2Time, Argon2Parallelism,
base64.RawStdEncoding.EncodeToString(salt),
base64.RawStdEncoding.EncodeToString(hash),
), nil
}
func verifyPassword(password, encodedHash string) bool {
parts := strings.Split(encodedHash, "$")
if len(parts) != 6 || parts[1] != "argon2id" {
return false
}
var memory uint32
var iterations uint32
var parallelism uint8
_, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &iterations, &parallelism)
if err != nil {
return false
}
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil {
return false
}
expectedHash, err := base64.RawStdEncoding.DecodeString(parts[5])
if err != nil {
return false
}
hash := argon2.IDKey([]byte(password), salt, iterations, memory, parallelism, uint32(len(expectedHash)))
return subtle.ConstantTimeCompare(hash, expectedHash) == 1
}
// dummyHash performs a hash operation to prevent timing-based username enumeration.
func dummyHash(password string) {
salt := make([]byte, Argon2SaltLength)
argon2.IDKey([]byte(password), salt, Argon2Time, Argon2Memory, Argon2Parallelism, Argon2KeyLength)
}

205
internal/store/user_test.go Normal file
View file

@ -0,0 +1,205 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package store
import (
"database/sql"
"testing"
_ "modernc.org/sqlite"
"kode.naiv.no/olemd/favoritter/internal/database"
)
func testDB(t *testing.T) *sql.DB {
t.Helper()
db, err := database.Open(":memory:")
if err != nil {
t.Fatalf("open test db: %v", err)
}
if err := database.Migrate(db); err != nil {
t.Fatalf("migrate test db: %v", err)
}
t.Cleanup(func() { db.Close() })
return db
}
func TestCreateAndAuthenticate(t *testing.T) {
db := testDB(t)
users := NewUserStore(db)
// Use fast Argon2 parameters for tests.
Argon2Memory = 1024
Argon2Time = 1
defer func() {
Argon2Memory = 65536
Argon2Time = 3
}()
// Create a user.
user, err := users.Create("testuser", "password123", "user")
if err != nil {
t.Fatalf("create user: %v", err)
}
if user.Username != "testuser" {
t.Errorf("username = %q, want %q", user.Username, "testuser")
}
if user.Role != "user" {
t.Errorf("role = %q, want %q", user.Role, "user")
}
// Authenticate with correct password.
authed, err := users.Authenticate("testuser", "password123")
if err != nil {
t.Fatalf("authenticate: %v", err)
}
if authed.ID != user.ID {
t.Errorf("authenticated user ID = %d, want %d", authed.ID, user.ID)
}
// Authenticate with wrong password.
_, err = users.Authenticate("testuser", "wrongpassword")
if err != ErrInvalidCredentials {
t.Errorf("wrong password error = %v, want ErrInvalidCredentials", err)
}
// Authenticate with non-existent user.
_, err = users.Authenticate("nouser", "password123")
if err != ErrInvalidCredentials {
t.Errorf("non-existent user error = %v, want ErrInvalidCredentials", err)
}
}
func TestCreateDuplicate(t *testing.T) {
db := testDB(t)
users := NewUserStore(db)
Argon2Memory = 1024
Argon2Time = 1
defer func() {
Argon2Memory = 65536
Argon2Time = 3
}()
_, err := users.Create("testuser", "password123", "user")
if err != nil {
t.Fatalf("create user: %v", err)
}
_, err = users.Create("testuser", "password456", "user")
if err != ErrUserExists {
t.Errorf("duplicate error = %v, want ErrUserExists", err)
}
// Case-insensitive duplicate.
_, err = users.Create("TestUser", "password456", "user")
if err != ErrUserExists {
t.Errorf("case-insensitive duplicate error = %v, want ErrUserExists", err)
}
}
func TestUpdatePassword(t *testing.T) {
db := testDB(t)
users := NewUserStore(db)
Argon2Memory = 1024
Argon2Time = 1
defer func() {
Argon2Memory = 65536
Argon2Time = 3
}()
user, err := users.CreateWithReset("admin", "temppass", "admin")
if err != nil {
t.Fatalf("create user: %v", err)
}
if !user.MustResetPassword {
t.Error("expected must_reset_password to be true")
}
err = users.UpdatePassword(user.ID, "newpassword123")
if err != nil {
t.Fatalf("update password: %v", err)
}
// Verify old password no longer works.
_, err = users.Authenticate("admin", "temppass")
if err != ErrInvalidCredentials {
t.Error("old password should not work after reset")
}
// Verify new password works and reset flag is cleared.
updated, err := users.Authenticate("admin", "newpassword123")
if err != nil {
t.Fatalf("authenticate with new password: %v", err)
}
if updated.MustResetPassword {
t.Error("must_reset_password should be false after update")
}
}
func TestEnsureAdmin(t *testing.T) {
db := testDB(t)
users := NewUserStore(db)
Argon2Memory = 1024
Argon2Time = 1
defer func() {
Argon2Memory = 65536
Argon2Time = 3
}()
// First call creates the admin.
err := users.EnsureAdmin("admin", "adminpass")
if err != nil {
t.Fatalf("ensure admin: %v", err)
}
admin, err := users.GetByUsername("admin")
if err != nil {
t.Fatalf("get admin: %v", err)
}
if !admin.IsAdmin() {
t.Error("expected admin role")
}
// Second call is a no-op.
err = users.EnsureAdmin("admin", "adminpass")
if err != nil {
t.Fatalf("ensure admin (second call): %v", err)
}
count, _ := users.Count()
if count != 1 {
t.Errorf("user count = %d, want 1", count)
}
}
func TestDisabledUser(t *testing.T) {
db := testDB(t)
users := NewUserStore(db)
Argon2Memory = 1024
Argon2Time = 1
defer func() {
Argon2Memory = 65536
Argon2Time = 3
}()
user, err := users.Create("testuser", "password123", "user")
if err != nil {
t.Fatalf("create user: %v", err)
}
// Disable the user.
err = users.SetDisabled(user.ID, true)
if err != nil {
t.Fatalf("disable user: %v", err)
}
// Authentication should fail.
_, err = users.Authenticate("testuser", "password123")
if err != ErrUserDisabled {
t.Errorf("disabled user error = %v, want ErrUserDisabled", err)
}
}

12
web/embed.go Normal file
View file

@ -0,0 +1,12 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// Package web embeds static assets and templates into the binary.
package web
import "embed"
//go:embed templates
var TemplatesFS embed.FS
//go:embed static
var StaticFS embed.FS

162
web/static/css/style.css Normal file
View file

@ -0,0 +1,162 @@
/* Favoritter — custom styles on top of Pico CSS */
/* Skip navigation link for accessibility */
.skip-link {
position: absolute;
top: -100%;
left: 0;
padding: 0.5rem 1rem;
background: var(--pico-primary-background);
color: var(--pico-primary-inverse);
z-index: 1000;
text-decoration: none;
}
.skip-link:focus {
top: 0;
}
/* Inline forms (e.g. logout button in nav) */
.inline-form {
display: inline;
margin: 0;
padding: 0;
}
.nav-button {
margin: 0;
padding: 0.25rem 0.75rem;
font-size: 0.875rem;
}
/* Flash messages */
.flash {
padding: 1rem;
border-radius: var(--pico-border-radius);
margin-bottom: 1rem;
}
.flash-success {
background: color-mix(in srgb, var(--pico-ins-color) 15%, transparent);
border: 1px solid var(--pico-ins-color);
}
.flash-error {
background: color-mix(in srgb, var(--pico-del-color) 15%, transparent);
border: 1px solid var(--pico-del-color);
}
.flash-info {
background: color-mix(in srgb, var(--pico-primary) 10%, transparent);
border: 1px solid var(--pico-primary);
}
/* Fave card grid */
.fave-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 1rem;
list-style: none;
padding: 0;
}
.fave-card {
margin: 0;
}
.fave-card img {
width: 100%;
height: 200px;
object-fit: cover;
border-radius: var(--pico-border-radius) var(--pico-border-radius) 0 0;
}
.fave-card header {
padding: 0.5rem 1rem 0;
}
.fave-card footer {
padding: 0 1rem 0.5rem;
}
/* Privacy badge */
.badge-private {
background: var(--pico-muted-border-color);
padding: 0.1rem 0.4rem;
border-radius: var(--pico-border-radius);
font-size: 0.75rem;
vertical-align: middle;
}
/* Tag chips */
.tag-chip {
display: inline-block;
background: var(--pico-primary-focus);
color: var(--pico-primary);
padding: 0.15rem 0.5rem;
border-radius: 1rem;
font-size: 0.8rem;
text-decoration: none;
margin: 0.1rem;
}
.tag-chip:hover {
background: var(--pico-primary);
color: var(--pico-primary-inverse);
}
/* Tag autocomplete suggestions */
.tag-suggestions {
list-style: none;
padding: 0;
margin: 0;
border: 1px solid var(--pico-muted-border-color);
border-radius: var(--pico-border-radius);
max-height: 200px;
overflow-y: auto;
}
.tag-suggestions:empty {
display: none;
}
.tag-suggestion {
padding: 0.5rem 0.75rem;
cursor: pointer;
}
.tag-suggestion:hover,
.tag-suggestion:focus {
background: var(--pico-primary-focus);
outline: none;
}
/* Fave detail actions */
.fave-actions {
display: flex;
gap: 0.5rem;
margin-top: 0.5rem;
}
.fave-actions a,
.fave-actions button {
margin: 0;
}
/* Current image preview in edit form */
.current-image {
margin-bottom: 1rem;
}
.current-image img {
border-radius: var(--pico-border-radius);
}
/* Respect reduced motion preference */
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}

71
web/static/js/app.js Normal file
View file

@ -0,0 +1,71 @@
// Favoritter — minimal JavaScript for HTMX configuration and form helpers.
// SPDX-License-Identifier: AGPL-3.0-or-later
(function () {
"use strict";
// Auto-include the CSRF token in all HTMX requests.
document.body.addEventListener("htmx:configRequest", function (event) {
var csrfCookie = getCookie("csrf_token");
if (csrfCookie) {
event.detail.headers["X-CSRF-Token"] = csrfCookie;
}
// For the tag search input, send the current value of the last
// comma-separated segment as the 'q' parameter.
var elt = event.detail.elt;
if (elt && elt.id === "tags") {
var val = elt.value;
var parts = val.split(",");
var lastPart = parts[parts.length - 1].trim();
event.detail.parameters["q"] = lastPart;
}
});
// Focus management after HTMX content swaps for accessibility.
document.body.addEventListener("htmx:afterSwap", function (event) {
var target = event.detail.target;
if (target) {
var autoFocus = target.querySelector("[autofocus]");
if (autoFocus) {
autoFocus.focus();
}
}
});
// After a successful HTMX DELETE, redirect if the element has a data-redirect attribute.
document.body.addEventListener("htmx:afterRequest", function (event) {
if (event.detail.successful && event.detail.verb === "delete") {
var redirect = event.detail.elt.getAttribute("data-redirect");
if (redirect) {
window.location.href = redirect;
}
}
});
// Tag autocomplete: add a selected tag to the tag input.
window.addTag = function (element, tagName) {
var input = document.getElementById("tags");
if (!input) return;
var parts = input.value.split(",").map(function (s) { return s.trim(); });
// Replace the last (incomplete) segment with the selected tag.
parts[parts.length - 1] = tagName;
// Add a trailing separator so the user can keep typing.
input.value = parts.join(", ") + ", ";
input.focus();
// Clear suggestions by removing all child elements.
var suggestions = document.getElementById("tag-suggestions");
if (suggestions) {
while (suggestions.firstChild) {
suggestions.removeChild(suggestions.firstChild);
}
}
};
function getCookie(name) {
var match = document.cookie.match(new RegExp("(^| )" + name + "=([^;]+)"));
return match ? match[2] : null;
}
})();

1
web/static/vendor/htmx.min.js vendored Normal file

File diff suppressed because one or more lines are too long

4
web/static/vendor/pico.min.css vendored Normal file

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,62 @@
{{define "base.html"}}<!DOCTYPE html>
<html lang="nb">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{if .Title}}{{.Title}} — {{end}}{{.SiteName}}</title>
<link rel="stylesheet" href="{{basePath}}/static/vendor/pico.min.css">
<link rel="stylesheet" href="{{basePath}}/static/css/style.css">
{{block "head" .}}{{end}}
</head>
<body>
<a href="#main-content" class="skip-link">Hopp til hovedinnhold</a>
<header class="container">
<nav aria-label="Hovednavigasjon">
<ul>
<li><a href="{{basePath}}/" class="site-title"><strong>{{.SiteName}}</strong></a></li>
</ul>
<ul>
{{if .User}}
<li><a href="{{basePath}}/faves">Mine favoritter</a></li>
<li><a href="{{basePath}}/u/{{.User.Username}}">Profil</a></li>
{{if .User.IsAdmin}}
<li><a href="{{basePath}}/admin">Admin</a></li>
{{end}}
<li>
<form method="POST" action="{{basePath}}/logout" class="inline-form">
<input type="hidden" name="csrf_token" value="{{.CSRFToken}}">
<button type="submit" class="outline secondary nav-button">Logg ut</button>
</form>
</li>
{{else}}
<li><a href="{{basePath}}/login">Logg inn</a></li>
<li><a href="{{basePath}}/signup">Registrer</a></li>
{{end}}
</ul>
</nav>
</header>
<main id="main-content" class="container">
{{if .Flash}}
<div class="flash flash-{{.FlashType}}" role="alert">
{{.Flash}}
</div>
{{end}}
{{block "content" .}}{{end}}
</main>
<footer class="container">
<hr>
<p>
<small>
Drevet av <a href="https://kode.naiv.no/olemd/favoritter" target="_blank" rel="noopener">Favoritter</a>
— fri programvare under <a href="https://www.gnu.org/licenses/agpl-3.0.html" target="_blank" rel="noopener">AGPL-3.0</a>
</small>
</p>
</footer>
<script src="{{basePath}}/static/vendor/htmx.min.js"></script>
<script src="{{basePath}}/static/js/app.js"></script>
</body>
</html>{{end}}

View file

@ -0,0 +1,73 @@
{{define "head"}}
{{with .Data}}{{with .Fave}}
{{if eq .Privacy "public"}}
<meta property="og:title" content="{{truncate 70 .Description}}">
<meta property="og:description" content="En favoritt av {{.DisplayName}} på {{$.SiteName}}">
<meta property="og:type" content="article">
{{if $.ExternalURL}}
<meta property="og:url" content="{{$.ExternalURL}}/faves/{{.ID}}">
{{if .ImagePath}}
<meta property="og:image" content="{{$.ExternalURL}}/uploads/{{.ImagePath}}">
<meta name="twitter:card" content="summary_large_image">
{{else}}
<meta name="twitter:card" content="summary">
{{end}}
{{end}}
<meta property="og:site_name" content="{{$.SiteName}}">
{{range .Tags}}
<meta property="article:tag" content="{{.Name}}">
{{end}}
{{end}}
{{end}}{{end}}
{{end}}
{{define "content"}}
{{with .Data}}
<article>
{{with .Fave}}
{{if .ImagePath}}
<img src="{{basePath}}/uploads/{{.ImagePath}}"
alt="Bilde for: {{.Description}}">
{{end}}
<header>
<h1>{{.Description}}</h1>
<p>
Av <a href="{{basePath}}/u/{{.Username}}">{{.DisplayName}}</a>
{{if eq .Privacy "private"}}
<small class="badge-private" aria-label="Privat">Privat</small>
{{end}}
</p>
</header>
{{if .URL}}
<p><a href="{{.URL}}" target="_blank" rel="noopener noreferrer">{{.URL}}</a></p>
{{end}}
{{if .Tags}}
<p>
{{range .Tags}}
<a href="{{basePath}}/tags/{{.Name}}" class="tag-chip">{{.Name}}</a>
{{end}}
</p>
{{end}}
<footer>
<small>Lagt til {{.CreatedAt.Format "02.01.2006"}}</small>
{{if $.IsOwner}}
<nav class="fave-actions">
<a href="{{basePath}}/faves/{{.ID}}/edit" role="button" class="outline">Rediger</a>
<button
hx-delete="{{basePath}}/faves/{{.ID}}"
hx-confirm="Er du sikker på at du vil slette denne favoritten?"
hx-headers='{"X-CSRF-Token": "{{$.CSRFToken}}"}'
class="outline secondary"
data-redirect="{{basePath}}/faves"
>Slett</button>
</nav>
{{end}}
</footer>
{{end}}
</article>
{{end}}
{{end}}

View file

@ -0,0 +1,92 @@
{{define "content"}}
<article>
{{with .Data}}
{{if .IsNew}}
<h1>Ny favoritt</h1>
{{else}}
<h1>Rediger favoritt</h1>
{{end}}
<form method="POST"
enctype="multipart/form-data"
{{if .IsNew}}
action="{{basePath}}/faves"
{{else}}
action="{{basePath}}/faves/{{.Fave.ID}}"
{{end}}>
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<label for="description">
Beskrivelse *
<input type="text" id="description" name="description"
value="{{.Description}}" required autofocus
placeholder="F.eks. «Blade Runner 2049» eller «Rød tulipan»">
</label>
<label for="url">
Lenke (valgfri)
<input type="url" id="url" name="url"
value="{{.URL}}"
placeholder="https://...">
</label>
<label for="image">
Bilde (valgfri)
<input type="file" id="image" name="image"
accept="image/jpeg,image/png,image/gif,image/webp">
</label>
{{if not .IsNew}}
{{if .Fave.ImagePath}}
<div class="current-image">
<img src="{{basePath}}/uploads/{{.Fave.ImagePath}}"
alt="Nåværende bilde"
style="max-width: 200px; max-height: 200px;">
<label>
<input type="checkbox" name="remove_image" value="1">
Fjern bilde
</label>
</div>
{{end}}
{{end}}
<label for="tags">
Merkelapper (kommaseparert)
<input type="text" id="tags" name="tags"
value="{{.Tags}}"
placeholder="film, sci-fi, favoritt"
autocomplete="off"
hx-get="{{basePath}}/tags/search"
hx-trigger="keyup changed delay:300ms"
hx-target="#tag-suggestions"
hx-params="*"
hx-vals='{"q": ""}'
aria-describedby="tags-help"
aria-autocomplete="list"
aria-controls="tag-suggestions">
<small id="tags-help">Skriv for å søke i eksisterende merkelapper. Maks {{maxTags}} stk.</small>
</label>
<ul id="tag-suggestions" role="listbox" class="tag-suggestions" aria-label="Merkelappforslag"></ul>
<fieldset>
<legend>Synlighet</legend>
<label>
<input type="radio" name="privacy" value="public"
{{if eq .Privacy "public"}}checked{{end}}
{{if .IsNew}}{{if eq .DefaultPrivacy "public"}}checked{{end}}{{end}}>
Offentlig
</label>
<label>
<input type="radio" name="privacy" value="private"
{{if eq .Privacy "private"}}checked{{end}}
{{if .IsNew}}{{if eq .DefaultPrivacy "private"}}checked{{end}}{{end}}>
Privat
</label>
</fieldset>
<button type="submit">
{{if .IsNew}}Legg til{{else}}Lagre{{end}}
</button>
</form>
{{end}}
</article>
{{end}}

View file

@ -0,0 +1,56 @@
{{define "content"}}
<header>
<hgroup>
<h1>Mine favoritter</h1>
<p>{{with .Data}}{{.Total}} favoritter totalt{{end}}</p>
</hgroup>
<a href="{{basePath}}/faves/new" role="button">+ Ny favoritt</a>
</header>
{{with .Data}}
{{if .Faves}}
<div class="fave-grid" role="list">
{{range .Faves}}
<article class="fave-card" role="listitem">
{{if .ImagePath}}
<img src="{{basePath}}/uploads/{{.ImagePath}}"
alt="Bilde for: {{.Description}}"
loading="lazy">
{{end}}
<header>
<a href="{{basePath}}/faves/{{.ID}}">
<strong>{{.Description}}</strong>
</a>
{{if eq .Privacy "private"}}
<small class="badge-private" aria-label="Privat">Privat</small>
{{end}}
</header>
{{if .Tags}}
<footer>
{{range .Tags}}
<a href="{{basePath}}/tags/{{.Name}}" class="tag-chip">{{.Name}}</a>
{{end}}
</footer>
{{end}}
</article>
{{end}}
</div>
{{if gt .TotalPages 1}}
<nav aria-label="Sidenavigasjon">
<ul>
{{if gt .Page 1}}
<li><a href="{{basePath}}/faves?page={{subtract .Page 1}}">← Forrige</a></li>
{{end}}
<li>Side {{.Page}} av {{.TotalPages}}</li>
{{if lt .Page .TotalPages}}
<li><a href="{{basePath}}/faves?page={{add .Page 1}}">Neste →</a></li>
{{end}}
</ul>
</nav>
{{end}}
{{else}}
<p>Du har ingen favoritter ennå. <a href="{{basePath}}/faves/new">Legg til din første!</a></p>
{{end}}
{{end}}
{{end}}

View file

@ -0,0 +1,13 @@
{{define "content"}}
<hgroup>
<h1>Velkommen til {{.SiteName}}</h1>
<p>Del dine favoritter med verden — eller behold dem for deg selv.</p>
</hgroup>
{{if not .User}}
<div class="grid">
<a href="{{basePath}}/login" role="button">Logg inn</a>
<a href="{{basePath}}/signup" role="button" class="outline">Registrer deg</a>
</div>
{{end}}
{{end}}

View file

@ -0,0 +1,24 @@
{{define "head"}}
<meta name="robots" content="noindex">
{{end}}
{{define "content"}}
<article>
<h1>Logg inn</h1>
<form method="POST" action="{{basePath}}/login">
<input type="hidden" name="csrf_token" value="{{.CSRFToken}}">
<label for="username">
Brukernavn
<input type="text" id="username" name="username" required autofocus
autocomplete="username" autocapitalize="none">
</label>
<label for="password">
Passord
<input type="password" id="password" name="password" required
autocomplete="current-password">
</label>
<button type="submit">Logg inn</button>
</form>
<p><a href="{{basePath}}/signup">Har du ikke konto? Registrer deg</a></p>
</article>
{{end}}

View file

@ -0,0 +1,24 @@
{{define "head"}}
<meta name="robots" content="noindex">
{{end}}
{{define "content"}}
<article>
<h1>Endre passord</h1>
<p>Du må velge et nytt passord før du kan fortsette.</p>
<form method="POST" action="{{basePath}}/reset-password">
<input type="hidden" name="csrf_token" value="{{.CSRFToken}}">
<label for="password">
Nytt passord
<input type="password" id="password" name="password" required autofocus
autocomplete="new-password" minlength="8">
</label>
<label for="password_confirm">
Bekreft nytt passord
<input type="password" id="password_confirm" name="password_confirm" required
autocomplete="new-password">
</label>
<button type="submit">Lagre nytt passord</button>
</form>
</article>
{{end}}

View file

@ -0,0 +1,62 @@
{{define "head"}}
<meta name="robots" content="noindex">
{{end}}
{{define "content"}}
<article>
{{with .Data}}
{{if eq .Mode "closed"}}
<h1>Registrering stengt</h1>
<p>Nye registreringer er for øyeblikket ikke tilgjengelig. Kontakt administrator for tilgang.</p>
{{else if eq .Mode "requests"}}
<h1>Be om tilgang</h1>
<p>Nye brukere må godkjennes av en administrator.</p>
<form method="POST" action="{{basePath}}/signup">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<label for="username">
Brukernavn
<input type="text" id="username" name="username" required autofocus
autocomplete="username" autocapitalize="none"
pattern="[a-zA-Z0-9_-]+" title="Bare bokstaver, tall, bindestrek og understrek"
minlength="2" maxlength="30">
</label>
<label for="password">
Passord
<input type="password" id="password" name="password" required
autocomplete="new-password" minlength="8">
</label>
<label for="password_confirm">
Bekreft passord
<input type="password" id="password_confirm" name="password_confirm" required
autocomplete="new-password">
</label>
<button type="submit">Send forespørsel</button>
</form>
{{else}}
<h1>Registrer deg</h1>
<form method="POST" action="{{basePath}}/signup">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<label for="username">
Brukernavn
<input type="text" id="username" name="username" required autofocus
autocomplete="username" autocapitalize="none"
pattern="[a-zA-Z0-9_-]+" title="Bare bokstaver, tall, bindestrek og understrek"
minlength="2" maxlength="30">
</label>
<label for="password">
Passord
<input type="password" id="password" name="password" required
autocomplete="new-password" minlength="8">
</label>
<label for="password_confirm">
Bekreft passord
<input type="password" id="password_confirm" name="password_confirm" required
autocomplete="new-password">
</label>
<button type="submit">Registrer</button>
</form>
{{end}}
{{end}}
<p><a href="{{basePath}}/login">Har du allerede konto? Logg inn</a></p>
</article>
{{end}}

View file

@ -0,0 +1,51 @@
{{define "content"}}
{{with .Data}}
<hgroup>
<h1>Merkelapp: {{.TagName}}</h1>
<p>{{.Total}} offentlige favoritter</p>
</hgroup>
{{if .Faves}}
<div class="fave-grid" role="list">
{{range .Faves}}
<article class="fave-card" role="listitem">
{{if .ImagePath}}
<img src="{{basePath}}/uploads/{{.ImagePath}}"
alt="Bilde for: {{.Description}}"
loading="lazy">
{{end}}
<header>
<a href="{{basePath}}/faves/{{.ID}}">
<strong>{{.Description}}</strong>
</a>
<small>av <a href="{{basePath}}/u/{{.Username}}">{{.DisplayName}}</a></small>
</header>
{{if .Tags}}
<footer>
{{range .Tags}}
<a href="{{basePath}}/tags/{{.Name}}" class="tag-chip">{{.Name}}</a>
{{end}}
</footer>
{{end}}
</article>
{{end}}
</div>
{{if gt .TotalPages 1}}
<nav aria-label="Sidenavigasjon">
<ul>
{{if gt .Page 1}}
<li><a href="{{basePath}}/tags/{{.TagName}}?page={{subtract .Page 1}}">← Forrige</a></li>
{{end}}
<li>Side {{.Page}} av {{.TotalPages}}</li>
{{if lt .Page .TotalPages}}
<li><a href="{{basePath}}/tags/{{.TagName}}?page={{add .Page 1}}">Neste →</a></li>
{{end}}
</ul>
</nav>
{{end}}
{{else}}
<p>Ingen offentlige favoritter med denne merkelappen.</p>
{{end}}
{{end}}
{{end}}

View file

@ -0,0 +1,6 @@
{{range .}}<li role="option"
class="tag-suggestion"
onclick="addTag(this, '{{.Name}}')"
onkeydown="if(event.key==='Enter'){addTag(this, '{{.Name}}')}"
tabindex="0">{{.Name}}</li>
{{end}}