Compare commits
No commits in common. "master" and "v1.0.0" have entirely different histories.
23 changed files with 208 additions and 618 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
@ -24,5 +24,3 @@ _testmain.go
|
|||
*.test
|
||||
*.prof
|
||||
|
||||
# Settings
|
||||
settings/*.env
|
||||
|
|
38
README.md
38
README.md
|
@ -4,7 +4,7 @@
|
|||
|
||||
### Setup
|
||||
|
||||
Install steps are for Debian 11 (bullseye)
|
||||
Install steps are for Debian 9 (stretch)
|
||||
|
||||
1. Install docker-ce
|
||||
```
|
||||
|
@ -20,29 +20,23 @@ Install steps are for Debian 11 (bullseye)
|
|||
Key fingerprint = 9DC8 5822 9FC7 DD38 854A E2D8 8D81 803C 0EBF CD88
|
||||
Docker Release (CE deb) <docker@docker.com>
|
||||
sub 4096R/F273FCD8 2017-02-22
|
||||
# ----------
|
||||
# ----------
|
||||
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/debian $(lsb_release -cs) stable"
|
||||
sudo apt-get update
|
||||
sudo apt-get install docker-ce docker-ce-cli containerd.io
|
||||
```
|
||||
|
||||
2. Install golang
|
||||
2. Install golang 1.11
|
||||
```
|
||||
# stretch doesn't have the latest golang so we install backports
|
||||
sudo add-apt-repository "deb http://deb.debian.org/debian stretch-backports main"
|
||||
sudo apt-get update
|
||||
sudo apt-get install golang
|
||||
sudo apt-get -t stretch-backports install golang
|
||||
# set the gopath manually for the rest of the setup
|
||||
export GOPATH=${HOME}/go
|
||||
```
|
||||
|
||||
3. Install migrate
|
||||
```
|
||||
# this assumes you have ${GOPATH}/bin in your ${PATH}
|
||||
go get -u -d github.com/mattes/migrate/cli github.com/lib/pq
|
||||
go build -tags 'postgres' -o ${GOPATH}/bin/migrate github.com/mattes/migrate/cli
|
||||
|
||||
```
|
||||
|
||||
4. Clone repo and configure the settings
|
||||
3. Clone repo and configure the settings
|
||||
```
|
||||
mkdir -p ${GOPATH}/src/git.minhas.io/asara
|
||||
cd ${GOPATH}/src/git.minhas.io/asara
|
||||
|
@ -51,16 +45,14 @@ Install steps are for Debian 11 (bullseye)
|
|||
# make sure the extension is .env (db.env, secrets.env, website.env... etc.)
|
||||
```
|
||||
|
||||
5. Configure docker postgres for testing
|
||||
4. Configure docker postgres for testing
|
||||
```
|
||||
# make sure your user is in the docker group
|
||||
sudo usermod -aG docker $(whoami)
|
||||
|
||||
# make sure you have some postgres client installed
|
||||
sudo apt-get install postgres-client
|
||||
docker pull postgres
|
||||
docker run -e POSTGRES_PASSWORD=${DB_ADMIN_PW} --name sudosci-db -d postgres
|
||||
|
||||
docker run --name sudosci-db -e POSTGRES_PASWORD=${DB_ADMIN_PW} -d postgres # please set the db admin pw manually
|
||||
# Initalize the postgres DB
|
||||
cd ${GOPATH}/src/git.minhas.io/asara/sudoscientist
|
||||
for i in settings/*; do source $i; done
|
||||
|
@ -69,22 +61,14 @@ Install steps are for Debian 11 (bullseye)
|
|||
CREATE DATABASE ${DB_NAME};
|
||||
CREATE USER ${DB_USER} WITH ENCRYPTED PASSWORD '${DB_PW}';
|
||||
GRANT ALL PRIVILEGES ON DATABASE ${DB_NAME} TO ${DB_USER};
|
||||
ALTER DATABASE ${DB_NAME} OWNER TO ${DB_USER};
|
||||
EOF
|
||||
```
|
||||
|
||||
6. Run the application!
|
||||
```
|
||||
PLEASE NOTE, THERE ARE DEFAULT TEST VALUES FOR A POSTAL SERVER
|
||||
PLEASE REMOVE THESE IF YOU DONT HAVE A POSTAL BACKEND TO TEST FROM!
|
||||
```
|
||||
[For more information on Postal](https://github.com/postalhq/postal)
|
||||
5. Run the application!
|
||||
```
|
||||
cd ${GOPATH}/src/git.minhas.io/asara/sudoscientist-go-backend
|
||||
for i in settings/*.env; do source $i; done
|
||||
for i in settings/*; do source $i; done
|
||||
export DB_HOST=$(docker inspect -f "{{ .NetworkSettings.IPAddress }}" sudosci-db)
|
||||
PSQL_QUERY_STRING="postgres://${DB_USER}:${DB_PW}@${DB_HOST}:${DB_PORT}/${DB_NAME}?sslmode=${DB_SSL}"
|
||||
migrate -path migrations/ -database ${PSQL_QUERY_STRING} up
|
||||
go get
|
||||
go run main.go
|
||||
```
|
||||
|
|
1
TODO.md
Normal file
1
TODO.md
Normal file
|
@ -0,0 +1 @@
|
|||
#. Implement comments
|
|
@ -12,6 +12,5 @@ psql -d postgres -U postgres -h ${DB_HOST} << EOF
|
|||
CREATE DATABASE ${DB_NAME};
|
||||
CREATE USER ${DB_USER} WITH ENCRYPTED PASSWORD '${DB_PW}';
|
||||
GRANT ALL PRIVILEGES ON DATABASE ${DB_NAME} TO ${DB_USER};
|
||||
ALTER DATABASE ${DB_NAME} OWNER TO ${DB_USER};
|
||||
EOF
|
||||
echo Done
|
||||
|
|
18
main.go
18
main.go
|
@ -1,15 +1,12 @@
|
|||
package main
|
||||
|
||||
// force pushing
|
||||
import (
|
||||
"compress/flate"
|
||||
"fmt"
|
||||
_ "github.com/lib/pq"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
_ "github.com/lib/pq"
|
||||
|
||||
"git.minhas.io/asara/sudoscientist-go-backend/packages/auth"
|
||||
"git.minhas.io/asara/sudoscientist-go-backend/packages/blog"
|
||||
"git.minhas.io/asara/sudoscientist-go-backend/packages/database"
|
||||
|
@ -26,17 +23,16 @@ func main() {
|
|||
db, _ := database.NewDB()
|
||||
defer db.Close()
|
||||
auth.DB = db
|
||||
auth.Init()
|
||||
users.DB = db
|
||||
users.Init()
|
||||
blog.DB = db
|
||||
blog.Init()
|
||||
|
||||
// initiate jwt token
|
||||
auth.TokenAuth = jwtauth.New("HS256", []byte(os.Getenv("JWT_SECRET")), nil)
|
||||
users.TokenAuth = auth.TokenAuth
|
||||
blog.TokenAuth = auth.TokenAuth
|
||||
|
||||
// initilize auth for email verification
|
||||
auth.Init()
|
||||
|
||||
// initiate the routes
|
||||
router := Routes()
|
||||
|
||||
|
@ -57,20 +53,18 @@ func main() {
|
|||
func Routes() *chi.Mux {
|
||||
router := chi.NewRouter()
|
||||
cors := cors.New(cors.Options{
|
||||
AllowedOrigins: []string{os.Getenv("UI_PROTO") + os.Getenv("UI_ADDR") + os.Getenv("UI_PORT"), os.Getenv("UI_PROTO") + "www." + os.Getenv("UI_ADDR") + os.Getenv("UI_PORT")},
|
||||
AllowedOrigins: []string{"https://sudoscientist.com", "https://www.sudoscientist.com"},
|
||||
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"},
|
||||
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
|
||||
AllowCredentials: true,
|
||||
MaxAge: 360,
|
||||
})
|
||||
|
||||
compressor := middleware.NewCompressor(flate.DefaultCompression)
|
||||
|
||||
router.Use(
|
||||
compressor.Handler,
|
||||
cors.Handler,
|
||||
render.SetContentType(render.ContentTypeJSON),
|
||||
middleware.Logger,
|
||||
middleware.DefaultCompress,
|
||||
middleware.RedirectSlashes,
|
||||
middleware.Recoverer,
|
||||
)
|
||||
|
|
|
@ -1,4 +0,0 @@
|
|||
DROP TABLE IF EXISTS tags;
|
||||
DROP TABLE IF EXISTS posts;
|
||||
DROP TABLE IF EXISTS user_profiles;
|
||||
DROP TABLE IF EXISTS users;
|
|
@ -1,34 +0,0 @@
|
|||
BEGIN;
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
username text PRIMARY KEY,
|
||||
email text,
|
||||
password text,
|
||||
admin boolean
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_profiles (
|
||||
id SERIAL PRIMARY KEY,
|
||||
username text REFERENCES users (username),
|
||||
email text,
|
||||
location text,
|
||||
bio text
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS posts (
|
||||
id SERIAL PRIMARY KEY,
|
||||
title text,
|
||||
slug text,
|
||||
author text REFERENCES users (username),
|
||||
content text,
|
||||
time_published timestamp,
|
||||
modified bool,
|
||||
last_modified timestamp
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tags (
|
||||
id SERIAL PRIMARY KEY,
|
||||
tag text,
|
||||
article_id int REFERENCES posts (id)
|
||||
);
|
||||
|
||||
COMMIT;
|
|
@ -1,4 +0,0 @@
|
|||
BEGIN;
|
||||
ALTER TABLE users
|
||||
DROP COLUMN verified IF EXISTS;
|
||||
COMMIT;
|
|
@ -1,4 +0,0 @@
|
|||
BEGIN;
|
||||
ALTER TABLE users
|
||||
ADD COLUMN verified boolean NOT NULL DEFAULT false;
|
||||
COMMIT;
|
|
@ -1,3 +0,0 @@
|
|||
BEGIN;
|
||||
DROP TABLE IF EXISTS comments;
|
||||
COMMIT;
|
|
@ -1,11 +0,0 @@
|
|||
BEGIN;
|
||||
CREATE TABLE IF NOT EXISTS comments (
|
||||
id SERIAL PRIMARY KEY,
|
||||
parent INTEGER REFERENCES posts (id),
|
||||
author text REFERENCES users (username),
|
||||
content text,
|
||||
time_published timestamp,
|
||||
modified bool,
|
||||
last_modified timestamp
|
||||
);
|
||||
COMMIT;
|
|
@ -1,53 +1,29 @@
|
|||
package auth
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"git.minhas.io/asara/sudoscientist-go-backend/packages/middleware"
|
||||
"git.minhas.io/asara/sudoscientist-go-backend/packages/users"
|
||||
"github.com/badoux/checkmail"
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/go-chi/jwtauth"
|
||||
"github.com/go-chi/render"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
DB *sql.DB
|
||||
TokenAuth *jwtauth.JWTAuth
|
||||
EmailAuth *jwtauth.JWTAuth
|
||||
PostalEnabled bool
|
||||
PostalKey string
|
||||
PostalAPI string
|
||||
PostalEmail string
|
||||
DB *sql.DB
|
||||
TokenAuth *jwtauth.JWTAuth
|
||||
)
|
||||
|
||||
func Init() {
|
||||
if postal_key, ok := os.LookupEnv("POSTAL_KEY"); ok {
|
||||
if postal_api, ok := os.LookupEnv("POSTAL_API"); ok {
|
||||
if email_src, ok := os.LookupEnv("POSTAL_SRC_EMAIL"); ok {
|
||||
if email_auth, ok := os.LookupEnv("EMAIL_SECRET"); ok {
|
||||
EmailAuth = jwtauth.New("HS256", []byte(email_auth), nil)
|
||||
PostalKey = postal_key
|
||||
PostalAPI = postal_api
|
||||
PostalEmail = email_src
|
||||
PostalEnabled = true
|
||||
fmt.Println("Postal Enabled")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type ReturnMessage struct {
|
||||
Message string `json:"msg"`
|
||||
Error bool `json:"error"`
|
||||
type ReturnError struct {
|
||||
Message string `json:"error"`
|
||||
}
|
||||
|
||||
type SignUpCredentials struct {
|
||||
|
@ -56,35 +32,26 @@ type SignUpCredentials struct {
|
|||
Password string `json:"password", db:"password"`
|
||||
}
|
||||
|
||||
type UserCredentials struct {
|
||||
type SignInCredentials struct {
|
||||
Username string `json:"username", db:"username"`
|
||||
Password string `json:"password", db:"password"`
|
||||
}
|
||||
|
||||
type Claims struct {
|
||||
Username string `json:"username", db:"username"`
|
||||
Admin bool `json:"admin", db:"admin"`
|
||||
Verified bool `json:"verified", db:"verified"`
|
||||
Username string `json:"username"`
|
||||
jwt.StandardClaims
|
||||
}
|
||||
|
||||
type JWT struct {
|
||||
JWT string `json:"jwt"`
|
||||
}
|
||||
|
||||
type ComposedEmail struct {
|
||||
To [1]string `json:"to"`
|
||||
From string `json:"from"`
|
||||
Subject string `json:"subject"`
|
||||
Plain_body string `json:"plain_body"`
|
||||
func Init() {
|
||||
DB.Exec("CREATE TABLE IF NOT EXISTS users (username text primary key, email text, password text, admin boolean);")
|
||||
}
|
||||
|
||||
func Routes() *chi.Mux {
|
||||
r := chi.NewRouter()
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(jwtauth.Verify(EmailAuth, auth_middleware.TokenFromUrl))
|
||||
r.Use(jwtauth.Authenticator)
|
||||
r.Get("/verify/{token}", verify)
|
||||
})
|
||||
r.Post("/signin", signin)
|
||||
r.Post("/register", register)
|
||||
r.Group(func(r chi.Router) {
|
||||
|
@ -95,246 +62,119 @@ func Routes() *chi.Mux {
|
|||
return r
|
||||
}
|
||||
|
||||
func verify(w http.ResponseWriter, r *http.Request) {
|
||||
returnMessage := ReturnMessage{}
|
||||
returnMessage.Error = false
|
||||
_, claims, _ := jwtauth.FromContext(r.Context())
|
||||
sqlStatement := `
|
||||
UPDATE users
|
||||
SET verified = $1
|
||||
WHERE username = $2;`
|
||||
_, err := DB.Exec(sqlStatement, true, claims["username"])
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
returnMessage.Message = "unexpected error verifying account. please contact the administrator"
|
||||
returnMessage.Error = true
|
||||
render.JSON(w, r, returnMessage)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
returnMessage.Message = "your email has been verified!"
|
||||
render.JSON(w, r, returnMessage)
|
||||
return
|
||||
}
|
||||
|
||||
func register(w http.ResponseWriter, r *http.Request) {
|
||||
returnMessage := ReturnMessage{}
|
||||
returnMessage.Error = false
|
||||
returnError := ReturnError{}
|
||||
creds := &SignUpCredentials{}
|
||||
err := json.NewDecoder(r.Body).Decode(creds)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
returnMessage.Message = "bad data provided"
|
||||
returnMessage.Error = true
|
||||
render.JSON(w, r, returnMessage)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
if creds.Username == "" {
|
||||
returnMessage.Message = "username is required"
|
||||
returnMessage.Error = true
|
||||
returnError.Message = "username is required"
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
render.JSON(w, r, returnMessage)
|
||||
render.JSON(w, r, returnError)
|
||||
return
|
||||
}
|
||||
if creds.Password == "" {
|
||||
returnMessage.Message = "password is required"
|
||||
returnMessage.Error = true
|
||||
returnError.Message = "password is required"
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
render.JSON(w, r, returnMessage)
|
||||
render.JSON(w, r, returnError)
|
||||
return
|
||||
}
|
||||
if creds.Email == "" {
|
||||
returnMessage.Message = "email is required"
|
||||
returnMessage.Error = true
|
||||
returnError.Message = "email is required"
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
render.JSON(w, r, returnMessage)
|
||||
render.JSON(w, r, returnError)
|
||||
return
|
||||
}
|
||||
err = checkmail.ValidateFormat(creds.Email)
|
||||
if err != nil {
|
||||
returnMessage.Message = "email not valid"
|
||||
returnMessage.Error = true
|
||||
returnError.Message = "email not valid"
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
render.JSON(w, r, returnMessage)
|
||||
render.JSON(w, r, returnError)
|
||||
return
|
||||
}
|
||||
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(creds.Password), 10)
|
||||
s := `INSERT INTO users (username, email, password, admin, verified)
|
||||
VALUES ($1, $2, $3, $4, $5)`
|
||||
if _, err = DB.Exec(s, creds.Username, creds.Email, string(hashedPassword), false, false); err != nil {
|
||||
fmt.Println(err)
|
||||
returnMessage.Message = "unexpected error. please contact the administrator"
|
||||
returnMessage.Error = true
|
||||
s := `INSERT INTO users (username, email, password, admin)
|
||||
VALUES ($1, $2, $3, $4)`
|
||||
if _, err = DB.Exec(s, creds.Username, creds.Email, string(hashedPassword), false); err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
render.JSON(w, r, returnMessage)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
users.CreateProfile(creds.Username, creds.Email)
|
||||
expirationTime := time.Now().Add(24 * time.Hour)
|
||||
claims := map[string]interface{}{
|
||||
"username": creds.Username,
|
||||
"admin": false,
|
||||
"verified": false,
|
||||
}
|
||||
jwtauth.SetExpiry(claims, expirationTime)
|
||||
if PostalEnabled {
|
||||
_, emailToken, _ := EmailAuth.Encode(claims)
|
||||
returnMessage, ok := sendEmailToken(w, emailToken, creds.Username, creds.Email)
|
||||
if !ok {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
render.JSON(w, r, returnMessage)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
render.JSON(w, r, returnMessage)
|
||||
return
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
expirationTime := time.Now().Add(6 * time.Hour)
|
||||
claims := &Claims{
|
||||
Username: creds.Username,
|
||||
StandardClaims: jwt.StandardClaims{
|
||||
ExpiresAt: expirationTime.Unix(),
|
||||
},
|
||||
}
|
||||
_, tokenString, _ := TokenAuth.Encode(claims)
|
||||
setCookies(w, tokenString, expirationTime)
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
returnMessage.Message = "User created! Welcome to the site!"
|
||||
render.JSON(w, r, returnMessage)
|
||||
return
|
||||
token := setCookies(w, tokenString, expirationTime)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
render.JSON(w, r, token)
|
||||
}
|
||||
|
||||
func signin(w http.ResponseWriter, r *http.Request) {
|
||||
returnMessage := ReturnMessage{}
|
||||
returnMessage.Error = false
|
||||
creds := &UserCredentials{}
|
||||
creds := &SignInCredentials{}
|
||||
err := json.NewDecoder(r.Body).Decode(creds)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
returnMessage.Message = "bad data provided"
|
||||
returnMessage.Error = true
|
||||
render.JSON(w, r, returnMessage)
|
||||
return
|
||||
}
|
||||
verify_pw, ok := checkPassword(w, *creds)
|
||||
if !ok {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
returnMessage.Message = verify_pw
|
||||
returnMessage.Error = true
|
||||
render.JSON(w, r, returnMessage)
|
||||
return
|
||||
}
|
||||
expirationTime := time.Now().Add(24 * time.Hour)
|
||||
user_claims := &Claims{}
|
||||
user_claims_query := DB.QueryRow("SELECT username, admin, verified FROM users WHERE username=$1", creds.Username)
|
||||
err = user_claims_query.Scan(&user_claims.Username, &user_claims.Admin, &user_claims.Verified)
|
||||
claims := map[string]interface{}{
|
||||
"username": user_claims.Username,
|
||||
"admin": user_claims.Admin,
|
||||
"verified": user_claims.Verified,
|
||||
}
|
||||
jwtauth.SetExpiry(claims, expirationTime)
|
||||
_, tokenString, _ := TokenAuth.Encode(claims)
|
||||
setCookies(w, tokenString, expirationTime)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
render.JSON(w, r, returnMessage)
|
||||
}
|
||||
|
||||
func refresh(w http.ResponseWriter, r *http.Request) {
|
||||
returnMessage := ReturnMessage{}
|
||||
returnMessage.Error = false
|
||||
_, claims, _ := jwtauth.FromContext(r.Context())
|
||||
w.WriteHeader(http.StatusOK)
|
||||
expirationTime := time.Now().Add(24 * time.Hour)
|
||||
user_claims := &Claims{}
|
||||
user_claims_query := DB.QueryRow("SELECT username, admin, verified FROM users WHERE username=$1", claims["username"].(string))
|
||||
err := user_claims_query.Scan(&user_claims.Username, &user_claims.Admin, &user_claims.Verified)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
returnMessage.Message = "unexpected error refreshing your token, please try again later"
|
||||
returnMessage.Error = true
|
||||
render.JSON(w, r, returnMessage)
|
||||
return
|
||||
}
|
||||
newClaims := map[string]interface{}{
|
||||
"username": user_claims.Username,
|
||||
"admin": user_claims.Admin,
|
||||
"verified": user_claims.Verified,
|
||||
}
|
||||
jwtauth.SetExpiry(newClaims, expirationTime)
|
||||
_, tokenString, _ := TokenAuth.Encode(newClaims)
|
||||
setCookies(w, tokenString, expirationTime)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
returnMessage.Message = "jwt refreshed"
|
||||
render.JSON(w, r, returnMessage)
|
||||
}
|
||||
|
||||
func setCookies(w http.ResponseWriter, jwt string, expiration time.Time) {
|
||||
splitToken := strings.Split(jwt, ".")
|
||||
dataCookie := http.Cookie{Name: "DataCookie", Value: strings.Join(splitToken[:2], "."), Expires: expiration, HttpOnly: false, Path: "/", Domain: os.Getenv("UI_ADDR"), MaxAge: 360}
|
||||
http.SetCookie(w, &dataCookie)
|
||||
signatureCookie := http.Cookie{Name: "SignatureCookie", Value: splitToken[2], Expires: expiration, HttpOnly: true, Path: "/", Domain: os.Getenv("UI_ADDR"), MaxAge: 360}
|
||||
http.SetCookie(w, &signatureCookie)
|
||||
return
|
||||
}
|
||||
|
||||
func sendEmailToken(w http.ResponseWriter, token string, name string, email string) (returnMessage ReturnMessage, ok bool) {
|
||||
header := "Thanks for joining sudoscientist, " + name + "!"
|
||||
body := "\n\nPlease click the following link to verify your email: "
|
||||
link := os.Getenv("API_ADDR") + "/v1/api/auth/verify/" + token
|
||||
email_array := [1]string{email}
|
||||
composed_email := ComposedEmail{
|
||||
To: email_array,
|
||||
From: PostalEmail,
|
||||
Subject: "sudoscientist: Please confirm your e-mail address",
|
||||
Plain_body: header + body + link,
|
||||
}
|
||||
postal_req, err := json.Marshal(&composed_email)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
returnMessage.Message = "unexpected error. your account may be in limbo. please contact the administrator"
|
||||
ok = false
|
||||
return returnMessage, ok
|
||||
}
|
||||
req, err := http.NewRequest("POST", fmt.Sprintf("%s/api/v1/send/message", PostalAPI), bytes.NewBuffer(postal_req))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-Server-API-Key", PostalKey)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
returnMessage.Message = "unexpected error. your account may be in limbo. please contact the administrator"
|
||||
ok = false
|
||||
return returnMessage, ok
|
||||
}
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
returnMessage.Message = "unexpected error. your account may be in limbo. please contact the administrator"
|
||||
ok = false
|
||||
return returnMessage, ok
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
returnMessage.Message = "verification email sent"
|
||||
ok = true
|
||||
return returnMessage, ok
|
||||
}
|
||||
|
||||
func checkPassword(w http.ResponseWriter, creds UserCredentials) (string, bool) {
|
||||
returnMessage := ""
|
||||
result := DB.QueryRow("SELECT password FROM users WHERE username=$1", creds.Username)
|
||||
storedCreds := &UserCredentials{}
|
||||
err := result.Scan(&storedCreds.Password)
|
||||
storedCreds := &SignInCredentials{}
|
||||
err = result.Scan(&storedCreds.Password)
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
returnMessage = "username or password incorrect"
|
||||
return returnMessage, false
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
returnMessage = "something is broken, please contact the administrator"
|
||||
return returnMessage, false
|
||||
return
|
||||
}
|
||||
if err = bcrypt.CompareHashAndPassword([]byte(storedCreds.Password), []byte(creds.Password)); err != nil {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
returnMessage = "username or password incorrect"
|
||||
return returnMessage, false
|
||||
}
|
||||
returnMessage = "user logged in"
|
||||
return returnMessage, true
|
||||
expirationTime := time.Now().Add(5 * time.Hour)
|
||||
claims := &Claims{
|
||||
Username: creds.Username,
|
||||
StandardClaims: jwt.StandardClaims{
|
||||
ExpiresAt: expirationTime.Unix(),
|
||||
},
|
||||
}
|
||||
_, tokenString, _ := TokenAuth.Encode(claims)
|
||||
token := setCookies(w, tokenString, expirationTime)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
render.JSON(w, r, token)
|
||||
}
|
||||
|
||||
func refresh(w http.ResponseWriter, r *http.Request) {
|
||||
_, claims, _ := jwtauth.FromContext(r.Context())
|
||||
w.WriteHeader(http.StatusOK)
|
||||
expirationTime := time.Now().Add(5 * time.Hour)
|
||||
newClaims := &Claims{
|
||||
Username: claims["username"].(string),
|
||||
StandardClaims: jwt.StandardClaims{
|
||||
ExpiresAt: expirationTime.Unix(),
|
||||
},
|
||||
}
|
||||
_, tokenString, _ := TokenAuth.Encode(newClaims)
|
||||
token := setCookies(w, tokenString, expirationTime)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
render.JSON(w, r, token)
|
||||
}
|
||||
|
||||
func setCookies(w http.ResponseWriter, jwt string, expiration time.Time) string {
|
||||
splitToken := strings.Split(jwt, ".")
|
||||
dataCookie := http.Cookie{Name: "DataCookie", Value: strings.Join(splitToken[:2], "."), Expires: expiration, HttpOnly: false, Path: "/", Domain: ".sudoscientist.com", MaxAge: 360, Secure: true}
|
||||
http.SetCookie(w, &dataCookie)
|
||||
signatureCookie := http.Cookie{Name: "SignatureCookie", Value: splitToken[2], Expires: expiration, HttpOnly: true, Path: "/", Domain: ".sudoscientist.com", MaxAge: 360, Secure: true}
|
||||
http.SetCookie(w, &signatureCookie)
|
||||
return strings.Join(splitToken[:2], ".")
|
||||
}
|
||||
|
|
|
@ -1,16 +0,0 @@
|
|||
package blog
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"github.com/go-chi/jwtauth"
|
||||
)
|
||||
|
||||
type ReturnMessage struct {
|
||||
Message string `json:"msg"`
|
||||
Error bool `json:"error"`
|
||||
}
|
||||
|
||||
var (
|
||||
DB *sql.DB
|
||||
TokenAuth *jwtauth.JWTAuth
|
||||
)
|
|
@ -4,6 +4,7 @@ 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"
|
||||
|
@ -13,6 +14,11 @@ import (
|
|||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
DB *sql.DB
|
||||
TokenAuth *jwtauth.JWTAuth
|
||||
)
|
||||
|
||||
type BlogPost struct {
|
||||
ID int `json:"id",db:"id"`
|
||||
Title string `json:"title",db:"title"`
|
||||
|
@ -37,52 +43,80 @@ type NewBlogPost struct {
|
|||
Author string `json:"author",db:"author"`
|
||||
}
|
||||
|
||||
type ReturnError struct {
|
||||
Message string `json:"error"`
|
||||
}
|
||||
|
||||
type ReturnSuccess struct {
|
||||
Message string `json:"success"`
|
||||
ID int `json:"id"`
|
||||
Slug string `json:"slug",db:"slug"`
|
||||
}
|
||||
|
||||
type ReferenceId struct {
|
||||
type ReferenceID struct {
|
||||
LastID int `json:"last_id"`
|
||||
}
|
||||
|
||||
func Init() {
|
||||
createPostsTable := `
|
||||
CREATE TABLE IF NOT EXISTS posts
|
||||
(id SERIAL PRIMARY KEY,
|
||||
title text,
|
||||
slug text,
|
||||
author text REFERENCES users (username),
|
||||
content text,
|
||||
time_published timestamp,
|
||||
modified bool,
|
||||
last_modified timestamp)`
|
||||
DB.Exec(createPostsTable)
|
||||
|
||||
createTagsTable := `
|
||||
CREATE TABLE IF NOT EXISTS tags
|
||||
(id SERIAL PRIMARY KEY,
|
||||
tag text,
|
||||
article_id int REFERENCES posts (id))`
|
||||
DB.Exec(createTagsTable)
|
||||
}
|
||||
|
||||
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.Post("/", createBlogPost)
|
||||
r.Patch("/by-id/{id}", updateBlogPostById)
|
||||
})
|
||||
r.Get("/", getBlogPosts)
|
||||
r.Get("/by-id/{id}", getBlogPostById)
|
||||
r.Get("/by-tag/{tag}", getBlogPostsByTag)
|
||||
r.Get("/by-author/{author}", getBlogPostsByAuthor)
|
||||
r.Get("/by-slug/{slug}", getBlogPostBySlug)
|
||||
return r
|
||||
}
|
||||
|
||||
func createBlogPost(w http.ResponseWriter, r *http.Request) {
|
||||
returnMessage := ReturnMessage{}
|
||||
returnMessage.Error = false
|
||||
returnError := ReturnError{}
|
||||
newBlogPost := &NewBlogPost{}
|
||||
// basic checks
|
||||
_, claims, _ := jwtauth.FromContext(r.Context())
|
||||
is_admin := claims["admin"].(bool)
|
||||
if !is_admin {
|
||||
returnMessage.Message = "sorry only admins are allowed to create blog posts"
|
||||
returnMessage.Error = true
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
render.JSON(w, r, returnMessage)
|
||||
return
|
||||
}
|
||||
|
||||
username := claims["username"].(string)
|
||||
err := json.NewDecoder(r.Body).Decode(newBlogPost)
|
||||
if err != nil {
|
||||
returnMessage.Message = "unknown error, try again later"
|
||||
returnMessage.Error = true
|
||||
returnError.Message = "unknown error, try again later"
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
render.JSON(w, r, returnMessage)
|
||||
render.JSON(w, r, returnError)
|
||||
return
|
||||
}
|
||||
if newBlogPost.Title == "" {
|
||||
returnMessage.Message = "title is required"
|
||||
returnMessage.Error = true
|
||||
returnError.Message = "title is required"
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
render.JSON(w, r, returnMessage)
|
||||
render.JSON(w, r, returnError)
|
||||
return
|
||||
}
|
||||
if newBlogPost.Content == "" {
|
||||
returnMessage.Message = "content is required"
|
||||
returnMessage.Error = true
|
||||
returnError.Message = "content is required"
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
render.JSON(w, r, returnMessage)
|
||||
render.JSON(w, r, returnError)
|
||||
return
|
||||
}
|
||||
as := slug.Make(newBlogPost.Title)
|
||||
|
@ -92,18 +126,16 @@ func createBlogPost(w http.ResponseWriter, r *http.Request) {
|
|||
scr := 0
|
||||
err = slugCheck.Scan(&scr)
|
||||
if err == nil {
|
||||
returnMessage.Message = "slug already exists"
|
||||
returnMessage.Error = true
|
||||
returnError.Message = "slug already exists"
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
render.JSON(w, r, returnMessage)
|
||||
render.JSON(w, r, returnError)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
if err != sql.ErrNoRows {
|
||||
returnMessage.Message = "something is super broken..."
|
||||
returnMessage.Error = true
|
||||
returnError.Message = "something is super broken..."
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
render.JSON(w, r, returnMessage)
|
||||
render.JSON(w, r, returnError)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
@ -116,17 +148,15 @@ func createBlogPost(w http.ResponseWriter, r *http.Request) {
|
|||
err = DB.QueryRow(s, newBlogPost.Title, as, username, newBlogPost.Content, time.Now().UTC(), false, time.Now().UTC()).Scan(&article_id)
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
returnMessage.Message = "something is super broken..."
|
||||
returnMessage.Error = true
|
||||
returnError.Message = "something is super broken..."
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
render.JSON(w, r, returnMessage)
|
||||
render.JSON(w, r, returnError)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
returnMessage.Message = "something is super broken..."
|
||||
returnMessage.Error = true
|
||||
returnError.Message = "something is super broken..."
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
render.JSON(w, r, returnMessage)
|
||||
render.JSON(w, r, returnError)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
@ -147,26 +177,23 @@ func createBlogPost(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
|
||||
func updateBlogPostById(w http.ResponseWriter, r *http.Request) {
|
||||
returnMessage := ReturnMessage{}
|
||||
returnMessage.Error = false
|
||||
returnError := ReturnError{}
|
||||
// Get the actual post
|
||||
id := chi.URLParam(r, "post_id")
|
||||
id := chi.URLParam(r, "id")
|
||||
result := DB.QueryRow("SELECT id, title, slug, author, content, time_published FROM posts WHERE id=$1", id)
|
||||
post := BlogPost{}
|
||||
err := result.Scan(&post.ID, &post.Title, &post.Slug, &post.Author, &post.Content, &post.TimePublished)
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
returnMessage.Message = "blog post requested for update not found"
|
||||
returnMessage.Error = true
|
||||
returnError.Message = "blog post requested for update not found"
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
render.JSON(w, r, returnMessage)
|
||||
render.JSON(w, r, returnError)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
returnMessage.Message = "something is super broken..."
|
||||
returnMessage.Error = true
|
||||
returnError.Message = "something is super broken..."
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
render.JSON(w, r, returnMessage)
|
||||
render.JSON(w, r, returnError)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
@ -175,10 +202,9 @@ func updateBlogPostById(w http.ResponseWriter, r *http.Request) {
|
|||
_, claims, _ := jwtauth.FromContext(r.Context())
|
||||
username := claims["username"].(string)
|
||||
if username != post.Author {
|
||||
returnMessage.Message = "unauthorized..."
|
||||
returnMessage.Error = true
|
||||
returnError.Message = "unauthorized..."
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
render.JSON(w, r, returnMessage)
|
||||
render.JSON(w, r, returnError)
|
||||
return
|
||||
}
|
||||
// update the post struct
|
||||
|
@ -193,10 +219,9 @@ func updateBlogPostById(w http.ResponseWriter, r *http.Request) {
|
|||
// write the row update
|
||||
_, err = DB.Exec(s, post.Title, post.Content, true, time.Now().UTC(), post.ID)
|
||||
if err != nil {
|
||||
returnMessage.Message = "something is super broken..."
|
||||
returnMessage.Error = true
|
||||
returnError.Message = "something is super broken..."
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
render.JSON(w, r, returnMessage)
|
||||
render.JSON(w, r, returnError)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
@ -208,9 +233,8 @@ func updateBlogPostById(w http.ResponseWriter, r *http.Request) {
|
|||
|
||||
// This will search by the last id seen, descending.
|
||||
func getBlogPosts(w http.ResponseWriter, r *http.Request) {
|
||||
returnMessage := ReturnMessage{}
|
||||
returnMessage.Error = false
|
||||
referenceID := &ReferenceId{}
|
||||
returnError := ReturnError{}
|
||||
referenceID := &ReferenceID{}
|
||||
err := json.NewDecoder(r.Body).Decode(referenceID)
|
||||
// hardcode 9001 for cool kid points
|
||||
if err != nil {
|
||||
|
@ -230,10 +254,9 @@ func getBlogPosts(w http.ResponseWriter, r *http.Request) {
|
|||
`
|
||||
rows, err := DB.Query(search, search_id)
|
||||
if err != nil {
|
||||
returnMessage.Message = "something is super broken..."
|
||||
returnMessage.Error = true
|
||||
returnError.Message = "something is super broken..."
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
render.JSON(w, r, returnMessage)
|
||||
render.JSON(w, r, returnError)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
@ -246,10 +269,9 @@ func getBlogPosts(w http.ResponseWriter, r *http.Request) {
|
|||
posts = append(posts, post)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
returnMessage.Message = "something is super broken..."
|
||||
returnMessage.Error = true
|
||||
returnError.Message = "something is super broken..."
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
render.JSON(w, r, returnMessage)
|
||||
render.JSON(w, r, returnError)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
@ -259,17 +281,15 @@ func getBlogPosts(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
|
||||
func getBlogPostBySlug(w http.ResponseWriter, r *http.Request) {
|
||||
returnMessage := ReturnMessage{}
|
||||
returnMessage.Error = false
|
||||
returnError := ReturnError{}
|
||||
slug := chi.URLParam(r, "slug")
|
||||
result := DB.QueryRow("SELECT id, title, slug, author, content, time_published, modified, last_modified FROM posts WHERE slug=$1", slug)
|
||||
post := BlogPost{}
|
||||
err := result.Scan(&post.ID, &post.Title, &post.Slug, &post.Author, &post.Content, &post.TimePublished, &post.Modified, &post.TimeModified)
|
||||
if err != nil {
|
||||
returnMessage.Message = "post not found"
|
||||
returnMessage.Error = true
|
||||
returnError.Message = "post not found"
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
render.JSON(w, r, returnMessage)
|
||||
render.JSON(w, r, returnError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
@ -278,17 +298,15 @@ func getBlogPostBySlug(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
|
||||
func getBlogPostById(w http.ResponseWriter, r *http.Request) {
|
||||
returnMessage := ReturnMessage{}
|
||||
returnMessage.Error = false
|
||||
returnError := ReturnError{}
|
||||
id := chi.URLParam(r, "id")
|
||||
result := DB.QueryRow("SELECT id, title, slug, author, content, time_published, modified, last_modified FROM posts WHERE id=$1", id)
|
||||
post := BlogPost{}
|
||||
err := result.Scan(&post.ID, &post.Title, &post.Slug, &post.Author, &post.Content, &post.TimePublished, &post.Modified, &post.TimeModified)
|
||||
if err != nil {
|
||||
returnMessage.Message = "post not found"
|
||||
returnMessage.Error = true
|
||||
returnError.Message = "post not found"
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
render.JSON(w, r, returnMessage)
|
||||
render.JSON(w, r, returnError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
@ -297,9 +315,8 @@ func getBlogPostById(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
|
||||
func getBlogPostsByTag(w http.ResponseWriter, r *http.Request) {
|
||||
returnMessage := ReturnMessage{}
|
||||
returnMessage.Error = false
|
||||
referenceID := &ReferenceId{}
|
||||
returnError := ReturnError{}
|
||||
referenceID := &ReferenceID{}
|
||||
err := json.NewDecoder(r.Body).Decode(referenceID)
|
||||
// hardcode 9001 for cool kid points
|
||||
if err != nil {
|
||||
|
@ -322,10 +339,9 @@ func getBlogPostsByTag(w http.ResponseWriter, r *http.Request) {
|
|||
`
|
||||
rows, err := DB.Query(search, search_id, tag)
|
||||
if err != nil {
|
||||
returnMessage.Message = "something is super broken..."
|
||||
returnMessage.Error = true
|
||||
returnError.Message = "something is super broken..."
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
render.JSON(w, r, returnMessage)
|
||||
render.JSON(w, r, returnError)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
@ -338,10 +354,9 @@ func getBlogPostsByTag(w http.ResponseWriter, r *http.Request) {
|
|||
posts = append(posts, post)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
returnMessage.Message = "something is super broken..."
|
||||
returnMessage.Error = true
|
||||
returnError.Message = "something is super broken..."
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
render.JSON(w, r, returnMessage)
|
||||
render.JSON(w, r, returnError)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
@ -351,9 +366,8 @@ func getBlogPostsByTag(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
|
||||
func getBlogPostsByAuthor(w http.ResponseWriter, r *http.Request) {
|
||||
returnMessage := ReturnMessage{}
|
||||
returnMessage.Error = false
|
||||
referenceID := &ReferenceId{}
|
||||
returnError := ReturnError{}
|
||||
referenceID := &ReferenceID{}
|
||||
err := json.NewDecoder(r.Body).Decode(referenceID)
|
||||
// hardcode 9001 for cool kid points
|
||||
if err != nil {
|
||||
|
@ -375,10 +389,9 @@ func getBlogPostsByAuthor(w http.ResponseWriter, r *http.Request) {
|
|||
`
|
||||
rows, err := DB.Query(search, search_id, author)
|
||||
if err != nil {
|
||||
returnMessage.Message = "something is super broken..."
|
||||
returnMessage.Error = true
|
||||
returnError.Message = "something is super broken..."
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
render.JSON(w, r, returnMessage)
|
||||
render.JSON(w, r, returnError)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
@ -391,10 +404,9 @@ func getBlogPostsByAuthor(w http.ResponseWriter, r *http.Request) {
|
|||
posts = append(posts, post)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
returnMessage.Message = "something is super broken..."
|
||||
returnMessage.Error = true
|
||||
returnError.Message = "something is super broken..."
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
render.JSON(w, r, returnMessage)
|
||||
render.JSON(w, r, returnError)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
|
@ -1,134 +0,0 @@
|
|||
package blog
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/go-chi/jwtauth"
|
||||
"github.com/go-chi/render"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Comment struct {
|
||||
ID int `json:"id",db:"id"`
|
||||
Parent string `json:"post_id",db:"parent"`
|
||||
Author string `json:"author",db:"author"`
|
||||
Content string `json:"content",db:"content"`
|
||||
TimePublished time.Time `json:"time_published", db:"time_published"`
|
||||
Modified bool `json:"modified", db:"modified"`
|
||||
TimeModified time.Time `json:"last_modified", db:"last_modified"`
|
||||
}
|
||||
|
||||
type Comments []Comment
|
||||
|
||||
func getCommentById(w http.ResponseWriter, r *http.Request) {
|
||||
returnMessage := ReturnMessage{}
|
||||
returnMessage.Error = false
|
||||
id := chi.URLParam(r, "id")
|
||||
result := DB.QueryRow("SELECT id, parent, author, content, time_published, modified, last_modified FROM comments WHERE id=$1", id)
|
||||
comment := Comment{}
|
||||
err := result.Scan(&comment.ID, &comment.Parent, &comment.Author, &comment.Content, &comment.TimePublished, &comment.Modified, &comment.TimeModified)
|
||||
if err != nil {
|
||||
returnMessage.Message = "comment not found"
|
||||
returnMessage.Error = true
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
render.JSON(w, r, returnMessage)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
render.JSON(w, r, comment)
|
||||
return
|
||||
}
|
||||
|
||||
func postComment(w http.ResponseWriter, r *http.Request) {
|
||||
returnMessage := ReturnMessage{}
|
||||
returnMessage.Error = false
|
||||
newComment := &Comment{}
|
||||
// basic checks
|
||||
_, claims, _ := jwtauth.FromContext(r.Context())
|
||||
|
||||
username := claims["username"].(string)
|
||||
post_id := chi.URLParam(r, "post_id")
|
||||
err := json.NewDecoder(r.Body).Decode(newComment)
|
||||
if err != nil {
|
||||
returnMessage.Message = "unknown error, try again later"
|
||||
returnMessage.Error = true
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
render.JSON(w, r, returnMessage)
|
||||
return
|
||||
}
|
||||
if newComment.Content == "" {
|
||||
returnMessage.Message = "content is required"
|
||||
returnMessage.Error = true
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
render.JSON(w, r, returnMessage)
|
||||
return
|
||||
}
|
||||
c := `INSERT INTO comments (parent, author, content, time_published, modified, last_modified)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
RETURNING id`
|
||||
comment_id := 0
|
||||
err = DB.QueryRow(c, post_id, username, newComment.Content, time.Now().UTC(), false, time.Now().UTC()).Scan(&comment_id)
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
returnMessage.Message = "something is super broken..."
|
||||
returnMessage.Error = true
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
render.JSON(w, r, returnMessage)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
returnMessage.Message = "something is super broken..."
|
||||
returnMessage.Error = true
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
render.JSON(w, r, returnMessage)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
returnMessage.Message = "comment added"
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
render.JSON(w, r, returnMessage)
|
||||
return
|
||||
}
|
||||
|
||||
func getCommentsByParentId(w http.ResponseWriter, r *http.Request) {
|
||||
returnMessage := ReturnMessage{}
|
||||
returnMessage.Error = false
|
||||
post_id := chi.URLParam(r, "post_id")
|
||||
search := `
|
||||
SELECT id, author, content, time_published, modified, last_modified
|
||||
FROM comments
|
||||
WHERE parent = $1
|
||||
ORDER BY id ASC
|
||||
`
|
||||
rows, err := DB.Query(search, post_id)
|
||||
if err != nil {
|
||||
returnMessage.Message = "something is super broken..."
|
||||
returnMessage.Error = true
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
render.JSON(w, r, returnMessage)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
comment := Comment{}
|
||||
comments := make(Comments, 0)
|
||||
for rows.Next() {
|
||||
if err := rows.Scan(&comment.ID, &comment.Author, &comment.Content, &comment.TimePublished, &comment.Modified, &comment.TimeModified); err != nil {
|
||||
}
|
||||
comments = append(comments, comment)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
returnMessage.Message = "something is super broken..."
|
||||
returnMessage.Error = true
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
render.JSON(w, r, returnMessage)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
render.JSON(w, r, comments)
|
||||
return
|
||||
}
|
|
@ -1,32 +0,0 @@
|
|||
package blog
|
||||
|
||||
import (
|
||||
"git.minhas.io/asara/sudoscientist-go-backend/packages/middleware"
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/go-chi/jwtauth"
|
||||
)
|
||||
|
||||
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.Post("/posts", createBlogPost)
|
||||
r.Patch("/posts/by-id/{id}", updateBlogPostById)
|
||||
r.Post("/comments/{post_id}", postComment)
|
||||
/*
|
||||
r.Patch("/comments/{id}", updateComment)
|
||||
*/
|
||||
})
|
||||
r.Get("/posts", getBlogPosts)
|
||||
r.Get("/posts/by-id/{id}", getBlogPostById)
|
||||
r.Get("/posts/by-tag/{tag}", getBlogPostsByTag)
|
||||
r.Get("/posts/by-author/{author}", getBlogPostsByAuthor)
|
||||
r.Get("/posts/by-slug/{slug}", getBlogPostBySlug)
|
||||
r.Get("/comments/{post_id}", getCommentsByParentId)
|
||||
/*
|
||||
r.Get("/by-author/{author}", getCommentsByAuthor)
|
||||
r.Get("/by-parent/{post_id}", getCommentsByPost)
|
||||
*/
|
||||
return r
|
||||
}
|
|
@ -2,7 +2,6 @@ package auth_middleware
|
|||
|
||||
import (
|
||||
"net/http"
|
||||
"path"
|
||||
)
|
||||
|
||||
func TokenFromSplitCookie(r *http.Request) string {
|
||||
|
@ -17,8 +16,3 @@ func TokenFromSplitCookie(r *http.Request) string {
|
|||
cookie := dataCookie.Value + "." + signatureCookie.Value
|
||||
return cookie
|
||||
}
|
||||
|
||||
func TokenFromUrl(r *http.Request) string {
|
||||
_, token := path.Split(r.URL.Path)
|
||||
return token
|
||||
}
|
||||
|
|
|
@ -23,6 +23,17 @@ type User struct {
|
|||
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,
|
||||
location text,
|
||||
bio text)`
|
||||
DB.Exec(dbCreateStatement)
|
||||
}
|
||||
|
||||
func Routes() *chi.Mux {
|
||||
r := chi.NewRouter()
|
||||
r.Group(func(r chi.Router) {
|
||||
|
|
4
settings/db.env
Normal file
4
settings/db.env
Normal file
|
@ -0,0 +1,4 @@
|
|||
export DB_PORT="5432"
|
||||
export DB_USER="sudosci"
|
||||
export DB_NAME="sudosci"
|
||||
export DB_SSL="disable"
|
1
settings/secrets.env
Normal file
1
settings/secrets.env
Normal file
|
@ -0,0 +1 @@
|
|||
export DB_PW="CHANGEME"
|
|
@ -1,2 +1 @@
|
|||
export DB_PW="CHANGEME"
|
||||
export POSTAL_KEY="POSTAL_API_KEY"
|
||||
|
|
2
settings/website.env
Normal file
2
settings/website.env
Normal file
|
@ -0,0 +1,2 @@
|
|||
export API_PORT="8080"
|
||||
export JWT_SECRET="CHANGEMEALSO"
|
|
@ -1,9 +1,2 @@
|
|||
export API_PORT="8080"
|
||||
export EMAIL_SECRET="CHANGEMEALSOPLS"
|
||||
export JWT_SECRET="CHANGEMEALSO"
|
||||
export POSTAL_API="https://POSTAL_URL"
|
||||
export POSTAL_SRC_EMAIL="postal-source@domain.com"
|
||||
export API_ADDR="https://apidomain.tld"
|
||||
export UI_ADDR="sudosci.ui"
|
||||
export UI_PORT=":3000"
|
||||
export UI_PROTO="http://"
|
||||
|
|
Reference in a new issue