databag/net/server/internal/api_setAccountAuthentication.go

51 lines
1.1 KiB
Go
Raw Normal View History

2022-03-08 18:18:31 +00:00
package databag
import (
"errors"
"strings"
2022-03-08 18:18:31 +00:00
"net/http"
2022-03-08 21:31:04 +00:00
"gorm.io/gorm"
2022-03-08 18:18:31 +00:00
"databag/internal/store"
)
func SetAccountAuthentication(w http.ResponseWriter, r *http.Request) {
token, res := BearerAccountToken(r)
2022-07-22 17:52:13 +00:00
if res != nil || token.TokenType != APPTokenReset {
2022-03-08 18:18:31 +00:00
ErrResponse(w, http.StatusUnauthorized, res)
return
}
if token.Account == nil {
ErrResponse(w, http.StatusUnauthorized, errors.New("invalid reset token"))
return
}
username, password, ret := BasicCredentials(r)
2022-03-08 21:31:04 +00:00
if ret != nil || username == "" || password == nil || len(password) == 0 {
ErrResponse(w, http.StatusBadRequest, errors.New("invalid credentials"))
2022-03-08 18:18:31 +00:00
return
}
token.Account.Username = username;
token.Account.Handle = strings.ToLower(username);
2022-03-08 18:18:31 +00:00
token.Account.Password = password;
2022-07-22 06:57:40 +00:00
2022-03-08 21:31:04 +00:00
err := store.DB.Transaction(func(tx *gorm.DB) error {
if res := tx.Save(token.Account).Error; res != nil {
return res
}
if res := tx.Delete(token).Error; res != nil {
return res
}
return nil
})
if err != nil {
2022-03-08 18:18:31 +00:00
ErrResponse(w, http.StatusInternalServerError, err)
return
}
WriteResponse(w, nil)
}