-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
239 lines (219 loc) · 6.1 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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
package auth
import (
"golang.org/x/crypto/bcrypt"
"crypto/md5"
"encoding/hex"
"encoding/json"
"html/template"
"io/ioutil"
"net/http"
"os"
"time"
)
var templates = template.Must(template.ParseFiles("./static/templates/main.html", "./static/templates/head.html", "./static/templates/menu.html", "./static/templates/content_auth.html", "./static/templates/footer.html"))
type RenderData struct {
Title string
Headline string
Message string
Action string
Submit string
MenuEntries [][2]string
}
type User struct {
Username string
Password string
Approvalstatus string
Adminstatus string
}
func Auth(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
renderAuth(w, "")
case "POST":
username := r.FormValue("username")
enteredPassword := r.FormValue("password")
filename := "./users/" + username
if _, err := os.Stat(filename); os.IsNotExist(err) {
renderAuth(w, "Wrong Credentials!")
return
} else {
file, erro := os.Open(filename)
if erro != nil {
println("Error opening the file")
}
defer file.Close()
decoder := json.NewDecoder(file)
var user User
err := decoder.Decode(&user)
if err != nil {
println("Error decoding json")
}
if user.Approvalstatus == "approved" {
err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(enteredPassword))
if err != nil {
renderAuth(w, "Wrong Credentials!")
} else {
t := time.Now()
expiration := time.Now().AddDate(1, 0, 0)
h := md5.New()
const layout = "2006-01-02 15:04:05"
hashedTime := t.Format(layout)
hashedStoredPassword := hex.EncodeToString(h.Sum([]byte(user.Password)))
cookie := http.Cookie{Name: "User", Value: username, Path: "/", Expires: expiration}
cookie2 := http.Cookie{Name: hashedStoredPassword, Value: hashedTime, Path: "/", Expires: expiration}
http.SetCookie(w, &cookie)
http.SetCookie(w, &cookie2)
http.Redirect(w, r, "/view/start", http.StatusFound)
}
} else {
renderAuth(w, "You are not approved. Please contact the Administrator!")
}
}
}
}
func renderAuth(w http.ResponseWriter, message string) {
templates.ExecuteTemplate(w, "main", &RenderData{
"Login",
"Login",
message,
"/auth/",
"Login",
[][2]string{
{"Home", "/view/start"},
{"Create Account", "/register"},
},
})
}
func Register(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
renderRegister(w, "")
case "POST":
username := r.FormValue("username")
password := r.FormValue("password")
if len(password) < 8 {
renderRegister(w, "Please choose a password with at least 8 characters!")
return
}
cryptPassword, err := Crypt([]byte(password))
if err != nil {
println("Error encrypting the password")
}
userfiles, _ := ioutil.ReadDir("./users")
user := &User{}
if len(userfiles) == 1{
user = &User{Username: username, Password: string(cryptPassword), Approvalstatus: "approved", Adminstatus: "admin"}
}else{
user = &User{Username: username, Password: string(cryptPassword), Approvalstatus: "not approved", Adminstatus: "user"}
}
filename := "./users/" + user.Username
jsoneduser, err := json.Marshal(user)
if err != nil {
println("error making json out of user")
}
if _, err := os.Stat(filename); os.IsNotExist(err) {
file, erro := os.Create(filename)
if erro != nil {
println("couldn't create the file")
}
defer file.Close()
ioutil.WriteFile(filename, jsoneduser, 0600)
http.Redirect(w, r, "/auth/", http.StatusFound)
} else {
renderRegister(w, "This User already exists!")
return
}
}
}
func renderRegister(w http.ResponseWriter, message string) {
templates.ExecuteTemplate(w, "main", &RenderData{
"Create Account",
"Register",
message,
"/register/",
"Create",
[][2]string{{"Home", "/view/start"}},
})
}
func clear(b []byte) {
for i := 0; i < len(b); i++ {
b[i] = 0
}
}
func Crypt(password []byte) ([]byte, error) {
defer clear(password)
return bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
}
func Chkauth(f http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("User")
if err != nil {
http.Redirect(w, r, "/auth/", http.StatusFound)
return
}
username := cookie.Value
filename := "./users/" + username
if _, err := os.Stat(filename); os.IsNotExist(err) {
http.Redirect(w, r, "/auth/", http.StatusFound)
return
} else {
file, erro := os.Open(filename)
if erro != nil {
println("Error opening the file")
}
defer file.Close()
decoder := json.NewDecoder(file)
var user User
err := decoder.Decode(&user)
if err != nil {
println("Error decoding json")
}
h := md5.New()
hashedStoredPassword := hex.EncodeToString(h.Sum([]byte(user.Password)))
_, err = r.Cookie(hashedStoredPassword)
if err != nil {
println("no cookie found")
http.Redirect(w, r, "/auth/", http.StatusFound)
return
}
if user.Approvalstatus != "approved" {
http.Redirect(w, r, "/auth", http.StatusFound)
}
}
f(w, r)
}
}
func Logout(w http.ResponseWriter, r *http.Request){
expiration := time.Now()
invalidcookie := http.Cookie{Name: "User", Value: "expired", Path: "/", Expires: expiration}
cookie, err := r.Cookie("User")
if err != nil {
http.Redirect(w, r, "/auth/", http.StatusFound)
return
}
username := cookie.Value
filename := "./users/" + username
file, erro := os.Open(filename)
if erro != nil {
println("Error opening the file")
}
defer file.Close()
decoder := json.NewDecoder(file)
var user User
err = decoder.Decode(&user)
if err != nil {
println("Error decoding json")
}
h := md5.New()
hashedStoredPassword := hex.EncodeToString(h.Sum([]byte(user.Password)))
_, err = r.Cookie(hashedStoredPassword)
if err != nil {
println("no cookie found")
http.Redirect(w, r, "/auth/", http.StatusFound)
return
}
invalidcookie2 := http.Cookie{Name: hashedStoredPassword, Value: "expired", Path: "/", Expires: expiration}
http.SetCookie(w, &invalidcookie)
http.SetCookie(w, &invalidcookie2)
http.Redirect(w, r, "/view/start", http.StatusFound)
}