github.com/nizigama/simple-note@v0.0.0-20210501235539-2cc762e06fe8/handlers.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "math/rand" 7 "net/http" 8 "os" 9 "strconv" 10 "strings" 11 "text/template" 12 "time" 13 14 models "github.com/nizigama/simple-note/models" 15 auth "github.com/nizigama/simple-note/services/middleware" 16 "golang.org/x/crypto/bcrypt" 17 ) 18 19 var tpl *template.Template 20 21 func init() { 22 tpl = template.Must(template.ParseGlob("./templates/includes/*.html")) 23 tpl = template.Must(tpl.ParseGlob("./templates/*.html")) 24 } 25 26 func index(w http.ResponseWriter, req *http.Request) { 27 28 c, err := req.Cookie("sessionID") 29 data := map[string]interface{}{ 30 "loggedIn": false, 31 "users": []models.User{}, 32 "year": time.Now().Year(), 33 } 34 35 if err == nil { 36 // var user users.User 37 // var userID int 38 39 for _, v := range auth.Sessions { 40 if c.Value == strconv.Itoa(int(v.ID)) { 41 // userID = v.UserID 42 // user, _ = users.Read(uint64(v.UserID)) 43 data["loggedIn"] = true 44 break 45 } 46 } 47 } 48 49 allUsers, err := models.ReadAllUsers() 50 51 if err != nil { 52 http.Error(w, "Error getting all app users", http.StatusInternalServerError) 53 return 54 } 55 56 data["users"] = allUsers 57 58 w.Header().Set("Content-Type", "text/html") 59 tpl.ExecuteTemplate(w, "index.html", data) 60 } 61 62 func login(w http.ResponseWriter, req *http.Request) { 63 64 if req.Method == http.MethodPost { 65 if err := req.ParseForm(); err != nil { 66 http.Error(w, "Error parsing your request", http.StatusUnprocessableEntity) 67 } 68 69 email, password := req.Form.Get("email"), req.Form.Get("pass") 70 71 if isValid := validateEmail(email); isValid != nil { 72 http.Error(w, "invalid email address", http.StatusUnprocessableEntity) 73 return 74 } 75 if strings.Trim(password, " ") == "" { 76 http.Error(w, "Password is required", http.StatusUnprocessableEntity) 77 return 78 } 79 80 user, userID, err := models.ReadSingleUserByEmail(email) 81 if err != nil { 82 http.Error(w, "Wrong credentials, there is no such email in our records", http.StatusForbidden) 83 return 84 } 85 86 err = auth.CheckCredentials([]byte(user.Password), []byte(password)) 87 88 if err != nil { 89 http.Error(w, "Wrong credentials", http.StatusForbidden) 90 return 91 } 92 93 r := rand.New(rand.NewSource(time.Now().UnixNano())) 94 95 sessionID := r.Uint64() 96 97 auth.CreateSession(sessionID, int(userID)) 98 99 http.SetCookie(w, &http.Cookie{ 100 Name: "sessionID", 101 Value: strconv.Itoa(int(sessionID)), 102 }) 103 104 w.Header().Set("Location", "/dashboard") 105 w.WriteHeader(http.StatusSeeOther) 106 107 } 108 w.Header().Set("Content-Type", "text/html") 109 tpl.ExecuteTemplate(w, "login.html", time.Now().Year()) 110 } 111 112 func register(w http.ResponseWriter, req *http.Request) { 113 114 if req.Method == http.MethodPost { 115 116 if err := req.ParseForm(); err != nil { 117 http.Error(w, "Error parsing your request", http.StatusUnprocessableEntity) 118 } 119 120 firstName, lastName, email, password, confirm := req.Form.Get("first"), req.Form.Get("last"), req.Form.Get("email"), req.Form.Get("pass"), req.Form.Get("confirm") 121 122 if strings.Trim(firstName, " ") == "" { 123 http.Error(w, "First name is required", http.StatusUnprocessableEntity) 124 return 125 } 126 if strings.Trim(lastName, " ") == "" { 127 http.Error(w, "Last name is required", http.StatusUnprocessableEntity) 128 return 129 } 130 if strings.Trim(email, " ") == "" { 131 http.Error(w, "Email is required", http.StatusUnprocessableEntity) 132 return 133 } 134 if isValid := validateEmail(email); isValid != nil { 135 http.Error(w, "invalid email address", http.StatusUnprocessableEntity) 136 return 137 } 138 if strings.Trim(password, " ") == "" { 139 http.Error(w, "Password is required", http.StatusUnprocessableEntity) 140 return 141 } 142 if strings.Trim(confirm, " ") == "" { 143 http.Error(w, "Password confirmation is required", http.StatusUnprocessableEntity) 144 return 145 } 146 if password != confirm { 147 http.Error(w, "Passwords don't match", http.StatusUnprocessableEntity) 148 return 149 } 150 151 hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost) 152 153 if err != nil { 154 http.Error(w, "Password hashing failed, Contact support", http.StatusInternalServerError) 155 return 156 } 157 158 newUser := models.User{ 159 FirstName: firstName, 160 LastName: lastName, 161 Email: email, 162 Password: string(hashedPassword), 163 Picture: "avatar.png", 164 } 165 166 userID, err := newUser.Save() 167 168 if err != nil { 169 http.Error(w, "Signup failed, Contact support", http.StatusInternalServerError) 170 return 171 } 172 173 r := rand.New(rand.NewSource(time.Now().UnixNano())) 174 175 sessionID := r.Uint64() 176 177 auth.CreateSession(sessionID, int(userID)) 178 179 http.SetCookie(w, &http.Cookie{ 180 Name: "sessionID", 181 Value: strconv.Itoa(int(sessionID)), 182 }) 183 184 w.Header().Set("Location", "/dashboard") 185 w.WriteHeader(http.StatusSeeOther) 186 187 } else { 188 w.Header().Set("Content-Type", "text/html") 189 tpl.ExecuteTemplate(w, "register.html", time.Now().Year()) 190 } 191 } 192 193 func profile(w http.ResponseWriter, req *http.Request) { 194 195 year := time.Now().Year() 196 user, userID := getLoggedInUser(req) 197 198 // TODO: code to upload and save profile picture 199 if req.Method == http.MethodPost { 200 f, h, err := req.FormFile("picture") 201 202 if err != nil { 203 http.Error(w, "No image file found", http.StatusNotFound) 204 return 205 } 206 xb, err := ioutil.ReadAll(f) 207 if err != nil { 208 http.Error(w, "Error reading file", http.StatusInternalServerError) 209 return 210 } 211 xs := strings.Split(h.Filename, ".") 212 ext := xs[len(xs)-1] 213 tsp := time.Now().UnixNano() 214 215 fileName := fmt.Sprintf("%v.%s", tsp, ext) 216 file, err := os.Create("./assets/" + fileName) 217 218 if err != nil { 219 http.Error(w, "Error saving file", http.StatusInternalServerError) 220 return 221 } 222 223 file.Write(xb) 224 if user.Picture != "avatar.png" { 225 os.Remove("./assets/" + user.Picture) 226 } 227 228 user.Picture = fileName 229 230 if err := models.UpdateUser(user, userID); err != nil { 231 http.Error(w, "Error updating database", http.StatusInternalServerError) 232 return 233 } 234 235 w.Header().Set("Location", "/profile") 236 w.WriteHeader(http.StatusSeeOther) 237 return 238 } 239 240 r := rand.New(rand.NewSource(time.Now().UnixNano())) 241 w.Header().Set("Content-Type", "text/html") 242 tpl.ExecuteTemplate(w, "profile.html", map[string]interface{}{ 243 "user": user, 244 "r": r.Uint64(), 245 "year": year, 246 }) 247 } 248 249 func profilePicture(w http.ResponseWriter, req *http.Request) { 250 user, _ := getLoggedInUser(req) 251 252 http.ServeFile(w, req, "assets/"+user.Picture) 253 } 254 255 func getPicture(w http.ResponseWriter, req *http.Request) { 256 257 picture := req.FormValue("name") 258 259 _, err := os.Open("assets/" + picture) 260 261 if err != nil { 262 http.ServeFile(w, req, "assets/avatar.png") 263 return 264 } 265 266 http.ServeFile(w, req, "assets/"+picture) 267 } 268 269 func newNote(w http.ResponseWriter, req *http.Request) { 270 _, userID := getLoggedInUser(req) 271 if req.Method == http.MethodPost { 272 273 if err := req.ParseForm(); err != nil { 274 http.Error(w, "Error parsing your request", http.StatusUnprocessableEntity) 275 } 276 277 title, note := req.Form.Get("title"), req.Form.Get("note") 278 279 if strings.Trim(title, " ") == "" { 280 http.Error(w, "Note title is required", http.StatusUnprocessableEntity) 281 return 282 } 283 if strings.Trim(note, " ") == "" { 284 http.Error(w, "note is required", http.StatusUnprocessableEntity) 285 return 286 } 287 288 newNote := models.Note{ 289 Title: title, 290 Body: note, 291 OwnerID: userID, 292 } 293 294 _, err := newNote.Save() 295 296 if err != nil { 297 http.Error(w, "Failed to save the note, Contact support", http.StatusInternalServerError) 298 return 299 } 300 301 w.Header().Set("Location", "/dashboard") 302 w.WriteHeader(http.StatusSeeOther) 303 304 } else { 305 data := map[string]interface{}{ 306 "year": time.Now().Year(), 307 } 308 w.Header().Set("Content-Type", "text/html") 309 tpl.ExecuteTemplate(w, "note.html", data) 310 } 311 } 312 313 func dashboard(w http.ResponseWriter, req *http.Request) { 314 data := map[string]interface{}{ 315 "notes": []models.Note{}, 316 "year": time.Now().Year(), 317 } 318 319 _, userID := getLoggedInUser(req) 320 321 allNotes, err := models.ReadAllUserNotes(userID) 322 323 if err != nil { 324 fmt.Println(err) 325 http.Error(w, "Error getting all app users", http.StatusInternalServerError) 326 return 327 } 328 329 data["notes"] = allNotes 330 331 tpl.ExecuteTemplate(w, "dashboard.html", data) 332 } 333 334 func updateNote(w http.ResponseWriter, req *http.Request) { 335 noteID := req.FormValue("noteID") 336 337 id, err := strconv.Atoi(noteID) 338 _, userID := getLoggedInUser(req) 339 340 if err != nil { 341 http.Error(w, "Invalid noteID", http.StatusUnprocessableEntity) 342 return 343 } 344 345 note, err := models.ReadNote(uint64(id)) 346 347 if err != nil { 348 http.Error(w, "No note found with ID", http.StatusNotFound) 349 return 350 } 351 352 if req.Method == http.MethodPost { 353 354 if err := req.ParseForm(); err != nil { 355 http.Error(w, "Error parsing your request", http.StatusUnprocessableEntity) 356 } 357 358 title, note := req.Form.Get("title"), req.Form.Get("note") 359 360 if strings.Trim(title, " ") == "" { 361 http.Error(w, "Note title is required", http.StatusUnprocessableEntity) 362 return 363 } 364 if strings.Trim(note, " ") == "" { 365 http.Error(w, "note is required", http.StatusUnprocessableEntity) 366 return 367 } 368 369 updatedNote := models.Note{ 370 Title: title, 371 Body: note, 372 OwnerID: userID, 373 } 374 375 err = models.UpdateNote(updatedNote, id) 376 377 if err != nil { 378 http.Error(w, "Failed to update the note, Contact support", http.StatusInternalServerError) 379 return 380 } 381 382 w.Header().Set("Location", "/dashboard") 383 w.WriteHeader(http.StatusSeeOther) 384 return 385 } 386 387 data := map[string]interface{}{ 388 "note": note, 389 "year": time.Now().Year(), 390 } 391 392 w.Header().Set("Content-Type", "text/html") 393 tpl.ExecuteTemplate(w, "updateNote.html", data) 394 395 } 396 397 func deleteNote(w http.ResponseWriter, req *http.Request) { 398 noteID := req.FormValue("noteID") 399 400 id, err := strconv.Atoi(noteID) 401 402 if err != nil { 403 http.Error(w, "Invalid noteID", http.StatusUnprocessableEntity) 404 return 405 } 406 407 _, err = models.ReadNote(uint64(id)) 408 409 if err != nil { 410 http.Error(w, "No note found with ID", http.StatusNotFound) 411 return 412 } 413 414 err = models.DeleteNote(id) 415 416 if err != nil { 417 http.Error(w, "Failed to delete note", http.StatusInternalServerError) 418 return 419 } 420 421 w.Header().Set("Location", "/dashboard") 422 w.WriteHeader(http.StatusSeeOther) 423 424 } 425 426 func logout(w http.ResponseWriter, req *http.Request) { 427 c, _ := req.Cookie("sessionID") 428 429 var sessionID int 430 431 for k, v := range auth.Sessions { 432 if c.Value == strconv.Itoa(int(v.ID)) { 433 sessionID = k 434 break 435 } 436 } 437 438 first := auth.Sessions[:sessionID] 439 second := auth.Sessions[sessionID+1:] 440 441 auth.Sessions = append(first, second...) 442 443 c.MaxAge = -1 444 http.SetCookie(w, c) 445 446 w.Header().Set("Location", "/login") 447 w.WriteHeader(http.StatusSeeOther) 448 } 449 450 func deleteAccount(w http.ResponseWriter, req *http.Request) { 451 c, _ := req.Cookie("sessionID") 452 453 var sessionID int 454 var userID int 455 456 for k, v := range auth.Sessions { 457 if c.Value == strconv.Itoa(int(v.ID)) { 458 sessionID = k 459 userID = v.UserID 460 break 461 } 462 } 463 464 allNotes, err := models.ReadAllUserNotes(userID) 465 466 if err != nil { 467 http.Error(w, "Error getting user's notes", http.StatusInternalServerError) 468 return 469 } 470 471 for _, note := range allNotes { 472 err = models.DeleteNote(note.ID) 473 474 if err != nil { 475 http.Error(w, "Failed to delete note", http.StatusInternalServerError) 476 return 477 } 478 } 479 480 err = models.DeleteUser(userID) 481 482 if err != nil { 483 http.Error(w, "Failed to delete the user", http.StatusInternalServerError) 484 return 485 } 486 487 first := auth.Sessions[:sessionID] 488 second := auth.Sessions[sessionID+1:] 489 490 auth.Sessions = append(first, second...) 491 492 c.MaxAge = -1 493 http.SetCookie(w, c) 494 495 w.Header().Set("Location", "/login") 496 w.WriteHeader(http.StatusSeeOther) 497 } 498 499 func validateEmail(email string) error { 500 501 if !strings.Contains(email, "@") || !strings.Contains(email, ".") { 502 return fmt.Errorf("invalid email") 503 } 504 505 parts := strings.Split(email, "@") 506 507 // if there is no content before or after the @ symbol 508 if len(parts[0]) == 0 || len(parts[1]) == 0 { 509 return fmt.Errorf("invalid email") 510 } 511 512 afterAtSymbol := strings.Split(parts[1], ".") 513 // if there is a dot after the @ symbol 514 if len(afterAtSymbol) == 0 { 515 return fmt.Errorf("invalid email") 516 } 517 518 // if there is content after the last dot(.) 519 if len(afterAtSymbol[len(afterAtSymbol)-1]) == 0 { 520 return fmt.Errorf("invalid email") 521 } 522 523 return nil 524 } 525 526 func getLoggedInUser(req *http.Request) (models.User, int) { 527 528 c, _ := req.Cookie("sessionID") 529 530 var user models.User 531 var userID int 532 533 for _, v := range auth.Sessions { 534 if c.Value == strconv.Itoa(int(v.ID)) { 535 userID = v.UserID 536 user, _ = models.ReadUser(uint64(v.UserID)) 537 break 538 } 539 } 540 541 return user, userID 542 }