aboutsummaryrefslogtreecommitdiff
path: root/cmd/web/handlers/login.go
blob: e867e07f250df93ff6962d739d2ad7a4676ae84e (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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
package handlers

import (
	"database/sql"
	"html/template"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/google/uuid"
	"golang.org/x/crypto/bcrypt"
	"paterissa.net/mblog/internal/models"
)

type loginContext struct {
	err *log.Logger
	db *sql.DB
}

func (ctx *loginContext) index(w http.ResponseWriter, r *http.Request) {
	files := []string{
		"ui/html/base.tmpl.html",
		"ui/html/login.tmpl.html",
		"ui/html/music_player.tmpl.html",
	}

	compiled, err := template.ParseFiles(files...)
	if err != nil {
		w.WriteHeader(500)
		w.Write([]byte("Internal Server Error"))
		ctx.err.Printf("Failed to parse templates: %v\n", err)
		return
	}

	err = compiled.ExecuteTemplate(w, "base", ctx)
	if err != nil {
		w.WriteHeader(500)
		w.Write([]byte("Internal Server Error"))
		ctx.err.Printf("Failed to parse templates: %v\n", err)
		return
	}

	return
}

func (ctx *loginContext) login(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		w.WriteHeader(405)
		w.Write([]byte("Method Not Allowed"))
		return
	}

	err := r.ParseForm()
	if err != nil {
		w.WriteHeader(500)
		w.Write([]byte("Internal Error"))
		ctx.err.Printf("Failed to retrieve form data: %v\n", err)
		return
	}

	user := r.PostForm.Get("user")
	passOne := r.PostForm.Get("pass_one")
	passTwo := r.PostForm.Get("pass_two")

	stmt, err := ctx.db.Prepare("SELECT * FROM logins WHERE name = $1;")
	if err != nil {
		w.WriteHeader(500)
		w.Write([]byte("Internal Error"))
		ctx.err.Printf("Failed to retrieve form data: %v\n", err)
		return
	}
	defer stmt.Close()

	var u models.User

	row := stmt.QueryRow(user)
	err = row.Scan(&u.Id, &u.Name, &u.Time, &u.PassOne, &u.PassTwo)
	if err != nil {
		w.WriteHeader(401)
		w.Write([]byte("Unauthorized"))
		ctx.err.Printf("Failed to retrieve user info from DB: %v\n", err)
		return
	}
	
	passOneErr := bcrypt.CompareHashAndPassword([]byte(u.PassOne), []byte(passOne))
	passTwoErr := bcrypt.CompareHashAndPassword([]byte(u.PassTwo), []byte(passTwo))
	if passOneErr != nil || passTwoErr != nil {
		w.WriteHeader(401)
		w.Write([]byte("Failed to login - not authorized"))
		return
	}

	cookie := http.Cookie{
		Name: "paterissa_session_token",
		Value: uuid.New().String(),
		Expires: time.Now().AddDate(0, 0, 1),
		Path: "/",
		Domain: os.Getenv("serv"),
		HttpOnly: true,
		Secure: true,
	}

	commit, err := ctx.db.Prepare("INSERT INTO cookies (content, user_id, expiration) VALUES ($1, $2, $3);")
	if err != nil {
		w.WriteHeader(500)
		w.Write([]byte("Internal Error"))
		ctx.err.Printf("Failed to prepare DB statement: %v\n", err)
		return
	}

	_, err = commit.Exec(cookie.Value, u.Id, cookie.Expires)
	if err != nil {
		w.WriteHeader(500)
		w.Write([]byte("Internal Error"))
		ctx.err.Printf("Failed to prepare DB statement: %v\n", err)
	}

	http.SetCookie(w, &cookie)
	http.Redirect(w, r, "/", http.StatusFound)
	return
}

func (ctx *loginContext) logout(w http.ResponseWriter, r *http.Request) {
	cookie, err := r.Cookie("paterissa_session_token")
	if err != nil {
		w.WriteHeader(405)
		w.Write([]byte("Unauthorized"))
		return
	}

	stmt, err := ctx.db.Prepare("UPDATE cookies SET expiration = $1 WHERE content = $2;")
	if err != nil {
		w.WriteHeader(500)
		w.Write([]byte("Internal Error"))
		ctx.err.Printf("Could not prepare DB statement: %v\n", err)
		return
	}
	defer stmt.Close()

	_, err = stmt.Exec(time.Now(), cookie.Value)
	if err != nil {
		w.WriteHeader(500)
		w.Write([]byte("Internal Error"))
		ctx.err.Printf("Could not execute DB statement: %v\n", err)
		return
	}

	cookie = &http.Cookie{
		Name: "paterissa_session_token",
		Value: "",
		Path: "/",
		MaxAge: -1,
		HttpOnly: true,
	}

	http.SetCookie(w, cookie)
	http.Redirect(w, r, "/", http.StatusFound)
	return
}

func (ctx *loginContext) handle(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		ctx.index(w, r)
		return
	} else {
		ctx.login(w, r)
		return
	}
}