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

76 lines
1.7 KiB
Go
Raw Normal View History

2019-02-07 04:46:30 +00:00
package users
import (
"database/sql"
2019-04-14 03:38:51 +00:00
"fmt"
2019-02-07 04:46:30 +00:00
"github.com/go-chi/chi"
2019-02-08 04:43:26 +00:00
"github.com/go-chi/jwtauth"
2019-02-07 04:46:30 +00:00
"github.com/go-chi/render"
"net/http"
)
var (
DB *sql.DB
2019-02-08 04:43:26 +00:00
TokenAuth *jwtauth.JWTAuth
2019-02-07 04:46:30 +00:00
)
type User struct {
2019-04-14 03:38:51 +00:00
Username string `json:"username"`
Email string `json:"email"`
Country string `json:"country"`
Bio string `json:"bio"`
2019-02-07 04:46:30 +00:00
}
func Init() {
dbCreateStatement := `
CREATE TABLE IF NOT EXISTS user_profiles
(id SERIAL PRIMARY KEY,
username text REFERENCES users (username),
2019-04-14 03:38:51 +00:00
email text,
2019-02-07 04:46:30 +00:00
country text,
bio text)`
DB.Exec(dbCreateStatement)
}
func Routes() *chi.Mux {
2019-02-08 04:43:26 +00:00
r := chi.NewRouter()
r.Group(func(r chi.Router) {
r.Use(jwtauth.Verifier(TokenAuth))
r.Use(jwtauth.Authenticator)
2019-04-14 03:38:51 +00:00
r.Put("/{username}", updateUser)
2019-02-08 04:43:26 +00:00
})
2019-04-14 03:38:51 +00:00
r.Get("/{username}", getUser)
2019-02-08 04:43:26 +00:00
return r
2019-02-07 04:46:30 +00:00
}
2019-02-08 04:43:26 +00:00
func getUser(w http.ResponseWriter, r *http.Request) {
2019-02-07 04:46:30 +00:00
username := chi.URLParam(r, "username")
2019-04-14 03:38:51 +00:00
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
2019-02-07 04:46:30 +00:00
}
2019-02-08 04:43:26 +00:00
render.JSON(w, r, user)
}
func updateUser(w http.ResponseWriter, r *http.Request) {
2019-04-14 03:38:51 +00:00
_, claims, _ := jwtauth.FromContext(r.Context())
2019-04-14 16:44:02 +00:00
username := claims["username"].(string)
2019-04-14 03:38:51 +00:00
searchname := chi.URLParam(r, "username")
if username != searchname {
w.WriteHeader(http.StatusUnauthorized)
return
}
2019-02-08 04:43:26 +00:00
return
2019-02-07 04:46:30 +00:00
}
2019-04-14 03:38:51 +00:00
func CreateProfile(username string, email string) {
2019-02-07 04:46:30 +00:00
blankProfileStatement := `
2019-04-14 03:38:51 +00:00
INSERT INTO user_profiles (username, email, country, bio)
VALUES ($1, $2, $3, $4)`
DB.Exec(blankProfileStatement, username, email, "", "")
2019-02-07 04:46:30 +00:00
}