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.

72 lines
1.8 KiB

  1. package Auth
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "net/http"
  6. "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
  7. )
  8. type rawChangePassword struct {
  9. OldPassword string `json:"old_password"`
  10. NewPassword string `json:"new_password"`
  11. NewPasswordConfirm string `json:"new_password_confirm"`
  12. PrivateKey string `json:"private_key"`
  13. }
  14. // ChangePassword handle change password action
  15. func ChangePassword(w http.ResponseWriter, r *http.Request) {
  16. var (
  17. user Database.User
  18. changePassword rawChangePassword
  19. requestBody []byte
  20. err error
  21. )
  22. user, err = CheckCookieCurrentUser(w, r)
  23. if err != nil {
  24. // Don't bother showing an error here, as the middleware handles auth
  25. return
  26. }
  27. requestBody, err = ioutil.ReadAll(r.Body)
  28. if err != nil {
  29. http.Error(w, "Error", http.StatusInternalServerError)
  30. return
  31. }
  32. err = json.Unmarshal(requestBody, &changePassword)
  33. if err != nil {
  34. http.Error(w, "Error", http.StatusInternalServerError)
  35. return
  36. }
  37. if !CheckPasswordHash(changePassword.OldPassword, user.Password) {
  38. http.Error(w, "Invalid Current Password", http.StatusForbidden)
  39. return
  40. }
  41. // This should never occur, due to frontend validation
  42. if changePassword.NewPassword != changePassword.NewPasswordConfirm {
  43. http.Error(w, "Invalid New Password", http.StatusUnprocessableEntity)
  44. return
  45. }
  46. user.Password, err = HashPassword(changePassword.NewPassword)
  47. if err != nil {
  48. http.Error(w, "Error", http.StatusInternalServerError)
  49. return
  50. }
  51. // Private key doesn't change at this point, is just re-encrypted with the new password
  52. user.AsymmetricPrivateKey = changePassword.PrivateKey
  53. err = (&user).UpdateUser()
  54. if err != nil {
  55. http.Error(w, "Error", http.StatusInternalServerError)
  56. return
  57. }
  58. w.WriteHeader(http.StatusNoContent)
  59. }