This repository has been archived on 2023-07-09. You can view files and clone it, but cannot push or open issues or pull requests.
sudoscientist-go-backend/packages/auth/auth.go

341 lines
11 KiB
Go

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/go-chi/chi"
"github.com/go-chi/jwtauth"
"github.com/go-chi/render"
"golang.org/x/crypto/bcrypt"
"net/http"
"os"
"strings"
"time"
)
var (
DB *sql.DB
TokenAuth *jwtauth.JWTAuth
EmailAuth *jwtauth.JWTAuth
PostalEnabled bool
PostalKey string
PostalAPI string
PostalEmail string
)
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 {
Username string `json:"username", db:"username"`
Email string `json:"email", db:"email"`
Password string `json:"password", db:"password"`
}
type UserCredentials struct {
Username string `json:"username", db:"username"`
Password string `json:"password", db:"password"`
}
type Claims struct {
Username string `json:"username", db:"username"`
Admin bool `json:"admin", db:"admin"`
Verified bool `json:"verified", db:"verified"`
}
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) {
r.Use(jwtauth.Verify(TokenAuth, auth_middleware.TokenFromSplitCookie))
r.Use(jwtauth.Authenticator)
r.Post("/refresh", refresh)
})
return r
}
func verify(w http.ResponseWriter, r *http.Request) {
returnMessage := ReturnMessage{}
returnMessage.Error = false
_, claims, _ := jwtauth.FromContext(r.Context())
sqlStatement := `
UPDATE users
SET verified = $1
WHERE username = $2;`
_, err := DB.Exec(sqlStatement, true, claims["username"])
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
returnMessage.Message = "unexpected error verifying account. please contact the administrator"
returnMessage.Error = true
render.JSON(w, r, returnMessage)
return
}
w.WriteHeader(http.StatusOK)
returnMessage.Message = "your email has been verified!"
render.JSON(w, r, returnMessage)
return
}
func register(w http.ResponseWriter, r *http.Request) {
returnMessage := ReturnMessage{}
returnMessage.Error = false
creds := &SignUpCredentials{}
err := json.NewDecoder(r.Body).Decode(creds)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusBadRequest)
returnMessage.Message = "bad data provided"
returnMessage.Error = true
render.JSON(w, r, returnMessage)
return
}
if creds.Username == "" {
returnMessage.Message = "username is required"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnMessage)
return
}
if creds.Password == "" {
returnMessage.Message = "password is required"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnMessage)
return
}
if creds.Email == "" {
returnMessage.Message = "email is required"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnMessage)
return
}
err = checkmail.ValidateFormat(creds.Email)
if err != nil {
returnMessage.Message = "email not valid"
returnMessage.Error = true
w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, returnMessage)
return
}
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(creds.Password), 10)
s := `INSERT INTO users (username, email, password, admin, verified)
VALUES ($1, $2, $3, $4, $5)`
if _, err = DB.Exec(s, creds.Username, creds.Email, string(hashedPassword), false, false); err != nil {
fmt.Println(err)
returnMessage.Message = "unexpected error. please contact the administrator"
returnMessage.Error = true
w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnMessage)
return
}
users.CreateProfile(creds.Username, creds.Email)
expirationTime := time.Now().Add(24 * time.Hour)
claims := map[string]interface{}{
"username": creds.Username,
"admin": false,
"verified": false,
}
jwtauth.SetExpiry(claims, expirationTime)
if PostalEnabled {
_, emailToken, _ := EmailAuth.Encode(claims)
returnMessage, ok := sendEmailToken(w, emailToken, creds.Username, creds.Email)
if !ok {
w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, returnMessage)
return
}
w.WriteHeader(http.StatusCreated)
render.JSON(w, r, returnMessage)
return
}
_, tokenString, _ := TokenAuth.Encode(claims)
setCookies(w, tokenString, expirationTime)
w.WriteHeader(http.StatusCreated)
returnMessage.Message = "User created! Welcome to the site!"
render.JSON(w, r, returnMessage)
return
}
func signin(w http.ResponseWriter, r *http.Request) {
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
}
verify_pw, ok := checkPassword(w, *creds)
if !ok {
w.WriteHeader(http.StatusBadRequest)
returnMessage.Message = verify_pw
returnMessage.Error = true
render.JSON(w, r, returnMessage)
return
}
expirationTime := time.Now().Add(24 * time.Hour)
user_claims := &Claims{}
user_claims_query := DB.QueryRow("SELECT username, admin, verified FROM users WHERE username=$1", creds.Username)
err = user_claims_query.Scan(&user_claims.Username, &user_claims.Admin, &user_claims.Verified)
claims := map[string]interface{}{
"username": user_claims.Username,
"admin": user_claims.Admin,
"verified": user_claims.Verified,
}
jwtauth.SetExpiry(claims, expirationTime)
_, tokenString, _ := TokenAuth.Encode(claims)
setCookies(w, tokenString, expirationTime)
w.WriteHeader(http.StatusOK)
render.JSON(w, r, returnMessage)
}
func refresh(w http.ResponseWriter, r *http.Request) {
returnMessage := ReturnMessage{}
returnMessage.Error = false
_, claims, _ := jwtauth.FromContext(r.Context())
w.WriteHeader(http.StatusOK)
expirationTime := time.Now().Add(24 * time.Hour)
user_claims := &Claims{}
user_claims_query := DB.QueryRow("SELECT username, admin, verified FROM users WHERE username=$1", claims["username"].(string))
err := user_claims_query.Scan(&user_claims.Username, &user_claims.Admin, &user_claims.Verified)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
returnMessage.Message = "unexpected error refreshing your token, please try again later"
returnMessage.Error = true
render.JSON(w, r, returnMessage)
return
}
newClaims := map[string]interface{}{
"username": user_claims.Username,
"admin": user_claims.Admin,
"verified": user_claims.Verified,
}
jwtauth.SetExpiry(newClaims, expirationTime)
_, tokenString, _ := TokenAuth.Encode(newClaims)
setCookies(w, tokenString, expirationTime)
w.WriteHeader(http.StatusOK)
returnMessage.Message = "jwt refreshed"
render.JSON(w, r, returnMessage)
}
func setCookies(w http.ResponseWriter, jwt string, expiration time.Time) {
splitToken := strings.Split(jwt, ".")
dataCookie := http.Cookie{Name: "DataCookie", Value: strings.Join(splitToken[:2], "."), Expires: expiration, HttpOnly: false, Path: "/", Domain: os.Getenv("UI_ADDR"), MaxAge: 360}
http.SetCookie(w, &dataCookie)
signatureCookie := http.Cookie{Name: "SignatureCookie", Value: splitToken[2], Expires: expiration, HttpOnly: true, Path: "/", Domain: os.Getenv("UI_ADDR"), MaxAge: 360}
http.SetCookie(w, &signatureCookie)
return
}
func sendEmailToken(w http.ResponseWriter, token string, name string, email string) (returnMessage ReturnMessage, ok bool) {
header := "Thanks for joining sudoscientist, " + name + "!"
body := "\n\nPlease click the following link to verify your email: "
link := os.Getenv("API_ADDR") + "/v1/api/auth/verify/" + token
email_array := [1]string{email}
composed_email := ComposedEmail{
To: email_array,
From: PostalEmail,
Subject: "sudoscientist: Please confirm your e-mail address",
Plain_body: header + body + link,
}
postal_req, err := json.Marshal(&composed_email)
if err != nil {
fmt.Println(err)
returnMessage.Message = "unexpected error. your account may be in limbo. please contact the administrator"
ok = false
return returnMessage, ok
}
req, err := http.NewRequest("POST", fmt.Sprintf("%s/api/v1/send/message", PostalAPI), bytes.NewBuffer(postal_req))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Server-API-Key", PostalKey)
if err != nil {
fmt.Println(err)
returnMessage.Message = "unexpected error. your account may be in limbo. please contact the administrator"
ok = false
return returnMessage, ok
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
returnMessage.Message = "unexpected error. your account may be in limbo. please contact the administrator"
ok = false
return returnMessage, ok
}
defer resp.Body.Close()
returnMessage.Message = "verification email sent"
ok = true
return returnMessage, ok
}
func checkPassword(w http.ResponseWriter, creds UserCredentials) (string, bool) {
returnMessage := ""
result := DB.QueryRow("SELECT password FROM users WHERE username=$1", creds.Username)
storedCreds := &UserCredentials{}
err := result.Scan(&storedCreds.Password)
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
}