76 lines
1.7 KiB
Go
76 lines
1.7 KiB
Go
package users
|
|
|
|
import (
|
|
"database/sql"
|
|
"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"`
|
|
Email string `json:"email"`
|
|
Country string `json:"country"`
|
|
Bio string `json:"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"]
|
|
searchname := chi.URLParam(r, "username")
|
|
if username != searchname {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
return
|
|
}
|
|
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, "", "")
|
|
}
|