login.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package api
  2. import (
  3. "errors"
  4. "log"
  5. "net/http"
  6. "net/url"
  7. "time"
  8. jwt "github.com/dgrijalva/jwt-go"
  9. "gogs.carducci-dante.gov.it/karmen/config"
  10. "gogs.carducci-dante.gov.it/karmen/core/renderer"
  11. )
  12. func logoutHandler() http.Handler {
  13. fn := func(w http.ResponseWriter, r *http.Request) {
  14. session, err := store.Get(r, "login-session")
  15. if err != nil {
  16. http.Error(w, err.Error(), http.StatusInternalServerError)
  17. return
  18. }
  19. session.Values["token"] = []uint8{}
  20. session.Save(r, w)
  21. http.Redirect(w, r, "/", http.StatusSeeOther)
  22. }
  23. return http.HandlerFunc(fn)
  24. }
  25. func loginHandler() http.Handler {
  26. fn := func(w http.ResponseWriter, r *http.Request) {
  27. if r.Method == "GET" {
  28. renderer.Render["html"](w, r, nil, url.Values{"tpl_layout": []string{"login"}, "tpl_content": []string{"login"}})
  29. }
  30. if r.Method == "POST" {
  31. r.ParseForm()
  32. token, err := getToken(r.FormValue("username"), r.FormValue("password"))
  33. if err != nil {
  34. panic(err)
  35. } else {
  36. session, err := store.Get(r, "login-session")
  37. if err != nil {
  38. panic(err)
  39. }
  40. session.Values["token"] = token
  41. session.Save(r, w)
  42. r.Method = "GET"
  43. http.Redirect(w, r, "/teachers?format=html&tpl_layout=base&tpl_content=teachers", http.StatusSeeOther)
  44. }
  45. }
  46. }
  47. return http.HandlerFunc(fn)
  48. }
  49. func queryDB(username string, password string) (*User, error) {
  50. log.Println(username, config.Config.Admin.Username, password, config.Config.Admin.Password)
  51. if username == config.Config.Admin.Username && password == config.Config.Admin.Password {
  52. return &User{username, true}, nil
  53. }
  54. return nil, errors.New("Authentication failed!")
  55. }
  56. func getToken(username string, password string) ([]byte, error) {
  57. user, err := queryDB(username, password)
  58. if err != nil {
  59. return nil, err
  60. }
  61. /* Set token claims */
  62. claims := make(map[string]interface{})
  63. claims["admin"] = user.Admin
  64. claims["name"] = user.Name
  65. claims["exp"] = time.Now().Add(time.Hour * 24).Unix()
  66. /* Create the token */
  67. token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims(claims))
  68. /* Sign the token with our secret */
  69. tokenString, err := token.SignedString(signingKey)
  70. if err != nil {
  71. return nil, err
  72. }
  73. return []byte(tokenString), nil
  74. }