Compare commits
No commits in common. "main" and "0.10.0" have entirely different histories.
11 changed files with 94 additions and 330 deletions
16
README.md
16
README.md
|
|
@ -1,8 +1,12 @@
|
||||||
# gonotes
|
# gonotes
|
||||||
|
|
||||||
A shared notebook of sorts implemented in go. Shared here means that the
|
A toyish project for a shared notebook of sorts implemented in go. It's mostly
|
||||||
content is visible to more than one user. It does not currently support
|
a learning opportunity for using go, and partially an intent to end up with a
|
||||||
simultaneous editing and there are no plans to do that. Furthe, it
|
shared notebook!
|
||||||
*currently* does not support the concept of a lock or checkout when a note
|
|
||||||
is edited. It's the responsibility of the editing parties to prevent races
|
It's not shared in the sense of simultaneous editing, don't do that!
|
||||||
and conflicts.
|
|
||||||
|
## TODO
|
||||||
|
|
||||||
|
* handle static urls in the django url mapping style
|
||||||
|
* Style up the templates better
|
||||||
|
|
|
||||||
|
|
@ -12,26 +12,18 @@ import (
|
||||||
"forgejo.gwairfelin.com/max/gonotes/internal/middleware"
|
"forgejo.gwairfelin.com/max/gonotes/internal/middleware"
|
||||||
"forgejo.gwairfelin.com/max/gonotes/internal/notes"
|
"forgejo.gwairfelin.com/max/gonotes/internal/notes"
|
||||||
"forgejo.gwairfelin.com/max/gonotes/internal/notes/views"
|
"forgejo.gwairfelin.com/max/gonotes/internal/notes/views"
|
||||||
"golang.org/x/oauth2"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
var confFile string
|
var confFile string
|
||||||
|
|
||||||
|
sessions := middleware.NewSessionStore()
|
||||||
|
|
||||||
flag.StringVar(&confFile, "c", "/etc/gonotes/conf.toml", "Specify path to config file.")
|
flag.StringVar(&confFile, "c", "/etc/gonotes/conf.toml", "Specify path to config file.")
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
|
|
||||||
conf.LoadConfig(confFile)
|
conf.LoadConfig(confFile)
|
||||||
|
|
||||||
oauth := &oauth2.Config{
|
|
||||||
ClientID: conf.Conf.OIDC.ClientID,
|
|
||||||
ClientSecret: conf.Conf.OIDC.ClientSecret,
|
|
||||||
Endpoint: oauth2.Endpoint{AuthURL: conf.Conf.OIDC.AuthURL, TokenURL: conf.Conf.OIDC.TokenURL},
|
|
||||||
RedirectURL: conf.Conf.OIDC.RedirectURL,
|
|
||||||
}
|
|
||||||
|
|
||||||
sessions := middleware.NewSessionStore(oauth, "/auth")
|
|
||||||
|
|
||||||
err := notes.Init()
|
err := notes.Init()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
|
|
@ -41,7 +33,6 @@ func main() {
|
||||||
|
|
||||||
router := http.NewServeMux()
|
router := http.NewServeMux()
|
||||||
notesRouter := views.GetRoutes("/notes")
|
notesRouter := views.GetRoutes("/notes")
|
||||||
sessionRouter := sessions.Routes.GetRouter()
|
|
||||||
|
|
||||||
cacheExpiration, err := time.ParseDuration("24h")
|
cacheExpiration, err := time.ParseDuration("24h")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -50,21 +41,31 @@ func main() {
|
||||||
|
|
||||||
etag := middleware.NewETag("static", cacheExpiration)
|
etag := middleware.NewETag("static", cacheExpiration)
|
||||||
|
|
||||||
|
if !conf.Conf.Production {
|
||||||
|
router.HandleFunc("/login/", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
user := r.FormValue("user")
|
||||||
|
if len(user) == 0 {
|
||||||
|
user = "anon"
|
||||||
|
}
|
||||||
|
sessions.Login(user, w)
|
||||||
|
|
||||||
|
http.Redirect(w, r, "/notes/", http.StatusFound)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
router.Handle("/logout/", sessions.AsMiddleware(
|
||||||
|
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
user := r.FormValue("user")
|
||||||
|
if len(user) == 0 {
|
||||||
|
user = "anon"
|
||||||
|
}
|
||||||
|
|
||||||
|
sessions.Logout(w, r)
|
||||||
|
|
||||||
|
http.Redirect(w, r, "/notes/", http.StatusFound)
|
||||||
|
})))
|
||||||
|
|
||||||
router.Handle("/", middleware.LoggingMiddleware(http.RedirectHandler("/notes/", http.StatusFound)))
|
router.Handle("/", middleware.LoggingMiddleware(http.RedirectHandler("/notes/", http.StatusFound)))
|
||||||
router.Handle(
|
router.Handle("/notes/", sessions.AsMiddleware(middleware.LoggingMiddleware(http.StripPrefix("/notes", notesRouter))))
|
||||||
"/notes/",
|
|
||||||
sessions.AsMiddleware(
|
|
||||||
middleware.LoggingMiddleware(
|
|
||||||
middleware.RejectAnonMiddleware(
|
|
||||||
"/auth/login/",
|
|
||||||
http.StripPrefix(
|
|
||||||
"/notes", notesRouter,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
router.Handle("/auth/", sessions.AsMiddleware(middleware.LoggingMiddleware(http.StripPrefix("/auth", sessionRouter))))
|
|
||||||
router.Handle(
|
router.Handle(
|
||||||
"/static/",
|
"/static/",
|
||||||
middleware.LoggingMiddleware(
|
middleware.LoggingMiddleware(
|
||||||
|
|
|
||||||
8
go.mod
8
go.mod
|
|
@ -8,7 +8,9 @@ require (
|
||||||
forgejo.gwairfelin.com/max/gispatcho v0.1.2
|
forgejo.gwairfelin.com/max/gispatcho v0.1.2
|
||||||
github.com/pelletier/go-toml/v2 v2.2.3
|
github.com/pelletier/go-toml/v2 v2.2.3
|
||||||
github.com/teekennedy/goldmark-markdown v0.5.1
|
github.com/teekennedy/goldmark-markdown v0.5.1
|
||||||
github.com/yuin/goldmark-meta v1.1.0
|
)
|
||||||
golang.org/x/oauth2 v0.34.0
|
|
||||||
gopkg.in/yaml.v2 v2.3.0
|
require (
|
||||||
|
github.com/yuin/goldmark-meta v1.1.0 // indirect
|
||||||
|
gopkg.in/yaml.v2 v2.3.0 // indirect
|
||||||
)
|
)
|
||||||
|
|
|
||||||
3
go.sum
3
go.sum
|
|
@ -18,9 +18,6 @@ github.com/yuin/goldmark-meta v1.1.0 h1:pWw+JLHGZe8Rk0EGsMVssiNb/AaPMHfSRszZeUei
|
||||||
github.com/yuin/goldmark-meta v1.1.0/go.mod h1:U4spWENafuA7Zyg+Lj5RqK/MF+ovMYtBvXi1lBb2VP0=
|
github.com/yuin/goldmark-meta v1.1.0/go.mod h1:U4spWENafuA7Zyg+Lj5RqK/MF+ovMYtBvXi1lBb2VP0=
|
||||||
go.abhg.dev/goldmark/toc v0.11.0 h1:IRixVy3/yVPKvFBc37EeBPi8XLTXrtH6BYaonSjkF8o=
|
go.abhg.dev/goldmark/toc v0.11.0 h1:IRixVy3/yVPKvFBc37EeBPi8XLTXrtH6BYaonSjkF8o=
|
||||||
go.abhg.dev/goldmark/toc v0.11.0/go.mod h1:XMFIoI1Sm6dwF9vKzVDOYE/g1o5BmKXghLG8q/wJNww=
|
go.abhg.dev/goldmark/toc v0.11.0/go.mod h1:XMFIoI1Sm6dwF9vKzVDOYE/g1o5BmKXghLG8q/wJNww=
|
||||||
golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw=
|
|
||||||
golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
|
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
|
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
|
||||||
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
|
|
|
||||||
|
|
@ -1,66 +0,0 @@
|
||||||
package auth
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/rand"
|
|
||||||
"encoding/base64"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"forgejo.gwairfelin.com/max/gonotes/internal/conf"
|
|
||||||
"golang.org/x/oauth2"
|
|
||||||
)
|
|
||||||
|
|
||||||
func GenerateStateOAUTHCookie(w http.ResponseWriter, prefix string) string {
|
|
||||||
|
|
||||||
b := make([]byte, 16)
|
|
||||||
rand.Read(b)
|
|
||||||
state := base64.URLEncoding.EncodeToString(b)
|
|
||||||
cookie := http.Cookie{
|
|
||||||
Name: "oauthstate", Value: state,
|
|
||||||
MaxAge: 30, Secure: true, HttpOnly: true, Path: prefix,
|
|
||||||
}
|
|
||||||
http.SetCookie(w, &cookie)
|
|
||||||
|
|
||||||
return state
|
|
||||||
}
|
|
||||||
|
|
||||||
func GetUserFromForgejo(code string, oauth *oauth2.Config) (string, error) {
|
|
||||||
// Use code to get token and get user info from Google.
|
|
||||||
|
|
||||||
token, err := oauth.Exchange(context.Background(), code)
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("code exchange wrong: %s", err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
request, err := http.NewRequest("GET", conf.Conf.OIDC.UserinfoURL, nil)
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("failed to init http client for userinfo: %s", err.Error())
|
|
||||||
}
|
|
||||||
request.Header.Set("Authorization", fmt.Sprintf("token %s", token.AccessToken))
|
|
||||||
response, err := http.DefaultClient.Do(request)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("failed getting user info: %s", err.Error())
|
|
||||||
}
|
|
||||||
defer response.Body.Close()
|
|
||||||
|
|
||||||
uInf := make(map[string]any)
|
|
||||||
|
|
||||||
err = json.NewDecoder(response.Body).Decode(&uInf)
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("failed to parse response as json: %s", err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
username, ok := uInf["preferred_username"]
|
|
||||||
if !ok {
|
|
||||||
return "", fmt.Errorf("no username in response: %s", err.Error())
|
|
||||||
}
|
|
||||||
userStr, ok := username.(string)
|
|
||||||
if !ok {
|
|
||||||
return "", fmt.Errorf("username not a string: %s", err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
return userStr, nil
|
|
||||||
}
|
|
||||||
|
|
@ -60,15 +60,6 @@ type Config struct {
|
||||||
NotesDir string
|
NotesDir string
|
||||||
LogAccess bool
|
LogAccess bool
|
||||||
Production bool
|
Production bool
|
||||||
OIDC struct {
|
|
||||||
ClientID string `toml:"client_id"`
|
|
||||||
ClientSecret string `toml:"client_secret"`
|
|
||||||
AuthURL string `toml:"auth_url"`
|
|
||||||
TokenURL string `toml:"token_url"`
|
|
||||||
RedirectURL string `toml:"redirect_url"`
|
|
||||||
UserinfoURL string `toml:"userinfo_url"`
|
|
||||||
}
|
|
||||||
AnonCIDRs []string `toml:"anon_networks"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
|
|
||||||
|
|
@ -62,15 +62,9 @@
|
||||||
</ul>
|
</ul>
|
||||||
</li>
|
</li>
|
||||||
{{template "navLinks" .}}
|
{{template "navLinks" .}}
|
||||||
{{if eq .user "anon"}}
|
|
||||||
<li>
|
<li>
|
||||||
<a class="nav-link" href="/auth/login/">Login</a>
|
<a class="nav-link" href="/logout/">Logout {{.user}}</a>
|
||||||
</li>
|
</li>
|
||||||
{{else}}
|
|
||||||
<li>
|
|
||||||
<a class="nav-link" href="/auth/logout/">Logout {{.user}}</a>
|
|
||||||
</li>
|
|
||||||
{{end}}
|
|
||||||
</ul>
|
</ul>
|
||||||
{{template "navExtra" .}}
|
{{template "navExtra" .}}
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -1,99 +0,0 @@
|
||||||
// Middleware designed to reject requests from anon users unless from 'safe'
|
|
||||||
// IP addresses
|
|
||||||
|
|
||||||
package middleware
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"forgejo.gwairfelin.com/max/gonotes/internal/conf"
|
|
||||||
)
|
|
||||||
|
|
||||||
type netList []net.IPNet
|
|
||||||
|
|
||||||
const ipHeader = "x-forwarded-for"
|
|
||||||
|
|
||||||
// Check if any IPNet in the netList contains the given IP
|
|
||||||
func (n *netList) Contains(ip net.IP) bool {
|
|
||||||
for _, net := range *n {
|
|
||||||
if contains := net.Contains(ip); contains {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// Redirect to redirect url any request where the user is anon and the request
|
|
||||||
// does not appear to come from a safe origin
|
|
||||||
func RejectAnonMiddleware(redirect string, next http.Handler) http.Handler {
|
|
||||||
safeOriginNets := make(netList, 0, len(conf.Conf.AnonCIDRs))
|
|
||||||
|
|
||||||
for _, cidr := range conf.Conf.AnonCIDRs {
|
|
||||||
_, net, err := net.ParseCIDR(cidr)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("ignoring invalid cidr: %s", err)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
safeOriginNets = append(safeOriginNets, *net)
|
|
||||||
}
|
|
||||||
|
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
user := r.Context().Value(ContextKey("user")).(string)
|
|
||||||
|
|
||||||
originIP, err := getOriginIP(r)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("unable to check origin ip: %s", err)
|
|
||||||
http.Redirect(w, r, redirect, http.StatusTemporaryRedirect)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Printf("origin ip: %s", originIP)
|
|
||||||
safeOrigin := safeOriginNets.Contains(originIP)
|
|
||||||
|
|
||||||
if user == "anon" && !safeOrigin {
|
|
||||||
http.Redirect(w, r, redirect, http.StatusTemporaryRedirect)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
next.ServeHTTP(w, r)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the origin ip from the x-forwarded-for header, or the source of
|
|
||||||
// the request if not available
|
|
||||||
func getOriginIP(r *http.Request) (net.IP, error) {
|
|
||||||
sourceIpHeader, ok := r.Header[http.CanonicalHeaderKey(ipHeader)]
|
|
||||||
|
|
||||||
if !ok {
|
|
||||||
addrParts := strings.Split(r.RemoteAddr, ":")
|
|
||||||
|
|
||||||
if len(addrParts) == 0 {
|
|
||||||
return nil, errors.New("no source ip available")
|
|
||||||
}
|
|
||||||
|
|
||||||
ip := net.ParseIP(addrParts[0])
|
|
||||||
if ip == nil {
|
|
||||||
return nil, fmt.Errorf("ip could not be parsed: %s", addrParts[0])
|
|
||||||
}
|
|
||||||
return ip, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(sourceIpHeader) != 1 {
|
|
||||||
return nil, fmt.Errorf("header has more than 1 value: %s=%v", ipHeader, sourceIpHeader)
|
|
||||||
}
|
|
||||||
|
|
||||||
ips := strings.Split(sourceIpHeader[0], ",")
|
|
||||||
ip := net.ParseIP(ips[0])
|
|
||||||
if ip == nil {
|
|
||||||
return nil, fmt.Errorf("not parseable as ip: %s", ips[0])
|
|
||||||
}
|
|
||||||
|
|
||||||
return ip, nil
|
|
||||||
}
|
|
||||||
|
|
@ -4,12 +4,7 @@ package middleware
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"log"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
urls "forgejo.gwairfelin.com/max/gispatcho"
|
|
||||||
"forgejo.gwairfelin.com/max/gonotes/internal/auth"
|
|
||||||
"golang.org/x/oauth2"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Session struct {
|
type Session struct {
|
||||||
|
|
@ -18,29 +13,14 @@ type Session struct {
|
||||||
|
|
||||||
type SessionStore struct {
|
type SessionStore struct {
|
||||||
sessions map[string]Session
|
sessions map[string]Session
|
||||||
oauth *oauth2.Config
|
|
||||||
Routes urls.URLs
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type ContextKey string
|
type ContextKey string
|
||||||
|
|
||||||
func NewSessionStore(oauth *oauth2.Config, prefix string) SessionStore {
|
func NewSessionStore() SessionStore {
|
||||||
store := SessionStore{
|
return SessionStore{sessions: make(map[string]Session, 10)}
|
||||||
sessions: make(map[string]Session, 10),
|
|
||||||
oauth: oauth,
|
|
||||||
}
|
|
||||||
store.Routes = urls.URLs{
|
|
||||||
Prefix: prefix,
|
|
||||||
URLs: map[string]urls.URL{
|
|
||||||
"login": {Path: "/login/", Protocol: "GET", Handler: store.LoginViewOAUTH},
|
|
||||||
"callback": {Path: "/callback/", Protocol: "GET", Handler: store.CallbackViewOAUTH},
|
|
||||||
"logout": {Path: "/logout/", Protocol: "GET", Handler: store.LogoutView},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
return store
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Log a user in
|
|
||||||
func (s *SessionStore) Login(user string, w http.ResponseWriter) string {
|
func (s *SessionStore) Login(user string, w http.ResponseWriter) string {
|
||||||
sessionID := rand.Text()
|
sessionID := rand.Text()
|
||||||
s.sessions[sessionID] = Session{User: user}
|
s.sessions[sessionID] = Session{User: user}
|
||||||
|
|
@ -54,8 +34,7 @@ func (s *SessionStore) Login(user string, w http.ResponseWriter) string {
|
||||||
return sessionID
|
return sessionID
|
||||||
}
|
}
|
||||||
|
|
||||||
// View to logout a user
|
func (s *SessionStore) Logout(w http.ResponseWriter, r *http.Request) {
|
||||||
func (s *SessionStore) LogoutView(w http.ResponseWriter, r *http.Request) {
|
|
||||||
session := r.Context().Value(ContextKey("session")).(string)
|
session := r.Context().Value(ContextKey("session")).(string)
|
||||||
|
|
||||||
delete(s.sessions, session)
|
delete(s.sessions, session)
|
||||||
|
|
@ -65,68 +44,42 @@ func (s *SessionStore) LogoutView(w http.ResponseWriter, r *http.Request) {
|
||||||
}
|
}
|
||||||
|
|
||||||
http.SetCookie(w, &cookie)
|
http.SetCookie(w, &cookie)
|
||||||
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// View to log in a user via oauth
|
|
||||||
func (s *SessionStore) LoginViewOAUTH(w http.ResponseWriter, r *http.Request) {
|
|
||||||
log.Printf("%+v", *s.oauth)
|
|
||||||
|
|
||||||
oauthState := auth.GenerateStateOAUTHCookie(w, s.Routes.Prefix)
|
|
||||||
|
|
||||||
url := s.oauth.AuthCodeURL(oauthState)
|
|
||||||
log.Printf("Redirecting to %s", url)
|
|
||||||
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Oauth callback view
|
|
||||||
func (s *SessionStore) CallbackViewOAUTH(w http.ResponseWriter, r *http.Request) {
|
|
||||||
// Read oauthState from Cookie
|
|
||||||
oauthState, err := r.Cookie("oauthstate")
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("An error occured during login: %s", err)
|
|
||||||
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Printf("%v", oauthState)
|
|
||||||
|
|
||||||
if r.FormValue("state") != oauthState.Value {
|
|
||||||
log.Println("invalid oauth state")
|
|
||||||
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
username, err := auth.GetUserFromForgejo(r.FormValue("code"), s.oauth)
|
|
||||||
if err != nil {
|
|
||||||
log.Println(err.Error())
|
|
||||||
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
s.Login(username, w)
|
|
||||||
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Turn the session store into a middleware.
|
|
||||||
// Sets the user on the context based on the available session cookie
|
|
||||||
func (s *SessionStore) AsMiddleware(next http.Handler) http.Handler {
|
func (s *SessionStore) AsMiddleware(next http.Handler) http.Handler {
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
sessionCookie, err := r.Cookie("id")
|
sessionCookie, err := r.Cookie("id")
|
||||||
user := "anon"
|
// No session yet
|
||||||
var cookieVal string
|
if err != nil {
|
||||||
// Session exists
|
user := r.Header.Get("X-Auth-Request-User")
|
||||||
if err == nil {
|
|
||||||
session, ok := s.sessions[sessionCookie.Value]
|
|
||||||
|
|
||||||
// Session not expired
|
if user != "" {
|
||||||
if ok {
|
sessionID := s.Login(user, w)
|
||||||
user = session.User
|
nextWithSessionContext(w, r, next, user, sessionID)
|
||||||
cookieVal = sessionCookie.Value
|
} else {
|
||||||
|
http.Redirect(w, r, "/login/", http.StatusFound)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
nextWithSessionContext(w, r, next, user, cookieVal)
|
session, ok := s.sessions[sessionCookie.Value]
|
||||||
|
|
||||||
|
// Session expired
|
||||||
|
if !ok {
|
||||||
|
user := r.Header.Get("X-Auth-Request-User")
|
||||||
|
|
||||||
|
if user != "" {
|
||||||
|
sessionID := s.Login(user, w)
|
||||||
|
nextWithSessionContext(w, r, next, user, sessionID)
|
||||||
|
} else {
|
||||||
|
http.Redirect(w, r, "/login/", http.StatusFound)
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
nextWithSessionContext(w, r, next, session.User, sessionCookie.Value)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -5,16 +5,13 @@ package notes
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
"bytes"
|
"bytes"
|
||||||
"cmp"
|
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"html/template"
|
"html/template"
|
||||||
"log"
|
"log"
|
||||||
"maps"
|
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"slices"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
|
@ -101,26 +98,14 @@ func Init() error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ns *noteSet) Sort() []*Note {
|
|
||||||
orderByTitle := func(a, b *Note) int {
|
|
||||||
return cmp.Compare(a.Title, b.Title)
|
|
||||||
}
|
|
||||||
return slices.SortedFunc(maps.Keys(*ns), orderByTitle)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ns *NoteStore) Get(owner string) noteSet {
|
func (ns *NoteStore) Get(owner string) noteSet {
|
||||||
return ns.notes[owner]
|
return ns.notes[owner]
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ns *NoteStore) GetOrdered(owner string) []*Note {
|
|
||||||
notes := ns.Get(owner)
|
|
||||||
return notes.Sort()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ns *NoteStore) GetOne(owner string, uid string) (*Note, bool) {
|
func (ns *NoteStore) GetOne(owner string, uid string) (*Note, bool) {
|
||||||
notes := ns.Get(owner)
|
notes := ns.Get(owner)
|
||||||
|
|
||||||
for note := range notes {
|
for note, _ := range notes {
|
||||||
if note.Uid == uid {
|
if note.Uid == uid {
|
||||||
log.Printf("Found single note during GetOne %s", note.Title)
|
log.Printf("Found single note during GetOne %s", note.Title)
|
||||||
return note, true
|
return note, true
|
||||||
|
|
@ -136,9 +121,8 @@ func (ns *NoteStore) Add(note *Note, user string) {
|
||||||
ns.notes[user][note] = true
|
ns.notes[user][note] = true
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ns *NoteStore) Del(note *Note, user string) error {
|
func (ns *NoteStore) Del(note *Note, user string) {
|
||||||
delete(ns.notes[user], note)
|
delete(ns.notes[user], note)
|
||||||
return note.Delete()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ns *NoteStore) UserTags(user string) []string {
|
func (ns *NoteStore) UserTags(user string) []string {
|
||||||
|
|
@ -161,7 +145,13 @@ func (ns *NoteStore) UserTags(user string) []string {
|
||||||
|
|
||||||
log.Printf("Tagset is %v", tagSet)
|
log.Printf("Tagset is %v", tagSet)
|
||||||
|
|
||||||
return slices.Sorted(maps.Keys(tagSet))
|
tags := make([]string, len(tagSet))
|
||||||
|
i := 0
|
||||||
|
for tag := range tagSet {
|
||||||
|
tags[i] = tag
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
return tags
|
||||||
}
|
}
|
||||||
|
|
||||||
func fmtPath(path string) string {
|
func fmtPath(path string) string {
|
||||||
|
|
@ -341,8 +331,8 @@ func (n *Note) DelViewer(viewer string) {
|
||||||
delete(n.Viewers, viewer)
|
delete(n.Viewers, viewer)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (n *Note) Delete() error {
|
func DeleteNote(uid string) error {
|
||||||
filename := filepath.Join(conf.Conf.NotesDir, fmtPath(n.Uid))
|
filename := filepath.Join(conf.Conf.NotesDir, fmtPath(uid))
|
||||||
return os.Remove(filename)
|
return os.Remove(filename)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -418,5 +408,10 @@ func (n *Note) ToggleBox(nthBox int) (bool, bool) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (n *Note) HasTag(tag string) bool {
|
func (n *Note) HasTag(tag string) bool {
|
||||||
return slices.Contains(n.Tags, tag)
|
for _, tag_ := range n.Tags {
|
||||||
|
if tag_ == tag {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -107,18 +107,10 @@ func new(w http.ResponseWriter, r *http.Request) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func delete(w http.ResponseWriter, r *http.Request) {
|
func delete(w http.ResponseWriter, r *http.Request) {
|
||||||
user := r.Context().Value(middleware.ContextKey("user")).(string)
|
// user := r.Context().Value(middleware.ContextKey("user")).(string)
|
||||||
|
|
||||||
uid := r.PathValue("note")
|
|
||||||
|
|
||||||
note, ok := notes.Notes.GetOne(user, uid)
|
|
||||||
|
|
||||||
if !ok {
|
|
||||||
http.NotFound(w, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
err := notes.Notes.Del(note, user)
|
|
||||||
|
|
||||||
|
encodedTitle := r.PathValue("note")
|
||||||
|
err := notes.DeleteNote(encodedTitle)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Print(err.Error())
|
log.Print(err.Error())
|
||||||
http.Error(w, "Couldn't delete note", http.StatusInternalServerError)
|
http.Error(w, "Couldn't delete note", http.StatusInternalServerError)
|
||||||
|
|
@ -223,11 +215,11 @@ func list(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
titlesAndUrls := make([]titleAndURL, 0)
|
titlesAndUrls := make([]titleAndURL, 0)
|
||||||
|
|
||||||
ns := notes.Notes.GetOrdered(user)
|
ns := notes.Notes.Get(user)
|
||||||
log.Printf("Notes: %+v", notes.Notes)
|
log.Printf("Notes: %+v", notes.Notes)
|
||||||
log.Printf("Notes for %s: %+v", user, ns)
|
log.Printf("Notes for %s: %+v", user, ns)
|
||||||
|
|
||||||
for _, note := range ns {
|
for note := range ns {
|
||||||
if tag == "" || note.HasTag(tag) {
|
if tag == "" || note.HasTag(tag) {
|
||||||
titlesAndUrls = append(
|
titlesAndUrls = append(
|
||||||
titlesAndUrls,
|
titlesAndUrls,
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue