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.5 KiB

  1. package Auth
  2. import (
  3. "database/sql/driver"
  4. "encoding/json"
  5. "net/http"
  6. "time"
  7. "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
  8. )
  9. type credentials struct {
  10. Username string `json:"username"`
  11. Password string `json:"password"`
  12. }
  13. type loginResponse struct {
  14. UserID string `json:"user_id"`
  15. Username string `json:"username"`
  16. AsymmetricPublicKey string `json:"asymmetric_public_key"`
  17. AsymmetricPrivateKey string `json:"asymmetric_private_key"`
  18. SymmetricKey string `json:"symmetric_key"`
  19. MessageExpiryDefault string `json:"message_expiry_default"`
  20. ImageLink string `json:"image_link"`
  21. }
  22. // Login logs the user into the system
  23. func Login(w http.ResponseWriter, r *http.Request) {
  24. var (
  25. creds credentials
  26. user Database.User
  27. session Database.Session
  28. expiresAt time.Time
  29. messageExpiryRaw driver.Value
  30. messageExpiry string
  31. imageLink string
  32. returnJSON []byte
  33. err error
  34. )
  35. err = json.NewDecoder(r.Body).Decode(&creds)
  36. if err != nil {
  37. http.Error(w, "Unauthorized", http.StatusUnauthorized)
  38. return
  39. }
  40. user, err = Database.GetUserByUsername(creds.Username)
  41. if err != nil {
  42. http.Error(w, "Unauthorized", http.StatusUnauthorized)
  43. return
  44. }
  45. if !CheckPasswordHash(creds.Password, user.Password) {
  46. http.Error(w, "Unauthorized", http.StatusUnauthorized)
  47. return
  48. }
  49. // TODO: Revisit before production
  50. expiresAt = time.Now().Add(12 * time.Hour)
  51. session = Database.Session{
  52. UserID: user.ID,
  53. Expiry: expiresAt,
  54. }
  55. err = (&session).CreateSession()
  56. if err != nil {
  57. http.Error(w, "Unauthorized", http.StatusUnauthorized)
  58. return
  59. }
  60. http.SetCookie(w, &http.Cookie{
  61. Name: "session_token",
  62. Value: session.ID.String(),
  63. Expires: expiresAt,
  64. })
  65. if user.AttachmentID != nil {
  66. imageLink = user.Attachment.FilePath
  67. }
  68. messageExpiryRaw, _ = user.MessageExpiryDefault.Value()
  69. messageExpiry, _ = messageExpiryRaw.(string)
  70. returnJSON, err = json.MarshalIndent(loginResponse{
  71. UserID: user.ID.String(),
  72. Username: user.Username,
  73. AsymmetricPublicKey: user.AsymmetricPublicKey,
  74. AsymmetricPrivateKey: user.AsymmetricPrivateKey,
  75. SymmetricKey: user.SymmetricKey,
  76. MessageExpiryDefault: messageExpiry,
  77. ImageLink: imageLink,
  78. }, "", " ")
  79. if err != nil {
  80. http.Error(w, "Unauthorized", http.StatusUnauthorized)
  81. return
  82. }
  83. // Return updated json
  84. w.WriteHeader(http.StatusOK)
  85. w.Write(returnJSON)
  86. }