This repository has been archived on 2023-07-09. You can view files and clone it, but cannot push or open issues or pull requests.
sudoscientist-go-backend/packages/users/users.go

93 lines
2.2 KiB
Go

package users
import (
"database/sql"
"encoding/json"
"fmt"
"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:"country",db:"country"`
Bio string `json:"bio",db:"bio"`
}
func Init() {
dbCreateStatement := `
CREATE TABLE IF NOT EXISTS user_profiles
(id SERIAL PRIMARY KEY,
username text REFERENCES users (username),
email text,
country text,
bio text)`
DB.Exec(dbCreateStatement)
}
func Routes() *chi.Mux {
r := chi.NewRouter()
r.Group(func(r chi.Router) {
r.Use(jwtauth.Verifier(TokenAuth))
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, country, 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,
country = $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, country, bio)
VALUES ($1, $2, $3, $4)`
DB.Exec(blankProfileStatement, username, email, "", "")
}