-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
167 lines (140 loc) · 3.67 KB
/
auth.go
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
package main
import (
"fmt"
"net/http"
"os"
"time"
"github.com/golang-jwt/jwt"
"golang.org/x/crypto/bcrypt"
)
func NewUser(name string, password string) (*User, error) {
hpw, err := hashPassword(password)
if err != nil {
return nil, err
}
now := time.Now()
return &User{
ID: NewUUID(),
Name: name,
HashedPassword: hpw,
CreatedAt: now,
UpdatedAt: now,
}, nil
}
func NewRootUser(username string, password string) (*User, error) {
user, err := NewUser(username, password)
if err != nil {
return nil, err
}
user.HashedPassword = password
if !IsRootUser(user) {
return nil, fmt.Errorf("invalid root user credentials")
}
user.ID = rootUserID
return user, nil
}
func IsRootUser(user *User) bool {
if user == nil {
return false
}
return user.Name == os.Getenv(EnvRootUsername) && user.HashedPassword == os.Getenv(EnvRootPassword)
}
func useProtectedRoute(w http.ResponseWriter, r *http.Request) (*User, error) {
var token *jwt.Token
cookie, err := r.Cookie(string(CookieNameJWT))
if err == nil && cookie != nil {
tk, err := validateJWT(cookie.Value)
if err == nil && tk != nil {
token = tk
}
}
if token != nil && token.Valid {
claims := token.Claims.(jwt.MapClaims)
userID := claims[JwtClaimUserID].(string)
user, err := storage.GetUserByID(userID)
if err != nil {
return nil, unauthorized()
}
return user, nil
}
username, password, ok := r.BasicAuth()
if !ok || username == "" || password == "" {
return nil, unauthorized()
}
// Check if credentials match root user credentials
rootUser, err := NewRootUser(username, password)
if err == nil {
return rootUser, nil
}
user, err := storage.GetUserByUsernameAndPassword(username, password)
if err != nil {
return nil, unauthorized()
}
Login(w, user)
return user, nil
}
func Auth(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
user, err := useProtectedRoute(w, r)
if err != nil || user == nil {
WriteUnauthorized(w)
return
}
h(w, r)
}
}
func RootAuth(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
user, err := useProtectedRoute(w, r)
if err != nil || !IsRootUser(user) {
WriteUnauthorized(w)
return
}
h(w, r)
}
}
func Login(w http.ResponseWriter, user *User) error {
jwtStr, err := newJWTStr(user)
if err != nil {
return err
}
setCookie(w, string(CookieNameJWT), jwtStr)
return nil
}
func Logout(w http.ResponseWriter) {
clearCookie(w, string(CookieNameJWT))
}
func newJWTStr(user *User) (string, error) {
claims := &jwt.MapClaims{
JwtClaimExpiresAt: jwtExpiry,
JwtClaimUserID: user.ID,
}
secret := os.Getenv(EnvJWTSecret)
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(secret))
}
func validateJWT(tokenStr string) (*jwt.Token, error) {
jwtSecret := os.Getenv(EnvJWTSecret)
return jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header[JwtHeaderAlg])
}
return []byte(jwtSecret), nil
})
}
func hashPassword(password string) (string, error) {
b, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return "", err
}
return string(b), nil
}
func validPassword(password string) (bool, error) {
if len(password) < minPasswordLength {
return false, fmt.Errorf("password should be at least %d characters long", minPasswordLength)
}
if len(password) > maxPasswordLength {
return false, fmt.Errorf("password should be at most %d characters long", maxPasswordLength)
}
return true, nil
}