Compare commits

...

34 commits

Author SHA1 Message Date
983e7bd659 Force push 2023-07-08 20:29:35 -04:00
5a28d214f2 Update readme to be more relevant to today 2021-05-15 16:53:02 -04:00
9a1f4a6fcf Merge pull request 'Update dependencies such as jwtauth and go-chi, remove jwt-go' (#5) from update_jwtauth into master
Reviewed-on: https://git.minhas.io/Asara/sudoscientist-go-backend/pulls/5
2021-01-17 00:37:28 +00:00
f1987e310a Update jwtauth and remove jwt-go since it has vulns 2021-01-16 19:26:19 -05:00
cb75af9997 Remove todo until I find things to add here 2020-02-09 21:11:06 -05:00
2a537d2924 Merge branch 'comments' of Asara/sudoscientist-go-backend into master 2020-02-09 19:37:06 -05:00
d19f8f1581 BAREBONE COMMENTS AWOOOOO 2020-01-30 00:37:14 -05:00
8cb7407561 Remove uneeded check 2020-01-29 21:21:38 -05:00
f51c5a78ea Sort by ascending 2020-01-26 01:26:56 -05:00
756f1aa161 Flesh out basic commenting functions 2020-01-25 23:19:39 -05:00
705c442114 Reorganize code, begin adding comments, split out routes 2020-01-25 22:56:11 -05:00
a804e048ff Merge branch 'postal_integration' of Asara/sudoscientist-go-backend into master 2020-01-25 18:10:30 -05:00
20ae72bc2e Extend ReturnMessage 2020-01-25 18:04:15 -05:00
4208190c9a Fix up accessing ui in dev mode via env variables 2020-01-22 22:45:07 -05:00
38bd348737 Update auth to return better errors, remove returning the token data as a blob 2020-01-21 23:49:07 -05:00
4457885685 Block non-admin users from posting 2020-01-21 22:19:35 -05:00
aa2731e789 Add backend hook to register users 2020-01-21 22:06:03 -05:00
d27a499c07 Split out url auth with email token 2020-01-20 20:06:32 -05:00
cc7225527e Change WEB_ADDR to the api address, not ui 2020-01-20 19:04:23 -05:00
d9153ea9bf Split out checking password, update claims to include admin+verified, some more cleanup 2020-01-20 18:55:12 -05:00
172dc2dc34 Fix up uneeded return 2020-01-20 15:21:56 -05:00
cba9967af0 Add postal backend integration 2020-01-20 13:40:05 -05:00
5a7281f1ae Clean up some error handling, remove debug logging 2020-01-19 00:31:21 -05:00
e082f55ebe Basic migrations, started breaking out postal stuff 2020-01-19 00:09:58 -05:00
f8cd0cdcf6 More readme cleaning 2020-01-18 21:52:56 -05:00
ddf5d2d767 Clean up readme 2020-01-18 21:52:22 -05:00
370b386bb4 Update readme 2020-01-18 21:51:33 -05:00
198fd10bf0 go fmt, add some basic tests for postal api info 2020-01-18 21:46:46 -05:00
f0799e0adb spacing 2020-01-18 21:03:45 -05:00
cc2411f1c6 remove unneeded files, update secrets to add postal env var 2020-01-18 20:47:59 -05:00
4aa812581f Update gitignore 2020-01-18 20:45:45 -05:00
8d29d8a744 Update Readme to include migrations 2020-01-18 14:58:55 -05:00
6656d8b474 Merge branch 'migrations' of Asara/sudoscientist-go-backend into master 2020-01-14 23:12:02 -05:00
9efabe0906 Split out migrations 2020-01-14 22:40:32 -05:00
23 changed files with 610 additions and 200 deletions

2
.gitignore vendored
View file

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

View file

@ -4,7 +4,7 @@
### Setup
Install steps are for Debian 9 (stretch)
Install steps are for Debian 11 (bullseye)
1. Install docker-ce
```
@ -20,23 +20,29 @@ Install steps are for Debian 9 (stretch)
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 1.11
2. Install golang
```
# 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 -t stretch-backports install golang
sudo apt-get install golang
# set the gopath manually for the rest of the setup
export GOPATH=${HOME}/go
```
3. Clone repo and configure the settings
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
```
mkdir -p ${GOPATH}/src/git.minhas.io/asara
cd ${GOPATH}/src/git.minhas.io/asara
@ -45,14 +51,16 @@ Install steps are for Debian 9 (stretch)
# make sure the extension is .env (db.env, secrets.env, website.env... etc.)
```
4. Configure docker postgres for testing
5. 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 --name sudosci-db -e POSTGRES_PASWORD=${DB_ADMIN_PW} -d postgres # please set the db admin pw manually
docker run -e POSTGRES_PASSWORD=${DB_ADMIN_PW} --name sudosci-db -d postgres
# Initalize the postgres DB
cd ${GOPATH}/src/git.minhas.io/asara/sudoscientist
for i in settings/*; do source $i; done
@ -61,14 +69,22 @@ Install steps are for Debian 9 (stretch)
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
```
5. Run the application!
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)
```
cd ${GOPATH}/src/git.minhas.io/asara/sudoscientist-go-backend
for i in settings/*; do source $i; done
for i in settings/*.env; 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
```

