Encrypted messaging app
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
2.3 KiB

  1. package Auth
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "time"
  6. "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
  7. "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
  8. )
  9. type Credentials struct {
  10. Username string `json:"username"`
  11. Password string `json:"password"`
  12. }
  13. type loginResponse struct {
  14. Status string `json:"status"`
  15. Message string `json:"message"`
  16. AsymmetricPublicKey string `json:"asymmetric_public_key"`
  17. AsymmetricPrivateKey string `json:"asymmetric_private_key"`
  18. }
  19. func makeLoginResponse(w http.ResponseWriter, code int, message, pubKey, privKey string) {
  20. var (
  21. status string = "error"
  22. returnJson []byte
  23. err error
  24. )
  25. if code > 200 && code < 300 {
  26. status = "success"
  27. }
  28. returnJson, err = json.MarshalIndent(loginResponse{
  29. Status: status,
  30. Message: message,
  31. AsymmetricPublicKey: pubKey,
  32. AsymmetricPrivateKey: privKey,
  33. }, "", " ")
  34. if err != nil {
  35. http.Error(w, "Error", http.StatusInternalServerError)
  36. w.WriteHeader(http.StatusInternalServerError)
  37. return
  38. }
  39. // Return updated json
  40. w.WriteHeader(code)
  41. w.Write(returnJson)
  42. }
  43. func Login(w http.ResponseWriter, r *http.Request) {
  44. var (
  45. creds Credentials
  46. userData Models.User
  47. session Models.Session
  48. expiresAt time.Time
  49. err error
  50. )
  51. err = json.NewDecoder(r.Body).Decode(&creds)
  52. if err != nil {
  53. makeLoginResponse(w, http.StatusInternalServerError, "An error occurred", "", "")
  54. return
  55. }
  56. userData, err = Database.GetUserByUsername(creds.Username)
  57. if err != nil {
  58. makeLoginResponse(w, http.StatusUnauthorized, "An error occurred", "", "")
  59. return
  60. }
  61. if !CheckPasswordHash(creds.Password, userData.Password) {
  62. makeLoginResponse(w, http.StatusUnauthorized, "An error occurred", "", "")
  63. return
  64. }
  65. expiresAt = time.Now().Add(12 * time.Hour)
  66. session = Models.Session{
  67. UserID: userData.ID,
  68. Expiry: expiresAt,
  69. }
  70. err = Database.CreateSession(&session)
  71. if err != nil {
  72. makeLoginResponse(w, http.StatusUnauthorized, "An error occurred", "", "")
  73. return
  74. }
  75. http.SetCookie(w, &http.Cookie{
  76. Name: "session_token",
  77. Value: session.ID.String(),
  78. Expires: expiresAt,
  79. })
  80. makeLoginResponse(
  81. w,
  82. http.StatusOK,
  83. "Successfully logged in",
  84. userData.AsymmetricPublicKey,
  85. userData.AsymmetricPrivateKey,
  86. )
  87. }