Merge branch 'postal_integration' of Asara/sudoscientist-go-backend into master

This commit is contained in:
Amarpreet Minhas 2020-01-25 18:10:30 -05:00 committed by Gogs
commit a804e048ff
13 changed files with 340 additions and 107 deletions

2
.gitignore vendored
View file

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

View file

@ -74,9 +74,14 @@ Install steps are for Debian 9 (stretch)
``` ```
6. 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 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) 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}" 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 migrate -path migrations/ -database ${PSQL_QUERY_STRING} up

View file

@ -30,6 +30,10 @@ func main() {
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()
@ -50,7 +54,7 @@ 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{"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"}, 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,

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

@ -1,6 +1,7 @@
package auth package auth
import ( import (
"bytes"
"database/sql" "database/sql"
"encoding/json" "encoding/json"
"fmt" "fmt"
@ -13,6 +14,7 @@ import (
"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"
) )
@ -20,10 +22,33 @@ 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
) )
type ReturnError struct { func Init() {
Message string `json:"error"` 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 { type SignUpCredentials struct {
@ -32,13 +57,15 @@ type SignUpCredentials struct {
Password string `json:"password", db:"password"` Password string `json:"password", db:"password"`
} }
type SignInCredentials struct { type UserCredentials 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"` Username string `json:"username", db:"username"`
Admin bool `json:"admin", db:"admin"`
Verified bool `json:"verified", db:"verified"`
jwt.StandardClaims jwt.StandardClaims
} }
@ -46,8 +73,20 @@ type JWT struct {
JWT string `json:"jwt"` 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 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) {
@ -58,119 +97,252 @@ 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) {
returnError := ReturnError{} returnMessage := ReturnMessage{}
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 {
w.WriteHeader(http.StatusBadRequest)
fmt.Println(err) fmt.Println(err)
w.WriteHeader(http.StatusBadRequest)
returnMessage.Message = "bad data provided"
returnMessage.Error = true
render.JSON(w, r, returnMessage)
return return
} }
if creds.Username == "" { if creds.Username == "" {
returnError.Message = "username is required" returnMessage.Message = "username is required"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnError) render.JSON(w, r, returnMessage)
return return
} }
if creds.Password == "" { if creds.Password == "" {
returnError.Message = "password is required" returnMessage.Message = "password is required"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnError) render.JSON(w, r, returnMessage)
return return
} }
if creds.Email == "" { if creds.Email == "" {
returnError.Message = "email is required" returnMessage.Message = "email is required"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnError) render.JSON(w, r, returnMessage)
return return
} }
err = checkmail.ValidateFormat(creds.Email) err = checkmail.ValidateFormat(creds.Email)
if err != nil { if err != nil {
returnError.Message = "email not valid" returnMessage.Message = "email not valid"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnError) render.JSON(w, r, returnMessage)
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) s := `INSERT INTO users (username, email, password, admin, verified)
VALUES ($1, $2, $3, $4)` VALUES ($1, $2, $3, $4, $5)`
if _, err = DB.Exec(s, creds.Username, creds.Email, string(hashedPassword), false); err != nil { if _, err = DB.Exec(s, creds.Username, creds.Email, string(hashedPassword), false, false); err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Println(err) fmt.Println(err)
returnMessage.Message = "unexpected error. please contact the administrator"
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnMessage)
return return
} }
users.CreateProfile(creds.Username, creds.Email) users.CreateProfile(creds.Username, creds.Email)
w.WriteHeader(http.StatusCreated) expirationTime := time.Now().Add(24 * time.Hour)
expirationTime := time.Now().Add(6 * time.Hour)
claims := &Claims{ claims := &Claims{
Username: creds.Username, Username: creds.Username,
Admin: false,
Verified: false,
StandardClaims: jwt.StandardClaims{ StandardClaims: jwt.StandardClaims{
ExpiresAt: expirationTime.Unix(), ExpiresAt: expirationTime.Unix(),
}, },
} }
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) _, tokenString, _ := TokenAuth.Encode(claims)
token := setCookies(w, tokenString, expirationTime) setCookies(w, tokenString, expirationTime)
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusCreated)
render.JSON(w, r, token) returnMessage.Message = "User created! Welcome to the site!"
render.JSON(w, r, returnMessage)
return
} }
func signin(w http.ResponseWriter, r *http.Request) { func signin(w http.ResponseWriter, r *http.Request) {
creds := &SignInCredentials{} returnMessage := ReturnMessage{}
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
} }
result := DB.QueryRow("SELECT password FROM users WHERE username=$1", creds.Username) verify_pw, ok := checkPassword(w, *creds)
storedCreds := &SignInCredentials{} if !ok {
err = result.Scan(&storedCreds.Password) w.WriteHeader(http.StatusBadRequest)
if err != nil { returnMessage.Message = verify_pw
if err == sql.ErrNoRows { returnMessage.Error = true
w.WriteHeader(http.StatusUnauthorized) render.JSON(w, r, returnMessage)
return return
} }
w.WriteHeader(http.StatusInternalServerError) expirationTime := time.Now().Add(24 * time.Hour)
return user_claims := &Claims{}
} user_claims_query := DB.QueryRow("SELECT username, admin, verified FROM users WHERE username=$1", creds.Username)
if err = bcrypt.CompareHashAndPassword([]byte(storedCreds.Password), []byte(creds.Password)); err != nil { err = user_claims_query.Scan(&user_claims.Username, &user_claims.Admin, &user_claims.Verified)
w.WriteHeader(http.StatusUnauthorized)
}
expirationTime := time.Now().Add(5 * time.Hour)
claims := &Claims{ claims := &Claims{
Username: creds.Username, Username: user_claims.Username,
Admin: user_claims.Admin,
Verified: user_claims.Verified,
StandardClaims: jwt.StandardClaims{ StandardClaims: jwt.StandardClaims{
ExpiresAt: expirationTime.Unix(), ExpiresAt: expirationTime.Unix(),
}, },
} }
_, tokenString, _ := TokenAuth.Encode(claims) _, tokenString, _ := TokenAuth.Encode(claims)
token := setCookies(w, tokenString, expirationTime) setCookies(w, tokenString, expirationTime)
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
render.JSON(w, r, token) render.JSON(w, r, returnMessage)
} }
func refresh(w http.ResponseWriter, r *http.Request) { func refresh(w http.ResponseWriter, r *http.Request) {
returnMessage := ReturnMessage{}
returnMessage.Error = false
_, claims, _ := jwtauth.FromContext(r.Context()) _, claims, _ := jwtauth.FromContext(r.Context())
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
expirationTime := time.Now().Add(5 * time.Hour) 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 := &Claims{ newClaims := &Claims{
Username: claims["username"].(string), Username: user_claims.Username,
Admin: user_claims.Admin,
Verified: user_claims.Verified,
StandardClaims: jwt.StandardClaims{ StandardClaims: jwt.StandardClaims{
ExpiresAt: expirationTime.Unix(), ExpiresAt: expirationTime.Unix(),
}, },
} }
_, tokenString, _ := TokenAuth.Encode(newClaims) _, tokenString, _ := TokenAuth.Encode(newClaims)
token := setCookies(w, tokenString, expirationTime) setCookies(w, tokenString, expirationTime)
w.WriteHeader(http.StatusOK) 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, ".") 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) 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) 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
} }

View file

@ -43,8 +43,9 @@ type NewBlogPost struct {
Author string `json:"author",db:"author"` Author string `json:"author",db:"author"`
} }
type ReturnError struct { type ReturnMessage struct {
Message string `json:"error"` Message string `json:"msg"`
Error bool `json:"error"`
} }
type ReturnSuccess struct { type ReturnSuccess struct {
@ -57,7 +58,6 @@ type ReferenceID struct {
LastID int `json:"last_id"` LastID int `json:"last_id"`
} }
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) {
@ -75,28 +75,41 @@ func Routes() *chi.Mux {
} }
func createBlogPost(w http.ResponseWriter, r *http.Request) { func createBlogPost(w http.ResponseWriter, r *http.Request) {
returnError := ReturnError{} returnMessage := ReturnMessage{}
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 {
returnError.Message = "unknown error, try again later" returnMessage.Message = "unknown error, try again later"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnError) render.JSON(w, r, returnMessage)
return return
} }
if newBlogPost.Title == "" { if newBlogPost.Title == "" {
returnError.Message = "title is required" returnMessage.Message = "title is required"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnError) render.JSON(w, r, returnMessage)
return return
} }
if newBlogPost.Content == "" { if newBlogPost.Content == "" {
returnError.Message = "content is required" returnMessage.Message = "content is required"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnError) render.JSON(w, r, returnMessage)
return return
} }
as := slug.Make(newBlogPost.Title) as := slug.Make(newBlogPost.Title)
@ -106,16 +119,18 @@ 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 {
returnError.Message = "slug already exists" returnMessage.Message = "slug already exists"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnError) render.JSON(w, r, returnMessage)
return return
} }
if err != nil { if err != nil {
if err != sql.ErrNoRows { if err != sql.ErrNoRows {
returnError.Message = "something is super broken..." returnMessage.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnError) render.JSON(w, r, returnMessage)
fmt.Println(err) fmt.Println(err)
return return
} }
@ -128,15 +143,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) 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 {
returnError.Message = "something is super broken..." returnMessage.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnError) render.JSON(w, r, returnMessage)
fmt.Println(err) fmt.Println(err)
return return
} }
returnError.Message = "something is super broken..." returnMessage.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnError) render.JSON(w, r, returnMessage)
fmt.Println(err) fmt.Println(err)
return return
} }
@ -157,7 +174,8 @@ func createBlogPost(w http.ResponseWriter, r *http.Request) {
} }
func updateBlogPostById(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 // Get the actual post
id := chi.URLParam(r, "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)
@ -165,15 +183,17 @@ func updateBlogPostById(w http.ResponseWriter, r *http.Request) {
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 {
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) w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnError) render.JSON(w, r, returnMessage)
fmt.Println(err) fmt.Println(err)
return return
} }
returnError.Message = "something is super broken..." returnMessage.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnError) render.JSON(w, r, returnMessage)
fmt.Println(err) fmt.Println(err)
return return
} }
@ -182,9 +202,10 @@ 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 {
returnError.Message = "unauthorized..." returnMessage.Message = "unauthorized..."
returnMessage.Error = true
w.WriteHeader(http.StatusUnauthorized) w.WriteHeader(http.StatusUnauthorized)
render.JSON(w, r, returnError) render.JSON(w, r, returnMessage)
return return
} }
// update the post struct // update the post struct
@ -199,9 +220,10 @@ 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 {
returnError.Message = "something is super broken..." returnMessage.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnError) render.JSON(w, r, returnMessage)
fmt.Println(err) fmt.Println(err)
return return
} }
@ -213,7 +235,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) {
returnError := ReturnError{} returnMessage := ReturnMessage{}
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
@ -234,9 +257,10 @@ 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 {
returnError.Message = "something is super broken..." returnMessage.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnError) render.JSON(w, r, returnMessage)
fmt.Println(err) fmt.Println(err)
return return
} }
@ -249,9 +273,10 @@ 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 {
returnError.Message = "something is super broken..." returnMessage.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnError) render.JSON(w, r, returnMessage)
fmt.Println(err) fmt.Println(err)
return return
} }
@ -261,15 +286,17 @@ func getBlogPosts(w http.ResponseWriter, r *http.Request) {
} }
func getBlogPostBySlug(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") 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 {
returnError.Message = "post not found" returnMessage.Message = "post not found"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnError) render.JSON(w, r, returnMessage)
return return
} }
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
@ -278,15 +305,17 @@ func getBlogPostBySlug(w http.ResponseWriter, r *http.Request) {
} }
func getBlogPostById(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") 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 {
returnError.Message = "post not found" returnMessage.Message = "post not found"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnError) render.JSON(w, r, returnMessage)
return return
} }
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
@ -295,7 +324,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) {
returnError := ReturnError{} returnMessage := ReturnMessage{}
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
@ -319,9 +349,10 @@ 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 {
returnError.Message = "something is super broken..." returnMessage.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnError) render.JSON(w, r, returnMessage)
fmt.Println(err) fmt.Println(err)
return return
} }
@ -334,9 +365,10 @@ 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 {
returnError.Message = "something is super broken..." returnMessage.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnError) render.JSON(w, r, returnMessage)
fmt.Println(err) fmt.Println(err)
return return
} }
@ -346,7 +378,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) {
returnError := ReturnError{} returnMessage := ReturnMessage{}
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
@ -369,9 +402,10 @@ 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 {
returnError.Message = "something is super broken..." returnMessage.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnError) render.JSON(w, r, returnMessage)
fmt.Println(err) fmt.Println(err)
return return
} }
@ -384,9 +418,10 @@ 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 {
returnError.Message = "something is super broken..." returnMessage.Message = "something is super broken..."
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnError) render.JSON(w, r, returnMessage)
fmt.Println(err) fmt.Println(err)
return return
} }

View file

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

@ -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 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 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://"