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.

76 lines
1.9 KiB

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