Merge branch 'postal_integration' of Asara/sudoscientist-go-backend into master
This commit is contained in:
commit
a804e048ff
13 changed files with 340 additions and 107 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
@ -24,3 +24,5 @@ _testmain.go
|
|||
*.test
|
||||
*.prof
|
||||
|
||||
# Settings
|
||||
settings/*.env
|
||||
|
|
|
@ -74,9 +74,14 @@ Install steps are for Debian 9 (stretch)
|
|||
```
|
||||
|
||||
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
|
||||
|
|
6
main.go
6
main.go
|
@ -30,6 +30,10 @@ func main() {
|
|||
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()
|
||||
|
||||
|
@ -50,7 +54,7 @@ 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,
|
||||
|
|
4
migrations/1579409382_verification.down.sql
Normal file
4
migrations/1579409382_verification.down.sql
Normal file
|
@ -0,0 +1,4 @@
|
|||
BEGIN;
|
||||
ALTER TABLE users
|
||||
DROP COLUMN verified IF EXISTS;
|
||||
COMMIT;
|
4
migrations/1579409382_verification.up.sql
Normal file
4
migrations/1579409382_verification.up.sql
Normal file
|
@ -0,0 +1,4 @@
|
|||
BEGIN;
|
||||
ALTER TABLE users
|
||||
ADD COLUMN verified boolean NOT NULL DEFAULT false;
|
||||
COMMIT;
|
|
@ -1,6 +1,7 @@
|
|||
package auth
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
@ -13,6 +14,7 @@ import (
|
|||
"github.com/go-chi/render"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
@ -20,10 +22,33 @@ import (
|
|||
var (
|
||||
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,13 +57,15 @@ 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"`
|
||||
Username string `json:"username", db:"username"`
|
||||
Admin bool `json:"admin", db:"admin"`
|
||||
Verified bool `json:"verified", db:"verified"`
|
||||
jwt.StandardClaims
|
||||
}
|
||||
|
||||
|
@ -46,8 +73,20 @@ type JWT struct {
|
|||
JWT string `json:"jwt"`
|
||||
}
|
||||
|
||||
type ComposedEmail struct {
|
||||
To [1]string `json:"to"`
|
||||
From string `json:"from"`
|
||||
Subject string `json:"subject"`
|
||||
Plain_body string `json:"plain_body"`
|
||||
}
|
||||
|
||||
func 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) {
|
||||
|
@ -58,119 +97,252 @@ 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)
|
||||
expirationTime := time.Now().Add(24 * time.Hour)
|
||||
claims := &Claims{
|
||||
Username: creds.Username,
|
||||
Admin: false,
|
||||
Verified: false,
|
||||
StandardClaims: jwt.StandardClaims{
|
||||
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)
|
||||
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)
|
||||
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
|
||||
}
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if err = bcrypt.CompareHashAndPassword([]byte(storedCreds.Password), []byte(creds.Password)); err != nil {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
}
|
||||
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", creds.Username)
|
||||
err = user_claims_query.Scan(&user_claims.Username, &user_claims.Admin, &user_claims.Verified)
|
||||
claims := &Claims{
|
||||
Username: creds.Username,
|
||||
Username: user_claims.Username,
|
||||
Admin: user_claims.Admin,
|
||||
Verified: user_claims.Verified,
|
||||
StandardClaims: jwt.StandardClaims{
|
||||
ExpiresAt: expirationTime.Unix(),
|
||||
},
|
||||
}
|
||||
_, 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)
|
||||
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{
|
||||
Username: claims["username"].(string),
|
||||
Username: user_claims.Username,
|
||||
Admin: user_claims.Admin,
|
||||
Verified: user_claims.Verified,
|
||||
StandardClaims: jwt.StandardClaims{
|
||||
ExpiresAt: expirationTime.Unix(),
|
||||
},
|
||||
}
|
||||
_, 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
|
||||
}
|
||||
|
|
|
@ -43,8 +43,9 @@ type NewBlogPost struct {
|
|||
Author string `json:"author",db:"author"`
|
||||
}
|
||||
|
||||
type ReturnError struct {
|
||||
Message string `json:"error"`
|
||||
type ReturnMessage struct {
|
||||
Message string `json:"msg"`
|
||||
Error bool `json:"error"`
|
||||
}
|
||||
|
||||
type ReturnSuccess struct {
|
||||
|
@ -57,7 +58,6 @@ type ReferenceID struct {
|
|||
LastID int `json:"last_id"`
|
||||
}
|
||||
|
||||
|
||||
func Routes() *chi.Mux {
|
||||
r := chi.NewRouter()
|
||||
r.Group(func(r chi.Router) {
|
||||
|
@ -75,28 +75,41 @@ func Routes() *chi.Mux {
|
|||
}
|
||||
|
||||
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)
|
||||
|
@ -106,16 +119,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
|
||||
}
|
||||
|
@ -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)
|
||||
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
|
||||
}
|
||||
|
@ -157,7 +174,8 @@ 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")
|
||||
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)
|
||||
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
|
||||
}
|
||||
|
@ -182,9 +202,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
|
||||
|
@ -199,9 +220,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
|
||||
}
|
||||
|
@ -213,7 +235,8 @@ func updateBlogPostById(w http.ResponseWriter, r *http.Request) {
|
|||
|
||||
// This will search by the last id seen, descending.
|
||||
func getBlogPosts(w http.ResponseWriter, r *http.Request) {
|
||||
returnError := ReturnError{}
|
||||
returnMessage := ReturnMessage{}
|
||||
returnMessage.Error = false
|
||||
referenceID := &ReferenceID{}
|
||||
err := json.NewDecoder(r.Body).Decode(referenceID)
|
||||
// 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)
|
||||
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
|
||||
}
|
||||
|
@ -249,9 +273,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
|
||||
}
|
||||
|
@ -261,15 +286,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)
|
||||
|
@ -278,15 +305,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)
|
||||
|
@ -295,7 +324,8 @@ func getBlogPostById(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
|
||||
func getBlogPostsByTag(w http.ResponseWriter, r *http.Request) {
|
||||
returnError := ReturnError{}
|
||||
returnMessage := ReturnMessage{}
|
||||
returnMessage.Error = false
|
||||
referenceID := &ReferenceID{}
|
||||
err := json.NewDecoder(r.Body).Decode(referenceID)
|
||||
// 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)
|
||||
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
|
||||
}
|
||||
|
@ -334,9 +365,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
|
||||
}
|
||||
|
@ -346,7 +378,8 @@ func getBlogPostsByTag(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
|
||||
func getBlogPostsByAuthor(w http.ResponseWriter, r *http.Request) {
|
||||
returnError := ReturnError{}
|
||||
returnMessage := ReturnMessage{}
|
||||
returnMessage.Error = false
|
||||
referenceID := &ReferenceID{}
|
||||
err := json.NewDecoder(r.Body).Decode(referenceID)
|
||||
// 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)
|
||||
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
|
||||
}
|
||||
|
@ -384,9 +418,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
|
||||
}
|
||||
|
|
|
@ -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
|
||||
}
|
||||
|
|
|
@ -1,4 +0,0 @@
|
|||
export DB_PORT="5432"
|
||||
export DB_USER="sudosci"
|
||||
export DB_NAME="sudosci"
|
||||
export DB_SSL="disable"
|
|
@ -1 +0,0 @@
|
|||
export DB_PW="CHANGEME"
|
|
@ -1 +1,2 @@
|
|||
export DB_PW="CHANGEME"
|
||||
export POSTAL_KEY="POSTAL_API_KEY"
|
||||
|
|
|
@ -1,2 +0,0 @@
|
|||
export API_PORT="8080"
|
||||
export JWT_SECRET="CHANGEMEALSO"
|
|
@ -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://"
|
||||
|
|
Reference in a new issue