View file

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

View file

@ -12,5 +12,6 @@ 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
View file

@ -1,12 +1,15 @@
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"
@ -23,16 +26,17 @@ 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()
@ -53,18 +57,20 @@ func main() {
func Routes() *chi.Mux {
router := chi.NewRouter()
cors := cors.New(cors.Options{
AllowedOrigins: []string{"https://sudoscientist.com", "https://www.sudoscientist.com"},
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")},
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,
)

View file

@ -0,0 +1,4 @@
DROP TABLE IF EXISTS tags;
DROP TABLE IF EXISTS posts;
DROP TABLE IF EXISTS user_profiles;
DROP TABLE IF EXISTS users;

View file

@ -0,0 +1,34 @@
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

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

View file

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

View file

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

View file

@ -0,0 +1,11 @@
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,29 +1,53 @@
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
DB *sql.DB
TokenAuth *jwtauth.JWTAuth
EmailAuth *jwtauth.JWTAuth
PostalEnabled bool
PostalKey string
PostalAPI string
PostalEmail string
)
type ReturnError struct {
Message string `json:"error"`
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 SignUpCredentials struct {
@ -32,26 +56,35 @@ type SignUpCredentials struct {
Password string `json:"password", db:"password"`
}
type SignInCredentials struct {
type UserCredentials struct {
Username string `json:"username", db:"username"`
Password string `json:"password", db:"password"`
}
type Claims struct {
Username string `json:"username"`
jwt.StandardClaims
Username string `json:"username", db:"username"`
Admin bool `json:"admin", db:"admin"`
Verified bool `json:"verified", db:"verified"`
}
type JWT struct {
JWT string `json:"jwt"`
}
func Init() {
DB.Exec("CREATE TABLE IF NOT EXISTS users (username text primary key, email text, password text, admin boolean);")
type ComposedEmail struct {
To [1]string `json:"to"`
From string `json:"from"`
Subject string `json:"subject"`
Plain_body string `json:"plain_body"`
}
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) {
@ -62,119 +95,246 @@ 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) {
returnError := ReturnError{}
returnMessage := ReturnMessage{}
returnMessage.Error = false
creds := &SignUpCredentials{}
err := json.NewDecoder(r.Body).Decode(creds)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Println(err)
w.WriteHeader(http.StatusBadRequest)
returnMessage.Message = "bad data provided"
returnMessage.Error = true
render.JSON(w, r, returnMessage)
return
}
if creds.Username == "" {
returnError.Message = "username is required"
returnMessage.Message = "username is required"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnError)
render.JSON(w, r, returnMessage)
return
}
if creds.Password == "" {
returnError.Message = "password is required"
returnMessage.Message = "password is required"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnError)
render.JSON(w, r, returnMessage)
return
}
if creds.Email == "" {
returnError.Message = "email is required"
returnMessage.Message = "email is required"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnError)
render.JSON(w, r, returnMessage)
return
}
err = checkmail.ValidateFormat(creds.Email)
if err != nil {
returnError.Message = "email not valid"
returnMessage.Message = "email not valid"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnError)
render.JSON(w, r, returnMessage)
return
}
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(creds.Password), 10)
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)
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
w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnMessage)
return
}
users.CreateProfile(creds.Username, creds.Email)
w.WriteHeader(http.StatusCreated)
expirationTime := time.Now().Add(6 * time.Hour)
claims := &Claims{
Username: creds.Username,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expirationTime.Unix(),
},
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
}
_, tokenString, _ := TokenAuth.Encode(claims)
token := setCookies(w, tokenString, expirationTime)
w.WriteHeader(http.StatusOK)
render.JSON(w, r, token)
setCookies(w, tokenString, expirationTime)
w.WriteHeader(http.StatusCreated)
returnMessage.Message = "User created! Welcome to the site!"
render.JSON(w, r, returnMessage)
return
}
func signin(w http.ResponseWriter, r *http.Request) {
creds := &SignInCredentials{}
returnMessage := ReturnMessage{}
returnMessage.Error = false
creds := &UserCredentials{}
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
}
result := DB.QueryRow("SELECT password FROM users WHERE username=$1", creds.Username)
storedCreds := &SignInCredentials{}
err = result.Scan(&storedCreds.Password)
if err != nil {
if err == sql.ErrNoRows {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.WriteHeader(http.StatusInternalServerError)
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
}
if err = bcrypt.CompareHashAndPassword([]byte(storedCreds.Password), []byte(creds.Password)); err != nil {
w.WriteHeader(http.StatusUnauthorized)
}
expirationTime := time.Now().Add(5 * time.Hour)
claims := &Claims{
Username: creds.Username,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expirationTime.Unix(),
},
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)
token := setCookies(w, tokenString, expirationTime)
setCookies(w, tokenString, expirationTime)
w.WriteHeader(http.StatusOK)
render.JSON(w, r, token)
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(5 * time.Hour)
newClaims := &Claims{
Username: claims["username"].(string),
StandardClaims: jwt.StandardClaims{
ExpiresAt: expirationTime.Unix(),
},
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)
token := setCookies(w, tokenString, expirationTime)
setCookies(w, tokenString, expirationTime)
w.WriteHeader(http.StatusOK)
render.JSON(w, r, token)
returnMessage.Message = "jwt refreshed"
render.JSON(w, r, returnMessage)
}
func setCookies(w http.ResponseWriter, jwt string, expiration time.Time) string {
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: ".sudoscientist.com", MaxAge: 360, Secure: true}
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: ".sudoscientist.com", MaxAge: 360, Secure: true}
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 strings.Join(splitToken[:2], ".")
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)
if err != nil {
if err == sql.ErrNoRows {
w.WriteHeader(http.StatusUnauthorized)
returnMessage = "username or password incorrect"
return returnMessage, false
}
w.WriteHeader(http.StatusInternalServerError)
returnMessage = "something is broken, please contact the administrator"
return returnMessage, false
}
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
}

