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.

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