add users
This commit is contained in:
51
backend/internal/users/password.go
Normal file
51
backend/internal/users/password.go
Normal file
@ -0,0 +1,51 @@
|
||||
package users
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/internal/auth"
|
||||
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/internal/model"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func (s Service) ChangePassword(w http.ResponseWriter, r *http.Request) {
|
||||
var err error
|
||||
var req Password
|
||||
user := model.NewUser()
|
||||
|
||||
if err = json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
if claims, ok := auth.ExtractClaims(r.Context()); !ok {
|
||||
log.Println("Error: was not able to extract Claims")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
} else {
|
||||
user.ID = claims.UserID
|
||||
}
|
||||
|
||||
if len([]byte(req.Password)) > 72 {
|
||||
fmt.Fprint(w, "Password to long, max 72 bytes")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if user.Password, err = bcrypt.GenerateFromPassword([]byte(req.Password), 6); err != nil {
|
||||
log.Println("Error: ", err)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
err = s.db.Model(&user).
|
||||
Where("id = ?", user.ID).
|
||||
Update("password", user.Password).
|
||||
Error
|
||||
if err != nil {
|
||||
log.Printf("Error: %v", err)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
Reference in New Issue
Block a user