auth.go 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package main
  2. import (
  3. "crypto/rand"
  4. "encoding/base64"
  5. "errors"
  6. "log"
  7. "net/http"
  8. "time"
  9. )
  10. type SessionData struct {
  11. username string
  12. }
  13. var (
  14. sessions = make(map[string]*SessionData)
  15. )
  16. func userOk(username, password string) bool {
  17. return (username == "Lamperi" && password == "paskaa")
  18. }
  19. func tryLogin(username, password string, longerTime bool) (http.Cookie, error) {
  20. if exists := userOk(username, password); !exists {
  21. return http.Cookie{},
  22. errors.New("The username or password you entered isn't correct.")
  23. }
  24. sid, err := randString(32)
  25. if err != nil {
  26. return http.Cookie{}, err
  27. }
  28. sessions[sid] = &SessionData{username}
  29. hours := time.Duration(1)
  30. if longerTime {
  31. hours = time.Duration(336)
  32. }
  33. loginCookie := http.Cookie{
  34. Name: "id",
  35. Value: sid,
  36. MaxAge: int((time.Hour * hours).Seconds()),
  37. HttpOnly: true,
  38. }
  39. return loginCookie, nil
  40. }
  41. func getSession(req *http.Request) (*SessionData, error) {
  42. cookie, err := req.Cookie("id")
  43. if err != nil {
  44. return nil, err
  45. }
  46. session, exists := sessions[cookie.Value]
  47. if !exists {
  48. return nil, errors.New("Session expired from server")
  49. }
  50. return session, nil
  51. }
  52. func randString(size int) (string, error) {
  53. buf := make([]byte, size)
  54. if _, err := rand.Read(buf); err != nil {
  55. log.Println(err)
  56. return "", errors.New("Couldn't generate random string")
  57. }
  58. return base64.URLEncoding.EncodeToString(buf)[:size], nil
  59. }