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.

107 lines
2.4 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. UserID string `json:"user_id"`
  19. }
  20. func makeLoginResponse(w http.ResponseWriter, code int, message, pubKey, privKey string, userId string) {
  21. var (
  22. status string = "error"
  23. returnJson []byte
  24. err error
  25. )
  26. if code > 200 && code < 300 {
  27. status = "success"
  28. }
  29. returnJson, err = json.MarshalIndent(loginResponse{
  30. Status: status,
  31. Message: message,
  32. AsymmetricPublicKey: pubKey,
  33. AsymmetricPrivateKey: privKey,
  34. UserID: userId,
  35. }, "", " ")
  36. if err != nil {
  37. http.Error(w, "Error", http.StatusInternalServerError)
  38. w.WriteHeader(http.StatusInternalServerError)
  39. return
  40. }
  41. // Return updated json
  42. w.WriteHeader(code)
  43. w.Write(returnJson)
  44. }
  45. func Login(w http.ResponseWriter, r *http.Request) {
  46. var (
  47. creds Credentials
  48. userData Models.User
  49. session Models.Session
  50. expiresAt time.Time
  51. err error
  52. )
  53. err = json.NewDecoder(r.Body).Decode(&creds)
  54. if err != nil {
  55. makeLoginResponse(w, http.StatusInternalServerError, "An error occurred", "", "", "")
  56. return
  57. }
  58. userData, err = Database.GetUserByUsername(creds.Username)
  59. if err != nil {
  60. makeLoginResponse(w, http.StatusUnauthorized, "An error occurred", "", "", "")
  61. return
  62. }
  63. if !CheckPasswordHash(creds.Password, userData.Password) {
  64. makeLoginResponse(w, http.StatusUnauthorized, "An error occurred", "", "", "")
  65. return
  66. }
  67. // TODO: Revisit before production
  68. expiresAt = time.Now().Add(12 * time.Hour)
  69. session = Models.Session{
  70. UserID: userData.ID,
  71. Expiry: expiresAt,
  72. }
  73. err = Database.CreateSession(&session)
  74. if err != nil {
  75. makeLoginResponse(w, http.StatusUnauthorized, "An error occurred", "", "", "")
  76. return
  77. }
  78. http.SetCookie(w, &http.Cookie{
  79. Name: "session_token",
  80. Value: session.ID.String(),
  81. Expires: expiresAt,
  82. })
  83. makeLoginResponse(
  84. w,
  85. http.StatusOK,
  86. "Successfully logged in",
  87. userData.AsymmetricPublicKey,
  88. userData.AsymmetricPrivateKey,
  89. userData.ID.String(),
  90. )
  91. }