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
View file

@ -24,5 +24,3 @@ _testmain.go
*.test *.test
*.prof *.prof
# Settings
settings/*.env

View file

@ -4,7 +4,7 @@
### Setup ### Setup
Install steps are for Debian 11 (bullseye) Install steps are for Debian 9 (stretch)
1. Install docker-ce 1. Install docker-ce
``` ```
@ -26,23 +26,17 @@ Install steps are for Debian 11 (bullseye)
sudo apt-get install docker-ce docker-ce-cli containerd.io 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 update
sudo apt-get install golang sudo apt-get -t stretch-backports install golang
# set the gopath manually for the rest of the setup # set the gopath manually for the rest of the setup
export GOPATH=${HOME}/go export GOPATH=${HOME}/go
``` ```
3. Install migrate 3. Clone repo and configure the settings
```
# 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
``` ```
mkdir -p ${GOPATH}/src/git.minhas.io/asara mkdir -p ${GOPATH}/src/git.minhas.io/asara
cd ${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.) # 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 # make sure your user is in the docker group
sudo usermod -aG docker $(whoami) sudo usermod -aG docker $(whoami)
# make sure you have some postgres client installed # make sure you have some postgres client installed
sudo apt-get install postgres-client sudo apt-get install postgres-client
docker pull postgres 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 # Initalize the postgres DB
cd ${GOPATH}/src/git.minhas.io/asara/sudoscientist cd ${GOPATH}/src/git.minhas.io/asara/sudoscientist
for i in settings/*; do source $i; done for i in settings/*; do source $i; done
@ -69,22 +61,14 @@ Install steps are for Debian 11 (bullseye)
CREATE DATABASE ${DB_NAME}; CREATE DATABASE ${DB_NAME};
CREATE USER ${DB_USER} WITH ENCRYPTED PASSWORD '${DB_PW}'; CREATE USER ${DB_USER} WITH ENCRYPTED PASSWORD '${DB_PW}';
GRANT ALL PRIVILEGES ON DATABASE ${DB_NAME} TO ${DB_USER}; GRANT ALL PRIVILEGES ON DATABASE ${DB_NAME} TO ${DB_USER};
ALTER DATABASE ${DB_NAME} OWNER TO ${DB_USER};
EOF EOF
``` ```
6. Run the application! 5. 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)
``` ```
cd ${GOPATH}/src/git.minhas.io/asara/sudoscientist-go-backend 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) 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 get
go run main.go go run main.go
``` ```

1
TODO.md Normal file
View file

@ -0,0 +1 @@
#. Implement comments

View file

@ -12,6 +12,5 @@ psql -d postgres -U postgres -h ${DB_HOST} << EOF
CREATE DATABASE ${DB_NAME}; CREATE DATABASE ${DB_NAME};
CREATE USER ${DB_USER} WITH ENCRYPTED PASSWORD '${DB_PW}'; CREATE USER ${DB_USER} WITH ENCRYPTED PASSWORD '${DB_PW}';
GRANT ALL PRIVILEGES ON DATABASE ${DB_NAME} TO ${DB_USER}; GRANT ALL PRIVILEGES ON DATABASE ${DB_NAME} TO ${DB_USER};
ALTER DATABASE ${DB_NAME} OWNER TO ${DB_USER};
EOF EOF
echo Done echo Done

18
main.go
View file

@ -1,15 +1,12 @@
package main package main
// force pushing
import ( import (
"compress/flate"
"fmt" "fmt"
_ "github.com/lib/pq"
"log" "log"
"net/http" "net/http"
"os" "os"
_ "github.com/lib/pq"
"git.minhas.io/asara/sudoscientist-go-backend/packages/auth" "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/blog"
"git.minhas.io/asara/sudoscientist-go-backend/packages/database" "git.minhas.io/asara/sudoscientist-go-backend/packages/database"
@ -26,17 +23,16 @@ func main() {
db, _ := database.NewDB() db, _ := database.NewDB()
defer db.Close() defer db.Close()
auth.DB = db auth.DB = db
auth.Init()
users.DB = db users.DB = db
users.Init()
blog.DB = db blog.DB = db
blog.Init()
// initiate jwt token // initiate jwt token
auth.TokenAuth = jwtauth.New("HS256", []byte(os.Getenv("JWT_SECRET")), nil) auth.TokenAuth = jwtauth.New("HS256", []byte(os.Getenv("JWT_SECRET")), nil)
users.TokenAuth = auth.TokenAuth users.TokenAuth = auth.TokenAuth
blog.TokenAuth = auth.TokenAuth blog.TokenAuth = auth.TokenAuth
// initilize auth for email verification
auth.Init()
// initiate the routes // initiate the routes
router := Routes() router := Routes()
@ -57,20 +53,18 @@ func main() {
func Routes() *chi.Mux { func Routes() *chi.Mux {
router := chi.NewRouter() router := chi.NewRouter()
cors := cors.New(cors.Options{ 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"}, AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"}, AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
AllowCredentials: true, AllowCredentials: true,
MaxAge: 360, MaxAge: 360,
}) })
compressor := middleware.NewCompressor(flate.DefaultCompression)
router.Use( router.Use(
compressor.Handler,
cors.Handler, cors.Handler,
render.SetContentType(render.ContentTypeJSON), render.SetContentType(render.ContentTypeJSON),
middleware.Logger, middleware.Logger,
middleware.DefaultCompress,
middleware.RedirectSlashes, middleware.RedirectSlashes,
middleware.Recoverer, middleware.Recoverer,
) )

View file

@ -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;

View file

@ -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;

View file

@ -1,4 +0,0 @@
BEGIN;
ALTER TABLE users
DROP COLUMN verified IF EXISTS;
COMMIT;

View file

@ -1,4 +0,0 @@
BEGIN;
ALTER TABLE users
ADD COLUMN verified boolean NOT NULL DEFAULT false;
COMMIT;

View file

@ -1,3 +0,0 @@
BEGIN;
DROP TABLE IF EXISTS comments;
COMMIT;

View file

@ -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;

View file

@ -1,19 +1,18 @@
package auth package auth
import ( import (
"bytes"
"database/sql" "database/sql"
"encoding/json" "encoding/json"
"fmt" "fmt"
"git.minhas.io/asara/sudoscientist-go-backend/packages/middleware" "git.minhas.io/asara/sudoscientist-go-backend/packages/middleware"
"git.minhas.io/asara/sudoscientist-go-backend/packages/users" "git.minhas.io/asara/sudoscientist-go-backend/packages/users"
"github.com/badoux/checkmail" "github.com/badoux/checkmail"
"github.com/dgrijalva/jwt-go"
"github.com/go-chi/chi" "github.com/go-chi/chi"
"github.com/go-chi/jwtauth" "github.com/go-chi/jwtauth"
"github.com/go-chi/render" "github.com/go-chi/render"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
"net/http" "net/http"
"os"
"strings" "strings"
"time" "time"
) )
@ -21,33 +20,10 @@ import (
var ( var (
DB *sql.DB DB *sql.DB
TokenAuth *jwtauth.JWTAuth TokenAuth *jwtauth.JWTAuth
EmailAuth *jwtauth.JWTAuth
PostalEnabled bool
PostalKey string
PostalAPI string
PostalEmail string
) )
func Init() { type ReturnError struct {
if postal_key, ok := os.LookupEnv("POSTAL_KEY"); ok { Message string `json:"error"`
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 SignUpCredentials struct { type SignUpCredentials struct {
@ -56,35 +32,26 @@ type SignUpCredentials struct {
Password string `json:"password", db:"password"` Password string `json:"password", db:"password"`
} }
type UserCredentials struct { type SignInCredentials struct {
Username string `json:"username", db:"username"` Username string `json:"username", db:"username"`
Password string `json:"password", db:"password"` Password string `json:"password", db:"password"`
} }
type Claims struct { type Claims struct {
Username string `json:"username", db:"username"` Username string `json:"username"`
Admin bool `json:"admin", db:"admin"` jwt.StandardClaims
Verified bool `json:"verified", db:"verified"`
} }
type JWT struct { type JWT struct {
JWT string `json:"jwt"` JWT string `json:"jwt"`
} }
type ComposedEmail struct { func Init() {
To [1]string `json:"to"` DB.Exec("CREATE TABLE IF NOT EXISTS users (username text primary key, email text, password text, admin boolean);")
From string `json:"from"`
Subject string `json:"subject"`
Plain_body string `json:"plain_body"`
} }
func Routes() *chi.Mux { func Routes() *chi.Mux {
r := chi.NewRouter() 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("/signin", signin)
r.Post("/register", register) r.Post("/register", register)
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
@ -95,246 +62,119 @@ func Routes() *chi.Mux {
return r 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) { func register(w http.ResponseWriter, r *http.Request) {
returnMessage := ReturnMessage{} returnError := ReturnError{}
returnMessage.Error = false
creds := &SignUpCredentials{} creds := &SignUpCredentials{}
err := json.NewDecoder(r.Body).Decode(creds) err := json.NewDecoder(r.Body).Decode(creds)
if err != nil { if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
returnMessage.Message = "bad data provided" fmt.Println(err)
returnMessage.Error = true
render.JSON(w, r, returnMessage)
return return
} }
if creds.Username == "" { if creds.Username == "" {
returnMessage.Message = "username is required" returnError.Message = "username is required"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnMessage) render.JSON(w, r, returnError)
return return
} }
if creds.Password == "" { if creds.Password == "" {
returnMessage.Message = "password is required" returnError.Message = "password is required"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnMessage) render.JSON(w, r, returnError)
return return
} }
if creds.Email == "" { if creds.Email == "" {
returnMessage.Message = "email is required" returnError.Message = "email is required"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnMessage) render.JSON(w, r, returnError)
return return
} }
err = checkmail.ValidateFormat(creds.Email) err = checkmail.ValidateFormat(creds.Email)
if err != nil { if err != nil {
returnMessage.Message = "email not valid" returnError.Message = "email not valid"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnMessage) render.JSON(w, r, returnError)
return return
} }
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(creds.Password), 10) hashedPassword, err := bcrypt.GenerateFromPassword([]byte(creds.Password), 10)
s := `INSERT INTO users (username, email, password, admin, verified) s := `INSERT INTO users (username, email, password, admin)
VALUES ($1, $2, $3, $4, $5)` VALUES ($1, $2, $3, $4)`
if _, err = DB.Exec(s, creds.Username, creds.Email, string(hashedPassword), false, false); err != nil { if _, err = DB.Exec(s, creds.Username, creds.Email, string(hashedPassword), false); err != nil {
fmt.Println(err)
returnMessage.Message = "unexpected error. please contact the administrator"
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnMessage) fmt.Println(err)
return return
} }
users.CreateProfile(creds.Username, creds.Email) 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) w.WriteHeader(http.StatusCreated)
render.JSON(w, r, returnMessage) expirationTime := time.Now().Add(6 * time.Hour)
return claims := &Claims{
Username: creds.Username,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expirationTime.Unix(),
},
} }
_, tokenString, _ := TokenAuth.Encode(claims) _, tokenString, _ := TokenAuth.Encode(claims)
setCookies(w, tokenString, expirationTime) token := setCookies(w, tokenString, expirationTime)
w.WriteHeader(http.StatusCreated) w.WriteHeader(http.StatusOK)
returnMessage.Message = "User created! Welcome to the site!" render.JSON(w, r, token)
render.JSON(w, r, returnMessage)
return
} }
func signin(w http.ResponseWriter, r *http.Request) { func signin(w http.ResponseWriter, r *http.Request) {
returnMessage := ReturnMessage{} creds := &SignInCredentials{}
returnMessage.Error = false
creds := &UserCredentials{}
err := json.NewDecoder(r.Body).Decode(creds) err := json.NewDecoder(r.Body).Decode(creds)
if err != nil { if err != nil {
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
returnMessage.Message = "bad data provided"
returnMessage.Error = true
render.JSON(w, r, returnMessage)
return 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) result := DB.QueryRow("SELECT password FROM users WHERE username=$1", creds.Username)
storedCreds := &UserCredentials{} storedCreds := &SignInCredentials{}
err := result.Scan(&storedCreds.Password) err = result.Scan(&storedCreds.Password)
if err != nil { if err != nil {
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
w.WriteHeader(http.StatusUnauthorized) w.WriteHeader(http.StatusUnauthorized)
returnMessage = "username or password incorrect" return
return returnMessage, false
} }
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
returnMessage = "something is broken, please contact the administrator" return
return returnMessage, false
} }
if err = bcrypt.CompareHashAndPassword([]byte(storedCreds.Password), []byte(creds.Password)); err != nil { if err = bcrypt.CompareHashAndPassword([]byte(storedCreds.Password), []byte(creds.Password)); err != nil {
w.WriteHeader(http.StatusUnauthorized) w.WriteHeader(http.StatusUnauthorized)
returnMessage = "username or password incorrect"
return returnMessage, false
} }
returnMessage = "user logged in" expirationTime := time.Now().Add(5 * time.Hour)
return returnMessage, true 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], ".")
} }

View file

@ -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
)

View file

@ -4,6 +4,7 @@ import (
"database/sql" "database/sql"
"encoding/json" "encoding/json"
"fmt" "fmt"
"git.minhas.io/asara/sudoscientist-go-backend/packages/middleware"
"github.com/go-chi/chi" "github.com/go-chi/chi"
"github.com/go-chi/jwtauth" "github.com/go-chi/jwtauth"
"github.com/go-chi/render" "github.com/go-chi/render"
@ -13,6 +14,11 @@ import (
"time" "time"
) )
var (
DB *sql.DB
TokenAuth *jwtauth.JWTAuth
)
type BlogPost struct { type BlogPost struct {
ID int `json:"id",db:"id"` ID int `json:"id",db:"id"`
Title string `json:"title",db:"title"` Title string `json:"title",db:"title"`
@ -37,52 +43,80 @@ type NewBlogPost struct {
Author string `json:"author",db:"author"` Author string `json:"author",db:"author"`
} }
type ReturnError struct {
Message string `json:"error"`
}
type ReturnSuccess struct { type ReturnSuccess struct {
Message string `json:"success"` Message string `json:"success"`
ID int `json:"id"` ID int `json:"id"`
Slug string `json:"slug",db:"slug"` Slug string `json:"slug",db:"slug"`
} }
type ReferenceId struct { type ReferenceID struct {
LastID int `json:"last_id"` 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) { func createBlogPost(w http.ResponseWriter, r *http.Request) {
returnMessage := ReturnMessage{} returnError := ReturnError{}
returnMessage.Error = false
newBlogPost := &NewBlogPost{} newBlogPost := &NewBlogPost{}
// basic checks // basic checks
_, claims, _ := jwtauth.FromContext(r.Context()) _, 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) username := claims["username"].(string)
err := json.NewDecoder(r.Body).Decode(newBlogPost) err := json.NewDecoder(r.Body).Decode(newBlogPost)
if err != nil { if err != nil {
returnMessage.Message = "unknown error, try again later" returnError.Message = "unknown error, try again later"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnMessage) render.JSON(w, r, returnError)
return return
} }
if newBlogPost.Title == "" { if newBlogPost.Title == "" {
returnMessage.Message = "title is required" returnError.Message = "title is required"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnMessage) render.JSON(w, r, returnError)
return return
} }
if newBlogPost.Content == "" { if newBlogPost.Content == "" {
returnMessage.Message = "content is required" returnError.Message = "content is required"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnMessage) render.JSON(w, r, returnError)
return return
} }
as := slug.Make(newBlogPost.Title) as := slug.Make(newBlogPost.Title)
@ -92,18 +126,16 @@ func createBlogPost(w http.ResponseWriter, r *http.Request) {
scr := 0 scr := 0
err = slugCheck.Scan(&scr) err = slugCheck.Scan(&scr)
if err == nil { if err == nil {
returnMessage.Message = "slug already exists" returnError.Message = "slug already exists"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnMessage) render.JSON(w, r, returnError)
return return
} }
if err != nil { if err != nil {
if err != sql.ErrNoRows { if err != sql.ErrNoRows {
returnMessage.Message = "something is super broken..." returnError.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnMessage) render.JSON(w, r, returnError)
fmt.Println(err) fmt.Println(err)
return 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) 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 != nil {
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
returnMessage.Message = "something is super broken..." returnError.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnMessage) render.JSON(w, r, returnError)
fmt.Println(err) fmt.Println(err)
return return
} }
returnMessage.Message = "something is super broken..." returnError.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnMessage) render.JSON(w, r, returnError)
fmt.Println(err) fmt.Println(err)
return return
} }
@ -147,26 +177,23 @@ func createBlogPost(w http.ResponseWriter, r *http.Request) {
} }
func updateBlogPostById(w http.ResponseWriter, r *http.Request) { func updateBlogPostById(w http.ResponseWriter, r *http.Request) {
returnMessage := ReturnMessage{} returnError := ReturnError{}
returnMessage.Error = false
// Get the actual post // 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) result := DB.QueryRow("SELECT id, title, slug, author, content, time_published FROM posts WHERE id=$1", id)
post := BlogPost{} post := BlogPost{}
err := result.Scan(&post.ID, &post.Title, &post.Slug, &post.Author, &post.Content, &post.TimePublished) err := result.Scan(&post.ID, &post.Title, &post.Slug, &post.Author, &post.Content, &post.TimePublished)
if err != nil { if err != nil {
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
returnMessage.Message = "blog post requested for update not found" returnError.Message = "blog post requested for update not found"
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnMessage) render.JSON(w, r, returnError)
fmt.Println(err) fmt.Println(err)
return return
} }
returnMessage.Message = "something is super broken..." returnError.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnMessage) render.JSON(w, r, returnError)
fmt.Println(err) fmt.Println(err)
return return
} }
@ -175,10 +202,9 @@ func updateBlogPostById(w http.ResponseWriter, r *http.Request) {
_, claims, _ := jwtauth.FromContext(r.Context()) _, claims, _ := jwtauth.FromContext(r.Context())
username := claims["username"].(string) username := claims["username"].(string)
if username != post.Author { if username != post.Author {
returnMessage.Message = "unauthorized..." returnError.Message = "unauthorized..."
returnMessage.Error = true
w.WriteHeader(http.StatusUnauthorized) w.WriteHeader(http.StatusUnauthorized)
render.JSON(w, r, returnMessage) render.JSON(w, r, returnError)
return return
} }
// update the post struct // update the post struct
@ -193,10 +219,9 @@ func updateBlogPostById(w http.ResponseWriter, r *http.Request) {
// write the row update // write the row update
_, err = DB.Exec(s, post.Title, post.Content, true, time.Now().UTC(), post.ID) _, err = DB.Exec(s, post.Title, post.Content, true, time.Now().UTC(), post.ID)
if err != nil { if err != nil {
returnMessage.Message = "something is super broken..." returnError.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnMessage) render.JSON(w, r, returnError)
fmt.Println(err) fmt.Println(err)
return return
} }
@ -208,9 +233,8 @@ func updateBlogPostById(w http.ResponseWriter, r *http.Request) {
// This will search by the last id seen, descending. // This will search by the last id seen, descending.
func getBlogPosts(w http.ResponseWriter, r *http.Request) { func getBlogPosts(w http.ResponseWriter, r *http.Request) {
returnMessage := ReturnMessage{} returnError := ReturnError{}
returnMessage.Error = false referenceID := &ReferenceID{}
referenceID := &ReferenceId{}
err := json.NewDecoder(r.Body).Decode(referenceID) err := json.NewDecoder(r.Body).Decode(referenceID)
// hardcode 9001 for cool kid points // hardcode 9001 for cool kid points
if err != nil { if err != nil {
@ -230,10 +254,9 @@ func getBlogPosts(w http.ResponseWriter, r *http.Request) {
` `
rows, err := DB.Query(search, search_id) rows, err := DB.Query(search, search_id)
if err != nil { if err != nil {
returnMessage.Message = "something is super broken..." returnError.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnMessage) render.JSON(w, r, returnError)
fmt.Println(err) fmt.Println(err)
return return
} }
@ -246,10 +269,9 @@ func getBlogPosts(w http.ResponseWriter, r *http.Request) {
posts = append(posts, post) posts = append(posts, post)
} }
if err := rows.Err(); err != nil { if err := rows.Err(); err != nil {
returnMessage.Message = "something is super broken..." returnError.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnMessage) render.JSON(w, r, returnError)
fmt.Println(err) fmt.Println(err)
return return
} }
@ -259,17 +281,15 @@ func getBlogPosts(w http.ResponseWriter, r *http.Request) {
} }
func getBlogPostBySlug(w http.ResponseWriter, r *http.Request) { func getBlogPostBySlug(w http.ResponseWriter, r *http.Request) {
returnMessage := ReturnMessage{} returnError := ReturnError{}
returnMessage.Error = false
slug := chi.URLParam(r, "slug") 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) result := DB.QueryRow("SELECT id, title, slug, author, content, time_published, modified, last_modified FROM posts WHERE slug=$1", slug)
post := BlogPost{} post := BlogPost{}
err := result.Scan(&post.ID, &post.Title, &post.Slug, &post.Author, &post.Content, &post.TimePublished, &post.Modified, &post.TimeModified) err := result.Scan(&post.ID, &post.Title, &post.Slug, &post.Author, &post.Content, &post.TimePublished, &post.Modified, &post.TimeModified)
if err != nil { if err != nil {
returnMessage.Message = "post not found" returnError.Message = "post not found"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnMessage) render.JSON(w, r, returnError)
return return
} }
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
@ -278,17 +298,15 @@ func getBlogPostBySlug(w http.ResponseWriter, r *http.Request) {
} }
func getBlogPostById(w http.ResponseWriter, r *http.Request) { func getBlogPostById(w http.ResponseWriter, r *http.Request) {
returnMessage := ReturnMessage{} returnError := ReturnError{}
returnMessage.Error = false
id := chi.URLParam(r, "id") 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) result := DB.QueryRow("SELECT id, title, slug, author, content, time_published, modified, last_modified FROM posts WHERE id=$1", id)
post := BlogPost{} post := BlogPost{}
err := result.Scan(&post.ID, &post.Title, &post.Slug, &post.Author, &post.Content, &post.TimePublished, &post.Modified, &post.TimeModified) err := result.Scan(&post.ID, &post.Title, &post.Slug, &post.Author, &post.Content, &post.TimePublished, &post.Modified, &post.TimeModified)
if err != nil { if err != nil {
returnMessage.Message = "post not found" returnError.Message = "post not found"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnMessage) render.JSON(w, r, returnError)
return return
} }
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
@ -297,9 +315,8 @@ func getBlogPostById(w http.ResponseWriter, r *http.Request) {
} }
func getBlogPostsByTag(w http.ResponseWriter, r *http.Request) { func getBlogPostsByTag(w http.ResponseWriter, r *http.Request) {
returnMessage := ReturnMessage{} returnError := ReturnError{}
returnMessage.Error = false referenceID := &ReferenceID{}
referenceID := &ReferenceId{}
err := json.NewDecoder(r.Body).Decode(referenceID) err := json.NewDecoder(r.Body).Decode(referenceID)
// hardcode 9001 for cool kid points // hardcode 9001 for cool kid points
if err != nil { if err != nil {
@ -322,10 +339,9 @@ func getBlogPostsByTag(w http.ResponseWriter, r *http.Request) {
` `
rows, err := DB.Query(search, search_id, tag) rows, err := DB.Query(search, search_id, tag)
if err != nil { if err != nil {
returnMessage.Message = "something is super broken..." returnError.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnMessage) render.JSON(w, r, returnError)
fmt.Println(err) fmt.Println(err)
return return
} }
@ -338,10 +354,9 @@ func getBlogPostsByTag(w http.ResponseWriter, r *http.Request) {
posts = append(posts, post) posts = append(posts, post)
} }
if err := rows.Err(); err != nil { if err := rows.Err(); err != nil {
returnMessage.Message = "something is super broken..." returnError.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnMessage) render.JSON(w, r, returnError)
fmt.Println(err) fmt.Println(err)
return return
} }
@ -351,9 +366,8 @@ func getBlogPostsByTag(w http.ResponseWriter, r *http.Request) {
} }
func getBlogPostsByAuthor(w http.ResponseWriter, r *http.Request) { func getBlogPostsByAuthor(w http.ResponseWriter, r *http.Request) {
returnMessage := ReturnMessage{} returnError := ReturnError{}
returnMessage.Error = false referenceID := &ReferenceID{}
referenceID := &ReferenceId{}
err := json.NewDecoder(r.Body).Decode(referenceID) err := json.NewDecoder(r.Body).Decode(referenceID)
// hardcode 9001 for cool kid points // hardcode 9001 for cool kid points
if err != nil { if err != nil {
@ -375,10 +389,9 @@ func getBlogPostsByAuthor(w http.ResponseWriter, r *http.Request) {
` `
rows, err := DB.Query(search, search_id, author) rows, err := DB.Query(search, search_id, author)
if err != nil { if err != nil {
returnMessage.Message = "something is super broken..." returnError.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnMessage) render.JSON(w, r, returnError)
fmt.Println(err) fmt.Println(err)
return return
} }
@ -391,10 +404,9 @@ func getBlogPostsByAuthor(w http.ResponseWriter, r *http.Request) {
posts = append(posts, post) posts = append(posts, post)
} }
if err := rows.Err(); err != nil { if err := rows.Err(); err != nil {
returnMessage.Message = "something is super broken..." returnError.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnMessage) render.JSON(w, r, returnError)
fmt.Println(err) fmt.Println(err)
return return
} }

View file

@ -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
}

View file

@ -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
}

View file

@ -2,7 +2,6 @@ package auth_middleware
import ( import (
"net/http" "net/http"
"path"
) )
func TokenFromSplitCookie(r *http.Request) string { func TokenFromSplitCookie(r *http.Request) string {
@ -17,8 +16,3 @@ func TokenFromSplitCookie(r *http.Request) string {
cookie := dataCookie.Value + "." + signatureCookie.Value cookie := dataCookie.Value + "." + signatureCookie.Value
return cookie return cookie
} }
func TokenFromUrl(r *http.Request) string {
_, token := path.Split(r.URL.Path)
return token
}

View file

@ -23,6 +23,17 @@ type User struct {
Bio string `json:"bio",db:"bio"` 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 { func Routes() *chi.Mux {
r := chi.NewRouter() r := chi.NewRouter()
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {

4
settings/db.env Normal file
View 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
View file

@ -0,0 +1 @@
export DB_PW="CHANGEME"

View file

@ -1,2 +1 @@
export DB_PW="CHANGEME" export DB_PW="CHANGEME"
export POSTAL_KEY="POSTAL_API_KEY"

2
settings/website.env Normal file
View file

@ -0,0 +1,2 @@
export API_PORT="8080"
export JWT_SECRET="CHANGEMEALSO"

View file

@ -1,9 +1,2 @@
export API_PORT="8080" export API_PORT="8080"
export EMAIL_SECRET="CHANGEMEALSOPLS"
export JWT_SECRET="CHANGEMEALSO" 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://"