82 lines
1.8 KiB
Go
82 lines
1.8 KiB
Go
|
package api
|
||
|
|
||
|
import (
|
||
|
"github.com/gorilla/mux"
|
||
|
"gorm.io/gorm"
|
||
|
"net/http"
|
||
|
"sonarqube-badge/router/middlewares"
|
||
|
"sonarqube-badge/router/utils"
|
||
|
"sonarqube-badge/store"
|
||
|
)
|
||
|
|
||
|
func changePassword(w http.ResponseWriter, r *http.Request) {
|
||
|
db, _, user, done := utils.VerifyUser(w, r)
|
||
|
if done {
|
||
|
return
|
||
|
}
|
||
|
|
||
|
password := r.FormValue("password")
|
||
|
verifyPassword := r.FormValue("verify_password")
|
||
|
|
||
|
if password != verifyPassword {
|
||
|
w.WriteHeader(http.StatusBadRequest)
|
||
|
w.Write([]byte("passwords do not match"))
|
||
|
return
|
||
|
}
|
||
|
|
||
|
user.ChangePassword(db, password)
|
||
|
|
||
|
refreshCookie(db, user.ID, r, w)
|
||
|
w.WriteHeader(http.StatusNoContent)
|
||
|
}
|
||
|
|
||
|
func changeEmail(w http.ResponseWriter, r *http.Request) {
|
||
|
db, _, user, done := utils.VerifyUser(w, r)
|
||
|
if done {
|
||
|
return
|
||
|
}
|
||
|
|
||
|
newEmail := r.FormValue("email")
|
||
|
if user.ChangeEmail(db, newEmail) != nil {
|
||
|
w.WriteHeader(http.StatusBadRequest)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
user.Email = newEmail
|
||
|
|
||
|
refreshCookie(db, user.ID, r, w)
|
||
|
w.WriteHeader(http.StatusNoContent)
|
||
|
}
|
||
|
|
||
|
func changeUsername(w http.ResponseWriter, r *http.Request) {
|
||
|
db, _, user, done := utils.VerifyUser(w, r)
|
||
|
if done {
|
||
|
return
|
||
|
}
|
||
|
|
||
|
newUsername := r.FormValue("username")
|
||
|
user.ChangeUsername(db, newUsername)
|
||
|
|
||
|
refreshCookie(db, user.ID, r, w)
|
||
|
w.WriteHeader(http.StatusNoContent)
|
||
|
}
|
||
|
|
||
|
func refreshCookie(db *gorm.DB, userId uint, r *http.Request, w http.ResponseWriter) {
|
||
|
var user store.User
|
||
|
db.First(&user, userId)
|
||
|
cookie, err := utils.CreateJWTCookie(&user, r)
|
||
|
if err != nil {
|
||
|
w.WriteHeader(http.StatusInternalServerError)
|
||
|
return
|
||
|
}
|
||
|
http.SetCookie(w, cookie)
|
||
|
}
|
||
|
|
||
|
func UserRouter(r *mux.Router) {
|
||
|
sr := r.PathPrefix("/").Subrouter()
|
||
|
sr.Use(middlewares.CheckJwtToken)
|
||
|
sr.HandleFunc("/password", changePassword).Methods("POST")
|
||
|
sr.HandleFunc("/email", changeEmail).Methods("POST")
|
||
|
sr.HandleFunc("/username", changeUsername).Methods("POST")
|
||
|
}
|