-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathauth_test.go
More file actions
84 lines (72 loc) · 2.34 KB
/
Copy pathauth_test.go
File metadata and controls
84 lines (72 loc) · 2.34 KB
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
package main
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"testing"
"golang.org/x/crypto/bcrypt"
)
func useTempDataPath(t *testing.T) {
oldDataPath, oldSongsFilePath, oldUsersFilePath := dataPath, songsFilePath, usersFilePath
dir := t.TempDir()
t.Setenv("DATA_PATH", dir)
if err := configureDataPath(); err != nil {
t.Fatal(err)
}
if dataPath != dir {
t.Fatalf("data path = %q, want %q", dataPath, dir)
}
t.Cleanup(func() { dataPath, songsFilePath, usersFilePath = oldDataPath, oldSongsFilePath, oldUsersFilePath })
}
func TestLoadUsersMigratesPlaintextPasswords(t *testing.T) {
useTempDataPath(t)
if err := os.WriteFile(usersFilePath, []byte(`[{"username":"alice","password":"secret"}]`), 0600); err != nil {
t.Fatal(err)
}
if err := loadUsers(); err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(usersFilePath)
if err != nil {
t.Fatal(err)
}
var migrated []User
if err := json.Unmarshal(data, &migrated); err != nil {
t.Fatal(err)
}
if migrated[0].Password == "secret" {
t.Fatal("password was not migrated")
}
if err := bcrypt.CompareHashAndPassword([]byte(migrated[0].Password), []byte("secret")); err != nil {
t.Fatal("migrated password no longer authenticates")
}
}
func TestPasswordHandlerHashesNewPassword(t *testing.T) {
useTempDataPath(t)
password, err := bcrypt.GenerateFromPassword([]byte("old"), bcrypt.DefaultCost)
if err != nil {
t.Fatal(err)
}
users = []User{{Username: "alice", Password: string(password)}}
sessions = []Session{{Token: "token", Username: "alice"}}
req := httptest.NewRequest(http.MethodPut, "/api/password", bytes.NewBufferString(`{"currentPassword":"old","newPassword":"new"}`))
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "token"})
req = req.WithContext(context.WithValue(req.Context(), "username", "alice"))
response := httptest.NewRecorder()
passwordHandler(response, req)
if response.Code != http.StatusOK {
t.Fatalf("unexpected status: %d", response.Code)
}
if err := bcrypt.CompareHashAndPassword([]byte(users[0].Password), []byte("new")); err != nil {
t.Fatal("new password was not hashed")
}
}
func TestSessionCookieIsNamespacedAndSiteWide(t *testing.T) {
cookie := createSessionCookie("token")
if cookie.Name != "beatstream_session" || cookie.Path != "/" {
t.Fatalf("unexpected session cookie: %#v", cookie)
}
}