summaryrefslogtreecommitdiff
path: root/internal/handlers/auth.go
blob: 435f8ffb3bbafad847b2b9f501dd5bb97b7a16cd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package handlers

import (
	"apjournal/internal/models"
	"apjournal/pkg/utils"
	"fmt"
	"html/template"
	"net/http"
	"strings"
	"time"
)

func abortWithError(w http.ResponseWriter, msg string) {
	tmpl := template.Must(template.ParseGlob("components/*.html"))
	tmpl.ExecuteTemplate(w, "error", msg)
}

func (h *Handlers) HandleLogin(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	username := r.PostFormValue("username")
	if username == "" {
		msg := "username not provided"
		h.log.Error(msg)
		abortWithError(w, msg)
		return
	}
	password := r.PostFormValue("password")
	if password == "" {
		msg := "password not provided"
		h.log.Error(msg)
		abortWithError(w, msg)
		return
	}
	cleanName := utils.RemoveSpacesFromStr(username)
	// allNames := h.s.CacheGetAllNames()
	allNames := []string{}
	if utils.StrInSlice(cleanName, allNames) {
		err := fmt.Errorf("name: %s already taken", cleanName)
		h.log.Error("already taken", "error", err)
		abortWithError(w, err.Error())
		return
	}
	cookie, err := h.makeCookie(cleanName, r.RemoteAddr)
	if err != nil {
		h.log.Error("failed to login", "error", err)
		abortWithError(w, err.Error())
	}
	http.SetCookie(w, cookie)
	http.Redirect(w, r, "/", 302)
}

func (h *Handlers) makeCookie(username string, remote string) (*http.Cookie, error) {
	// Create a new random session token
	// sessionToken := xid.New().String()
	sessionToken := "token"
	expiresAt := time.Now().Add(time.Duration(h.cfg.SessionLifetime) * time.Second)
	// Set the token in the session map, along with the session information
	session := &models.Session{
		Username: username,
		Expiry:   expiresAt,
	}
	// TODO: write session to db
	cookie := &http.Cookie{
		Name:     "session_token",
		Value:    sessionToken,
		Secure:   true,
		HttpOnly: true,
		SameSite: http.SameSiteNoneMode,
		Domain:   h.cfg.ServerConfig.Host,
	}
	h.log.Info("check remote addr for cookie set",
		"remote", remote, "session", session)
	if strings.Contains(remote, "192.168.0") {
		// no idea what is going on
		// domainName = "192.168.0.101"
		cookie.Domain = "192.168.0.101"
	}
	// set ctx?
	// c.Set("username", username)
	return cookie, nil
}