16
packages/blog/base.go Normal file
View file

@ -0,0 +1,16 @@
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
)

134
packages/blog/comments.go Normal file
View file

@ -0,0 +1,134 @@
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

@ -4,7 +4,6 @@ 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"
@ -14,11 +13,6 @@ import (
"time"
)
var (
DB *sql.DB
TokenAuth *jwtauth.JWTAuth
)
type BlogPost struct {
ID int `json:"id",db:"id"`
Title string `json:"title",db:"title"`
@ -43,80 +37,52 @@ 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) {
returnError := ReturnError{}
returnMessage := ReturnMessage{}
returnMessage.Error = false
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 {
returnError.Message = "unknown error, try again later"
returnMessage.Message = "unknown error, try again later"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnError)
render.JSON(w, r, returnMessage)
return
}
if newBlogPost.Title == "" {
returnError.Message = "title is required"
returnMessage.Message = "title is required"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnError)
render.JSON(w, r, returnMessage)
return
}
if newBlogPost.Content == "" {
returnError.Message = "content is required"
returnMessage.Message = "content is required"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnError)
render.JSON(w, r, returnMessage)
return
}
as := slug.Make(newBlogPost.Title)
@ -126,16 +92,18 @@ func createBlogPost(w http.ResponseWriter, r *http.Request) {
scr := 0
err = slugCheck.Scan(&scr)
if err == nil {
returnError.Message = "slug already exists"
returnMessage.Message = "slug already exists"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnError)
render.JSON(w, r, returnMessage)
return
}
if err != nil {
if err != sql.ErrNoRows {
returnError.Message = "something is super broken..."
returnMessage.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnError)
render.JSON(w, r, returnMessage)
fmt.Println(err)
return
}
@ -148,15 +116,17 @@ 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 {
returnError.Message = "something is super broken..."
returnMessage.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnError)
render.JSON(w, r, returnMessage)
fmt.Println(err)
return
}
returnError.Message = "something is super broken..."
returnMessage.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnError)
render.JSON(w, r, returnMessage)
fmt.Println(err)
return
}
@ -177,23 +147,26 @@ func createBlogPost(w http.ResponseWriter, r *http.Request) {
}
func updateBlogPostById(w http.ResponseWriter, r *http.Request) {
returnError := ReturnError{}
returnMessage := ReturnMessage{}
returnMessage.Error = false
// Get the actual post
id := chi.URLParam(r, "id")
id := chi.URLParam(r, "post_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 {
returnError.Message = "blog post requested for update not found"
returnMessage.Message = "blog post requested for update not found"
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnError)
render.JSON(w, r, returnMessage)
fmt.Println(err)
return
}
returnError.Message = "something is super broken..."
returnMessage.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnError)
render.JSON(w, r, returnMessage)
fmt.Println(err)
return
}
@ -202,9 +175,10 @@ func updateBlogPostById(w http.ResponseWriter, r *http.Request) {
_, claims, _ := jwtauth.FromContext(r.Context())
username := claims["username"].(string)
if username != post.Author {
returnError.Message = "unauthorized..."
returnMessage.Message = "unauthorized..."
returnMessage.Error = true
w.WriteHeader(http.StatusUnauthorized)
render.JSON(w, r, returnError)
render.JSON(w, r, returnMessage)
return
}
// update the post struct
@ -219,9 +193,10 @@ 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 {
returnError.Message = "something is super broken..."
returnMessage.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnError)
render.JSON(w, r, returnMessage)
fmt.Println(err)
return
}
@ -233,8 +208,9 @@ 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) {
returnError := ReturnError{}
referenceID := &ReferenceID{}
returnMessage := ReturnMessage{}
returnMessage.Error = false
referenceID := &ReferenceId{}
err := json.NewDecoder(r.Body).Decode(referenceID)
// hardcode 9001 for cool kid points
if err != nil {
@ -254,9 +230,10 @@ func getBlogPosts(w http.ResponseWriter, r *http.Request) {
`
rows, err := DB.Query(search, search_id)
if err != nil {
returnError.Message = "something is super broken..."
returnMessage.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnError)
render.JSON(w, r, returnMessage)
fmt.Println(err)
return
}
@ -269,9 +246,10 @@ func getBlogPosts(w http.ResponseWriter, r *http.Request) {
posts = append(posts, post)
}
if err := rows.Err(); err != nil {
returnError.Message = "something is super broken..."
returnMessage.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnError)
render.JSON(w, r, returnMessage)
fmt.Println(err)
return
}
@ -281,15 +259,17 @@ func getBlogPosts(w http.ResponseWriter, r *http.Request) {
}
func getBlogPostBySlug(w http.ResponseWriter, r *http.Request) {
returnError := ReturnError{}
returnMessage := ReturnMessage{}
returnMessage.Error = false
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 {
returnError.Message = "post not found"
returnMessage.Message = "post not found"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnError)
render.JSON(w, r, returnMessage)
return
}
w.WriteHeader(http.StatusOK)
@ -298,15 +278,17 @@ func getBlogPostBySlug(w http.ResponseWriter, r *http.Request) {
}
func getBlogPostById(w http.ResponseWriter, r *http.Request) {
returnError := ReturnError{}
returnMessage := ReturnMessage{}
returnMessage.Error = false
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 {
returnError.Message = "post not found"
returnMessage.Message = "post not found"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnError)
render.JSON(w, r, returnMessage)
return
}
w.WriteHeader(http.StatusOK)
@ -315,8 +297,9 @@ func getBlogPostById(w http.ResponseWriter, r *http.Request) {
}
func getBlogPostsByTag(w http.ResponseWriter, r *http.Request) {
returnError := ReturnError{}
referenceID := &ReferenceID{}
returnMessage := ReturnMessage{}
returnMessage.Error = false
referenceID := &ReferenceId{}
err := json.NewDecoder(r.Body).Decode(referenceID)
// hardcode 9001 for cool kid points
if err != nil {
@ -339,9 +322,10 @@ func getBlogPostsByTag(w http.ResponseWriter, r *http.Request) {
`
rows, err := DB.Query(search, search_id, tag)
if err != nil {
returnError.Message = "something is super broken..."
returnMessage.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnError)
render.JSON(w, r, returnMessage)
fmt.Println(err)
return
}
@ -354,9 +338,10 @@ func getBlogPostsByTag(w http.ResponseWriter, r *http.Request) {
posts = append(posts, post)
}
if err := rows.Err(); err != nil {
returnError.Message = "something is super broken..."
returnMessage.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnError)
render.JSON(w, r, returnMessage)
fmt.Println(err)
return
}
@ -366,8 +351,9 @@ func getBlogPostsByTag(w http.ResponseWriter, r *http.Request) {
}
func getBlogPostsByAuthor(w http.ResponseWriter, r *http.Request) {
returnError := ReturnError{}
referenceID := &ReferenceID{}
returnMessage := ReturnMessage{}
returnMessage.Error = false
referenceID := &ReferenceId{}
err := json.NewDecoder(r.Body).Decode(referenceID)
// hardcode 9001 for cool kid points
if err != nil {
@ -389,9 +375,10 @@ func getBlogPostsByAuthor(w http.ResponseWriter, r *http.Request) {
`
rows, err := DB.Query(search, search_id, author)
if err != nil {
returnError.Message = "something is super broken..."
returnMessage.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnError)
render.JSON(w, r, returnMessage)
fmt.Println(err)
return
}
@ -404,9 +391,10 @@ func getBlogPostsByAuthor(w http.ResponseWriter, r *http.Request) {
posts = append(posts, post)
}
if err := rows.Err(); err != nil {
returnError.Message = "something is super broken..."
returnMessage.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnError)
render.JSON(w, r, returnMessage)
fmt.Println(err)
return
}

32
packages/blog/routes.go Normal file
View file

@ -0,0 +1,32 @@
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,6 +2,7 @@ package auth_middleware
import (
"net/http"
"path"
)
func TokenFromSplitCookie(r *http.Request) string {
@ -16,3 +17,8 @@ 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
}

View file

@ -23,17 +23,6 @@ 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) {

View file

@ -1,4 +0,0 @@
export DB_PORT="5432"
export DB_USER="sudosci"
export DB_NAME="sudosci"
export DB_SSL="disable"

View file

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

View file

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

View file

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

View file

@ -1,2 +1,9 @@
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://"