package users import ( "database/sql" "encoding/json" "fmt" "git.minhas.io/asara/sudoscientist-go-backend/packages/middleware" "github.com/go-chi/chi" "github.com/go-chi/jwtauth" "github.com/go-chi/render" "net/http" ) var ( DB *sql.DB TokenAuth *jwtauth.JWTAuth ) type User struct { Username string `json:"username",db:"username"` Email string `json:"email",db:"email"` Country string `json:"location",db:"location"` Bio string `json:"bio",db:"bio"` } func Routes() *chi.Mux { r := chi.NewRouter() r.Group(func(r chi.Router) { r.Use(jwtauth.Verify(TokenAuth, auth_middleware.TokenFromSplitCookie)) r.Use(jwtauth.Authenticator) r.Put("/{username}", updateUser) }) r.Get("/{username}", getUser) return r } func getUser(w http.ResponseWriter, r *http.Request) { username := chi.URLParam(r, "username") result := DB.QueryRow("SELECT username, email, location, bio FROM user_profiles WHERE username=$1", username) user := User{} err := result.Scan(&user.Username, &user.Email, &user.Country, &user.Bio) fmt.Println(err) if err != nil { w.WriteHeader(http.StatusBadRequest) return } render.JSON(w, r, user) } func updateUser(w http.ResponseWriter, r *http.Request) { _, claims, _ := jwtauth.FromContext(r.Context()) username := claims["username"].(string) searchname := chi.URLParam(r, "username") if username != searchname { w.WriteHeader(http.StatusUnauthorized) return } user := &User{} err := json.NewDecoder(r.Body).Decode(user) if err != nil { w.WriteHeader(http.StatusBadRequest) return } user.Username = username updateProfileStatement := ` UPDATE user_profiles SET username = $1, email = $2, location = $3, bio = $4 WHERE username = $5` _, err = DB.Exec(updateProfileStatement, user.Username, user.Email, user.Country, user.Bio, username) fmt.Println(err) return } func CreateProfile(username string, email string) { blankProfileStatement := ` INSERT INTO user_profiles (username, email, location, bio) VALUES ($1, $2, $3, $4)` DB.Exec(blankProfileStatement, username, email, "", "") }